prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>release.js<|end_file_name|><|fim▁begin|>#!/usr/bin/env node
/* global cat:true, cd:true, echo:true, exec:true, exit:true */
// Usage:
// stable release: node release.js
// pre-release: node release.js --pre-release {version}
// test run: node release.js --remote={repo}
// - repo: "/tmp/repo" (filesystem), "user/repo" (github), "http://mydomain/repo.git" (another domain)
"use strict";
var baseDir, downloadBuilder, repoDir, prevVersion, newVersion, nextVersion, tagTime, preRelease, repo,
fs = require( "fs" ),
path = require( "path" ),
rnewline = /\r?\n/,
branch = "master";
walk([
bootstrap,
section( "setting up repo" ),
cloneRepo,
checkState,
section( "calculating versions" ),
getVersions,
confirm,
section( "building release" ),
buildReleaseBranch,
buildPackage,
section( "pushing tag" ),
confirmReview,
pushRelease,
section( "updating branch version" ),
updateBranchVersion,
section( "pushing " + branch ),
confirmReview,
pushBranch,
section( "generating changelog" ),
generateChangelog,
section( "gathering contributors" ),
gatherContributors,
section( "updating trac" ),
updateTrac,
confirm
]);
function cloneRepo() {
echo( "Cloning " + repo.cyan + "..." );
git( "clone " + repo + " " + repoDir, "Error cloning repo." );
cd( repoDir );
echo( "Checking out " + branch.cyan + " branch..." );
git( "checkout " + branch, "Error checking out branch." );
echo();
echo( "Installing dependencies..." );
if ( exec( "npm install" ).code !== 0 ) {
abort( "Error installing dependencies." );
}
echo();
}
function checkState() {
echo( "Checking AUTHORS.txt..." );
var result, lastActualAuthor,
lastListedAuthor = cat( "AUTHORS.txt" ).trim().split( rnewline ).pop();
result = exec( "grunt authors", { silent: true });
if ( result.code !== 0 ) {
abort( "Error getting list of authors." );
}
lastActualAuthor = result.output.split( rnewline ).splice( -4, 1 )[ 0 ];
if ( lastListedAuthor !== lastActualAuthor ) {
echo( "Last listed author is " + lastListedAuthor.red + "." );
echo( "Last actual author is " + lastActualAuthor.green + "." );
abort( "Please update AUTHORS.txt." );
}
echo( "Last listed author (" + lastListedAuthor.cyan + ") is correct." );
}
function getVersions() {
// prevVersion, newVersion, nextVersion are defined in the parent scope
var parts, major, minor, patch,
currentVersion = readPackage().version;
echo( "Validating current version..." );
if ( currentVersion.substr( -3, 3 ) !== "pre" ) {
echo( "The current version is " + currentVersion.red + "." );
abort( "The version must be a pre version." );
}
if ( preRelease ) {
newVersion = preRelease;
// Note: prevVersion is not currently used for pre-releases.
prevVersion = nextVersion = currentVersion;
} else {
newVersion = currentVersion.substr( 0, currentVersion.length - 3 );
parts = newVersion.split( "." );
major = parseInt( parts[ 0 ], 10 );
minor = parseInt( parts[ 1 ], 10 );
patch = parseInt( parts[ 2 ], 10 );
if ( minor === 0 && patch === 0 ) {
abort( "This script is not smart enough to handle major release (eg. 2.0.0)." );
} else if ( patch === 0 ) {
prevVersion = git( "for-each-ref --count=1 --sort=-authordate --format='%(refname:short)' refs/tags/" + [ major, minor - 1 ].join( "." ) + "*" ).trim();
} else {
prevVersion = [ major, minor, patch - 1 ].join( "." );
}
nextVersion = [ major, minor, patch + 1 ].join( "." ) + "pre";
}
echo( "We are going from " + prevVersion.cyan + " to " + newVersion.cyan + "." );
echo( "After the release, the version will be " + nextVersion.cyan + "." );
}
function buildReleaseBranch() {
var pkg;
echo( "Creating " + "release".cyan + " branch..." );
git( "checkout -b release", "Error creating release branch." );
echo();
echo( "Updating package.json..." );
pkg = readPackage();
pkg.version = newVersion;
pkg.author.url = pkg.author.url.replace( "master", newVersion );
pkg.licenses.forEach(function( license ) {
license.url = license.url.replace( "master", newVersion );
});
writePackage( pkg );
echo( "Generating manifest files..." );
if ( exec( "grunt manifest" ).code !== 0 ) {
abort( "Error generating manifest files." );
}
echo();
echo( "Committing release artifacts..." );
git( "add *.jquery.json", "Error adding manifest files to git." );
git( "commit -am 'Tagging the " + newVersion + " release.'",
"Error committing release changes." );
echo();
echo( "Tagging release..." );
git( "tag " + newVersion, "Error tagging " + newVersion + "." );
tagTime = git( "log -1 --format='%ad'", "Error getting tag timestamp." ).trim();
}
function buildPackage( callback ) {
if( preRelease ) {
return buildPreReleasePackage( callback );
} else {
return buildCDNPackage( callback );
}
}
function buildPreReleasePackage( callback ) {
var build, files, jqueryUi, packer, target, targetZip;
echo( "Build pre-release Package" );
jqueryUi = new downloadBuilder.JqueryUi( path.resolve( "." ) );
build = new downloadBuilder.Builder( jqueryUi, ":all:" );
packer = new downloadBuilder.Packer( build, null, {
addTests: true,
bundleSuffix: "",
skipDocs: true,
skipTheme: true
});
target = "../" + jqueryUi.pkg.name + "-" + jqueryUi.pkg.version;
targetZip = target + ".zip";
return walk([
function( callback ) {
echo( "Building release files" );
packer.pack(function( error, _files ) {
if( error ) {
abort( error.stack );
}
files = _files.map(function( file ) {
// Strip first path
file.path = file.path.replace( /^[^\/]*\//, "" );
return file;
}).filter(function( file ) {
// Filter development-bundle content only
return (/^development-bundle/).test( file.path );
}).map(function( file ) {
// Strip development-bundle
file.path = file.path.replace( /^development-bundle\//, "" );
return file;
});
return callback();
});
},
function() {
downloadBuilder.util.createZip( files, targetZip, function( error ) {
if ( error ) {
abort( error.stack );
}
echo( "Built zip package at " + path.relative( "../..", targetZip ).cyan );
return callback();
});
}
]);
}
function buildCDNPackage( callback ) {
var build, output, target, targetZip,
add = function( file ) {
output.push( file );<|fim▁hole|> },
jqueryUi = new downloadBuilder.JqueryUi( path.resolve( "." ) ),
themeGallery = downloadBuilder.themeGallery( jqueryUi );
echo( "Build CDN Package" );
build = new downloadBuilder.Builder( jqueryUi, ":all:" );
output = [];
target = "../" + jqueryUi.pkg.name + "-" + jqueryUi.pkg.version + "-cdn";
targetZip = target + ".zip";
[ "AUTHORS.txt", "MIT-LICENSE.txt", "package.json" ].map(function( name ) {
return build.get( name );
}).forEach( add );
// "ui/*.js"
build.componentFiles.filter(function( file ) {
return (/^ui\//).test( file.path );
}).forEach( add );
// "ui/*.min.js"
build.componentMinFiles.filter(function( file ) {
return (/^ui\//).test( file.path );
}).forEach( add );
// "i18n/*.js"
build.i18nFiles.rename( /^ui\//, "" ).forEach( add );
build.i18nMinFiles.rename( /^ui\//, "" ).forEach( add );
build.bundleI18n.into( "i18n/" ).forEach( add );
build.bundleI18nMin.into( "i18n/" ).forEach( add );
build.bundleJs.forEach( add );
build.bundleJsMin.forEach( add );
walk( themeGallery.map(function( theme ) {
return function( callback ) {
var themeCssOnlyRe, themeDirRe,
folderName = theme.folderName(),
packer = new downloadBuilder.Packer( build, theme, {
skipDocs: true
});
// TODO improve code by using custom packer instead of download packer (Packer)
themeCssOnlyRe = new RegExp( "development-bundle/themes/" + folderName + "/jquery.ui.theme.css" );
themeDirRe = new RegExp( "css/" + folderName );
packer.pack(function( error, files ) {
if ( error ) {
abort( error.stack );
}
// Add theme files.
files
// Pick only theme files we need on the bundle.
.filter(function( file ) {
if ( themeCssOnlyRe.test( file.path ) || themeDirRe.test( file.path ) ) {
return true;
}
return false;
})
// Convert paths the way bundle needs
.map(function( file ) {
file.path = file.path
// Remove initial package name eg. "jquery-ui-1.10.0.custom"
.split( "/" ).slice( 1 ).join( "/" )
.replace( /development-bundle\/themes/, "css" )
.replace( /css/, "themes" )
// Make jquery-ui-1.10.0.custom.css into jquery-ui.css, or jquery-ui-1.10.0.custom.min.css into jquery-ui.min.css
.replace( /jquery-ui-.*?(\.min)*\.css/, "jquery-ui$1.css" );
return file;
}).forEach( add );
return callback();
});
};
}).concat([function() {
var crypto = require( "crypto" );
// Create MD5 manifest
output.push({
path: "MANIFEST",
data: output.sort(function( a, b ) {
return a.path.localeCompare( b.path );
}).map(function( file ) {
var md5 = crypto.createHash( "md5" );
md5.update( file.data );
return file.path + " " + md5.digest( "hex" );
}).join( "\n" )
});
downloadBuilder.util.createZip( output, targetZip, function( error ) {
if ( error ) {
abort( error.stack );
}
echo( "Built zip CDN package at " + path.relative( "../..", targetZip ).cyan );
return callback();
});
}]));
}
function pushRelease() {
echo( "Pushing release to GitHub..." );
git( "push --tags", "Error pushing tags to GitHub." );
}
function updateBranchVersion() {
// Pre-releases don't change the master version
if ( preRelease ) {
return;
}
var pkg;
echo( "Checking out " + branch.cyan + " branch..." );
git( "checkout " + branch, "Error checking out " + branch + " branch." );
echo( "Updating package.json..." );
pkg = readPackage();
pkg.version = nextVersion;
writePackage( pkg );
echo( "Committing version update..." );
git( "commit -am 'Updating the " + branch + " version to " + nextVersion + ".'",
"Error committing package.json." );
}
function pushBranch() {
// Pre-releases don't change the master version
if ( preRelease ) {
return;
}
echo( "Pushing " + branch.cyan + " to GitHub..." );
git( "push", "Error pushing to GitHub." );
}
function generateChangelog() {
if ( preRelease ) {
return;
}
var commits,
changelogPath = baseDir + "/changelog",
changelog = cat( "build/release/changelog-shell" ) + "\n",
fullFormat = "* %s (TICKETREF, [%h](http://github.com/jquery/jquery-ui/commit/%H))";
changelog = changelog.replace( "{title}", "jQuery UI " + newVersion + " Changelog" );
echo ( "Adding commits..." );
commits = gitLog( fullFormat );
echo( "Adding links to tickets..." );
changelog += commits
// Add ticket references
.map(function( commit ) {
var tickets = [];
commit.replace( /Fixe[sd] #(\d+)/g, function( match, ticket ) {
tickets.push( ticket );
});
return tickets.length ?
commit.replace( "TICKETREF", tickets.map(function( ticket ) {
return "[#" + ticket + "](http://bugs.jqueryui.com/ticket/" + ticket + ")";
}).join( ", " ) ) :
// Leave TICKETREF token in place so it's easy to find commits without tickets
commit;
})
// Sort commits so that they're grouped by component
.sort()
.join( "\n" ) + "\n";
echo( "Adding Trac tickets..." );
changelog += trac( "/query?milestone=" + newVersion + "&resolution=fixed" +
"&col=id&col=component&col=summary&order=component" ) + "\n";
fs.writeFileSync( changelogPath, changelog );
echo( "Stored changelog in " + changelogPath.cyan + "." );
}
function gatherContributors() {
if ( preRelease ) {
return;
}
var contributors,
contributorsPath = baseDir + "/contributors";
echo( "Adding committers and authors..." );
contributors = gitLog( "%aN%n%cN" );
echo( "Adding reporters and commenters from Trac..." );
contributors = contributors.concat(
trac( "/report/22?V=" + newVersion + "&max=-1" )
.split( rnewline )
// Remove header and trailing newline
.slice( 1, -1 ) );
echo( "Sorting contributors..." );
contributors = unique( contributors ).sort(function( a, b ) {
return a.toLowerCase() < b.toLowerCase() ? -1 : 1;
});
echo ( "Adding people thanked in commits..." );
contributors = contributors.concat(
gitLog( "%b%n%s" ).filter(function( line ) {
return (/thank/i).test( line );
}));
fs.writeFileSync( contributorsPath, contributors.join( "\n" ) );
echo( "Stored contributors in " + contributorsPath.cyan + "." );
}
function updateTrac() {
echo( newVersion.cyan + " was tagged at " + tagTime.cyan + "." );
if ( !preRelease ) {
echo( "Close the " + newVersion.cyan + " Milestone." );
}
echo( "Create the " + newVersion.cyan + " Version." );
echo( "When Trac asks for date and time, match the above. Should only change minutes and seconds." );
echo( "Create a Milestone for the next minor release." );
}
// ===== HELPER FUNCTIONS ======================================================
function git( command, errorMessage ) {
var result = exec( "git " + command );
if ( result.code !== 0 ) {
abort( errorMessage );
}
return result.output;
}
function gitLog( format ) {
var result = exec( "git log " + prevVersion + ".." + newVersion + " " +
"--format='" + format + "'",
{ silent: true });
if ( result.code !== 0 ) {
abort( "Error getting git log." );
}
result = result.output.split( rnewline );
if ( result[ result.length - 1 ] === "" ) {
result.pop();
}
return result;
}
function trac( path ) {
var result = exec( "curl -s 'http://bugs.jqueryui.com" + path + "&format=tab'",
{ silent: true });
if ( result.code !== 0 ) {
abort( "Error getting Trac data." );
}
return result.output;
}
function unique( arr ) {
var obj = {};
arr.forEach(function( item ) {
obj[ item ] = 1;
});
return Object.keys( obj );
}
function readPackage() {
return JSON.parse( fs.readFileSync( repoDir + "/package.json" ) );
}
function writePackage( pkg ) {
fs.writeFileSync( repoDir + "/package.json",
JSON.stringify( pkg, null, "\t" ) + "\n" );
}
function bootstrap( fn ) {
getRemote(function( remote ) {
if ( (/:/).test( remote ) || fs.existsSync( remote ) ) {
repo = remote;
} else {
repo = "[email protected]:" + remote + ".git";
}
_bootstrap( fn );
});
}
function getRemote( fn ) {
var matches, remote;
console.log( "Determining remote repo..." );
process.argv.forEach(function( arg ) {
matches = /--remote=(.+)/.exec( arg );
if ( matches ) {
remote = matches[ 1 ];
}
});
if ( remote ) {
fn( remote );
return;
}
console.log();
console.log( " !!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
console.log( " !!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
console.log( " !! !!" );
console.log( " !! Using jquery/jquery-ui !!" );
console.log( " !! !!" );
console.log( " !!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
console.log( " !!!!!!!!!!!!!!!!!!!!!!!!!!!!" );
console.log();
console.log( "Press enter to continue, or ctrl+c to cancel." );
prompt(function() {
fn( "jquery/jquery-ui" );
});
}
function _bootstrap( fn ) {
console.log( "Determining release type..." );
preRelease = process.argv.indexOf( "--pre-release" );
if ( preRelease !== -1 ) {
preRelease = process.argv[ preRelease + 1 ];
console.log( "pre-release" );
} else {
preRelease = null;
console.log( "stable release" );
}
console.log( "Determining directories..." );
baseDir = process.cwd() + "/__release";
repoDir = baseDir + "/repo";
if ( fs.existsSync( baseDir ) ) {
console.log( "The directory '" + baseDir + "' already exists." );
console.log( "Aborting." );
process.exit( 1 );
}
console.log( "Creating directory..." );
fs.mkdirSync( baseDir );
console.log( "Installing dependencies..." );
require( "child_process" ).exec( "npm install shelljs colors [email protected]", function( error ) {
if ( error ) {
console.log( error );
return process.exit( 1 );
}
require( "shelljs/global" );
require( "colors" );
downloadBuilder = require( "download.jqueryui.com" );
fn();
});
}
function section( name ) {
return function() {
echo();
echo( "##" );
echo( "## " + name.toUpperCase().magenta );
echo( "##" );
echo();
};
}
function prompt( fn ) {
process.stdin.once( "data", function( chunk ) {
process.stdin.pause();
fn( chunk.toString().trim() );
});
process.stdin.resume();
}
function confirm( fn ) {
echo( "Press enter to continue, or ctrl+c to cancel.".yellow );
prompt( fn );
}
function confirmReview( fn ) {
echo( "Please review the output and generated files as a sanity check.".yellow );
confirm( fn );
}
function abort( msg ) {
echo( msg.red );
echo( "Aborting.".red );
exit( 1 );
}
function walk( methods ) {
var method = methods.shift();
function next() {
if ( methods.length ) {
walk( methods );
}
}
if ( !method.length ) {
method();
next();
} else {
method( next );
}
}<|fim▁end|> | |
<|file_name|>calculator.rs<|end_file_name|><|fim▁begin|>pub fn num_words(words: &Vec<&str>) -> f32 {
let num_words;
num_words = words.len() as f32;
return num_words as f32;
}
pub fn word_mean(words: &Vec<&str>) -> f32 {
let word_mean: f32;
let mut word_length_total = 0;
let word_total = num_words(words) as f32;
for word in words {
word_length_total += word.len();
}
let total_length = word_length_total as f32;
word_mean = total_length / word_total;
return word_mean;
}
pub fn sent_mean(word_total: &f32, sentences: &Vec<&str>) -> f32 {
let sent_mean: f32;
let sent_total;
sent_total = sentences.len() as f32;
let total_sent = sent_total as f32;<|fim▁hole|> return sent_mean;
}
pub fn word_freq(words: &Vec<&str>) -> (i32, i32, i32, i32, i32, i32, i32, i32, i32, i32) {
let mut num_and = 0;
let mut num_but = 0;
let mut num_however = 0;
let mut num_if = 0;
let mut num_that = 0;
let mut num_more = 0;
let mut num_must = 0;
let mut num_might = 0;
let mut num_this = 0;
let mut num_very = 0;
for &word in words {
match word {
"and" | "And" | "AND" => num_and +=1,
"but" | "But" | "BUT" => num_but +=1,
"however" | "However" | "HOWEVER" => num_however +=1,
"if" | "If" | "IF" => num_if +=1,
"that" | "That" | "THAT" => num_that +=1,
"more" | "More" | "MORE" => num_more +=1,
"must" | "Must" | "MUST" => num_must +=1,
"might" | "Might" | "MIGHT" => num_might +=1,
"this" | "This" | "THIS" => num_this +=1,
"very" | "Very" | "VERY" => num_very +=1,
_ => continue,
}
}
return (num_and, num_but, num_however, num_if, num_that, num_more, num_must, num_might, num_this, num_very);
}<|fim▁end|> |
sent_mean = word_total / total_sent;
|
<|file_name|>mclogger.hh<|end_file_name|><|fim▁begin|>// This file belongs to the "MiniCore" game engine.
// Copyright (C) 2012 Jussi Lind <[email protected]>
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
// MA 02110-1301, USA.
//
#ifndef MCLOGGER_HH
#define MCLOGGER_HH
#include "mcmacros.hh"
#include <cstdio>
#include <sstream>
/*! A logging class. A MCLogger instance flushes on destruction.
*
* Example initialization:
*
* MCLogger::init("myLog.txt");
* MCLogger::enableEchoMode(true);
*
* Example logging:
*
* MCLogger().info() << "Initialization finished.";
* MCLogger().error() << "Foo happened!";
*/
class MCLogger
{
public:
//! Constructor.
MCLogger();
//! Destructor.
~MCLogger();
/*! Initialize the logger.
* \param fileName Log to fileName. Can be nullptr.
* \param append The existing log will be appended if true.
* \return false if file couldn't be opened. */
static bool init(const char * fileName, bool append = false);
//! Enable/disable echo mode.
//! \param enable Echo everything if true. Default is false.
static void enableEchoMode(bool enable);
//! Enable/disable date and time prefix.
//! \param enable Prefix with date and time if true. Default is true.
static void enableDateTimePrefix(bool enable);
//! Get stream to the info log message.
std::ostringstream & info();
//! Get stream to the warning log message.
std::ostringstream & warning();
//! Get stream to the error log message.
std::ostringstream & error();
//! Get stream to the fatal log message.
std::ostringstream & fatal();
private:
DISABLE_COPY(MCLogger);
DISABLE_ASSI(MCLogger);
void prefixDateTime();
static bool m_echoMode;
static bool m_dateTime;
static FILE * m_file;<|fim▁hole|>
std::ostringstream m_oss;
};
#endif // MCLOGGER_HH<|fim▁end|> | |
<|file_name|>ScoringConfigPanel.hpp<|end_file_name|><|fim▁begin|>/*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2014 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program 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 General Public License for more details.
<|fim▁hole|>*/
#ifndef XCSOAR_SCORING_CONFIG_PANEL_HPP
#define XCSOAR_SCORING_CONFIG_PANEL_HPP
class Widget;
Widget *
CreateScoringConfigPanel();
#endif /* TASKRULESCONFIGPANEL_HPP */<|fim▁end|> | You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
} |
<|file_name|>ClusteringTasksServiceTest.java<|end_file_name|><|fim▁begin|>package com.orange.documentare.core.comp.clustering.tasksservice;
/*
* Copyright (c) 2016 Orange
*
* Authors: Christophe Maldivi & Joel Gardes
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*/
import com.orange.documentare.core.comp.clustering.graph.ClusteringParameters;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.fest.assertions.Assertions;
import org.junit.After;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
@Slf4j
public class ClusteringTasksServiceTest {
private static final int NB_TASKS = 4 * 10;
private static final String CLUSTERING_TASK_FILE_PREFIX = "clustering_tasks_";
private static final String STRIPPED_CLUSTERING_JSON = "stripped_clustering.json";
private static final String NOT_STRIPPED_CLUSTERING_JSON = "not_stripped_clustering.json";
private final ClusteringTasksService tasksHandler = ClusteringTasksService.instance();
private final ClusteringParameters parameters = ClusteringParameters.builder().acut().qcut().build();
@After
public void cleanup() {
FileUtils.deleteQuietly(new File(STRIPPED_CLUSTERING_JSON));
FileUtils.deleteQuietly(new File(NOT_STRIPPED_CLUSTERING_JSON));
}
@Test
public void runSeveralDistinctTasks() throws IOException, InterruptedException {
// given
String refJson1 = FileUtils.readFileToString(new File(getClass().getResource("/clusteringtasks/latin1_clustering.ref.json").getFile()));
String refJson2 = FileUtils.readFileToString(new File(getClass().getResource("/clusteringtasks/latin2_clustering.ref.json").getFile()));
String refJson3 = FileUtils.readFileToString(new File(getClass().getResource("/clusteringtasks/latin3_clustering.ref.json").getFile()));
String refJson4 = FileUtils.readFileToString(new File(getClass().getResource("/clusteringtasks/latin4_clustering.ref.json").getFile()));
File segFile1 = new File(getClass().getResource("/clusteringtasks/latin1_segmentation.json").getFile());
File segFile2 = new File(getClass().getResource("/clusteringtasks/latin2_segmentation.json").getFile());
File segFile3 = new File(getClass().getResource("/clusteringtasks/latin3_segmentation.json").getFile());<|fim▁hole|> File segFile4 = new File(getClass().getResource("/clusteringtasks/latin4_segmentation.json").getFile());
String[] outputFilenames = new String[NB_TASKS];
ClusteringTask[] clusteringTasks = new ClusteringTask[NB_TASKS];
for (int i = 0; i < NB_TASKS; i++) {
outputFilenames[i] = CLUSTERING_TASK_FILE_PREFIX + i + ".json";
}
for (int i = 0; i < NB_TASKS/4; i++) {
clusteringTasks[i * 4] = ClusteringTask.builder()
.inputFilename(segFile1.getAbsolutePath())
.outputFilename(outputFilenames[i * 4])
.clusteringParameters(parameters)
.build();
clusteringTasks[i * 4 + 1] = ClusteringTask.builder()
.inputFilename(segFile2.getAbsolutePath())
.outputFilename(outputFilenames[i * 4 + 1])
.clusteringParameters(parameters)
.build();
clusteringTasks[i * 4 + 2] = ClusteringTask.builder()
.inputFilename(segFile3.getAbsolutePath())
.outputFilename(outputFilenames[i * 4 + 2])
.clusteringParameters(parameters)
.build();
clusteringTasks[i * 4 + 3] = ClusteringTask.builder()
.inputFilename(segFile4.getAbsolutePath())
.outputFilename(outputFilenames[i * 4 + 3])
.clusteringParameters(parameters)
.build();
}
// when
for (int i = 0; i < NB_TASKS; i++) {
tasksHandler.addNewTask(clusteringTasks[i]);
Thread.sleep(200);
log.info(tasksHandler.tasksDescription().toString());
}
tasksHandler.waitForAllTasksDone();
String[] outputJsons = new String[NB_TASKS];
for (int i = 0; i < NB_TASKS; i++) {
outputJsons[i] = FileUtils.readFileToString(new File(outputFilenames[i]));
}
// then
for (int i = 0; i < NB_TASKS/4; i++) {
Assertions.assertThat(outputJsons[i * 4]).isEqualTo(refJson1);
Assertions.assertThat(outputJsons[i * 4 + 1]).isEqualTo(refJson2);
Assertions.assertThat(outputJsons[i * 4 + 2]).isEqualTo(refJson3);
Assertions.assertThat(outputJsons[i * 4 + 3]).isEqualTo(refJson4);
}
Arrays.stream(outputFilenames)
.forEach(f -> FileUtils.deleteQuietly(new File(f)));
}
@Test
public void saveStrippedOutput() throws IOException, InterruptedException {
// given
File ref = new File(getClass().getResource("/clusteringtasks/stripped_clustering.ref.json").getFile());
String jsonRef = FileUtils.readFileToString(ref);
String strippedFilename = STRIPPED_CLUSTERING_JSON;
File strippedFile = new File(strippedFilename);
strippedFile.delete();
File segFile = new File(getClass().getResource("/clusteringtasks/latin1_segmentation.json").getFile());
String outputFilename = NOT_STRIPPED_CLUSTERING_JSON;
ClusteringTask task = ClusteringTask.builder()
.inputFilename(segFile.getAbsolutePath())
.outputFilename(outputFilename)
.clusteringParameters(parameters)
.strippedOutputFilename(strippedFilename)
.build();
// when
tasksHandler.addNewTask(task);
tasksHandler.waitForAllTasksDone();
// then
String strippedJson = FileUtils.readFileToString(strippedFile);
Assertions.assertThat(strippedFile).exists();
Assertions.assertThat(strippedJson).isEqualTo(jsonRef);
}
}<|fim▁end|> | |
<|file_name|>schroedinger_app.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import
import os
import time
from math import pi
import numpy as nm
from sfepy.base.base import Struct, output, get_default
from sfepy.applications import PDESolverApp
from sfepy.solvers import Solver
from six.moves import range
def guess_n_eigs(n_electron, n_eigs=None):
"""
Guess the number of eigenvalues (energies) to compute so that the smearing
iteration converges. Passing n_eigs overrides the guess.
"""
if n_eigs is not None: return n_eigs
if n_electron > 2:
n_eigs = int(1.2 * ((0.5 * n_electron) + 5))
else:
n_eigs = n_electron
return n_eigs
class SchroedingerApp(PDESolverApp):
"""
Base application for electronic structure calculations.
Subclasses should typically override `solve_eigen_problem()` method.
This class allows solving only simple single electron problems,
e.g. well, oscillator, hydrogen atom and boron atom with 1 electron.
"""
@staticmethod
def process_options(options):
"""
Application options setup. Sets default values for missing
non-compulsory options.
Options:
save_eig_vectors : (from_largest, from_smallest) or None
If None, save all.
"""
get = options.get
<|fim▁hole|> n_electron = get('n_electron', 5)
n_eigs = guess_n_eigs(n_electron, n_eigs=get('n_eigs', None))
return Struct(eigen_solver=get('eigen_solver', None,
'missing "eigen_solver" in options!'),
n_electron=n_electron,
n_eigs=n_eigs,
save_eig_vectors=get('save_eig_vectors', None))
def __init__(self, conf, options, output_prefix, **kwargs):
PDESolverApp.__init__(self, conf, options, output_prefix,
init_equations=False)
def setup_options(self):
PDESolverApp.setup_options(self)
opts = SchroedingerApp.process_options(self.conf.options)
self.app_options += opts
def setup_output(self):
"""
Setup various file names for the output directory given by
`self.problem.output_dir`.
"""
output_dir = self.problem.output_dir
opts = self.app_options
opts.output_dir = output_dir
self.mesh_results_name = os.path.join(opts.output_dir,
self.problem.get_output_name())
self.eig_results_name = os.path.join(opts.output_dir,
self.problem.ofn_trunk
+ '_eigs.txt')
def call(self):
# This cannot be in __init__(), as parametric calls may change
# the output directory.
self.setup_output()
evp = self.solve_eigen_problem()
output("solution saved to %s" % self.problem.get_output_name())
output("in %s" % self.app_options.output_dir)
if self.post_process_hook_final is not None: # User postprocessing.
self.post_process_hook_final(self.problem, evp=evp)
return evp
def solve_eigen_problem(self):
options = self.options
opts = self.app_options
pb = self.problem
dim = pb.domain.mesh.dim
pb.set_equations(pb.conf.equations)
pb.time_update()
output('assembling lhs...')
tt = time.clock()
mtx_a = pb.evaluate(pb.conf.equations['lhs'], mode='weak',
auto_init=True, dw_mode='matrix')
output('...done in %.2f s' % (time.clock() - tt))
output('assembling rhs...')
tt = time.clock()
mtx_b = pb.evaluate(pb.conf.equations['rhs'], mode='weak',
dw_mode='matrix')
output('...done in %.2f s' % (time.clock() - tt))
n_eigs = get_default(opts.n_eigs, mtx_a.shape[0])
output('computing resonance frequencies...')
eig = Solver.any_from_conf(pb.get_solver_conf(opts.eigen_solver))
eigs, mtx_s_phi = eig(mtx_a, mtx_b, n_eigs, eigenvectors=True)
output('...done')
bounding_box = pb.domain.mesh.get_bounding_box()
# this assumes a box (3D), or a square (2D):
a = bounding_box[1][0] - bounding_box[0][0]
E_exact = None
if options.hydrogen or options.boron:
if options.hydrogen:
Z = 1
elif options.boron:
Z = 5
if dim == 2:
E_exact = [-float(Z)**2/2/(n-0.5)**2/4
for n in [1]+[2]*3+[3]*5 + [4]*8 + [5]*15]
elif dim == 3:
E_exact = [-float(Z)**2/2/n**2 for n in [1]+[2]*2**2+[3]*3**2 ]
if options.well:
if dim == 2:
E_exact = [pi**2/(2*a**2)*x
for x in [2, 5, 5, 8, 10, 10, 13, 13,
17, 17, 18, 20, 20 ] ]
elif dim == 3:
E_exact = [pi**2/(2*a**2)*x
for x in [3, 6, 6, 6, 9, 9, 9, 11, 11,
11, 12, 14, 14, 14, 14, 14,
14, 17, 17, 17] ]
if options.oscillator:
if dim == 2:
E_exact = [1] + [2]*2 + [3]*3 + [4]*4 + [5]*5 + [6]*6
elif dim == 3:
E_exact = [float(1)/2+x for x in [1]+[2]*3+[3]*6+[4]*10 ]
if E_exact is not None:
output("a=%f" % a)
output("Energies:")
output("n exact FEM error")
for i, e in enumerate(eigs):
from numpy import NaN
if i < len(E_exact):
exact = E_exact[i]
err = 100*abs((exact - e)/exact)
else:
exact = NaN
err = NaN
output("%d: %.8f %.8f %5.2f%%" % (i, exact, e, err))
else:
output(eigs)
mtx_phi = self.make_full(mtx_s_phi)
self.save_results(eigs, mtx_phi)
return Struct(pb=pb, eigs=eigs, mtx_phi=mtx_phi)
def make_full(self, mtx_s_phi):
variables = self.problem.get_variables()
mtx_phi = nm.empty((variables.di.ptr[-1], mtx_s_phi.shape[1]),
dtype=nm.float64)
for ii in range(mtx_s_phi.shape[1]):
mtx_phi[:,ii] = variables.make_full_vec(mtx_s_phi[:,ii])
return mtx_phi
def save_results(self, eigs, mtx_phi, out=None,
mesh_results_name=None, eig_results_name=None):
mesh_results_name = get_default(mesh_results_name,
self.mesh_results_name)
eig_results_name = get_default(eig_results_name,
self.eig_results_name)
pb = self.problem
save = self.app_options.save_eig_vectors
n_eigs = self.app_options.n_eigs
out = get_default(out, {})
state = pb.create_state()
aux = {}
for ii in range(eigs.shape[0]):
if save is not None:
if (ii > save[0]) and (ii < (n_eigs - save[1])): continue
state.set_full(mtx_phi[:,ii])
aux = state.create_output_dict()
key = list(aux.keys())[0]
out[key+'%03d' % ii] = aux[key]
if aux.get('__mesh__') is not None:
out['__mesh__'] = aux['__mesh__']
pb.save_state(mesh_results_name, out=out)
fd = open(eig_results_name, 'w')
eigs.tofile(fd, ' ')
fd.close()<|fim▁end|> | |
<|file_name|>0002_auto_20150708_1158.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
('taskmanager', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Project',
fields=[
('id', models.AutoField(verbose_name='ID', auto_created=True, serialize=False, primary_key=True)),
('name', models.CharField(verbose_name='name', max_length=100, help_text='Enter the project name')),
('color', models.CharField(verbose_name='color', validators=[django.core.validators.RegexValidator('(^#[0-9a-fA-F]{3}$)|(^#[0-9a-fA-F]{6}$)')], default='#fff', max_length=7, help_text='Enter the hex color code, like #ccc or #cccccc')),
('user', models.ForeignKey(verbose_name='user', related_name='profjects', to='taskmanager.Profile')),
],
options={<|fim▁hole|> 'verbose_name': 'Project',
'verbose_name_plural': 'Projects',
},
),
migrations.AlterUniqueTogether(
name='project',
unique_together=set([('user', 'name')]),
),
]<|fim▁end|> | 'ordering': ('user', 'name'), |
<|file_name|>index.js<|end_file_name|><|fim▁begin|>/*global d3 */
// asynchronously load data from the Lagotto API
queue()
.defer(d3.json, encodeURI("/api/agents/"))
.await(function(error, a) {
if (error) { return console.warn(error); }
agentsViz(a.agents);
});
// add data to page
function agentsViz(data) {
for (var i=0; i<data.length; i++) {
var agent = data[i];
// responses tab
d3.select("#response_count_" + agent.id)
.text(numberWithDelimiter(agent.responses.count));
d3.select("#average_count_" + agent.id)
.text(numberWithDelimiter(agent.responses.average));<|fim▁hole|><|fim▁end|> | }
} |
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>pub fn encode(keyword: &str, message: &str) -> String {
panic!("todo")
}<|fim▁hole|>pub fn decode(keyword: &str, message: &str) -> String {
panic!("todo")
}
pub fn decipher(encoded: &str, original: &str) -> String {
panic!("todo")
}<|fim▁end|> | |
<|file_name|>while-loop-constraints-2.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license<|fim▁hole|>#[allow(dead_assignment)];
#[allow(unused_variable)];
pub fn main() {
let mut y: int = 42;
let mut z: int = 42;
let mut x: int;
while z < 50 {
z += 1;
while false { x = y; y = z; }
info!("{}", y);
}
assert!((y == 42 && z == 50));
}<|fim▁end|> | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
|
<|file_name|>qgsgeometry.cpp<|end_file_name|><|fim▁begin|>/***************************************************************************
qgsgeometry.cpp - Geometry (stored as Open Geospatial Consortium WKB)
-------------------------------------------------------------------
Date : 02 May 2005
Copyright : (C) 2005 by Brendan Morley
email : morb at ozemail dot com dot au
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include <limits>
#include <cstdarg>
#include <cstdio>
#include <cmath>
#include <nlohmann/json.hpp>
#include "qgis.h"
#include "qgsgeometry.h"
#include "qgsgeometryeditutils.h"
#include "qgsgeometryfactory.h"
#include "qgsgeometrymakevalid.h"
#include "qgsgeometryutils.h"
#include "qgsinternalgeometryengine.h"
#include "qgsgeos.h"
#include "qgsapplication.h"
#include "qgslogger.h"
#include "qgsmaptopixel.h"
#include "qgsmessagelog.h"
#include "qgspointxy.h"
#include "qgsrectangle.h"
#include "qgsvectorlayer.h"
#include "qgsgeometryvalidator.h"
#include "qgsmulticurve.h"
#include "qgsmultilinestring.h"
#include "qgsmultipoint.h"
#include "qgsmultipolygon.h"
#include "qgsmultisurface.h"
#include "qgspoint.h"
#include "qgspolygon.h"
#include "qgslinestring.h"
#include "qgscircle.h"
#include "qgscurve.h"
struct QgsGeometryPrivate
{
QgsGeometryPrivate(): ref( 1 ) {}
QAtomicInt ref;
std::unique_ptr< QgsAbstractGeometry > geometry;
};
QgsGeometry::QgsGeometry()
: d( new QgsGeometryPrivate() )
{
}
QgsGeometry::~QgsGeometry()
{
if ( !d->ref.deref() )
delete d;
}
QgsGeometry::QgsGeometry( QgsAbstractGeometry *geom )
: d( new QgsGeometryPrivate() )
{
d->geometry.reset( geom );
d->ref = QAtomicInt( 1 );
}
QgsGeometry::QgsGeometry( std::unique_ptr<QgsAbstractGeometry> geom )
: d( new QgsGeometryPrivate() )
{
d->geometry = std::move( geom );
d->ref = QAtomicInt( 1 );
}
QgsGeometry::QgsGeometry( const QgsGeometry &other )
{
d = other.d;
mLastError = other.mLastError;
d->ref.ref();
}
QgsGeometry &QgsGeometry::operator=( QgsGeometry const &other )
{
if ( !d->ref.deref() )
{
delete d;
}
mLastError = other.mLastError;
d = other.d;
d->ref.ref();
return *this;
}
void QgsGeometry::detach()
{
if ( d->ref <= 1 )
return;
std::unique_ptr< QgsAbstractGeometry > cGeom;
if ( d->geometry )
cGeom.reset( d->geometry->clone() );
reset( std::move( cGeom ) );
}
void QgsGeometry::reset( std::unique_ptr<QgsAbstractGeometry> newGeometry )
{
if ( d->ref > 1 )
{
( void )d->ref.deref();
d = new QgsGeometryPrivate();
}
d->geometry = std::move( newGeometry );
}
const QgsAbstractGeometry *QgsGeometry::constGet() const
{
return d->geometry.get();
}
QgsAbstractGeometry *QgsGeometry::get()
{
detach();
return d->geometry.get();
}
void QgsGeometry::set( QgsAbstractGeometry *geometry )
{
if ( d->geometry.get() == geometry )
{
return;
}
reset( std::unique_ptr< QgsAbstractGeometry >( geometry ) );
}
bool QgsGeometry::isNull() const
{
return !d->geometry;
}
QgsGeometry QgsGeometry::fromWkt( const QString &wkt )
{
std::unique_ptr< QgsAbstractGeometry > geom = QgsGeometryFactory::geomFromWkt( wkt );
if ( !geom )
{
return QgsGeometry();
}
return QgsGeometry( std::move( geom ) );
}
QgsGeometry QgsGeometry::fromPointXY( const QgsPointXY &point )
{
std::unique_ptr< QgsAbstractGeometry > geom( QgsGeometryFactory::fromPointXY( point ) );
if ( geom )
{
return QgsGeometry( geom.release() );
}
return QgsGeometry();
}
QgsGeometry QgsGeometry::fromPolylineXY( const QgsPolylineXY &polyline )
{
std::unique_ptr< QgsAbstractGeometry > geom = QgsGeometryFactory::fromPolylineXY( polyline );
if ( geom )
{
return QgsGeometry( std::move( geom ) );
}
return QgsGeometry();
}
QgsGeometry QgsGeometry::fromPolyline( const QgsPolyline &polyline )
{
return QgsGeometry( qgis::make_unique< QgsLineString >( polyline ) );
}
QgsGeometry QgsGeometry::fromPolygonXY( const QgsPolygonXY &polygon )
{
std::unique_ptr< QgsPolygon > geom = QgsGeometryFactory::fromPolygonXY( polygon );
if ( geom )
{
return QgsGeometry( std::move( geom.release() ) );
}
return QgsGeometry();
}
QgsGeometry QgsGeometry::fromMultiPointXY( const QgsMultiPointXY &multipoint )
{
std::unique_ptr< QgsMultiPoint > geom = QgsGeometryFactory::fromMultiPointXY( multipoint );
if ( geom )
{
return QgsGeometry( std::move( geom ) );
}
return QgsGeometry();
}
QgsGeometry QgsGeometry::fromMultiPolylineXY( const QgsMultiPolylineXY &multiline )
{
std::unique_ptr< QgsMultiLineString > geom = QgsGeometryFactory::fromMultiPolylineXY( multiline );
if ( geom )
{
return QgsGeometry( std::move( geom ) );
}
return QgsGeometry();
}
QgsGeometry QgsGeometry::fromMultiPolygonXY( const QgsMultiPolygonXY &multipoly )
{
std::unique_ptr< QgsMultiPolygon > geom = QgsGeometryFactory::fromMultiPolygonXY( multipoly );
if ( geom )
{
return QgsGeometry( std::move( geom ) );
}
return QgsGeometry();
}
QgsGeometry QgsGeometry::fromRect( const QgsRectangle &rect )
{
std::unique_ptr< QgsLineString > ext = qgis::make_unique< QgsLineString >(
QVector< double >() << rect.xMinimum()
<< rect.xMaximum()
<< rect.xMaximum()
<< rect.xMinimum()
<< rect.xMinimum(),
QVector< double >() << rect.yMinimum()
<< rect.yMinimum()
<< rect.yMaximum()
<< rect.yMaximum()
<< rect.yMinimum() );
std::unique_ptr< QgsPolygon > polygon = qgis::make_unique< QgsPolygon >();
polygon->setExteriorRing( ext.release() );
return QgsGeometry( std::move( polygon ) );
}
QgsGeometry QgsGeometry::collectGeometry( const QVector< QgsGeometry > &geometries )
{
QgsGeometry collected;
for ( const QgsGeometry &g : geometries )
{
if ( collected.isNull() )
{
collected = g;
collected.convertToMultiType();
}
else
{
if ( g.isMultipart() )
{
for ( auto p = g.const_parts_begin(); p != g.const_parts_end(); ++p )
{
collected.addPart( ( *p )->clone() );
}
}
else
{
collected.addPart( g );
}
}
}
return collected;
}
QgsGeometry QgsGeometry::createWedgeBuffer( const QgsPoint ¢er, const double azimuth, const double angularWidth, const double outerRadius, const double innerRadius )
{
if ( std::abs( angularWidth ) >= 360.0 )
{
std::unique_ptr< QgsCompoundCurve > outerCc = qgis::make_unique< QgsCompoundCurve >();
QgsCircle outerCircle = QgsCircle( center, outerRadius );
outerCc->addCurve( outerCircle.toCircularString() );
std::unique_ptr< QgsCurvePolygon > cp = qgis::make_unique< QgsCurvePolygon >();
cp->setExteriorRing( outerCc.release() );
if ( !qgsDoubleNear( innerRadius, 0.0 ) && innerRadius > 0 )
{
std::unique_ptr< QgsCompoundCurve > innerCc = qgis::make_unique< QgsCompoundCurve >();
QgsCircle innerCircle = QgsCircle( center, innerRadius );
innerCc->addCurve( innerCircle.toCircularString() );
cp->setInteriorRings( { innerCc.release() } );
}
return QgsGeometry( std::move( cp ) );
}
std::unique_ptr< QgsCompoundCurve > wedge = qgis::make_unique< QgsCompoundCurve >();
const double startAngle = azimuth - angularWidth * 0.5;
const double endAngle = azimuth + angularWidth * 0.5;
const QgsPoint outerP1 = center.project( outerRadius, startAngle );
const QgsPoint outerP2 = center.project( outerRadius, endAngle );
const bool useShortestArc = angularWidth <= 180.0;
wedge->addCurve( new QgsCircularString( QgsCircularString::fromTwoPointsAndCenter( outerP1, outerP2, center, useShortestArc ) ) );
if ( !qgsDoubleNear( innerRadius, 0.0 ) && innerRadius > 0 )
{
const QgsPoint innerP1 = center.project( innerRadius, startAngle );
const QgsPoint innerP2 = center.project( innerRadius, endAngle );
wedge->addCurve( new QgsLineString( outerP2, innerP2 ) );
wedge->addCurve( new QgsCircularString( QgsCircularString::fromTwoPointsAndCenter( innerP2, innerP1, center, useShortestArc ) ) );
wedge->addCurve( new QgsLineString( innerP1, outerP1 ) );
}
else
{
wedge->addCurve( new QgsLineString( outerP2, center ) );
wedge->addCurve( new QgsLineString( center, outerP1 ) );
}
std::unique_ptr< QgsCurvePolygon > cp = qgis::make_unique< QgsCurvePolygon >();
cp->setExteriorRing( wedge.release() );
return QgsGeometry( std::move( cp ) );
}
void QgsGeometry::fromWkb( unsigned char *wkb, int length )
{
QgsConstWkbPtr ptr( wkb, length );
reset( QgsGeometryFactory::geomFromWkb( ptr ) );
delete [] wkb;
}
void QgsGeometry::fromWkb( const QByteArray &wkb )
{
QgsConstWkbPtr ptr( wkb );
reset( QgsGeometryFactory::geomFromWkb( ptr ) );
}
QgsWkbTypes::Type QgsGeometry::wkbType() const
{
if ( !d->geometry )
{
return QgsWkbTypes::Unknown;
}
else
{
return d->geometry->wkbType();
}
}
QgsWkbTypes::GeometryType QgsGeometry::type() const
{
if ( !d->geometry )
{
return QgsWkbTypes::UnknownGeometry;
}
return static_cast< QgsWkbTypes::GeometryType >( QgsWkbTypes::geometryType( d->geometry->wkbType() ) );
}
bool QgsGeometry::isEmpty() const
{
if ( !d->geometry )
{
return true;
}
return d->geometry->isEmpty();
}
bool QgsGeometry::isMultipart() const
{
if ( !d->geometry )
{
return false;
}
return QgsWkbTypes::isMultiType( d->geometry->wkbType() );
}
QgsPointXY QgsGeometry::closestVertex( const QgsPointXY &point, int &atVertex, int &beforeVertex, int &afterVertex, double &sqrDist ) const
{
if ( !d->geometry )
{
sqrDist = -1;
return QgsPointXY( 0, 0 );
}
QgsPoint pt( point.x(), point.y() );
QgsVertexId id;
QgsPoint vp = QgsGeometryUtils::closestVertex( *( d->geometry ), pt, id );
if ( !id.isValid() )
{
sqrDist = -1;
return QgsPointXY( 0, 0 );
}
sqrDist = QgsGeometryUtils::sqrDistance2D( pt, vp );
QgsVertexId prevVertex;
QgsVertexId nextVertex;
d->geometry->adjacentVertices( id, prevVertex, nextVertex );
atVertex = vertexNrFromVertexId( id );
beforeVertex = vertexNrFromVertexId( prevVertex );
afterVertex = vertexNrFromVertexId( nextVertex );
return QgsPointXY( vp.x(), vp.y() );
}
double QgsGeometry::distanceToVertex( int vertex ) const
{
if ( !d->geometry )
{
return -1;
}
QgsVertexId id;
if ( !vertexIdFromVertexNr( vertex, id ) )
{
return -1;
}
return QgsGeometryUtils::distanceToVertex( *( d->geometry ), id );
}
double QgsGeometry::angleAtVertex( int vertex ) const
{
if ( !d->geometry )
{
return 0;
}
QgsVertexId v2;
if ( !vertexIdFromVertexNr( vertex, v2 ) )
{
return 0;
}
return d->geometry->vertexAngle( v2 );
}
void QgsGeometry::adjacentVertices( int atVertex, int &beforeVertex, int &afterVertex ) const
{
if ( !d->geometry )
{
return;
}
QgsVertexId id;
if ( !vertexIdFromVertexNr( atVertex, id ) )
{
beforeVertex = -1;
afterVertex = -1;
return;
}
QgsVertexId beforeVertexId, afterVertexId;
d->geometry->adjacentVertices( id, beforeVertexId, afterVertexId );
beforeVertex = vertexNrFromVertexId( beforeVertexId );
afterVertex = vertexNrFromVertexId( afterVertexId );
}
bool QgsGeometry::moveVertex( double x, double y, int atVertex )
{
if ( !d->geometry )
{
return false;
}
QgsVertexId id;
if ( !vertexIdFromVertexNr( atVertex, id ) )
{
return false;
}
detach();
return d->geometry->moveVertex( id, QgsPoint( x, y ) );
}
bool QgsGeometry::moveVertex( const QgsPoint &p, int atVertex )
{
if ( !d->geometry )
{
return false;
}
QgsVertexId id;
if ( !vertexIdFromVertexNr( atVertex, id ) )
{
return false;
}
detach();
return d->geometry->moveVertex( id, p );
}
bool QgsGeometry::deleteVertex( int atVertex )
{
if ( !d->geometry )
{
return false;
}
//maintain compatibility with < 2.10 API
if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::MultiPoint )
{
detach();
//delete geometry instead of point
return static_cast< QgsGeometryCollection * >( d->geometry.get() )->removeGeometry( atVertex );
}
//if it is a point, set the geometry to nullptr
if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::Point )
{
reset( nullptr );
return true;
}
QgsVertexId id;
if ( !vertexIdFromVertexNr( atVertex, id ) )
{
return false;
}
detach();
return d->geometry->deleteVertex( id );
}
bool QgsGeometry::insertVertex( double x, double y, int beforeVertex )
{
if ( !d->geometry )
{
return false;
}
//maintain compatibility with < 2.10 API
if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::MultiPoint )
{
detach();
//insert geometry instead of point
return static_cast< QgsGeometryCollection * >( d->geometry.get() )->insertGeometry( new QgsPoint( x, y ), beforeVertex );
}
QgsVertexId id;
if ( !vertexIdFromVertexNr( beforeVertex, id ) )
{
return false;
}
detach();
return d->geometry->insertVertex( id, QgsPoint( x, y ) );
}
bool QgsGeometry::insertVertex( const QgsPoint &point, int beforeVertex )
{
if ( !d->geometry )
{
return false;
}
//maintain compatibility with < 2.10 API
if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::MultiPoint )
{
detach();
//insert geometry instead of point
return static_cast< QgsGeometryCollection * >( d->geometry.get() )->insertGeometry( new QgsPoint( point ), beforeVertex );
}
QgsVertexId id;
if ( !vertexIdFromVertexNr( beforeVertex, id ) )
{
return false;
}
detach();
return d->geometry->insertVertex( id, point );
}
QgsPoint QgsGeometry::vertexAt( int atVertex ) const
{
if ( !d->geometry )
{
return QgsPoint();
}
QgsVertexId vId;
( void )vertexIdFromVertexNr( atVertex, vId );
if ( vId.vertex < 0 )
{
return QgsPoint();
}
return d->geometry->vertexAt( vId );
}
double QgsGeometry::sqrDistToVertexAt( QgsPointXY &point, int atVertex ) const
{
QgsPointXY vertexPoint = vertexAt( atVertex );
return QgsGeometryUtils::sqrDistance2D( QgsPoint( vertexPoint ), QgsPoint( point ) );
}
QgsGeometry QgsGeometry::nearestPoint( const QgsGeometry &other ) const
{
QgsGeos geos( d->geometry.get() );
mLastError.clear();
QgsGeometry result = geos.closestPoint( other );
result.mLastError = mLastError;
return result;
}
QgsGeometry QgsGeometry::shortestLine( const QgsGeometry &other ) const
{
QgsGeos geos( d->geometry.get() );
mLastError.clear();
QgsGeometry result = geos.shortestLine( other, &mLastError );
result.mLastError = mLastError;
return result;
}
double QgsGeometry::closestVertexWithContext( const QgsPointXY &point, int &atVertex ) const
{
if ( !d->geometry )
{
return -1;
}
QgsVertexId vId;
QgsPoint pt( point.x(), point.y() );
QgsPoint closestPoint = QgsGeometryUtils::closestVertex( *( d->geometry ), pt, vId );
if ( !vId.isValid() )
return -1;
atVertex = vertexNrFromVertexId( vId );
return QgsGeometryUtils::sqrDistance2D( closestPoint, pt );
}
double QgsGeometry::closestSegmentWithContext( const QgsPointXY &point,
QgsPointXY &minDistPoint,
int &afterVertex,
int *leftOf,
double epsilon ) const
{
if ( !d->geometry )
{
return -1;
}
QgsPoint segmentPt;
QgsVertexId vertexAfter;
double sqrDist = d->geometry->closestSegment( QgsPoint( point ), segmentPt, vertexAfter, leftOf, epsilon );
if ( sqrDist < 0 )
return -1;
minDistPoint.setX( segmentPt.x() );
minDistPoint.setY( segmentPt.y() );
afterVertex = vertexNrFromVertexId( vertexAfter );
return sqrDist;
}
QgsGeometry::OperationResult QgsGeometry::addRing( const QVector<QgsPointXY> &ring )
{
std::unique_ptr< QgsLineString > ringLine = qgis::make_unique< QgsLineString >( ring );
return addRing( ringLine.release() );
}
QgsGeometry::OperationResult QgsGeometry::addRing( QgsCurve *ring )
{
std::unique_ptr< QgsCurve > r( ring );
if ( !d->geometry )
{
return InvalidInputGeometryType;
}
detach();
return QgsGeometryEditUtils::addRing( d->geometry.get(), std::move( r ) );
}
QgsGeometry::OperationResult QgsGeometry::addPart( const QVector<QgsPointXY> &points, QgsWkbTypes::GeometryType geomType )
{
QgsPointSequence l;
convertPointList( points, l );
return addPart( l, geomType );
}
QgsGeometry::OperationResult QgsGeometry::addPart( const QgsPointSequence &points, QgsWkbTypes::GeometryType geomType )
{
std::unique_ptr< QgsAbstractGeometry > partGeom;
if ( points.size() == 1 )
{
partGeom = qgis::make_unique< QgsPoint >( points[0] );
}
else if ( points.size() > 1 )
{
std::unique_ptr< QgsLineString > ringLine = qgis::make_unique< QgsLineString >();
ringLine->setPoints( points );
partGeom = std::move( ringLine );
}
return addPart( partGeom.release(), geomType );
}
QgsGeometry::OperationResult QgsGeometry::addPart( QgsAbstractGeometry *part, QgsWkbTypes::GeometryType geomType )
{
std::unique_ptr< QgsAbstractGeometry > p( part );
if ( !d->geometry )
{
switch ( geomType )
{
case QgsWkbTypes::PointGeometry:
reset( qgis::make_unique< QgsMultiPoint >() );
break;
case QgsWkbTypes::LineGeometry:
reset( qgis::make_unique< QgsMultiLineString >() );
break;
case QgsWkbTypes::PolygonGeometry:
reset( qgis::make_unique< QgsMultiPolygon >() );
break;
default:
reset( nullptr );
return QgsGeometry::OperationResult::AddPartNotMultiGeometry;
}
}
else
{
detach();
}
convertToMultiType();
return QgsGeometryEditUtils::addPart( d->geometry.get(), std::move( p ) );
}
QgsGeometry::OperationResult QgsGeometry::addPart( const QgsGeometry &newPart )
{
if ( !d->geometry )
{
return QgsGeometry::InvalidBaseGeometry;
}
if ( newPart.isNull() || !newPart.d->geometry )
{
return QgsGeometry::AddPartNotMultiGeometry;
}
return addPart( newPart.d->geometry->clone() );
}
QgsGeometry QgsGeometry::removeInteriorRings( double minimumRingArea ) const
{
if ( !d->geometry || type() != QgsWkbTypes::PolygonGeometry )
{
return QgsGeometry();
}
if ( QgsWkbTypes::isMultiType( d->geometry->wkbType() ) )
{
const QVector<QgsGeometry> parts = asGeometryCollection();
QVector<QgsGeometry> results;
results.reserve( parts.count() );
for ( const QgsGeometry &part : parts )
{
QgsGeometry result = part.removeInteriorRings( minimumRingArea );
if ( !result.isNull() )
results << result;
}
if ( results.isEmpty() )
return QgsGeometry();
QgsGeometry first = results.takeAt( 0 );
for ( const QgsGeometry &result : qgis::as_const( results ) )
{
first.addPart( result );
}
return first;
}
else
{
std::unique_ptr< QgsCurvePolygon > newPoly( static_cast< QgsCurvePolygon * >( d->geometry->clone() ) );
newPoly->removeInteriorRings( minimumRingArea );
return QgsGeometry( std::move( newPoly ) );
}
}
QgsGeometry::OperationResult QgsGeometry::translate( double dx, double dy, double dz, double dm )
{
if ( !d->geometry )
{
return QgsGeometry::InvalidBaseGeometry;
}
detach();
d->geometry->transform( QTransform::fromTranslate( dx, dy ), dz, 1.0, dm );
return QgsGeometry::Success;
}
QgsGeometry::OperationResult QgsGeometry::rotate( double rotation, const QgsPointXY ¢er )
{
if ( !d->geometry )
{
return QgsGeometry::InvalidBaseGeometry;
}
detach();
QTransform t = QTransform::fromTranslate( center.x(), center.y() );
t.rotate( -rotation );
t.translate( -center.x(), -center.y() );
d->geometry->transform( t );
return QgsGeometry::Success;
}
QgsGeometry::OperationResult QgsGeometry::splitGeometry( const QVector<QgsPointXY> &splitLine, QVector<QgsGeometry> &newGeometries, bool topological, QVector<QgsPointXY> &topologyTestPoints, bool splitFeature )
{
QgsPointSequence split, topology;
convertPointList( splitLine, split );
convertPointList( topologyTestPoints, topology );
return splitGeometry( split, newGeometries, topological, topology, splitFeature );
}
QgsGeometry::OperationResult QgsGeometry::splitGeometry( const QgsPointSequence &splitLine, QVector<QgsGeometry> &newGeometries, bool topological, QgsPointSequence &topologyTestPoints, bool splitFeature )
{
if ( !d->geometry )
{
return QgsGeometry::OperationResult::InvalidBaseGeometry;
}
QVector<QgsGeometry > newGeoms;
QgsLineString splitLineString( splitLine );
QgsGeos geos( d->geometry.get() );
mLastError.clear();
QgsGeometryEngine::EngineOperationResult result = geos.splitGeometry( splitLineString, newGeoms, topological, topologyTestPoints, &mLastError );
if ( result == QgsGeometryEngine::Success )
{
if ( splitFeature )
*this = newGeoms.takeAt( 0 );
newGeometries = newGeoms;
}
switch ( result )
{
case QgsGeometryEngine::Success:
return QgsGeometry::OperationResult::Success;
case QgsGeometryEngine::MethodNotImplemented:
case QgsGeometryEngine::EngineError:
case QgsGeometryEngine::NodedGeometryError:
return QgsGeometry::OperationResult::GeometryEngineError;
case QgsGeometryEngine::InvalidBaseGeometry:
return QgsGeometry::OperationResult::InvalidBaseGeometry;
case QgsGeometryEngine::InvalidInput:
return QgsGeometry::OperationResult::InvalidInputGeometryType;
case QgsGeometryEngine::SplitCannotSplitPoint:
return QgsGeometry::OperationResult::SplitCannotSplitPoint;
case QgsGeometryEngine::NothingHappened:
return QgsGeometry::OperationResult::NothingHappened;
//default: do not implement default to handle properly all cases
}
// this should never be reached
Q_ASSERT( false );
return QgsGeometry::NothingHappened;
}
QgsGeometry::OperationResult QgsGeometry::reshapeGeometry( const QgsLineString &reshapeLineString )
{
if ( !d->geometry )
{
return InvalidBaseGeometry;
}
QgsGeos geos( d->geometry.get() );
QgsGeometryEngine::EngineOperationResult errorCode = QgsGeometryEngine::Success;
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > geom( geos.reshapeGeometry( reshapeLineString, &errorCode, &mLastError ) );
if ( errorCode == QgsGeometryEngine::Success && geom )
{
reset( std::move( geom ) );
return Success;
}
switch ( errorCode )
{
case QgsGeometryEngine::Success:
return Success;
case QgsGeometryEngine::MethodNotImplemented:
case QgsGeometryEngine::EngineError:
case QgsGeometryEngine::NodedGeometryError:
return GeometryEngineError;
case QgsGeometryEngine::InvalidBaseGeometry:
return InvalidBaseGeometry;
case QgsGeometryEngine::InvalidInput:
return InvalidInputGeometryType;
case QgsGeometryEngine::SplitCannotSplitPoint: // should not happen
return GeometryEngineError;
case QgsGeometryEngine::NothingHappened:
return NothingHappened;
}
// should not be reached
return GeometryEngineError;
}
int QgsGeometry::makeDifferenceInPlace( const QgsGeometry &other )
{
if ( !d->geometry || !other.d->geometry )
{
return 0;
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > diffGeom( geos.intersection( other.constGet(), &mLastError ) );
if ( !diffGeom )
{
return 1;
}
reset( std::move( diffGeom ) );
return 0;
}
QgsGeometry QgsGeometry::makeDifference( const QgsGeometry &other ) const
{
if ( !d->geometry || other.isNull() )
{
return QgsGeometry();
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > diffGeom( geos.intersection( other.constGet(), &mLastError ) );
if ( !diffGeom )
{
QgsGeometry result;
result.mLastError = mLastError;
return result;
}
return QgsGeometry( diffGeom.release() );
}
QgsRectangle QgsGeometry::boundingBox() const
{
if ( d->geometry )
{
return d->geometry->boundingBox();
}
return QgsRectangle();
}
QgsGeometry QgsGeometry::orientedMinimumBoundingBox( double &area, double &angle, double &width, double &height ) const
{
QgsRectangle minRect;
area = std::numeric_limits<double>::max();
angle = 0;
width = std::numeric_limits<double>::max();
height = std::numeric_limits<double>::max();
if ( !d->geometry || d->geometry->nCoordinates() < 2 )
return QgsGeometry();
QgsGeometry hull = convexHull();
if ( hull.isNull() )
return QgsGeometry();
QgsVertexId vertexId;
QgsPoint pt0;
QgsPoint pt1;
QgsPoint pt2;
// get first point
hull.constGet()->nextVertex( vertexId, pt0 );
pt1 = pt0;
double prevAngle = 0.0;
while ( hull.constGet()->nextVertex( vertexId, pt2 ) )
{
double currentAngle = QgsGeometryUtils::lineAngle( pt1.x(), pt1.y(), pt2.x(), pt2.y() );
double rotateAngle = 180.0 / M_PI * ( currentAngle - prevAngle );
prevAngle = currentAngle;
QTransform t = QTransform::fromTranslate( pt0.x(), pt0.y() );
t.rotate( rotateAngle );
t.translate( -pt0.x(), -pt0.y() );
hull.get()->transform( t );
QgsRectangle bounds = hull.constGet()->boundingBox();
double currentArea = bounds.width() * bounds.height();
if ( currentArea < area )
{
minRect = bounds;
area = currentArea;
angle = 180.0 / M_PI * currentAngle;
width = bounds.width();
height = bounds.height();
}
pt1 = pt2;
}
QgsGeometry minBounds = QgsGeometry::fromRect( minRect );
minBounds.rotate( angle, QgsPointXY( pt0.x(), pt0.y() ) );
// constrain angle to 0 - 180
if ( angle > 180.0 )
angle = std::fmod( angle, 180.0 );
return minBounds;
}
QgsGeometry QgsGeometry::orientedMinimumBoundingBox() const
{
double area, angle, width, height;
return orientedMinimumBoundingBox( area, angle, width, height );
}
static QgsCircle __recMinimalEnclosingCircle( QgsMultiPointXY points, QgsMultiPointXY boundary )
{
auto l_boundary = boundary.length();
QgsCircle circ_mec;
if ( ( points.length() == 0 ) || ( l_boundary == 3 ) )
{
switch ( l_boundary )
{
case 0:
circ_mec = QgsCircle();
break;
case 1:
circ_mec = QgsCircle( QgsPoint( boundary.last() ), 0 );
boundary.pop_back();
break;
case 2:
{
QgsPointXY p1 = boundary.last();
boundary.pop_back();
QgsPointXY p2 = boundary.last();
boundary.pop_back();
circ_mec = QgsCircle().from2Points( QgsPoint( p1 ), QgsPoint( p2 ) );
}
break;
default:
QgsPoint p1( boundary.at( 0 ) );
QgsPoint p2( boundary.at( 1 ) );
QgsPoint p3( boundary.at( 2 ) );
circ_mec = QgsCircle().minimalCircleFrom3Points( p1, p2, p3 );
break;
}
return circ_mec;
}
else
{
QgsPointXY pxy = points.last();
points.pop_back();
circ_mec = __recMinimalEnclosingCircle( points, boundary );
QgsPoint p( pxy );
if ( !circ_mec.contains( p ) )
{
boundary.append( pxy );
circ_mec = __recMinimalEnclosingCircle( points, boundary );
}
}
return circ_mec;
}
QgsGeometry QgsGeometry::minimalEnclosingCircle( QgsPointXY ¢er, double &radius, unsigned int segments ) const
{
center = QgsPointXY();
radius = 0;
if ( isEmpty() )
{
return QgsGeometry();
}
/* optimization */
QgsGeometry hull = convexHull();
if ( hull.isNull() )
return QgsGeometry();
QgsMultiPointXY P = hull.convertToPoint( true ).asMultiPoint();
QgsMultiPointXY R;
QgsCircle circ = __recMinimalEnclosingCircle( P, R );
center = QgsPointXY( circ.center() );
radius = circ.radius();
QgsGeometry geom;
geom.set( circ.toPolygon( segments ) );
return geom;
}
QgsGeometry QgsGeometry::minimalEnclosingCircle( unsigned int segments ) const
{
QgsPointXY center;
double radius;
return minimalEnclosingCircle( center, radius, segments );
}
QgsGeometry QgsGeometry::orthogonalize( double tolerance, int maxIterations, double angleThreshold ) const
{
QgsInternalGeometryEngine engine( *this );
return engine.orthogonalize( tolerance, maxIterations, angleThreshold );
}
QgsGeometry QgsGeometry::snappedToGrid( double hSpacing, double vSpacing, double dSpacing, double mSpacing ) const
{
if ( !d->geometry )
{
return QgsGeometry();
}
return QgsGeometry( d->geometry->snappedToGrid( hSpacing, vSpacing, dSpacing, mSpacing ) );
}
bool QgsGeometry::removeDuplicateNodes( double epsilon, bool useZValues )
{
if ( !d->geometry )
return false;
detach();
return d->geometry->removeDuplicateNodes( epsilon, useZValues );
}
bool QgsGeometry::intersects( const QgsRectangle &r ) const
{
// fast case, check bounding boxes
if ( !boundingBoxIntersects( r ) )
return false;
// optimise trivial case for point intersections -- the bounding box test has already given us the answer
if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::Point )
{
return true;
}
QgsGeometry g = fromRect( r );
return intersects( g );
}
bool QgsGeometry::intersects( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return false;
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
return geos.intersects( geometry.d->geometry.get(), &mLastError );
}
bool QgsGeometry::boundingBoxIntersects( const QgsRectangle &rectangle ) const
{
if ( !d->geometry )
{
return false;
}
// optimise trivial case for point intersections
if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::Point )
{
const QgsPoint *point = qgsgeometry_cast< const QgsPoint * >( d->geometry.get() );
return rectangle.contains( QgsPointXY( point->x(), point->y() ) );
}
return d->geometry->boundingBox().intersects( rectangle );
}
bool QgsGeometry::boundingBoxIntersects( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return false;
}
return d->geometry->boundingBox().intersects( geometry.constGet()->boundingBox() );
}
bool QgsGeometry::contains( const QgsPointXY *p ) const
{
if ( !d->geometry || !p )
{
return false;
}
QgsPoint pt( p->x(), p->y() );
QgsGeos geos( d->geometry.get() );
mLastError.clear();
return geos.contains( &pt, &mLastError );
}
bool QgsGeometry::contains( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return false;
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
return geos.contains( geometry.d->geometry.get(), &mLastError );
}
bool QgsGeometry::disjoint( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return false;
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
return geos.disjoint( geometry.d->geometry.get(), &mLastError );
}
bool QgsGeometry::equals( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return false;
}
// fast check - are they shared copies of the same underlying geometry?
if ( d == geometry.d )
return true;
// fast check - distinct geometry types?
if ( type() != geometry.type() )
return false;
// slower check - actually test the geometries
return *d->geometry == *geometry.d->geometry;
}
bool QgsGeometry::touches( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return false;
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
return geos.touches( geometry.d->geometry.get(), &mLastError );
}
bool QgsGeometry::overlaps( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return false;
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
return geos.overlaps( geometry.d->geometry.get(), &mLastError );
}
bool QgsGeometry::within( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return false;
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
return geos.within( geometry.d->geometry.get(), &mLastError );
}
bool QgsGeometry::crosses( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return false;
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
return geos.crosses( geometry.d->geometry.get(), &mLastError );
}
QString QgsGeometry::asWkt( int precision ) const
{
if ( !d->geometry )
{
return QString();
}
return d->geometry->asWkt( precision );
}
QString QgsGeometry::asJson( int precision ) const
{
return QString::fromStdString( asJsonObject( precision ).dump() );
}
json QgsGeometry::asJsonObject( int precision ) const
{
if ( !d->geometry )
{
return nullptr;
}
return d->geometry->asJsonObject( precision );
}
QVector<QgsGeometry> QgsGeometry::coerceToType( const QgsWkbTypes::Type type ) const
{
QVector< QgsGeometry > res;
if ( isNull() )
return res;
if ( wkbType() == type || type == QgsWkbTypes::Unknown )
{
res << *this;
return res;
}
if ( type == QgsWkbTypes::NoGeometry )
{
return res;
}
QgsGeometry newGeom = *this;
// Curved -> straight
if ( !QgsWkbTypes::isCurvedType( type ) && QgsWkbTypes::isCurvedType( newGeom.wkbType() ) )
{
newGeom = QgsGeometry( d->geometry.get()->segmentize() );
}
// polygon -> line
if ( QgsWkbTypes::geometryType( type ) == QgsWkbTypes::LineGeometry &&
newGeom.type() == QgsWkbTypes::PolygonGeometry )
{
// boundary gives us a (multi)line string of exterior + interior rings
newGeom = QgsGeometry( newGeom.constGet()->boundary() );
}
// line -> polygon
if ( QgsWkbTypes::geometryType( type ) == QgsWkbTypes::PolygonGeometry &&
newGeom.type() == QgsWkbTypes::LineGeometry )
{
std::unique_ptr< QgsGeometryCollection > gc( QgsGeometryFactory::createCollectionOfType( type ) );
const QgsGeometry source = newGeom;
for ( auto part = source.const_parts_begin(); part != source.const_parts_end(); ++part )
{
std::unique_ptr< QgsAbstractGeometry > exterior( ( *part )->clone() );
if ( QgsCurve *curve = qgsgeometry_cast< QgsCurve * >( exterior.get() ) )
{
if ( QgsWkbTypes::isCurvedType( type ) )
{
std::unique_ptr< QgsCurvePolygon > cp = qgis::make_unique< QgsCurvePolygon >();
cp->setExteriorRing( curve );
exterior.release();
gc->addGeometry( cp.release() );
}
else
{
std::unique_ptr< QgsPolygon > p = qgis::make_unique< QgsPolygon >();
p->setExteriorRing( qgsgeometry_cast< QgsLineString * >( curve ) );
exterior.release();
gc->addGeometry( p.release() );
}
}
}
newGeom = QgsGeometry( std::move( gc ) );
}
// line/polygon -> points
if ( QgsWkbTypes::geometryType( type ) == QgsWkbTypes::PointGeometry &&
( newGeom.type() == QgsWkbTypes::LineGeometry ||
newGeom.type() == QgsWkbTypes::PolygonGeometry ) )
{
// lines/polygons to a point layer, extract all vertices
std::unique_ptr< QgsMultiPoint > mp = qgis::make_unique< QgsMultiPoint >();
const QgsGeometry source = newGeom;
QSet< QgsPoint > added;
for ( auto vertex = source.vertices_begin(); vertex != source.vertices_end(); ++vertex )
{
if ( added.contains( *vertex ) )
continue; // avoid duplicate points, e.g. start/end of rings
mp->addGeometry( ( *vertex ).clone() );
added.insert( *vertex );
}
newGeom = QgsGeometry( std::move( mp ) );
}
// Single -> multi
if ( QgsWkbTypes::isMultiType( type ) && ! newGeom.isMultipart( ) )
{
newGeom.convertToMultiType();
}
// Drop Z/M
if ( newGeom.constGet()->is3D() && ! QgsWkbTypes::hasZ( type ) )
{
newGeom.get()->dropZValue();
}
if ( newGeom.constGet()->isMeasure() && ! QgsWkbTypes::hasM( type ) )
{
newGeom.get()->dropMValue();
}
// Add Z/M back, set to 0
if ( ! newGeom.constGet()->is3D() && QgsWkbTypes::hasZ( type ) )
{
newGeom.get()->addZValue( 0.0 );
}
if ( ! newGeom.constGet()->isMeasure() && QgsWkbTypes::hasM( type ) )
{
newGeom.get()->addMValue( 0.0 );
}
// Multi -> single
if ( ! QgsWkbTypes::isMultiType( type ) && newGeom.isMultipart( ) )
{
const QgsGeometryCollection *parts( static_cast< const QgsGeometryCollection * >( newGeom.constGet() ) );
QgsAttributeMap attrMap;
res.reserve( parts->partCount() );
for ( int i = 0; i < parts->partCount( ); i++ )
{
res << QgsGeometry( parts->geometryN( i )->clone() );
}
}
else
{
res << newGeom;
}
return res;
}
QgsGeometry QgsGeometry::convertToType( QgsWkbTypes::GeometryType destType, bool destMultipart ) const
{
switch ( destType )
{
case QgsWkbTypes::PointGeometry:
return convertToPoint( destMultipart );
case QgsWkbTypes::LineGeometry:
return convertToLine( destMultipart );
case QgsWkbTypes::PolygonGeometry:
return convertToPolygon( destMultipart );
default:
return QgsGeometry();
}
}
bool QgsGeometry::convertToMultiType()
{
if ( !d->geometry )
{
return false;
}
if ( isMultipart() ) //already multitype, no need to convert
{
return true;
}
std::unique_ptr< QgsAbstractGeometry >geom = QgsGeometryFactory::geomFromWkbType( QgsWkbTypes::multiType( d->geometry->wkbType() ) );
QgsGeometryCollection *multiGeom = qgsgeometry_cast<QgsGeometryCollection *>( geom.get() );
if ( !multiGeom )
{
return false;
}
//try to avoid cloning existing geometry whenever we can
//want to see a magic trick?... gather round kiddies...
detach(); // maybe a clone, hopefully not if we're the only ref to the private data
// now we cheat a bit and steal the private geometry and add it direct to the multigeom
// we can do this because we're the only ref to this geometry, guaranteed by the detach call above
multiGeom->addGeometry( d->geometry.release() );
// and replace it with the multi geometry.
// TADA! a clone free conversion in some cases
d->geometry = std::move( geom );
return true;
}
bool QgsGeometry::convertToSingleType()
{
if ( !d->geometry )
{
return false;
}
if ( !isMultipart() ) //already single part, no need to convert
{
return true;
}
QgsGeometryCollection *multiGeom = qgsgeometry_cast<QgsGeometryCollection *>( d->geometry.get() );
if ( !multiGeom || multiGeom->partCount() < 1 )
return false;
std::unique_ptr< QgsAbstractGeometry > firstPart( multiGeom->geometryN( 0 )->clone() );
reset( std::move( firstPart ) );
return true;
}
bool QgsGeometry::convertGeometryCollectionToSubclass( QgsWkbTypes::GeometryType geomType )
{
const QgsGeometryCollection *origGeom = qgsgeometry_cast<const QgsGeometryCollection *>( constGet() );
if ( !origGeom )
return false;
std::unique_ptr<QgsGeometryCollection> resGeom;
switch ( geomType )
{
case QgsWkbTypes::PointGeometry:
resGeom = qgis::make_unique<QgsMultiPoint>();
break;
case QgsWkbTypes::LineGeometry:
resGeom = qgis::make_unique<QgsMultiLineString>();
break;
case QgsWkbTypes::PolygonGeometry:
resGeom = qgis::make_unique<QgsMultiPolygon>();
break;
default:
break;
}
if ( !resGeom )
return false;
resGeom->reserve( origGeom->numGeometries() );
for ( int i = 0; i < origGeom->numGeometries(); ++i )
{
const QgsAbstractGeometry *g = origGeom->geometryN( i );
if ( QgsWkbTypes::geometryType( g->wkbType() ) == geomType )
resGeom->addGeometry( g->clone() );
}
set( resGeom.release() );
return true;
}
QgsPointXY QgsGeometry::asPoint() const
{
if ( !d->geometry || QgsWkbTypes::flatType( d->geometry->wkbType() ) != QgsWkbTypes::Point )
{
return QgsPointXY();
}
QgsPoint *pt = qgsgeometry_cast<QgsPoint *>( d->geometry.get() );
if ( !pt )
{
return QgsPointXY();
}
return QgsPointXY( pt->x(), pt->y() );
}
QgsPolylineXY QgsGeometry::asPolyline() const
{
QgsPolylineXY polyLine;
if ( !d->geometry )
{
return polyLine;
}
bool doSegmentation = ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::CompoundCurve
|| QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::CircularString );
std::unique_ptr< QgsLineString > segmentizedLine;
QgsLineString *line = nullptr;
if ( doSegmentation )
{
QgsCurve *curve = qgsgeometry_cast<QgsCurve *>( d->geometry.get() );
if ( !curve )
{
return polyLine;
}
segmentizedLine.reset( curve->curveToLine() );
line = segmentizedLine.get();
}
else
{
line = qgsgeometry_cast<QgsLineString *>( d->geometry.get() );
if ( !line )
{
return polyLine;
}
}
int nVertices = line->numPoints();
polyLine.resize( nVertices );
QgsPointXY *data = polyLine.data();
const double *xData = line->xData();
const double *yData = line->yData();
for ( int i = 0; i < nVertices; ++i )
{
data->setX( *xData++ );
data->setY( *yData++ );
data++;
}
return polyLine;
}
QgsPolygonXY QgsGeometry::asPolygon() const
{
if ( !d->geometry )
return QgsPolygonXY();
bool doSegmentation = ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::CurvePolygon );
QgsPolygon *p = nullptr;
std::unique_ptr< QgsPolygon > segmentized;
if ( doSegmentation )
{
QgsCurvePolygon *curvePoly = qgsgeometry_cast<QgsCurvePolygon *>( d->geometry.get() );
if ( !curvePoly )
{
return QgsPolygonXY();
}
segmentized.reset( curvePoly->toPolygon() );
p = segmentized.get();
}
else
{
p = qgsgeometry_cast<QgsPolygon *>( d->geometry.get() );
}
if ( !p )
{
return QgsPolygonXY();
}
QgsPolygonXY polygon;
convertPolygon( *p, polygon );
return polygon;
}
QgsMultiPointXY QgsGeometry::asMultiPoint() const
{
if ( !d->geometry || QgsWkbTypes::flatType( d->geometry->wkbType() ) != QgsWkbTypes::MultiPoint )
{
return QgsMultiPointXY();
}
const QgsMultiPoint *mp = qgsgeometry_cast<QgsMultiPoint *>( d->geometry.get() );
if ( !mp )
{
return QgsMultiPointXY();
}
int nPoints = mp->numGeometries();
QgsMultiPointXY multiPoint( nPoints );
for ( int i = 0; i < nPoints; ++i )
{
const QgsPoint *pt = static_cast<const QgsPoint *>( mp->geometryN( i ) );
multiPoint[i].setX( pt->x() );
multiPoint[i].setY( pt->y() );
}
return multiPoint;
}
QgsMultiPolylineXY QgsGeometry::asMultiPolyline() const
{
if ( !d->geometry )
{
return QgsMultiPolylineXY();
}
QgsGeometryCollection *geomCollection = qgsgeometry_cast<QgsGeometryCollection *>( d->geometry.get() );
if ( !geomCollection )
{
return QgsMultiPolylineXY();
}
int nLines = geomCollection->numGeometries();
if ( nLines < 1 )
{
return QgsMultiPolylineXY();
}
QgsMultiPolylineXY mpl;
mpl.reserve( nLines );
for ( int i = 0; i < nLines; ++i )
{
const QgsLineString *line = qgsgeometry_cast<const QgsLineString *>( geomCollection->geometryN( i ) );
std::unique_ptr< QgsLineString > segmentized;
if ( !line )
{
const QgsCurve *curve = qgsgeometry_cast<const QgsCurve *>( geomCollection->geometryN( i ) );
if ( !curve )
{
continue;
}
segmentized.reset( curve->curveToLine() );
line = segmentized.get();
}
QgsPolylineXY polyLine;
int nVertices = line->numPoints();
polyLine.resize( nVertices );
QgsPointXY *data = polyLine.data();
const double *xData = line->xData();
const double *yData = line->yData();
for ( int i = 0; i < nVertices; ++i )
{
data->setX( *xData++ );
data->setY( *yData++ );
data++;
}
mpl.append( polyLine );
}
return mpl;
}
QgsMultiPolygonXY QgsGeometry::asMultiPolygon() const
{
if ( !d->geometry )
{
return QgsMultiPolygonXY();
}
QgsGeometryCollection *geomCollection = qgsgeometry_cast<QgsGeometryCollection *>( d->geometry.get() );
if ( !geomCollection )
{
return QgsMultiPolygonXY();
}
int nPolygons = geomCollection->numGeometries();
if ( nPolygons < 1 )
{
return QgsMultiPolygonXY();
}
QgsMultiPolygonXY mp;
for ( int i = 0; i < nPolygons; ++i )
{
const QgsPolygon *polygon = qgsgeometry_cast<const QgsPolygon *>( geomCollection->geometryN( i ) );
if ( !polygon )
{
const QgsCurvePolygon *cPolygon = qgsgeometry_cast<const QgsCurvePolygon *>( geomCollection->geometryN( i ) );
if ( cPolygon )
{
polygon = cPolygon->toPolygon();
}
else
{
continue;
}
}
QgsPolygonXY poly;
convertPolygon( *polygon, poly );
mp.append( poly );
}
return mp;
}
double QgsGeometry::area() const
{
if ( !d->geometry )
{
return -1.0;
}
QgsGeos g( d->geometry.get() );
#if 0
//debug: compare geos area with calculation in QGIS
double geosArea = g.area();
double qgisArea = 0;
QgsSurface *surface = qgsgeometry_cast<QgsSurface *>( d->geometry );
if ( surface )
{
qgisArea = surface->area();
}
#endif
mLastError.clear();
return g.area( &mLastError );
}
double QgsGeometry::length() const
{
if ( !d->geometry )
{
return -1.0;
}
QgsGeos g( d->geometry.get() );
mLastError.clear();
return g.length( &mLastError );
}
double QgsGeometry::distance( const QgsGeometry &geom ) const
{
if ( !d->geometry || !geom.d->geometry )
{
return -1.0;
}
// avoid calling geos for trivial point-to-point distance calculations
if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::Point && QgsWkbTypes::flatType( geom.wkbType() ) == QgsWkbTypes::Point )
{
return qgsgeometry_cast< const QgsPoint * >( d->geometry.get() )->distance( *qgsgeometry_cast< const QgsPoint * >( geom.constGet() ) );
}
QgsGeos g( d->geometry.get() );
mLastError.clear();
return g.distance( geom.d->geometry.get(), &mLastError );
}
double QgsGeometry::hausdorffDistance( const QgsGeometry &geom ) const
{
if ( !d->geometry || !geom.d->geometry )
{
return -1.0;
}
QgsGeos g( d->geometry.get() );
mLastError.clear();
return g.hausdorffDistance( geom.d->geometry.get(), &mLastError );
}
double QgsGeometry::hausdorffDistanceDensify( const QgsGeometry &geom, double densifyFraction ) const
{
if ( !d->geometry || !geom.d->geometry )
{
return -1.0;
}
QgsGeos g( d->geometry.get() );
mLastError.clear();
return g.hausdorffDistanceDensify( geom.d->geometry.get(), densifyFraction, &mLastError );
}
QgsAbstractGeometry::vertex_iterator QgsGeometry::vertices_begin() const
{
if ( !d->geometry || d->geometry.get()->isEmpty() )
return QgsAbstractGeometry::vertex_iterator();
return d->geometry->vertices_begin();
}
QgsAbstractGeometry::vertex_iterator QgsGeometry::vertices_end() const
{
if ( !d->geometry || d->geometry.get()->isEmpty() )
return QgsAbstractGeometry::vertex_iterator();
return d->geometry->vertices_end();
}
QgsVertexIterator QgsGeometry::vertices() const
{
if ( !d->geometry || d->geometry.get()->isEmpty() )
return QgsVertexIterator();
return QgsVertexIterator( d->geometry.get() );
}
QgsAbstractGeometry::part_iterator QgsGeometry::parts_begin()
{
if ( !d->geometry )
return QgsAbstractGeometry::part_iterator();
detach();
return d->geometry->parts_begin();
}
QgsAbstractGeometry::part_iterator QgsGeometry::parts_end()
{
if ( !d->geometry )
return QgsAbstractGeometry::part_iterator();
return d->geometry->parts_end();
}
QgsAbstractGeometry::const_part_iterator QgsGeometry::const_parts_begin() const
{
if ( !d->geometry )
return QgsAbstractGeometry::const_part_iterator();
return d->geometry->const_parts_begin();
}
QgsAbstractGeometry::const_part_iterator QgsGeometry::const_parts_end() const
{
if ( !d->geometry )
return QgsAbstractGeometry::const_part_iterator();
return d->geometry->const_parts_end();
}
QgsGeometryPartIterator QgsGeometry::parts()
{
if ( !d->geometry )
return QgsGeometryPartIterator();
detach();
return QgsGeometryPartIterator( d->geometry.get() );
}
QgsGeometryConstPartIterator QgsGeometry::constParts() const
{
if ( !d->geometry )
return QgsGeometryConstPartIterator();
return QgsGeometryConstPartIterator( d->geometry.get() );
}
QgsGeometry QgsGeometry::buffer( double distance, int segments ) const
{
if ( !d->geometry )
{
return QgsGeometry();
}
QgsGeos g( d->geometry.get() );
mLastError.clear();
std::unique_ptr<QgsAbstractGeometry> geom( g.buffer( distance, segments, &mLastError ) );
if ( !geom )
{
QgsGeometry result;
result.mLastError = mLastError;
return result;
}
return QgsGeometry( std::move( geom ) );
}
QgsGeometry QgsGeometry::buffer( double distance, int segments, EndCapStyle endCapStyle, JoinStyle joinStyle, double miterLimit ) const
{
if ( !d->geometry )
{
return QgsGeometry();
}
QgsGeos g( d->geometry.get() );
mLastError.clear();
QgsAbstractGeometry *geom = g.buffer( distance, segments, endCapStyle, joinStyle, miterLimit, &mLastError );
if ( !geom )
{
QgsGeometry result;
result.mLastError = mLastError;
return result;
}
return QgsGeometry( geom );
}
QgsGeometry QgsGeometry::offsetCurve( double distance, int segments, JoinStyle joinStyle, double miterLimit ) const
{
if ( !d->geometry || type() != QgsWkbTypes::LineGeometry )
{
return QgsGeometry();
}
if ( QgsWkbTypes::isMultiType( d->geometry->wkbType() ) )
{
const QVector<QgsGeometry> parts = asGeometryCollection();
QVector<QgsGeometry> results;
results.reserve( parts.count() );
for ( const QgsGeometry &part : parts )
{
QgsGeometry result = part.offsetCurve( distance, segments, joinStyle, miterLimit );<|fim▁hole|> if ( !result.isNull() )
results << result;
}
if ( results.isEmpty() )
return QgsGeometry();
QgsGeometry first = results.takeAt( 0 );
for ( const QgsGeometry &result : qgis::as_const( results ) )
{
first.addPart( result );
}
return first;
}
else
{
QgsGeos geos( d->geometry.get() );
mLastError.clear();
// GEOS can flip the curve orientation in some circumstances. So record previous orientation and correct if required
const QgsCurve::Orientation prevOrientation = qgsgeometry_cast< const QgsCurve * >( d->geometry.get() )->orientation();
std::unique_ptr< QgsAbstractGeometry > offsetGeom( geos.offsetCurve( distance, segments, joinStyle, miterLimit, &mLastError ) );
if ( !offsetGeom )
{
QgsGeometry result;
result.mLastError = mLastError;
return result;
}
if ( const QgsCurve *offsetCurve = qgsgeometry_cast< const QgsCurve * >( offsetGeom.get() ) )
{
const QgsCurve::Orientation newOrientation = offsetCurve->orientation();
if ( newOrientation != prevOrientation )
{
// GEOS has flipped line orientation, flip it back
std::unique_ptr< QgsAbstractGeometry > flipped( offsetCurve->reversed() );
offsetGeom = std::move( flipped );
}
}
return QgsGeometry( std::move( offsetGeom ) );
}
}
QgsGeometry QgsGeometry::singleSidedBuffer( double distance, int segments, BufferSide side, JoinStyle joinStyle, double miterLimit ) const
{
if ( !d->geometry || type() != QgsWkbTypes::LineGeometry )
{
return QgsGeometry();
}
if ( QgsWkbTypes::isMultiType( d->geometry->wkbType() ) )
{
const QVector<QgsGeometry> parts = asGeometryCollection();
QVector<QgsGeometry> results;
results.reserve( parts.count() );
for ( const QgsGeometry &part : parts )
{
QgsGeometry result = part.singleSidedBuffer( distance, segments, side, joinStyle, miterLimit );
if ( !result.isNull() )
results << result;
}
if ( results.isEmpty() )
return QgsGeometry();
QgsGeometry first = results.takeAt( 0 );
for ( const QgsGeometry &result : qgis::as_const( results ) )
{
first.addPart( result );
}
return first;
}
else
{
QgsGeos geos( d->geometry.get() );
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > bufferGeom = geos.singleSidedBuffer( distance, segments, side,
joinStyle, miterLimit, &mLastError );
if ( !bufferGeom )
{
QgsGeometry result;
result.mLastError = mLastError;
return result;
}
return QgsGeometry( std::move( bufferGeom ) );
}
}
QgsGeometry QgsGeometry::taperedBuffer( double startWidth, double endWidth, int segments ) const
{
QgsInternalGeometryEngine engine( *this );
return engine.taperedBuffer( startWidth, endWidth, segments );
}
QgsGeometry QgsGeometry::variableWidthBufferByM( int segments ) const
{
QgsInternalGeometryEngine engine( *this );
return engine.variableWidthBufferByM( segments );
}
QgsGeometry QgsGeometry::extendLine( double startDistance, double endDistance ) const
{
if ( !d->geometry || type() != QgsWkbTypes::LineGeometry )
{
return QgsGeometry();
}
if ( QgsWkbTypes::isMultiType( d->geometry->wkbType() ) )
{
const QVector<QgsGeometry> parts = asGeometryCollection();
QVector<QgsGeometry> results;
results.reserve( parts.count() );
for ( const QgsGeometry &part : parts )
{
QgsGeometry result = part.extendLine( startDistance, endDistance );
if ( !result.isNull() )
results << result;
}
if ( results.isEmpty() )
return QgsGeometry();
QgsGeometry first = results.takeAt( 0 );
for ( const QgsGeometry &result : qgis::as_const( results ) )
{
first.addPart( result );
}
return first;
}
else
{
QgsLineString *line = qgsgeometry_cast< QgsLineString * >( d->geometry.get() );
if ( !line )
return QgsGeometry();
std::unique_ptr< QgsLineString > newLine( line->clone() );
newLine->extend( startDistance, endDistance );
return QgsGeometry( std::move( newLine ) );
}
}
QgsGeometry QgsGeometry::simplify( double tolerance ) const
{
if ( !d->geometry )
{
return QgsGeometry();
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > simplifiedGeom( geos.simplify( tolerance, &mLastError ) );
if ( !simplifiedGeom )
{
QgsGeometry result;
result.mLastError = mLastError;
return result;
}
return QgsGeometry( std::move( simplifiedGeom ) );
}
QgsGeometry QgsGeometry::densifyByCount( int extraNodesPerSegment ) const
{
QgsInternalGeometryEngine engine( *this );
return engine.densifyByCount( extraNodesPerSegment );
}
QgsGeometry QgsGeometry::densifyByDistance( double distance ) const
{
QgsInternalGeometryEngine engine( *this );
return engine.densifyByDistance( distance );
}
QgsGeometry QgsGeometry::convertToCurves( double distanceTolerance, double angleTolerance ) const
{
QgsInternalGeometryEngine engine( *this );
return engine.convertToCurves( distanceTolerance, angleTolerance );
}
QgsGeometry QgsGeometry::centroid() const
{
if ( !d->geometry )
{
return QgsGeometry();
}
// avoid calling geos for trivial point centroids
if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::Point )
{
QgsGeometry c = *this;
c.get()->dropZValue();
c.get()->dropMValue();
return c;
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
QgsGeometry result( geos.centroid( &mLastError ) );
result.mLastError = mLastError;
return result;
}
QgsGeometry QgsGeometry::pointOnSurface() const
{
if ( !d->geometry )
{
return QgsGeometry();
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
QgsGeometry result( geos.pointOnSurface( &mLastError ) );
result.mLastError = mLastError;
return result;
}
QgsGeometry QgsGeometry::poleOfInaccessibility( double precision, double *distanceToBoundary ) const
{
QgsInternalGeometryEngine engine( *this );
return engine.poleOfInaccessibility( precision, distanceToBoundary );
}
QgsGeometry QgsGeometry::convexHull() const
{
if ( !d->geometry )
{
return QgsGeometry();
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > cHull( geos.convexHull( &mLastError ) );
if ( !cHull )
{
QgsGeometry geom;
geom.mLastError = mLastError;
return geom;
}
return QgsGeometry( std::move( cHull ) );
}
QgsGeometry QgsGeometry::voronoiDiagram( const QgsGeometry &extent, double tolerance, bool edgesOnly ) const
{
if ( !d->geometry )
{
return QgsGeometry();
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
QgsGeometry result = geos.voronoiDiagram( extent.constGet(), tolerance, edgesOnly, &mLastError );
result.mLastError = mLastError;
return result;
}
QgsGeometry QgsGeometry::delaunayTriangulation( double tolerance, bool edgesOnly ) const
{
if ( !d->geometry )
{
return QgsGeometry();
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
QgsGeometry result = geos.delaunayTriangulation( tolerance, edgesOnly );
result.mLastError = mLastError;
return result;
}
QgsGeometry QgsGeometry::subdivide( int maxNodes ) const
{
if ( !d->geometry )
{
return QgsGeometry();
}
const QgsAbstractGeometry *geom = d->geometry.get();
std::unique_ptr< QgsAbstractGeometry > segmentizedCopy;
if ( QgsWkbTypes::isCurvedType( d->geometry->wkbType() ) )
{
segmentizedCopy.reset( d->geometry->segmentize() );
geom = segmentizedCopy.get();
}
QgsGeos geos( geom );
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > result( geos.subdivide( maxNodes, &mLastError ) );
if ( !result )
{
QgsGeometry geom;
geom.mLastError = mLastError;
return geom;
}
return QgsGeometry( std::move( result ) );
}
QgsGeometry QgsGeometry::interpolate( double distance ) const
{
if ( !d->geometry )
{
return QgsGeometry();
}
QgsGeometry line = *this;
if ( type() == QgsWkbTypes::PointGeometry )
return QgsGeometry();
else if ( type() == QgsWkbTypes::PolygonGeometry )
{
line = QgsGeometry( d->geometry->boundary() );
}
const QgsCurve *curve = nullptr;
if ( line.isMultipart() )
{
// if multi part, iterate through parts to find target part
const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( line.constGet() );
for ( int part = 0; part < collection->numGeometries(); ++part )
{
const QgsCurve *candidate = qgsgeometry_cast< const QgsCurve * >( collection->geometryN( part ) );
if ( !candidate )
continue;
const double candidateLength = candidate->length();
if ( candidateLength >= distance )
{
curve = candidate;
break;
}
distance -= candidateLength;
}
}
else
{
curve = qgsgeometry_cast< const QgsCurve * >( line.constGet() );
}
if ( !curve )
return QgsGeometry();
std::unique_ptr< QgsPoint > result( curve->interpolatePoint( distance ) );
if ( !result )
{
return QgsGeometry();
}
return QgsGeometry( std::move( result ) );
}
double QgsGeometry::lineLocatePoint( const QgsGeometry &point ) const
{
if ( type() != QgsWkbTypes::LineGeometry )
return -1;
if ( QgsWkbTypes::flatType( point.wkbType() ) != QgsWkbTypes::Point )
return -1;
QgsGeometry segmentized = *this;
if ( QgsWkbTypes::isCurvedType( wkbType() ) )
{
segmentized = QgsGeometry( static_cast< QgsCurve * >( d->geometry.get() )->segmentize() );
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
return geos.lineLocatePoint( *( static_cast< QgsPoint * >( point.d->geometry.get() ) ), &mLastError );
}
double QgsGeometry::interpolateAngle( double distance ) const
{
if ( !d->geometry )
return 0.0;
// always operate on segmentized geometries
QgsGeometry segmentized = *this;
if ( QgsWkbTypes::isCurvedType( wkbType() ) )
{
segmentized = QgsGeometry( static_cast< QgsCurve * >( d->geometry.get() )->segmentize() );
}
QgsVertexId previous;
QgsVertexId next;
if ( !QgsGeometryUtils::verticesAtDistance( *segmentized.constGet(), distance, previous, next ) )
return 0.0;
if ( previous == next )
{
// distance coincided exactly with a vertex
QgsVertexId v2 = previous;
QgsVertexId v1;
QgsVertexId v3;
segmentized.constGet()->adjacentVertices( v2, v1, v3 );
if ( v1.isValid() && v3.isValid() )
{
QgsPoint p1 = segmentized.constGet()->vertexAt( v1 );
QgsPoint p2 = segmentized.constGet()->vertexAt( v2 );
QgsPoint p3 = segmentized.constGet()->vertexAt( v3 );
double angle1 = QgsGeometryUtils::lineAngle( p1.x(), p1.y(), p2.x(), p2.y() );
double angle2 = QgsGeometryUtils::lineAngle( p2.x(), p2.y(), p3.x(), p3.y() );
return QgsGeometryUtils::averageAngle( angle1, angle2 );
}
else if ( v3.isValid() )
{
QgsPoint p1 = segmentized.constGet()->vertexAt( v2 );
QgsPoint p2 = segmentized.constGet()->vertexAt( v3 );
return QgsGeometryUtils::lineAngle( p1.x(), p1.y(), p2.x(), p2.y() );
}
else
{
QgsPoint p1 = segmentized.constGet()->vertexAt( v1 );
QgsPoint p2 = segmentized.constGet()->vertexAt( v2 );
return QgsGeometryUtils::lineAngle( p1.x(), p1.y(), p2.x(), p2.y() );
}
}
else
{
QgsPoint p1 = segmentized.constGet()->vertexAt( previous );
QgsPoint p2 = segmentized.constGet()->vertexAt( next );
return QgsGeometryUtils::lineAngle( p1.x(), p1.y(), p2.x(), p2.y() );
}
}
QgsGeometry QgsGeometry::intersection( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return QgsGeometry();
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > resultGeom( geos.intersection( geometry.d->geometry.get(), &mLastError ) );
if ( !resultGeom )
{
QgsGeometry geom;
geom.mLastError = mLastError;
return geom;
}
return QgsGeometry( std::move( resultGeom ) );
}
QgsGeometry QgsGeometry::combine( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return QgsGeometry();
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > resultGeom( geos.combine( geometry.d->geometry.get(), &mLastError ) );
if ( !resultGeom )
{
QgsGeometry geom;
geom.mLastError = mLastError;
return geom;
}
return QgsGeometry( std::move( resultGeom ) );
}
QgsGeometry QgsGeometry::mergeLines() const
{
if ( !d->geometry )
{
return QgsGeometry();
}
if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::LineString )
{
// special case - a single linestring was passed
return QgsGeometry( *this );
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
QgsGeometry result = geos.mergeLines( &mLastError );
result.mLastError = mLastError;
return result;
}
QgsGeometry QgsGeometry::difference( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return QgsGeometry();
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > resultGeom( geos.difference( geometry.d->geometry.get(), &mLastError ) );
if ( !resultGeom )
{
QgsGeometry geom;
geom.mLastError = mLastError;
return geom;
}
return QgsGeometry( std::move( resultGeom ) );
}
QgsGeometry QgsGeometry::symDifference( const QgsGeometry &geometry ) const
{
if ( !d->geometry || geometry.isNull() )
{
return QgsGeometry();
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > resultGeom( geos.symDifference( geometry.d->geometry.get(), &mLastError ) );
if ( !resultGeom )
{
QgsGeometry geom;
geom.mLastError = mLastError;
return geom;
}
return QgsGeometry( std::move( resultGeom ) );
}
QgsGeometry QgsGeometry::extrude( double x, double y )
{
QgsInternalGeometryEngine engine( *this );
return engine.extrude( x, y );
}
///@cond PRIVATE // avoid dox warning
QVector<QgsPointXY> QgsGeometry::randomPointsInPolygon( int count, const std::function< bool( const QgsPointXY & ) > &acceptPoint, unsigned long seed, QgsFeedback *feedback ) const
{
if ( type() != QgsWkbTypes::PolygonGeometry )
return QVector< QgsPointXY >();
return QgsInternalGeometryEngine::randomPointsInPolygon( *this, count, acceptPoint, seed, feedback );
}
QVector<QgsPointXY> QgsGeometry::randomPointsInPolygon( int count, unsigned long seed, QgsFeedback *feedback ) const
{
if ( type() != QgsWkbTypes::PolygonGeometry )
return QVector< QgsPointXY >();
return QgsInternalGeometryEngine::randomPointsInPolygon( *this, count, []( const QgsPointXY & ) { return true; }, seed, feedback );
}
///@endcond
QByteArray QgsGeometry::asWkb() const
{
return d->geometry ? d->geometry->asWkb() : QByteArray();
}
QVector<QgsGeometry> QgsGeometry::asGeometryCollection() const
{
QVector<QgsGeometry> geometryList;
if ( !d->geometry )
{
return geometryList;
}
QgsGeometryCollection *gc = qgsgeometry_cast<QgsGeometryCollection *>( d->geometry.get() );
if ( gc )
{
int numGeom = gc->numGeometries();
geometryList.reserve( numGeom );
for ( int i = 0; i < numGeom; ++i )
{
geometryList.append( QgsGeometry( gc->geometryN( i )->clone() ) );
}
}
else //a singlepart geometry
{
geometryList.append( *this );
}
return geometryList;
}
QPointF QgsGeometry::asQPointF() const
{
QgsPointXY point = asPoint();
return point.toQPointF();
}
QPolygonF QgsGeometry::asQPolygonF() const
{
const QgsWkbTypes::Type type = wkbType();
const QgsLineString *line = nullptr;
if ( QgsWkbTypes::flatType( type ) == QgsWkbTypes::LineString )
{
line = qgsgeometry_cast< const QgsLineString * >( constGet() );
}
else if ( QgsWkbTypes::flatType( type ) == QgsWkbTypes::Polygon )
{
const QgsPolygon *polygon = qgsgeometry_cast< const QgsPolygon * >( constGet() );
if ( polygon )
line = qgsgeometry_cast< const QgsLineString * >( polygon->exteriorRing() );
}
if ( line )
{
const double *srcX = line->xData();
const double *srcY = line->yData();
const int count = line->numPoints();
QPolygonF res( count );
QPointF *dest = res.data();
for ( int i = 0; i < count; ++i )
{
*dest++ = QPointF( *srcX++, *srcY++ );
}
return res;
}
else
{
return QPolygonF();
}
}
bool QgsGeometry::deleteRing( int ringNum, int partNum )
{
if ( !d->geometry )
{
return false;
}
detach();
bool ok = QgsGeometryEditUtils::deleteRing( d->geometry.get(), ringNum, partNum );
return ok;
}
bool QgsGeometry::deletePart( int partNum )
{
if ( !d->geometry )
{
return false;
}
if ( !isMultipart() && partNum < 1 )
{
set( nullptr );
return true;
}
detach();
bool ok = QgsGeometryEditUtils::deletePart( d->geometry.get(), partNum );
return ok;
}
int QgsGeometry::avoidIntersections( const QList<QgsVectorLayer *> &avoidIntersectionsLayers, const QHash<QgsVectorLayer *, QSet<QgsFeatureId> > &ignoreFeatures )
{
if ( !d->geometry )
{
return 1;
}
std::unique_ptr< QgsAbstractGeometry > diffGeom = QgsGeometryEditUtils::avoidIntersections( *( d->geometry ), avoidIntersectionsLayers, ignoreFeatures );
if ( diffGeom )
{
reset( std::move( diffGeom ) );
}
return 0;
}
QgsGeometry QgsGeometry::makeValid() const
{
if ( !d->geometry )
return QgsGeometry();
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > g( _qgis_lwgeom_make_valid( d->geometry.get(), mLastError ) );
QgsGeometry result = QgsGeometry( std::move( g ) );
result.mLastError = mLastError;
return result;
}
QgsGeometry QgsGeometry::forceRHR() const
{
if ( !d->geometry )
return QgsGeometry();
if ( isMultipart() )
{
const QgsGeometryCollection *collection = qgsgeometry_cast< const QgsGeometryCollection * >( d->geometry.get() );
std::unique_ptr< QgsGeometryCollection > newCollection( collection->createEmptyWithSameType() );
newCollection->reserve( collection->numGeometries() );
for ( int i = 0; i < collection->numGeometries(); ++i )
{
const QgsAbstractGeometry *g = collection->geometryN( i );
if ( const QgsCurvePolygon *cp = qgsgeometry_cast< const QgsCurvePolygon * >( g ) )
{
std::unique_ptr< QgsCurvePolygon > corrected( cp->clone() );
corrected->forceRHR();
newCollection->addGeometry( corrected.release() );
}
else
{
newCollection->addGeometry( g->clone() );
}
}
return QgsGeometry( std::move( newCollection ) );
}
else
{
if ( const QgsCurvePolygon *cp = qgsgeometry_cast< const QgsCurvePolygon * >( d->geometry.get() ) )
{
std::unique_ptr< QgsCurvePolygon > corrected( cp->clone() );
corrected->forceRHR();
return QgsGeometry( std::move( corrected ) );
}
else
{
// not a curve polygon, so return unchanged
return *this;
}
}
}
void QgsGeometry::validateGeometry( QVector<QgsGeometry::Error> &errors, const ValidationMethod method, const QgsGeometry::ValidityFlags flags ) const
{
errors.clear();
if ( !d->geometry )
return;
// avoid expensive calcs for trivial point geometries
if ( QgsWkbTypes::geometryType( d->geometry->wkbType() ) == QgsWkbTypes::PointGeometry )
{
return;
}
switch ( method )
{
case ValidatorQgisInternal:
QgsGeometryValidator::validateGeometry( *this, errors, method );
return;
case ValidatorGeos:
{
QgsGeos geos( d->geometry.get() );
QString error;
QgsGeometry errorLoc;
if ( !geos.isValid( &error, flags & FlagAllowSelfTouchingHoles, &errorLoc ) )
{
if ( errorLoc.isNull() )
{
errors.append( QgsGeometry::Error( error ) );
}
else
{
const QgsPointXY point = errorLoc.asPoint();
errors.append( QgsGeometry::Error( error, point ) );
}
return;
}
}
}
}
bool QgsGeometry::isGeosValid( const QgsGeometry::ValidityFlags flags ) const
{
if ( !d->geometry )
{
return false;
}
return d->geometry->isValid( mLastError, static_cast< int >( flags ) );
}
bool QgsGeometry::isSimple() const
{
if ( !d->geometry )
return false;
QgsGeos geos( d->geometry.get() );
mLastError.clear();
return geos.isSimple( &mLastError );
}
bool QgsGeometry::isGeosEqual( const QgsGeometry &g ) const
{
if ( !d->geometry || !g.d->geometry )
{
return false;
}
// fast check - are they shared copies of the same underlying geometry?
if ( d == g.d )
return true;
// fast check - distinct geometry types?
if ( type() != g.type() )
return false;
// avoid calling geos for trivial point case
if ( QgsWkbTypes::flatType( d->geometry->wkbType() ) == QgsWkbTypes::Point
&& QgsWkbTypes::flatType( g.d->geometry->wkbType() ) == QgsWkbTypes::Point )
{
return equals( g );
}
// another nice fast check upfront -- if the bounding boxes aren't equal, the geometries themselves can't be equal!
if ( d->geometry->boundingBox() != g.d->geometry->boundingBox() )
return false;
QgsGeos geos( d->geometry.get() );
mLastError.clear();
return geos.isEqual( g.d->geometry.get(), &mLastError );
}
QgsGeometry QgsGeometry::unaryUnion( const QVector<QgsGeometry> &geometries )
{
QgsGeos geos( nullptr );
QString error;
std::unique_ptr< QgsAbstractGeometry > geom( geos.combine( geometries, &error ) );
QgsGeometry result( std::move( geom ) );
result.mLastError = error;
return result;
}
QgsGeometry QgsGeometry::polygonize( const QVector<QgsGeometry> &geometryList )
{
QgsGeos geos( nullptr );
QVector<const QgsAbstractGeometry *> geomV2List;
for ( const QgsGeometry &g : geometryList )
{
if ( !( g.isNull() ) )
{
geomV2List.append( g.constGet() );
}
}
QString error;
QgsGeometry result = geos.polygonize( geomV2List, &error );
result.mLastError = error;
return result;
}
void QgsGeometry::convertToStraightSegment( double tolerance, QgsAbstractGeometry::SegmentationToleranceType toleranceType )
{
if ( !d->geometry || !requiresConversionToStraightSegments() )
{
return;
}
std::unique_ptr< QgsAbstractGeometry > straightGeom( d->geometry->segmentize( tolerance, toleranceType ) );
reset( std::move( straightGeom ) );
}
bool QgsGeometry::requiresConversionToStraightSegments() const
{
if ( !d->geometry )
{
return false;
}
return d->geometry->hasCurvedSegments();
}
QgsGeometry::OperationResult QgsGeometry::transform( const QgsCoordinateTransform &ct, const QgsCoordinateTransform::TransformDirection direction, const bool transformZ )
{
if ( !d->geometry )
{
return QgsGeometry::InvalidBaseGeometry;
}
detach();
d->geometry->transform( ct, direction, transformZ );
return QgsGeometry::Success;
}
QgsGeometry::OperationResult QgsGeometry::transform( const QTransform &ct, double zTranslate, double zScale, double mTranslate, double mScale )
{
if ( !d->geometry )
{
return QgsGeometry::InvalidBaseGeometry;
}
detach();
d->geometry->transform( ct, zTranslate, zScale, mTranslate, mScale );
return QgsGeometry::Success;
}
void QgsGeometry::mapToPixel( const QgsMapToPixel &mtp )
{
if ( d->geometry )
{
detach();
d->geometry->transform( mtp.transform() );
}
}
QgsGeometry QgsGeometry::clipped( const QgsRectangle &rectangle )
{
if ( !d->geometry || rectangle.isNull() || rectangle.isEmpty() )
{
return QgsGeometry();
}
QgsGeos geos( d->geometry.get() );
mLastError.clear();
std::unique_ptr< QgsAbstractGeometry > resultGeom = geos.clip( rectangle, &mLastError );
if ( !resultGeom )
{
QgsGeometry result;
result.mLastError = mLastError;
return result;
}
return QgsGeometry( std::move( resultGeom ) );
}
void QgsGeometry::draw( QPainter &p ) const
{
if ( d->geometry )
{
d->geometry->draw( p );
}
}
static bool vertexIndexInfo( const QgsAbstractGeometry *g, int vertexIndex, int &partIndex, int &ringIndex, int &vertex )
{
if ( vertexIndex < 0 )
return false; // clearly something wrong
if ( const QgsGeometryCollection *geomCollection = qgsgeometry_cast<const QgsGeometryCollection *>( g ) )
{
partIndex = 0;
int offset = 0;
for ( int i = 0; i < geomCollection->numGeometries(); ++i )
{
const QgsAbstractGeometry *part = geomCollection->geometryN( i );
// count total number of vertices in the part
int numPoints = 0;
for ( int k = 0; k < part->ringCount(); ++k )
numPoints += part->vertexCount( 0, k );
if ( vertexIndex < numPoints )
{
int nothing;
return vertexIndexInfo( part, vertexIndex, nothing, ringIndex, vertex ); // set ring_index + index
}
vertexIndex -= numPoints;
offset += numPoints;
partIndex++;
}
}
else if ( const QgsCurvePolygon *curvePolygon = qgsgeometry_cast<const QgsCurvePolygon *>( g ) )
{
const QgsCurve *ring = curvePolygon->exteriorRing();
if ( vertexIndex < ring->numPoints() )
{
partIndex = 0;
ringIndex = 0;
vertex = vertexIndex;
return true;
}
vertexIndex -= ring->numPoints();
ringIndex = 1;
for ( int i = 0; i < curvePolygon->numInteriorRings(); ++i )
{
const QgsCurve *ring = curvePolygon->interiorRing( i );
if ( vertexIndex < ring->numPoints() )
{
partIndex = 0;
vertex = vertexIndex;
return true;
}
vertexIndex -= ring->numPoints();
ringIndex += 1;
}
}
else if ( const QgsCurve *curve = qgsgeometry_cast<const QgsCurve *>( g ) )
{
if ( vertexIndex < curve->numPoints() )
{
partIndex = 0;
ringIndex = 0;
vertex = vertexIndex;
return true;
}
}
else if ( qgsgeometry_cast<const QgsPoint *>( g ) )
{
if ( vertexIndex == 0 )
{
partIndex = 0;
ringIndex = 0;
vertex = 0;
return true;
}
}
return false;
}
bool QgsGeometry::vertexIdFromVertexNr( int nr, QgsVertexId &id ) const
{
if ( !d->geometry )
{
return false;
}
id.type = QgsVertexId::SegmentVertex;
bool res = vertexIndexInfo( d->geometry.get(), nr, id.part, id.ring, id.vertex );
if ( !res )
return false;
// now let's find out if it is a straight or circular segment
const QgsAbstractGeometry *g = d->geometry.get();
if ( const QgsGeometryCollection *geomCollection = qgsgeometry_cast<const QgsGeometryCollection *>( g ) )
{
g = geomCollection->geometryN( id.part );
}
if ( const QgsCurvePolygon *curvePolygon = qgsgeometry_cast<const QgsCurvePolygon *>( g ) )
{
g = id.ring == 0 ? curvePolygon->exteriorRing() : curvePolygon->interiorRing( id.ring - 1 );
}
if ( const QgsCurve *curve = qgsgeometry_cast<const QgsCurve *>( g ) )
{
QgsPoint p;
res = curve->pointAt( id.vertex, p, id.type );
if ( !res )
return false;
}
return true;
}
int QgsGeometry::vertexNrFromVertexId( QgsVertexId id ) const
{
if ( !d->geometry )
{
return -1;
}
return d->geometry->vertexNumberFromVertexId( id );
}
QString QgsGeometry::lastError() const
{
return mLastError;
}
void QgsGeometry::filterVertices( const std::function<bool ( const QgsPoint & )> &filter )
{
if ( !d->geometry )
return;
detach();
d->geometry->filterVertices( filter );
}
void QgsGeometry::transformVertices( const std::function<QgsPoint( const QgsPoint & )> &transform )
{
if ( !d->geometry )
return;
detach();
d->geometry->transformVertices( transform );
}
void QgsGeometry::convertPointList( const QVector<QgsPointXY> &input, QgsPointSequence &output )
{
output.clear();
for ( const QgsPointXY &p : input )
{
output.append( QgsPoint( p ) );
}
}
void QgsGeometry::convertPointList( const QgsPointSequence &input, QVector<QgsPointXY> &output )
{
output.clear();
for ( const QgsPoint &p : input )
{
output.append( QgsPointXY( p.x(), p.y() ) );
}
}
void QgsGeometry::convertToPolyline( const QgsPointSequence &input, QgsPolylineXY &output )
{
output.clear();
output.resize( input.size() );
for ( int i = 0; i < input.size(); ++i )
{
const QgsPoint &pt = input.at( i );
output[i].setX( pt.x() );
output[i].setY( pt.y() );
}
}
void QgsGeometry::convertPolygon( const QgsPolygon &input, QgsPolygonXY &output )
{
output.clear();
QgsCoordinateSequence coords = input.coordinateSequence();
if ( coords.empty() )
{
return;
}
const QgsRingSequence &rings = coords[0];
output.resize( rings.size() );
for ( int i = 0; i < rings.size(); ++i )
{
convertToPolyline( rings[i], output[i] );
}
}
QgsGeometry QgsGeometry::fromQPointF( QPointF point )
{
return QgsGeometry( qgis::make_unique< QgsPoint >( point.x(), point.y() ) );
}
QgsGeometry QgsGeometry::fromQPolygonF( const QPolygonF &polygon )
{
std::unique_ptr < QgsLineString > ring( QgsLineString::fromQPolygonF( polygon ) );
if ( polygon.isClosed() )
{
std::unique_ptr< QgsPolygon > poly = qgis::make_unique< QgsPolygon >();
poly->setExteriorRing( ring.release() );
return QgsGeometry( std::move( poly ) );
}
else
{
return QgsGeometry( std::move( ring ) );
}
}
QgsPolygonXY QgsGeometry::createPolygonFromQPolygonF( const QPolygonF &polygon )
{
Q_NOWARN_DEPRECATED_PUSH
QgsPolygonXY result;
result << createPolylineFromQPolygonF( polygon );
return result;
Q_NOWARN_DEPRECATED_POP
}
QgsPolylineXY QgsGeometry::createPolylineFromQPolygonF( const QPolygonF &polygon )
{
QgsPolylineXY result;
result.reserve( polygon.count() );
for ( const QPointF &p : polygon )
{
result.append( QgsPointXY( p ) );
}
return result;
}
bool QgsGeometry::compare( const QgsPolylineXY &p1, const QgsPolylineXY &p2, double epsilon )
{
if ( p1.count() != p2.count() )
return false;
for ( int i = 0; i < p1.count(); ++i )
{
if ( !p1.at( i ).compare( p2.at( i ), epsilon ) )
return false;
}
return true;
}
bool QgsGeometry::compare( const QgsPolygonXY &p1, const QgsPolygonXY &p2, double epsilon )
{
if ( p1.count() != p2.count() )
return false;
for ( int i = 0; i < p1.count(); ++i )
{
if ( !QgsGeometry::compare( p1.at( i ), p2.at( i ), epsilon ) )
return false;
}
return true;
}
bool QgsGeometry::compare( const QgsMultiPolygonXY &p1, const QgsMultiPolygonXY &p2, double epsilon )
{
if ( p1.count() != p2.count() )
return false;
for ( int i = 0; i < p1.count(); ++i )
{
if ( !QgsGeometry::compare( p1.at( i ), p2.at( i ), epsilon ) )
return false;
}
return true;
}
QgsGeometry QgsGeometry::smooth( const unsigned int iterations, const double offset, double minimumDistance, double maxAngle ) const
{
if ( !d->geometry || d->geometry->isEmpty() )
return QgsGeometry();
QgsGeometry geom = *this;
if ( QgsWkbTypes::isCurvedType( wkbType() ) )
geom = QgsGeometry( d->geometry->segmentize() );
switch ( QgsWkbTypes::flatType( geom.wkbType() ) )
{
case QgsWkbTypes::Point:
case QgsWkbTypes::MultiPoint:
//can't smooth a point based geometry
return geom;
case QgsWkbTypes::LineString:
{
QgsLineString *lineString = static_cast< QgsLineString * >( d->geometry.get() );
return QgsGeometry( smoothLine( *lineString, iterations, offset, minimumDistance, maxAngle ) );
}
case QgsWkbTypes::MultiLineString:
{
QgsMultiLineString *multiLine = static_cast< QgsMultiLineString * >( d->geometry.get() );
std::unique_ptr< QgsMultiLineString > resultMultiline = qgis::make_unique< QgsMultiLineString> ();
resultMultiline->reserve( multiLine->numGeometries() );
for ( int i = 0; i < multiLine->numGeometries(); ++i )
{
resultMultiline->addGeometry( smoothLine( *( static_cast< QgsLineString * >( multiLine->geometryN( i ) ) ), iterations, offset, minimumDistance, maxAngle ).release() );
}
return QgsGeometry( std::move( resultMultiline ) );
}
case QgsWkbTypes::Polygon:
{
QgsPolygon *poly = static_cast< QgsPolygon * >( d->geometry.get() );
return QgsGeometry( smoothPolygon( *poly, iterations, offset, minimumDistance, maxAngle ) );
}
case QgsWkbTypes::MultiPolygon:
{
QgsMultiPolygon *multiPoly = static_cast< QgsMultiPolygon * >( d->geometry.get() );
std::unique_ptr< QgsMultiPolygon > resultMultiPoly = qgis::make_unique< QgsMultiPolygon >();
resultMultiPoly->reserve( multiPoly->numGeometries() );
for ( int i = 0; i < multiPoly->numGeometries(); ++i )
{
resultMultiPoly->addGeometry( smoothPolygon( *( static_cast< QgsPolygon * >( multiPoly->geometryN( i ) ) ), iterations, offset, minimumDistance, maxAngle ).release() );
}
return QgsGeometry( std::move( resultMultiPoly ) );
}
case QgsWkbTypes::Unknown:
default:
return QgsGeometry( *this );
}
}
std::unique_ptr< QgsLineString > smoothCurve( const QgsLineString &line, const unsigned int iterations,
const double offset, double squareDistThreshold, double maxAngleRads,
bool isRing )
{
std::unique_ptr< QgsLineString > result = qgis::make_unique< QgsLineString >( line );
QgsPointSequence outputLine;
for ( unsigned int iteration = 0; iteration < iterations; ++iteration )
{
outputLine.resize( 0 );
outputLine.reserve( 2 * ( result->numPoints() - 1 ) );
bool skipFirst = false;
bool skipLast = false;
if ( isRing )
{
QgsPoint p1 = result->pointN( result->numPoints() - 2 );
QgsPoint p2 = result->pointN( 0 );
QgsPoint p3 = result->pointN( 1 );
double angle = QgsGeometryUtils::angleBetweenThreePoints( p1.x(), p1.y(), p2.x(), p2.y(),
p3.x(), p3.y() );
angle = std::fabs( M_PI - angle );
skipFirst = angle > maxAngleRads;
}
for ( int i = 0; i < result->numPoints() - 1; i++ )
{
QgsPoint p1 = result->pointN( i );
QgsPoint p2 = result->pointN( i + 1 );
double angle = M_PI;
if ( i == 0 && isRing )
{
QgsPoint p3 = result->pointN( result->numPoints() - 2 );
angle = QgsGeometryUtils::angleBetweenThreePoints( p1.x(), p1.y(), p2.x(), p2.y(),
p3.x(), p3.y() );
}
else if ( i < result->numPoints() - 2 )
{
QgsPoint p3 = result->pointN( i + 2 );
angle = QgsGeometryUtils::angleBetweenThreePoints( p1.x(), p1.y(), p2.x(), p2.y(),
p3.x(), p3.y() );
}
else if ( i == result->numPoints() - 2 && isRing )
{
QgsPoint p3 = result->pointN( 1 );
angle = QgsGeometryUtils::angleBetweenThreePoints( p1.x(), p1.y(), p2.x(), p2.y(),
p3.x(), p3.y() );
}
skipLast = angle < M_PI - maxAngleRads || angle > M_PI + maxAngleRads;
// don't apply distance threshold to first or last segment
if ( i == 0 || i >= result->numPoints() - 2
|| QgsGeometryUtils::sqrDistance2D( p1, p2 ) > squareDistThreshold )
{
if ( !isRing )
{
if ( !skipFirst )
outputLine << ( i == 0 ? result->pointN( i ) : QgsGeometryUtils::interpolatePointOnLine( p1, p2, offset ) );
if ( !skipLast )
outputLine << ( i == result->numPoints() - 2 ? result->pointN( i + 1 ) : QgsGeometryUtils::interpolatePointOnLine( p1, p2, 1.0 - offset ) );
else
outputLine << p2;
}
else
{
// ring
if ( !skipFirst )
outputLine << QgsGeometryUtils::interpolatePointOnLine( p1, p2, offset );
else if ( i == 0 )
outputLine << p1;
if ( !skipLast )
outputLine << QgsGeometryUtils::interpolatePointOnLine( p1, p2, 1.0 - offset );
else
outputLine << p2;
}
}
skipFirst = skipLast;
}
if ( isRing && outputLine.at( 0 ) != outputLine.at( outputLine.count() - 1 ) )
outputLine << outputLine.at( 0 );
result->setPoints( outputLine );
}
return result;
}
std::unique_ptr<QgsLineString> QgsGeometry::smoothLine( const QgsLineString &line, const unsigned int iterations, const double offset, double minimumDistance, double maxAngle ) const
{
double maxAngleRads = maxAngle * M_PI / 180.0;
double squareDistThreshold = minimumDistance > 0 ? minimumDistance * minimumDistance : -1;
return smoothCurve( line, iterations, offset, squareDistThreshold, maxAngleRads, false );
}
std::unique_ptr<QgsPolygon> QgsGeometry::smoothPolygon( const QgsPolygon &polygon, const unsigned int iterations, const double offset, double minimumDistance, double maxAngle ) const
{
double maxAngleRads = maxAngle * M_PI / 180.0;
double squareDistThreshold = minimumDistance > 0 ? minimumDistance * minimumDistance : -1;
std::unique_ptr< QgsPolygon > resultPoly = qgis::make_unique< QgsPolygon >();
resultPoly->setExteriorRing( smoothCurve( *( static_cast< const QgsLineString *>( polygon.exteriorRing() ) ), iterations, offset,
squareDistThreshold, maxAngleRads, true ).release() );
for ( int i = 0; i < polygon.numInteriorRings(); ++i )
{
resultPoly->addInteriorRing( smoothCurve( *( static_cast< const QgsLineString *>( polygon.interiorRing( i ) ) ), iterations, offset,
squareDistThreshold, maxAngleRads, true ).release() );
}
return resultPoly;
}
QgsGeometry QgsGeometry::convertToPoint( bool destMultipart ) const
{
switch ( type() )
{
case QgsWkbTypes::PointGeometry:
{
bool srcIsMultipart = isMultipart();
if ( ( destMultipart && srcIsMultipart ) ||
( !destMultipart && !srcIsMultipart ) )
{
// return a copy of the same geom
return QgsGeometry( *this );
}
if ( destMultipart )
{
// layer is multipart => make a multipoint with a single point
return fromMultiPointXY( QgsMultiPointXY() << asPoint() );
}
else
{
// destination is singlepart => make a single part if possible
QgsMultiPointXY multiPoint = asMultiPoint();
if ( multiPoint.count() == 1 )
{
return fromPointXY( multiPoint[0] );
}
}
return QgsGeometry();
}
case QgsWkbTypes::LineGeometry:
{
// only possible if destination is multipart
if ( !destMultipart )
return QgsGeometry();
// input geometry is multipart
if ( isMultipart() )
{
const QgsMultiPolylineXY multiLine = asMultiPolyline();
QgsMultiPointXY multiPoint;
for ( const QgsPolylineXY &l : multiLine )
for ( const QgsPointXY &p : l )
multiPoint << p;
return fromMultiPointXY( multiPoint );
}
// input geometry is not multipart: copy directly the line into a multipoint
else
{
QgsPolylineXY line = asPolyline();
if ( !line.isEmpty() )
return fromMultiPointXY( line );
}
return QgsGeometry();
}
case QgsWkbTypes::PolygonGeometry:
{
// can only transform if destination is multipoint
if ( !destMultipart )
return QgsGeometry();
// input geometry is multipart: make a multipoint from multipolygon
if ( isMultipart() )
{
const QgsMultiPolygonXY multiPolygon = asMultiPolygon();
QgsMultiPointXY multiPoint;
for ( const QgsPolygonXY &poly : multiPolygon )
for ( const QgsPolylineXY &line : poly )
for ( const QgsPointXY &pt : line )
multiPoint << pt;
return fromMultiPointXY( multiPoint );
}
// input geometry is not multipart: make a multipoint from polygon
else
{
const QgsPolygonXY polygon = asPolygon();
QgsMultiPointXY multiPoint;
for ( const QgsPolylineXY &line : polygon )
for ( const QgsPointXY &pt : line )
multiPoint << pt;
return fromMultiPointXY( multiPoint );
}
}
default:
return QgsGeometry();
}
}
QgsGeometry QgsGeometry::convertToLine( bool destMultipart ) const
{
switch ( type() )
{
case QgsWkbTypes::PointGeometry:
{
if ( !isMultipart() )
return QgsGeometry();
QgsMultiPointXY multiPoint = asMultiPoint();
if ( multiPoint.count() < 2 )
return QgsGeometry();
if ( destMultipart )
return fromMultiPolylineXY( QgsMultiPolylineXY() << multiPoint );
else
return fromPolylineXY( multiPoint );
}
case QgsWkbTypes::LineGeometry:
{
bool srcIsMultipart = isMultipart();
if ( ( destMultipart && srcIsMultipart ) ||
( !destMultipart && ! srcIsMultipart ) )
{
// return a copy of the same geom
return QgsGeometry( *this );
}
if ( destMultipart )
{
// destination is multipart => makes a multipoint with a single line
QgsPolylineXY line = asPolyline();
if ( !line.isEmpty() )
return fromMultiPolylineXY( QgsMultiPolylineXY() << line );
}
else
{
// destination is singlepart => make a single part if possible
QgsMultiPolylineXY multiLine = asMultiPolyline();
if ( multiLine.count() == 1 )
return fromPolylineXY( multiLine[0] );
}
return QgsGeometry();
}
case QgsWkbTypes::PolygonGeometry:
{
// input geometry is multipolygon
if ( isMultipart() )
{
const QgsMultiPolygonXY multiPolygon = asMultiPolygon();
QgsMultiPolylineXY multiLine;
for ( const QgsPolygonXY &poly : multiPolygon )
for ( const QgsPolylineXY &line : poly )
multiLine << line;
if ( destMultipart )
{
// destination is multipart
return fromMultiPolylineXY( multiLine );
}
else if ( multiLine.count() == 1 )
{
// destination is singlepart => make a single part if possible
return fromPolylineXY( multiLine[0] );
}
}
// input geometry is single polygon
else
{
QgsPolygonXY polygon = asPolygon();
// if polygon has rings
if ( polygon.count() > 1 )
{
// cannot fit a polygon with rings in a single line layer
// TODO: would it be better to remove rings?
if ( destMultipart )
{
const QgsPolygonXY polygon = asPolygon();
QgsMultiPolylineXY multiLine;
multiLine.reserve( polygon.count() );
for ( const QgsPolylineXY &line : polygon )
multiLine << line;
return fromMultiPolylineXY( multiLine );
}
}
// no rings
else if ( polygon.count() == 1 )
{
if ( destMultipart )
{
return fromMultiPolylineXY( polygon );
}
else
{
return fromPolylineXY( polygon[0] );
}
}
}
return QgsGeometry();
}
default:
return QgsGeometry();
}
}
QgsGeometry QgsGeometry::convertToPolygon( bool destMultipart ) const
{
switch ( type() )
{
case QgsWkbTypes::PointGeometry:
{
if ( !isMultipart() )
return QgsGeometry();
QgsMultiPointXY multiPoint = asMultiPoint();
if ( multiPoint.count() < 3 )
return QgsGeometry();
if ( multiPoint.last() != multiPoint.first() )
multiPoint << multiPoint.first();
QgsPolygonXY polygon = QgsPolygonXY() << multiPoint;
if ( destMultipart )
return fromMultiPolygonXY( QgsMultiPolygonXY() << polygon );
else
return fromPolygonXY( polygon );
}
case QgsWkbTypes::LineGeometry:
{
// input geometry is multiline
if ( isMultipart() )
{
QgsMultiPolylineXY multiLine = asMultiPolyline();
QgsMultiPolygonXY multiPolygon;
for ( QgsMultiPolylineXY::iterator multiLineIt = multiLine.begin(); multiLineIt != multiLine.end(); ++multiLineIt )
{
// do not create polygon for a 1 segment line
if ( ( *multiLineIt ).count() < 3 )
return QgsGeometry();
if ( ( *multiLineIt ).count() == 3 && ( *multiLineIt ).first() == ( *multiLineIt ).last() )
return QgsGeometry();
// add closing node
if ( ( *multiLineIt ).first() != ( *multiLineIt ).last() )
*multiLineIt << ( *multiLineIt ).first();
multiPolygon << ( QgsPolygonXY() << *multiLineIt );
}
// check that polygons were inserted
if ( !multiPolygon.isEmpty() )
{
if ( destMultipart )
{
return fromMultiPolygonXY( multiPolygon );
}
else if ( multiPolygon.count() == 1 )
{
// destination is singlepart => make a single part if possible
return fromPolygonXY( multiPolygon[0] );
}
}
}
// input geometry is single line
else
{
QgsPolylineXY line = asPolyline();
// do not create polygon for a 1 segment line
if ( line.count() < 3 )
return QgsGeometry();
if ( line.count() == 3 && line.first() == line.last() )
return QgsGeometry();
// add closing node
if ( line.first() != line.last() )
line << line.first();
// destination is multipart
if ( destMultipart )
{
return fromMultiPolygonXY( QgsMultiPolygonXY() << ( QgsPolygonXY() << line ) );
}
else
{
return fromPolygonXY( QgsPolygonXY() << line );
}
}
return QgsGeometry();
}
case QgsWkbTypes::PolygonGeometry:
{
bool srcIsMultipart = isMultipart();
if ( ( destMultipart && srcIsMultipart ) ||
( !destMultipart && ! srcIsMultipart ) )
{
// return a copy of the same geom
return QgsGeometry( *this );
}
if ( destMultipart )
{
// destination is multipart => makes a multipoint with a single polygon
QgsPolygonXY polygon = asPolygon();
if ( !polygon.isEmpty() )
return fromMultiPolygonXY( QgsMultiPolygonXY() << polygon );
}
else
{
QgsMultiPolygonXY multiPolygon = asMultiPolygon();
if ( multiPolygon.count() == 1 )
{
// destination is singlepart => make a single part if possible
return fromPolygonXY( multiPolygon[0] );
}
}
return QgsGeometry();
}
default:
return QgsGeometry();
}
}
QgsGeometryEngine *QgsGeometry::createGeometryEngine( const QgsAbstractGeometry *geometry )
{
return new QgsGeos( geometry );
}
QDataStream &operator<<( QDataStream &out, const QgsGeometry &geometry )
{
out << geometry.asWkb();
return out;
}
QDataStream &operator>>( QDataStream &in, QgsGeometry &geometry )
{
QByteArray byteArray;
in >> byteArray;
if ( byteArray.isEmpty() )
{
geometry.set( nullptr );
return in;
}
geometry.fromWkb( byteArray );
return in;
}
QString QgsGeometry::Error::what() const
{
return mMessage;
}
QgsPointXY QgsGeometry::Error::where() const
{
return mLocation;
}
bool QgsGeometry::Error::hasWhere() const
{
return mHasLocation;
}<|fim▁end|> | |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>import os.path
from pyneuroml.lems.LEMSSimulation import LEMSSimulation
import shutil
import os
from pyneuroml.pynml import read_neuroml2_file, get_next_hex_color, print_comment_v, print_comment
import random
def generate_lems_file_for_neuroml(sim_id,
neuroml_file,
target,
duration,
dt,
lems_file_name,
target_dir,
gen_plots_for_all_v = True,
plot_all_segments = False,
gen_plots_for_only = [], # List of populations
gen_plots_for_quantities = {}, # Dict with displays vs lists of quantity paths
gen_saves_for_all_v = True,
save_all_segments = False,
gen_saves_for_only = [], # List of populations
gen_saves_for_quantities = {}, # Dict with file names vs lists of quantity paths
copy_neuroml = True,<|fim▁hole|> random.seed(seed) # To ensure same LEMS file (e.g. colours of plots) are generated every time for the same input
file_name_full = '%s/%s'%(target_dir,lems_file_name)
print_comment_v('Creating LEMS file at: %s for NeuroML 2 file: %s'%(file_name_full,neuroml_file))
ls = LEMSSimulation(sim_id, duration, dt, target)
nml_doc = read_neuroml2_file(neuroml_file, include_includes=True, verbose=True)
quantities_saved = []
if not copy_neuroml:
rel_nml_file = os.path.relpath(os.path.abspath(neuroml_file), os.path.abspath(target_dir))
print_comment_v("Including existing NeuroML file (%s) as: %s"%(neuroml_file, rel_nml_file))
ls.include_neuroml2_file(rel_nml_file, include_included=True, relative_to_dir=os.path.abspath(target_dir))
else:
print_comment_v("Copying NeuroML file (%s) to: %s (%s)"%(neuroml_file, target_dir, os.path.abspath(target_dir)))
if os.path.abspath(os.path.dirname(neuroml_file))!=os.path.abspath(target_dir):
shutil.copy(neuroml_file, target_dir)
neuroml_file_name = os.path.basename(neuroml_file)
ls.include_neuroml2_file(neuroml_file_name, include_included=False)
for include in nml_doc.includes:
incl_curr = '%s/%s'%(os.path.dirname(neuroml_file),include.href)
print_comment_v(' - Including %s located at %s'%(include.href, incl_curr))
shutil.copy(incl_curr, target_dir)
ls.include_neuroml2_file(include.href, include_included=False)
sub_doc = read_neuroml2_file(incl_curr)
for include in sub_doc.includes:
incl_curr = '%s/%s'%(os.path.dirname(neuroml_file),include.href)
print_comment_v(' -- Including %s located at %s'%(include.href, incl_curr))
shutil.copy(incl_curr, target_dir)
ls.include_neuroml2_file(include.href, include_included=False)
if gen_plots_for_all_v or gen_saves_for_all_v or len(gen_plots_for_only)>0 or len(gen_saves_for_only)>0 :
for network in nml_doc.networks:
for population in network.populations:
quantity_template = "%s[%i]/v"
component = population.component
size = population.size
cell = None
segment_ids = []
if plot_all_segments:
for c in nml_doc.cells:
if c.id == component:
cell = c
for segment in cell.morphology.segments:
segment_ids.append(segment.id)
segment_ids.sort()
if population.type and population.type == 'populationList':
quantity_template = "%s/%i/"+component+"/v"
size = len(population.instances)
if gen_plots_for_all_v or population.id in gen_plots_for_only:
print_comment('Generating %i plots for %s in population %s'%(size, component, population.id))
disp0 = 'DispPop__%s'%population.id
ls.create_display(disp0, "Voltages of %s"%disp0, "-90", "50")
for i in range(size):
if plot_all_segments:
quantity_template_seg = "%s/%i/"+component+"/%i/v"
for segment_id in segment_ids:
quantity = quantity_template_seg%(population.id, i, segment_id)
ls.add_line_to_display(disp0, "v in seg %i %s"%(segment_id,safe_variable(quantity)), quantity, "1mV", get_next_hex_color())
else:
quantity = quantity_template%(population.id, i)
ls.add_line_to_display(disp0, "v %s"%safe_variable(quantity), quantity, "1mV", get_next_hex_color())
if gen_saves_for_all_v or population.id in gen_saves_for_only:
print_comment('Saving %i values of v for %s in population %s'%(size, component, population.id))
of0 = 'Volts_file__%s'%population.id
ls.create_output_file(of0, "%s.%s.v.dat"%(sim_id,population.id))
for i in range(size):
if save_all_segments:
quantity_template_seg = "%s/%i/"+component+"/%i/v"
for segment_id in segment_ids:
quantity = quantity_template_seg%(population.id, i, segment_id)
ls.add_column_to_output_file(of0, 'v_%s'%safe_variable(quantity), quantity)
quantities_saved.append(quantity)
else:
quantity = quantity_template%(population.id, i)
ls.add_column_to_output_file(of0, 'v_%s'%safe_variable(quantity), quantity)
quantities_saved.append(quantity)
for display in gen_plots_for_quantities.keys():
quantities = gen_plots_for_quantities[display]
ls.create_display(display, "Plots of %s"%display, "-90", "50")
for q in quantities:
ls.add_line_to_display(display, safe_variable(q), q, "1", get_next_hex_color())
for file_name in gen_saves_for_quantities.keys():
quantities = gen_saves_for_quantities[file_name]
ls.create_output_file(file_name, file_name)
for q in quantities:
ls.add_column_to_output_file(file_name, safe_variable(q), q)
ls.save_to_file(file_name=file_name_full)
return quantities_saved
# Mainly for NEURON etc.
def safe_variable(quantity):
return quantity.replace(' ','_').replace('[','_').replace(']','_').replace('/','_')<|fim▁end|> | seed=None):
if seed: |
<|file_name|>siteProcessor.js<|end_file_name|><|fim▁begin|>import {first, uniq, compact, startsWith} from 'lodash'
import cheerio from 'cheerio'
import urijs from 'urijs'
import {flattenDeepCheerioElements} from 'utils'
export function getRelevantTags(htmlText, urlToFetch){
return new Promise((resolve, reject) => {
const doc = cheerio.load(htmlText, {
ignoreWhitespace: true,
decodeEntities: true,
lowerCaseTags: true,
lowerCaseAttributeNames: true,
recognizeCDATA: true,
recognizeSelfClosing: true
})
resolve({
title: extractTitle(doc) || '',
description: extractDescription(doc) || '',
imageUrls: extractImages(doc, urlToFetch)
})
})
}
function extractDescription(doc){
return first(compact([
doc("meta[name='description']").attr('content'),
doc("meta[property='og:description']").attr('content')
]))
}
function extractTitle(doc) {
return first(compact([
doc("meta[name='title']").attr('content'),
doc("meta[property='og:title']").attr('content'),
doc('title').text(),
]))
}
function extractImages(doc, urlToFetch) {
const imageUrls = flattenDeepCheerioElements([
doc("meta[name='image']").attr("content"),
doc("meta[property='og:image']").attr("content"),
doc("img").map((i, imgNode) => doc(imgNode).attr("src"))
])
return uniq(imageUrls
.map(imageUrl => imageUrl.replace('\\', '/'))
.map(imageUrl => {
const imageProtocol = urijs(imageUrl).protocol()
if(imageProtocol){
return imageUrl
}
if(startsWith(imageUrl, '//')){
const urlToFetchProtocol = urijs(urlToFetch).protocol()
return urijs(imageUrl).protocol(urlToFetchProtocol).toString()
}
<|fim▁hole|> })
)
}<|fim▁end|> | return urijs(imageUrl).absoluteTo(urlToFetch).toString() |
<|file_name|>winsock2.rs<|end_file_name|><|fim▁begin|>// Copyright © 2015, Peter Atashian
// Licensed under the MIT License <LICENSE.md>
//! This file contains the core definitions for the Winsock2 specification that can be used by
//! both user-mode and kernel mode modules.
use ctypes::{c_int, c_void, c_char, __int64, c_short};
use shared::guiddef::{LPGUID};
use shared::inaddr::{IN_ADDR};
use shared::minwindef::{INT, ULONG, DWORD, USHORT};
use um::winnt::{PWSTR, CHAR, PROCESSOR_NUMBER};
use vc::vcruntime::{size_t};
pub type ADDRESS_FAMILY = USHORT;
pub const AF_UNSPEC: c_int = 0;
pub const AF_UNIX: c_int = 1;
pub const AF_INET: c_int = 2;
pub const AF_IMPLINK: c_int = 3;
pub const AF_PUP: c_int = 4;
pub const AF_CHAOS: c_int = 5;
pub const AF_NS: c_int = 6;
pub const AF_IPX: c_int = AF_NS;
pub const AF_ISO: c_int = 7;
pub const AF_OSI: c_int = AF_ISO;
pub const AF_ECMA: c_int = 8;
pub const AF_DATAKIT: c_int = 9;
pub const AF_CCITT: c_int = 10;
pub const AF_SNA: c_int = 11;
pub const AF_DECnet: c_int = 12;
pub const AF_DLI: c_int = 13;
pub const AF_LAT: c_int = 14;
pub const AF_HYLINK: c_int = 15;
pub const AF_APPLETALK: c_int = 16;
pub const AF_NETBIOS: c_int = 17;
pub const AF_VOICEVIEW: c_int = 18;
pub const AF_FIREFOX: c_int = 19;
pub const AF_UNKNOWN1: c_int = 20;
pub const AF_BAN: c_int = 21;
pub const AF_ATM: c_int = 22;
pub const AF_INET6: c_int = 23;
pub const AF_CLUSTER: c_int = 24;
pub const AF_12844: c_int = 25;
pub const AF_IRDA: c_int = 26;
pub const AF_NETDES: c_int = 28;
pub const AF_TCNPROCESS: c_int = 29;
pub const AF_TCNMESSAGE: c_int = 30;
pub const AF_ICLFXBM: c_int = 31;
pub const AF_BTH: c_int = 32;
pub const AF_LINK: c_int = 33;
pub const AF_MAX: c_int = 34;
pub const SOCK_STREAM: c_int = 1;
pub const SOCK_DGRAM: c_int = 2;
pub const SOCK_RAW: c_int = 3;
pub const SOCK_RDM: c_int = 4;
pub const SOCK_SEQPACKET: c_int = 5;
pub const SOL_SOCKET: c_int = 0xffff;
pub const SO_DEBUG: c_int = 0x0001;
pub const SO_ACCEPTCONN: c_int = 0x0002;
pub const SO_REUSEADDR: c_int = 0x0004;
pub const SO_KEEPALIVE: c_int = 0x0008;
pub const SO_DONTROUTE: c_int = 0x0010;
pub const SO_BROADCAST: c_int = 0x0020;
pub const SO_USELOOPBACK: c_int = 0x0040;
pub const SO_LINGER: c_int = 0x0080;
pub const SO_OOBINLINE: c_int = 0x0100;
pub const SO_DONTLINGER: c_int = !SO_LINGER;
pub const SO_EXCLUSIVEADDRUSE: c_int = !SO_REUSEADDR;
pub const SO_SNDBUF: c_int = 0x1001;
pub const SO_RCVBUF: c_int = 0x1002;
pub const SO_SNDLOWAT: c_int = 0x1003;
pub const SO_RCVLOWAT: c_int = 0x1004;
pub const SO_SNDTIMEO: c_int = 0x1005;
pub const SO_RCVTIMEO: c_int = 0x1006;
pub const SO_ERROR: c_int = 0x1007;
pub const SO_TYPE: c_int = 0x1008;
pub const SO_BSP_STATE: c_int = 0x1009;
pub const SO_GROUP_ID: c_int = 0x2001;
pub const SO_GROUP_PRIORITY: c_int = 0x2002;
pub const SO_MAX_MSG_SIZE: c_int = 0x2003;
pub const SO_CONDITIONAL_ACCEPT: c_int = 0x3002;
pub const SO_PAUSE_ACCEPT: c_int = 0x3003;
pub const SO_COMPARTMENT_ID: c_int = 0x3004;
pub const SO_RANDOMIZE_PORT: c_int = 0x3005;
pub const SO_PORT_SCALABILITY: c_int = 0x3006;
pub const WSK_SO_BASE: c_int = 0x4000;
pub const TCP_NODELAY: c_int = 0x0001;
STRUCT!{struct SOCKADDR {
sa_family: ADDRESS_FAMILY,
sa_data: [CHAR; 14],
}}
pub type PSOCKADDR = *mut SOCKADDR;
pub type LPSOCKADDR = *mut SOCKADDR;
STRUCT!{struct SOCKET_ADDRESS {
lpSockaddr: LPSOCKADDR,
iSockaddrLength: INT,
}}
pub type PSOCKET_ADDRESS = *mut SOCKET_ADDRESS;
pub type LPSOCKET_ADDRESS = *mut SOCKET_ADDRESS;
STRUCT!{struct SOCKET_ADDRESS_LIST {
iAddressCount: INT,
Address: [SOCKET_ADDRESS; 0],
}}
pub type PSOCKET_ADDRESS_LIST = *mut SOCKET_ADDRESS_LIST;
pub type LPSOCKET_ADDRESS_LIST = *mut SOCKET_ADDRESS_LIST;
STRUCT!{struct CSADDR_INFO {
LocalAddr: SOCKET_ADDRESS,
RemoteAddr: SOCKET_ADDRESS,
iSocketType: INT,
iProtocol: INT,
}}
pub type PCSADDR_INFO = *mut CSADDR_INFO;
pub type LPCSADDR_INFO = *mut CSADDR_INFO;
STRUCT!{struct SOCKADDR_STORAGE_LH {
ss_family: ADDRESS_FAMILY,
__ss_pad1: [CHAR; 6],
__ss_align: __int64,
__ss_pad2: [CHAR; 112],
}}
pub type PSOCKADDR_STORAGE_LH = *mut SOCKADDR_STORAGE_LH;
pub type LPSOCKADDR_STORAGE_LH = *mut SOCKADDR_STORAGE_LH;
STRUCT!{struct SOCKADDR_STORAGE_XP {
ss_family: c_short,
__ss_pad1: [CHAR; 6],
__ss_align: __int64,
__ss_pad2: [CHAR; 112],
}}
pub type PSOCKADDR_STORAGE_XP = *mut SOCKADDR_STORAGE_XP;
pub type LPSOCKADDR_STORAGE_XP = *mut SOCKADDR_STORAGE_XP;
pub type SOCKADDR_STORAGE = SOCKADDR_STORAGE_LH;
pub type PSOCKADDR_STORAGE = *mut SOCKADDR_STORAGE;
pub type LPSOCKADDR_STORAGE = *mut SOCKADDR_STORAGE;
STRUCT!{struct SOCKET_PROCESSOR_AFFINITY {
Processor: PROCESSOR_NUMBER,
NumaNodeId: USHORT,
Reserved: USHORT,
}}
pub type PSOCKET_PROCESSOR_AFFINITY = *mut SOCKET_PROCESSOR_AFFINITY;
pub const IOC_UNIX: DWORD = 0x00000000;
pub const IOC_WS2: DWORD = 0x08000000;
pub const IOC_PROTOCOL: DWORD = 0x10000000;
pub const IOC_VENDOR: DWORD = 0x18000000;
pub const IOC_WSK: DWORD = IOC_WS2 | 0x07000000;
macro_rules! _WSAIO { ($x:expr, $y:expr) => { IOC_VOID | $x | $y } }
macro_rules! _WSAIOR { ($x:expr, $y:expr) => { IOC_OUT | $x | $y } }
macro_rules! _WSAIOW { ($x:expr, $y:expr) => { IOC_IN | $x | $y } }
macro_rules! _WSAIORW { ($x:expr, $y:expr) => { IOC_INOUT | $x | $y } }
pub const SIO_ASSOCIATE_HANDLE: DWORD = _WSAIOW!(IOC_WS2, 1);
pub const SIO_ENABLE_CIRCULAR_QUEUEING: DWORD = _WSAIO!(IOC_WS2, 2);
pub const SIO_FIND_ROUTE: DWORD = _WSAIOR!(IOC_WS2, 3);
pub const SIO_FLUSH: DWORD = _WSAIO!(IOC_WS2, 4);
pub const SIO_GET_BROADCAST_ADDRESS: DWORD = _WSAIOR!(IOC_WS2, 5);<|fim▁hole|>pub const SIO_GET_QOS: DWORD = _WSAIORW!(IOC_WS2, 7);
pub const SIO_GET_GROUP_QOS: DWORD = _WSAIORW!(IOC_WS2, 8);
pub const SIO_MULTIPOINT_LOOPBACK: DWORD = _WSAIOW!(IOC_WS2, 9);
pub const SIO_MULTICAST_SCOPE: DWORD = _WSAIOW!(IOC_WS2, 10);
pub const SIO_SET_QOS: DWORD = _WSAIOW!(IOC_WS2, 11);
pub const SIO_SET_GROUP_QOS: DWORD = _WSAIOW!(IOC_WS2, 12);
pub const SIO_TRANSLATE_HANDLE: DWORD = _WSAIORW!(IOC_WS2, 13);
pub const SIO_ROUTING_INTERFACE_QUERY: DWORD = _WSAIORW!(IOC_WS2, 20);
pub const SIO_ROUTING_INTERFACE_CHANGE: DWORD = _WSAIOW!(IOC_WS2, 21);
pub const SIO_ADDRESS_LIST_QUERY: DWORD = _WSAIOR!(IOC_WS2, 22);
pub const SIO_ADDRESS_LIST_CHANGE: DWORD = _WSAIO!(IOC_WS2, 23);
pub const SIO_QUERY_TARGET_PNP_HANDLE: DWORD = _WSAIOR!(IOC_WS2, 24);
pub const SIO_QUERY_RSS_PROCESSOR_INFO: DWORD = _WSAIOR!(IOC_WS2, 37);
pub const SIO_ADDRESS_LIST_SORT: DWORD = _WSAIORW!(IOC_WS2, 25);
pub const SIO_RESERVED_1: DWORD = _WSAIOW!(IOC_WS2, 26);
pub const SIO_RESERVED_2: DWORD = _WSAIOW!(IOC_WS2, 33);
pub const SIO_GET_MULTIPLE_EXTENSION_FUNCTION_POINTER: DWORD = _WSAIORW!(IOC_WS2, 36);
pub const IPPROTO_IP: c_int = 0;
ENUM!{enum IPPROTO {
IPPROTO_HOPOPTS = 0, // IPv6 Hop-by-Hop options
IPPROTO_ICMP = 1,
IPPROTO_IGMP = 2,
IPPROTO_GGP = 3,
IPPROTO_IPV4 = 4,
IPPROTO_ST = 5,
IPPROTO_TCP = 6,
IPPROTO_CBT = 7,
IPPROTO_EGP = 8,
IPPROTO_IGP = 9,
IPPROTO_PUP = 12,
IPPROTO_UDP = 17,
IPPROTO_IDP = 22,
IPPROTO_RDP = 27,
IPPROTO_IPV6 = 41, // IPv6 header
IPPROTO_ROUTING = 43, // IPv6 Routing header
IPPROTO_FRAGMENT = 44, // IPv6 fragmentation header
IPPROTO_ESP = 50, // encapsulating security payload
IPPROTO_AH = 51, // authentication header
IPPROTO_ICMPV6 = 58, // ICMPv6
IPPROTO_NONE = 59, // IPv6 no next header
IPPROTO_DSTOPTS = 60, // IPv6 Destination options
IPPROTO_ND = 77,
IPPROTO_ICLFXBM = 78,
IPPROTO_PIM = 103,
IPPROTO_PGM = 113,
IPPROTO_L2TP = 115,
IPPROTO_SCTP = 132,
IPPROTO_RAW = 255,
IPPROTO_MAX = 256,
IPPROTO_RESERVED_RAW = 257,
IPPROTO_RESERVED_IPSEC = 258,
IPPROTO_RESERVED_IPSECOFFLOAD = 259,
IPPROTO_RESERVED_WNV = 260,
IPPROTO_RESERVED_MAX = 261,
}}
pub type PIPPROTO = *mut IPPROTO;
STRUCT!{struct SOCKADDR_IN {
sin_family: ADDRESS_FAMILY,
sin_port: USHORT,
sin_addr: IN_ADDR,
sin_zero: [CHAR; 8],
}}
pub type PSOCKADDR_IN = *mut SOCKADDR_IN;
//645
pub const IOCPARM_MASK: DWORD = 0x7f;
pub const IOC_VOID: DWORD = 0x20000000;
pub const IOC_OUT: DWORD = 0x40000000;
pub const IOC_IN: DWORD = 0x80000000;
pub const IOC_INOUT: DWORD = IOC_IN | IOC_OUT;
STRUCT!{struct WSABUF {
len: ULONG,
buf: *mut CHAR,
}}
pub type LPWSABUF = *mut WSABUF;
STRUCT!{struct WSAMSG {
name: LPSOCKADDR,
namelen: INT,
lpBuffers: LPWSABUF,
dwBufferCount: ULONG,
Control: WSABUF,
dwFlags: ULONG,
}}
pub type PWSAMSG = *mut WSAMSG;
pub type LPWSAMSG = *mut WSAMSG;
STRUCT!{struct ADDRINFOA {
ai_flags: c_int,
ai_family: c_int,
ai_socktype: c_int,
ai_protocol: c_int,
ai_addrlen: size_t,
ai_canonname: *mut c_char,
ai_addr: *mut SOCKADDR,
ai_next: *mut ADDRINFOA,
}}
pub type PADDRINFOA = *mut ADDRINFOA;
STRUCT!{struct ADDRINFOW {
ai_flags: c_int,
ai_family: c_int,
ai_socktype: c_int,
ai_protocol: c_int,
ai_addrlen: size_t,
ai_canonname: PWSTR,
ai_addr: *mut SOCKADDR,
ai_next: *mut ADDRINFOW,
}}
pub type PADDRINFOW = *mut ADDRINFOW;
STRUCT!{struct ADDRINFOEXA {
ai_flags: c_int,
ai_family: c_int,
ai_socktype: c_int,
ai_protocol: c_int,
ai_addrlen: size_t,
ai_canonname: *mut c_char,
ai_addr: *mut SOCKADDR,
ai_blob: *mut c_void,
ai_bloblen: size_t,
ai_provider: LPGUID,
ai_next: *mut ADDRINFOEXW,
}}
pub type PADDRINFOEXA = *mut ADDRINFOEXA;
pub type LPADDRINFOEXA = *mut ADDRINFOEXA;
STRUCT!{struct ADDRINFOEXW {
ai_flags: c_int,
ai_family: c_int,
ai_socktype: c_int,
ai_protocol: c_int,
ai_addrlen: size_t,
ai_canonname: PWSTR,
ai_addr: *mut SOCKADDR,
ai_blob: *mut c_void,
ai_bloblen: size_t,
ai_provider: LPGUID,
ai_next: *mut ADDRINFOEXW,
}}
pub type PADDRINFOEXW = *mut ADDRINFOEXW;
pub type LPADDRINFOEXW = *mut ADDRINFOEXW;<|fim▁end|> | pub const SIO_GET_EXTENSION_FUNCTION_POINTER: DWORD = _WSAIORW!(IOC_WS2, 6); |
<|file_name|>serverstats_cmd.go<|end_file_name|><|fim▁begin|>package main
import (
"fmt"
"github.com/aleasoluciones/serverstats"
)
func main() {
serverStats := serverstats.NewServerStats(serverstats.DefaultPeriodes)
for metric := range serverStats.Metrics {
fmt.Println(metric.Timestamp, fmt.Sprintf("%-15s", metric.Name), metric.Value, metric.Unit)<|fim▁hole|>
}<|fim▁end|> | } |
<|file_name|>imgui.cpp<|end_file_name|><|fim▁begin|>// dear imgui, v1.71 WIP
// (main code and documentation)
// Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code.
// Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
// Get latest version at https://github.com/ocornut/imgui
// Releases change-log at https://github.com/ocornut/imgui/releases
// Technical Support for Getting Started https://discourse.dearimgui.org/c/getting-started
// Gallery (please post your screenshots/video there!): https://github.com/ocornut/imgui/issues/1269
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
// See LICENSE.txt for copyright and licensing details (standard MIT License).
// This library is free but I need your support to sustain development and maintenance.
// Businesses: you can support continued maintenance and development via support contracts or sponsoring, see docs/README.
// Individuals: you can support continued maintenance and development via donations or Patreon https://www.patreon.com/imgui.
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
// to a better solution or official support for them.
/*
Index of this file:
DOCUMENTATION
- MISSION STATEMENT
- END-USER GUIDE
- PROGRAMMER GUIDE (read me!)
- Read first.
- How to update to a newer version of Dear ImGui.
- Getting started with integrating Dear ImGui in your code/engine.
- This is how a simple application may look like (2 variations).
- This is how a simple rendering function may look like.
- Using gamepad/keyboard navigation controls.
- API BREAKING CHANGES (read me when you update!)
- FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
- Where is the documentation?
- Which version should I get?
- Who uses Dear ImGui?
- Why the odd dual naming, "Dear ImGui" vs "ImGui"?
- How can I tell whether to dispatch mouse/keyboard to imgui or to my application?
- How can I display an image? What is ImTextureID, how does it works?
- Why are multiple widgets reacting when I interact with a single one? How can I have
multiple widgets with the same label or with an empty label? A primer on labels and the ID Stack...
- How can I use my own math types instead of ImVec2/ImVec4?
- How can I load a different font than the default?
- How can I easily use icons in my application?
- How can I load multiple fonts?
- How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic?
- How can I interact with standard C++ types (such as std::string and std::vector)?
- How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
- How can I use Dear ImGui on a platform that doesn't have a mouse or a keyboard? (input share, remoting, gamepad)
- I integrated Dear ImGui in my engine and the text or lines are blurry..
- I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
- How can I help?
CODE
(search for "[SECTION]" in the code to find them)
// [SECTION] FORWARD DECLARATIONS
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
// [SECTION] MAIN USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
// [SECTION] MISC HELPERS/UTILITIES (Maths, String, Format, Hash, File functions)
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
// [SECTION] ImGuiStorage
// [SECTION] ImGuiTextFilter
// [SECTION] ImGuiTextBuffer
// [SECTION] ImGuiListClipper
// [SECTION] RENDER HELPERS
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
// [SECTION] TOOLTIPS
// [SECTION] POPUPS
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
// [SECTION] COLUMNS
// [SECTION] DRAG AND DROP
// [SECTION] LOGGING/CAPTURING
// [SECTION] SETTINGS
// [SECTION] PLATFORM DEPENDENT HELPERS
// [SECTION] METRICS/DEBUG WINDOW
*/
//-----------------------------------------------------------------------------
// DOCUMENTATION
//-----------------------------------------------------------------------------
/*
MISSION STATEMENT
=================
- Easy to use to create code-driven and data-driven tools.
- Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
- Easy to hack and improve.
- Minimize screen real-estate usage.
- Minimize setup and maintenance.
- Minimize state storage on user side.
- Portable, minimize dependencies, run on target (consoles, phones, etc.).
- Efficient runtime and memory consumption (NB- we do allocate when "growing" content e.g. creating a window,.
opening a tree node for the first time, etc. but a typical frame should not allocate anything).
Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes:
- Doesn't look fancy, doesn't animate.
- Limited layout features, intricate layouts are typically crafted in code.
END-USER GUIDE
==============
- Double-click on title bar to collapse window.
- Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin().
- Click and drag on lower right corner to resize window (double-click to auto fit window to its contents).
- Click and drag on any empty space to move window.
- TAB/SHIFT+TAB to cycle through keyboard editable fields.
- CTRL+Click on a slider or drag box to input value as text.
- Use mouse wheel to scroll.
- Text editor:
- Hold SHIFT or use mouse to select text.
- CTRL+Left/Right to word jump.
- CTRL+Shift+Left/Right to select words.
- CTRL+A our Double-Click to select all.
- CTRL+X,CTRL+C,CTRL+V to use OS clipboard/
- CTRL+Z,CTRL+Y to undo/redo.
- ESCAPE to revert text to its original value.
- You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!)
- Controls are automatically adjusted for OSX to match standard OSX text editing operations.
- General Keyboard controls: enable with ImGuiConfigFlags_NavEnableKeyboard.
- General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. See suggested mappings in imgui.h ImGuiNavInput_ + download PNG/PSD at http://goo.gl/9LgVZW
PROGRAMMER GUIDE
================
READ FIRST:
- Read the FAQ below this section!
- Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction
or destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, less bugs.
- Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
- The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
- Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links docs/README.md.
- Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
For every application frame your UI code will be called only once. This is in contrast to e.g. Unity's own implementation of an IMGUI,
where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
- Our origin are on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
- This codebase is also optimized to yield decent performances with typical "Debug" builds settings.
- Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
If you get an assert, read the messages and comments around the assert.
- C++: this is a very C-ish codebase: we don't rely on C++11, we don't include any C++ headers, and ImGui:: is a namespace.
- C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase.
- C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!).
HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI:
- Overwrite all the sources files except for imconfig.h (if you have made modification to your copy of imconfig.h)
- Or maintain your own branch where you have imconfig.h modified.
- Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
likely be a comment about it. Please report any issue to the GitHub page!
- Try to keep your copy of dear imgui reasonably up to date.
GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE:
- Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
- Add the Dear ImGui source files to your projects or using your preferred build system.
It is recommended you build and statically link the .cpp files as part of your project and not as shared library (DLL).
- You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating imgui types with your own maths types.
- When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
- Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
phases of your own application. All rendering informatioe are stored into command-lists that you will retrieve after calling ImGui::Render().
- Refer to the bindings and demo applications in the examples/ folder for instruction on how to setup your code.
- If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
HOW A SIMPLE APPLICATION MAY LOOK LIKE:
EXHIBIT 1: USING THE EXAMPLE BINDINGS (imgui_impl_XXX.cpp files from the examples/ folder).
// Application init: create a dear imgui context, setup some options, load fonts
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
// TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
// TODO: Fill optional fields of the io structure later.
// TODO: Load TTF/OTF fonts if you don't want to use the default font.
// Initialize helper Platform and Renderer bindings (here we are using imgui_impl_win32 and imgui_impl_dx11)
ImGui_ImplWin32_Init(hwnd);
ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
// Application main loop
while (true)
{
// Feed inputs to dear imgui, start new frame
ImGui_ImplDX11_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
// Any application code here
ImGui::Text("Hello, world!");
// Render dear imgui into screen
ImGui::Render();
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
g_pSwapChain->Present(1, 0);
}
// Shutdown
ImGui_ImplDX11_Shutdown();
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext();
HOW A SIMPLE APPLICATION MAY LOOK LIKE:
EXHIBIT 2: IMPLEMENTING CUSTOM BINDING / CUSTOM ENGINE.
// Application init: create a dear imgui context, setup some options, load fonts
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
// TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
// TODO: Fill optional fields of the io structure later.
// TODO: Load TTF/OTF fonts if you don't want to use the default font.
// Build and load the texture atlas into a texture
// (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
int width, height;
unsigned char* pixels = NULL;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
// At this point you've got the texture data and you need to upload that your your graphic system:
// After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
// This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ below for details about ImTextureID.
MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
io.Fonts->TexID = (void*)texture;
// Application main loop
while (true)
{
// Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
// (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform bindings)
io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds)
io.DisplaySize.x = 1920.0f; // set the current display width
io.DisplaySize.y = 1280.0f; // set the current display height here
io.MousePos = my_mouse_pos; // set the mouse position
io.MouseDown[0] = my_mouse_buttons[0]; // set the mouse button states
io.MouseDown[1] = my_mouse_buttons[1];
// Call NewFrame(), after this point you can use ImGui::* functions anytime
// (So you want to try calling NewFrame() as early as you can in your mainloop to be able to use imgui everywhere)
ImGui::NewFrame();
// Most of your application code here
ImGui::Text("Hello, world!");
MyGameUpdate(); // may use any ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
MyGameRender(); // may use any ImGui functions as well!
// Render imgui, swap buffers
// (You want to try calling EndFrame/Render as late as you can, to be able to use imgui in your own game rendering code)
ImGui::EndFrame();
ImGui::Render();
ImDrawData* draw_data = ImGui::GetDrawData();
MyImGuiRenderFunction(draw_data);
SwapBuffers();
}
// Shutdown
ImGui::DestroyContext();
HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE:
void void MyImGuiRenderFunction(ImDrawData* draw_data)
{
// TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
// TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
// TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
// TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by ImGui
const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by ImGui
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback)
{
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
// The texture for the draw call is specified by pcmd->TextureId.
// The vast majority of draw calls will use the imgui texture atlas, which value you have set yourself during initialization.
MyEngineBindTexture((MyTexture*)pcmd->TextureId);
// We are using scissoring to clip some objects. All low-level graphics API should supports it.
// - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
// (some elements visible outside their bounds) but you can fix that once everything else works!
// - Clipping coordinates are provided in imgui coordinates space (from draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize)
// In a single viewport application, draw_data->DisplayPos will always be (0,0) and draw_data->DisplaySize will always be == io.DisplaySize.
// However, in the interest of supporting multi-viewport applications in the future (see 'viewport' branch on github),
// always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
// - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
ImVec2 pos = draw_data->DisplayPos;
MyEngineScissor((int)(pcmd->ClipRect.x - pos.x), (int)(pcmd->ClipRect.y - pos.y), (int)(pcmd->ClipRect.z - pos.x), (int)(pcmd->ClipRect.w - pos.y));
// Render 'pcmd->ElemCount/3' indexed triangles.
// By default the indices ImDrawIdx are 16-bits, you can change them to 32-bits in imconfig.h if your engine doesn't support 16-bits indices.
MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer);
}
idx_buffer += pcmd->ElemCount;
}
}
}
- The examples/ folders contains many actual implementation of the pseudo-codes above.
- When calling NewFrame(), the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags are updated.
They tell you if Dear ImGui intends to use your inputs. When a flag is set you want to hide the corresponding inputs
from the rest of your application. In every cases you need to pass on the inputs to imgui. Refer to the FAQ for more information.
- Please read the FAQ below!. Amusingly, it is called a FAQ because people frequently run into the same issues!
USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
- The gamepad/keyboard navigation is fairly functional and keeps being improved.
- Gamepad support is particularly useful to use dear imgui on a console system (e.g. PS4, Switch, XB1) without a mouse!
- You can ask questions and report issues at https://github.com/ocornut/imgui/issues/787
- The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable.
- Gamepad:
- Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable.
- Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + fill the io.NavInputs[] fields before calling NewFrame().
Note that io.NavInputs[] is cleared by EndFrame().
- See 'enum ImGuiNavInput_' in imgui.h for a description of inputs. For each entry of io.NavInputs[], set the following values:
0.0f= not held. 1.0f= fully held. Pass intermediate 0.0f..1.0f values for analog triggers/sticks.
- We uses a simple >0.0f test for activation testing, and won't attempt to test for a dead-zone.
Your code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
- You can download PNG/PSD files depicting the gamepad controls for common controllers at: http://goo.gl/9LgVZW.
- If you need to share inputs between your game and the imgui parts, the easiest approach is to go all-or-nothing, with a buttons combo
to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
- Keyboard:
- Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable.
NewFrame() will automatically fill io.NavInputs[] based on your io.KeysDown[] + io.KeyMap[] arrays.
- When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard), the io.WantCaptureKeyboard flag
will be set. For more advanced uses, you may want to read from:
- io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
- io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used).
- or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions.
Please reach out if you think the game vs navigation input sharing could be improved.
- Mouse:
- PS4 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback.
- Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + uSynergy.c (on your console/tablet/phone app) to share your PC mouse/keyboard.
- On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs dear imgui to move your mouse cursor along with navigation movements.
When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
When that happens your back-end NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the binding in examples/ do that.
(If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, imgui will misbehave as it will see your mouse as moving back and forth!)
(In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
to set a boolean to ignore your other external mouse positions until the external source is moved again.)
API BREAKING CHANGES
====================
Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
You can read releases logs https://github.com/ocornut/imgui/releases for more details.
- 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
- 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
- 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
- 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
- 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
- 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with a dummy small value!
- 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
- 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
- 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Keep redirection typedef (will obsolete).
- 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
- 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
- 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
- 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
- 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
- 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
- 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
- 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
- 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
- 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
- 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
- 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
- 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
- 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
- 2018/06/08 (1.62) - examples: the imgui_impl_xxx files have been split to separate platform (Win32, Glfw, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan, etc.).
old bindings will still work as is, however prefer using the separated bindings as they will be updated to support multi-viewports.
when adopting new bindings follow the main.cpp code of your preferred examples/ folder to know which functions to call.
in particular, note that old bindings called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
- 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
- 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
- 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
- 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
consistent with other functions. Kept redirection functions (will obsolete).
- 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
- 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some binding ahead of merging the Nav branch).
- 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
- 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
- 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
- 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
- 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
- 2018/02/07 (1.60) - reorganized context handling to be more explicit,
- YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
- removed Shutdown() function, as DestroyContext() serve this purpose.
- you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
- removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
- removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
- 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
- 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
- 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
- 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
- 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
- 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
- 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
- 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
- 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
- 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
- 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
- obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
- 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
- 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
- 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
- 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
- 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
- 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
- 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
- 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
- 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
- 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
- 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
- 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
- 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
- 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Keep redirection typedef (will obsolete).
- 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
- 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your binding if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
- 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
- renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
- renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
- 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
- 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
- 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame.
- 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
- 2017/08/13 (1.51) - renamed ImGuiCol_Columns*** to ImGuiCol_Separator***. Kept redirection enums (will obsolete).
- 2017/08/11 (1.51) - renamed ImGuiSetCond_*** types and flags to ImGuiCond_***. Kept redirection enums (will obsolete).
- 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
- 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
- changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
- changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0))'
- 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
- 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
- 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
- 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetId() and use it instead of passing string to BeginChild().
- 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
- 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
- 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully breakage should be minimal.
- 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you.
If your TitleBg/TitleBgActive alpha was <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color.
ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col)
{
float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a;
return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a);
}
If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
- 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
- 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
- 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
- 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
- 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref github issue #337).
- 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
- 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
- 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
- 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
- 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
- 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
- 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
- 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
- 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
- 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
- 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
- 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
- if you are using a vanilla copy of one of the imgui_impl_XXXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
- the signature of the io.RenderDrawListsFn handler has changed!
old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
- each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
- if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
- refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
- 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
- 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
- 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
- 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
- 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely be used. Sorry!
- 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
- 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
- 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
- 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
- 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
- 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
- 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
- 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
- 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
- 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
- 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
- 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
- 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
- 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
- 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
- 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
- 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
- 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
- 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
- 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
- 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
(1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
font init: { const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); <..Upload texture to GPU..>; }
became: { unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); <..Upload texture to GPU>; io.Fonts->TexId = YourTextureIdentifier; }
you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs.
it is now recommended that you sample the font texture with bilinear interpolation.
(1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID.
(1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
(1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
- 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
- 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
- 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
- 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
- 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
- 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
- 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
- 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
- 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
- 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
- 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
======================================
Q: Where is the documentation?
A: This library is poorly documented at the moment and expects of the user to be acquainted with C/C++.
- Run the examples/ and explore them.
- See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
- The demo covers most features of Dear ImGui, so you can read the code and see its output.
- See documentation and comments at the top of imgui.cpp + effectively imgui.h.
- Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the examples/
folder to explain how to integrate Dear ImGui with your own engine/application.
- Your programming IDE is your friend, find the type or function declaration to find comments
associated to it.
Q: Which version should I get?
A: I occasionally tag Releases (https://github.com/ocornut/imgui/releases) but it is generally safe
and recommended to sync to master/latest. The library is fairly stable and regressions tend to be
fixed fast when reported. You may also peak at the 'docking' branch which includes:
- Docking/Merging features (https://github.com/ocornut/imgui/issues/2109)
- Multi-viewport features (https://github.com/ocornut/imgui/issues/1542)
Many projects are using this branch and it is kept in sync with master regularly.
Q: Who uses Dear ImGui?
A: See "Quotes" (https://github.com/ocornut/imgui/wiki/Quotes) and
"Software using Dear ImGui" (https://github.com/ocornut/imgui/wiki/Software-using-dear-imgui) Wiki pages
for a list of games/software which are publicly known to use dear imgui. Please add yours if you can!
Q: Why the odd dual naming, "Dear ImGui" vs "ImGui"?
A: The library started its life as "ImGui" due to the fact that I didn't give it a proper name when
when I released 1.0, and had no particular expectation that it would take off. However, the term IMGUI
(immediate-mode graphical user interface) was coined before and is being used in variety of other
situations (e.g. Unity uses it own implementation of the IMGUI paradigm).
To reduce the ambiguity without affecting existing code bases, I have decided on an alternate,
longer name "Dear ImGui" that people can use to refer to this specific library.
Please try to refer to this library as "Dear ImGui".
Q: How can I tell whether to dispatch mouse/keyboard to imgui or to my application?
A: You can read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags from the ImGuiIO structure (e.g. if (ImGui::GetIO().WantCaptureMouse) { ... } )
- When 'io.WantCaptureMouse' is set, imgui wants to use your mouse state, and you may want to discard/hide the inputs from the rest of your application.
- When 'io.WantCaptureKeyboard' is set, imgui wants to use your keyboard state, and you may want to discard/hide the inputs from the rest of your application.
- When 'io.WantTextInput' is set to may want to notify your OS to popup an on-screen keyboard, if available (e.g. on a mobile phone, or console OS).
Note: you should always pass your mouse/keyboard inputs to imgui, even when the io.WantCaptureXXX flag are set false.
This is because imgui needs to detect that you clicked in the void to unfocus its own windows.
Note: The 'io.WantCaptureMouse' is more accurate that any attempt to "check if the mouse is hovering a window" (don't do that!).
It handle mouse dragging correctly (both dragging that started over your application or over an imgui window) and handle e.g. modal windows blocking inputs.
Those flags are updated by ImGui::NewFrame(). Preferably read the flags after calling NewFrame() if you can afford it, but reading them before is also
perfectly fine, as the bool toggle fairly rarely. If you have on a touch device, you might find use for an early call to UpdateHoveredWindowAndCaptureFlags().
Note: Text input widget releases focus on "Return KeyDown", so the subsequent "Return KeyUp" event that your application receive will typically
have 'io.WantCaptureKeyboard=false'. Depending on your application logic it may or not be inconvenient. You might want to track which key-downs
were targeted for Dear ImGui, e.g. with an array of bool, and filter out the corresponding key-ups.)
Q: How can I display an image? What is ImTextureID, how does it works?
A: Short explanation:
- You may use functions such as ImGui::Image(), ImGui::ImageButton() or lower-level ImDrawList::AddImage() to emit draw calls that will use your own textures.
- Actual textures are identified in a way that is up to the user/engine. Those identifiers are stored and passed as ImTextureID (void*) value.
- Loading image files from the disk and turning them into a texture is not within the scope of Dear ImGui (for a good reason).
Please read documentations or tutorials on your graphics API to understand how to display textures on the screen before moving onward.
Long explanation:
- Dear ImGui's job is to create "meshes", defined in a renderer-agnostic format made of draw commands and vertices.
At the end of the frame those meshes (ImDrawList) will be displayed by your rendering function. They are made up of textured polygons and the code
to render them is generally fairly short (a few dozen lines). In the examples/ folder we provide functions for popular graphics API (OpenGL, DirectX, etc.).
- Each rendering function decides on a data type to represent "textures". The concept of what is a "texture" is entirely tied to your underlying engine/graphics API.
We carry the information to identify a "texture" in the ImTextureID type.
ImTextureID is nothing more that a void*, aka 4/8 bytes worth of data: just enough to store 1 pointer or 1 integer of your choice.
Dear ImGui doesn't know or understand what you are storing in ImTextureID, it merely pass ImTextureID values until they reach your rendering function.
- In the examples/ bindings, for each graphics API binding we decided on a type that is likely to be a good representation for specifying
an image from the end-user perspective. This is what the _examples_ rendering functions are using:
OpenGL: ImTextureID = GLuint (see ImGui_ImplGlfwGL3_RenderDrawData() function in imgui_impl_glfw_gl3.cpp)
DirectX9: ImTextureID = LPDIRECT3DTEXTURE9 (see ImGui_ImplDX9_RenderDrawData() function in imgui_impl_dx9.cpp)
DirectX11: ImTextureID = ID3D11ShaderResourceView* (see ImGui_ImplDX11_RenderDrawData() function in imgui_impl_dx11.cpp)
DirectX12: ImTextureID = D3D12_GPU_DESCRIPTOR_HANDLE (see ImGui_ImplDX12_RenderDrawData() function in imgui_impl_dx12.cpp)
For example, in the OpenGL example binding we store raw OpenGL texture identifier (GLuint) inside ImTextureID.
Whereas in the DirectX11 example binding we store a pointer to ID3D11ShaderResourceView inside ImTextureID, which is a higher-level structure
tying together both the texture and information about its format and how to read it.
- If you have a custom engine built over e.g. OpenGL, instead of passing GLuint around you may decide to use a high-level data type to carry information about
the texture as well as how to display it (shaders, etc.). The decision of what to use as ImTextureID can always be made better knowing how your codebase
is designed. If your engine has high-level data types for "textures" and "material" then you may want to use them.
If you are starting with OpenGL or DirectX or Vulkan and haven't built much of a rendering engine over them, keeping the default ImTextureID
representation suggested by the example bindings is probably the best choice.
(Advanced users may also decide to keep a low-level type in ImTextureID, and use ImDrawList callback and pass information to their renderer)
User code may do:
// Cast our texture type to ImTextureID / void*
MyTexture* texture = g_CoffeeTableTexture;
ImGui::Image((void*)texture, ImVec2(texture->Width, texture->Height));
The renderer function called after ImGui::Render() will receive that same value that the user code passed:
// Cast ImTextureID / void* stored in the draw command as our texture type
MyTexture* texture = (MyTexture*)pcmd->TextureId;
MyEngineBindTexture2D(texture);
Once you understand this design you will understand that loading image files and turning them into displayable textures is not within the scope of Dear ImGui.
This is by design and is actually a good thing, because it means your code has full control over your data types and how you display them.
If you want to display an image file (e.g. PNG file) into the screen, please refer to documentation and tutorials for the graphics API you are using.
Here's a simplified OpenGL example using stb_image.h:
// Use stb_image.h to load a PNG from disk and turn it into raw RGBA pixel data:
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
[...]
int my_image_width, my_image_height;
unsigned char* my_image_data = stbi_load("my_image.png", &my_image_width, &my_image_height, NULL, 4);
// Turn the RGBA pixel data into an OpenGL texture:
GLuint my_opengl_texture;
glGenTextures(1, &my_opengl_texture);
glBindTexture(GL_TEXTURE_2D, my_opengl_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image_width, image_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data);
// Now that we have an OpenGL texture, assuming our imgui rendering function (imgui_impl_xxx.cpp file) takes GLuint as ImTextureID, we can display it:
ImGui::Image((void*)(intptr_t)my_opengl_texture, ImVec2(my_image_width, my_image_height));
C/C++ tip: a void* is pointer-sized storage. You may safely store any pointer or integer into it by casting your value to ImTextureID / void*, and vice-versa.
Because both end-points (user code and rendering function) are under your control, you know exactly what is stored inside the ImTextureID / void*.
Examples:
GLuint my_tex = XXX;
void* my_void_ptr;
my_void_ptr = (void*)(intptr_t)my_tex; // cast a GLuint into a void* (we don't take its address! we literally store the value inside the pointer)
my_tex = (GLuint)(intptr_t)my_void_ptr; // cast a void* into a GLuint
ID3D11ShaderResourceView* my_dx11_srv = XXX;
void* my_void_ptr;
my_void_ptr = (void*)my_dx11_srv; // cast a ID3D11ShaderResourceView* into an opaque void*
my_dx11_srv = (ID3D11ShaderResourceView*)my_void_ptr; // cast a void* into a ID3D11ShaderResourceView*
Finally, you may call ImGui::ShowMetricsWindow() to explore/visualize/understand how the ImDrawList are generated.
Q: Why are multiple widgets reacting when I interact with a single one?
Q: How can I have multiple widgets with the same label or with an empty label?
A: A primer on labels and the ID Stack...
Dear ImGui internally need to uniquely identify UI elements.
Elements that are typically not clickable (such as calls to the Text functions) don't need an ID.
Interactive widgets (such as calls to Button buttons) need a unique ID.
Unique ID are used internally to track active widgets and occasionally associate state to widgets.
Unique ID are implicitly built from the hash of multiple elements that identify the "path" to the UI element.
- Unique ID are often derived from a string label:
Button("OK"); // Label = "OK", ID = hash of (..., "OK")
Button("Cancel"); // Label = "Cancel", ID = hash of (..., "Cancel")
- ID are uniquely scoped within windows, tree nodes, etc. which all pushes to the ID stack. Having
two buttons labeled "OK" in different windows or different tree locations is fine.
We used "..." above to signify whatever was already pushed to the ID stack previously:
Begin("MyWindow");
Button("OK"); // Label = "OK", ID = hash of ("MyWindow", "OK")
End();
Begin("MyOtherWindow");
Button("OK"); // Label = "OK", ID = hash of ("MyOtherWindow", "OK")
End();
- If you have a same ID twice in the same location, you'll have a conflict:
Button("OK");
Button("OK"); // ID collision! Interacting with either button will trigger the first one.
Fear not! this is easy to solve and there are many ways to solve it!
- Solving ID conflict in a simple/local context:
When passing a label you can optionally specify extra ID information within string itself.
Use "##" to pass a complement to the ID that won't be visible to the end-user.
This helps solving the simple collision cases when you know e.g. at compilation time which items
are going to be created:
Begin("MyWindow");
Button("Play"); // Label = "Play", ID = hash of ("MyWindow", "Play")
Button("Play##foo1"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo1") // Different from above
Button("Play##foo2"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo2") // Different from above
End();
- If you want to completely hide the label, but still need an ID:
Checkbox("##On", &b); // Label = "", ID = hash of (..., "##On") // No visible label, just a checkbox!
- Occasionally/rarely you might want change a label while preserving a constant ID. This allows
you to animate labels. For example you may want to include varying information in a window title bar,
but windows are uniquely identified by their ID. Use "###" to pass a label that isn't part of ID:
Button("Hello###ID"); // Label = "Hello", ID = hash of (..., "###ID")
Button("World###ID"); // Label = "World", ID = hash of (..., "###ID") // Same as above, even though the label looks different
sprintf(buf, "My game (%f FPS)###MyGame", fps);
Begin(buf); // Variable title, ID = hash of "MyGame"
- Solving ID conflict in a more general manner:
Use PushID() / PopID() to create scopes and manipulate the ID stack, as to avoid ID conflicts
within the same window. This is the most convenient way of distinguishing ID when iterating and
creating many UI elements programmatically.
You can push a pointer, a string or an integer value into the ID stack.
Remember that ID are formed from the concatenation of _everything_ pushed into the ID stack.
At each level of the stack we store the seed used for items at this level of the ID stack.
Begin("Window");
for (int i = 0; i < 100; i++)
{
PushID(i); // Push i to the id tack
Button("Click"); // Label = "Click", ID = hash of ("Window", i, "Click")
PopID();
}
for (int i = 0; i < 100; i++)
{
MyObject* obj = Objects[i];
PushID(obj);
Button("Click"); // Label = "Click", ID = hash of ("Window", obj pointer, "Click")
PopID();
}
for (int i = 0; i < 100; i++)
{
MyObject* obj = Objects[i];
PushID(obj->Name);
Button("Click"); // Label = "Click", ID = hash of ("Window", obj->Name, "Click")
PopID();
}
End();
- You can stack multiple prefixes into the ID stack:
Button("Click"); // Label = "Click", ID = hash of (..., "Click")
PushID("node");
Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click")
PushID(my_ptr);
Button("Click"); // Label = "Click", ID = hash of (..., "node", my_ptr, "Click")
PopID();
PopID();
- Tree nodes implicitly creates a scope for you by calling PushID().
Button("Click"); // Label = "Click", ID = hash of (..., "Click")
if (TreeNode("node")) // <-- this function call will do a PushID() for you (unless instructed not to, with a special flag)
{
Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click")
TreePop();
}
- When working with trees, ID are used to preserve the open/close state of each tree node.
Depending on your use cases you may want to use strings, indices or pointers as ID.
e.g. when following a single pointer that may change over time, using a static string as ID
will preserve your node open/closed state when the targeted object change.
e.g. when displaying a list of objects, using indices or pointers as ID will preserve the
node open/closed state differently. See what makes more sense in your situation!
Q: How can I use my own math types instead of ImVec2/ImVec4?
A: You can edit imconfig.h and setup the IM_VEC2_CLASS_EXTRA/IM_VEC4_CLASS_EXTRA macros to add implicit type conversions.
This way you'll be able to use your own types everywhere, e.g. passing glm::vec2 to ImGui functions instead of ImVec2.
Q: How can I load a different font than the default?
A: Use the font atlas to load the TTF/OTF file you want:
ImGuiIO& io = ImGui::GetIO();
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
Default is ProggyClean.ttf, monospace, rendered at size 13, embedded in dear imgui's source code.
(Tip: monospace fonts are convenient because they allow to facilitate horizontal alignment directly at the string level.)
(Read the 'misc/fonts/README.txt' file for more details about font loading.)
New programmers: remember that in C/C++ and most programming languages if you want to use a
backslash \ within a string literal, you need to write it double backslash "\\":
io.Fonts->AddFontFromFileTTF("MyDataFolder\MyFontFile.ttf", size_in_pixels); // WRONG (you are escape the M here!)
io.Fonts->AddFontFromFileTTF("MyDataFolder\\MyFontFile.ttf", size_in_pixels); // CORRECT
io.Fonts->AddFontFromFileTTF("MyDataFolder/MyFontFile.ttf", size_in_pixels); // ALSO CORRECT
Q: How can I easily use icons in my application?
A: The most convenient and practical way is to merge an icon font such as FontAwesome inside you
main font. Then you can refer to icons within your strings.
You may want to see ImFontConfig::GlyphMinAdvanceX to make your icon look monospace to facilitate alignment.
(Read the 'misc/fonts/README.txt' file for more details about icons font loading.)
Q: How can I load multiple fonts?
A: Use the font atlas to pack them into a single texture:
(Read the 'misc/fonts/README.txt' file and the code in ImFontAtlas for more details.)
ImGuiIO& io = ImGui::GetIO();
ImFont* font0 = io.Fonts->AddFontDefault();
ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels);
io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
// the first loaded font gets used by default
// use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime
// Options
ImFontConfig config;
config.OversampleH = 2;
config.OversampleV = 1;
config.GlyphOffset.y -= 1.0f; // Move everything by 1 pixels up
config.GlyphExtraSpacing.x = 1.0f; // Increase spacing between characters
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels, &config);
// Combine multiple fonts into one (e.g. for icon fonts)
static ImWchar ranges[] = { 0xf000, 0xf3ff, 0 };
ImFontConfig config;
config.MergeMode = true;
io.Fonts->AddFontDefault();
io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges); // Merge icon font
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge japanese glyphs
Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
A: When loading a font, pass custom Unicode ranges to specify the glyphs to load.
// Add default Japanese ranges
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese());
// Or create your own custom ranges (e.g. for a game you can feed your entire game script and only build the characters the game need)
ImVector<ImWchar> ranges;
ImFontGlyphRangesBuilder builder;
builder.AddText("Hello world"); // Add a string (here "Hello world" contains 7 unique characters)
builder.AddChar(0x7262); // Add a specific character
builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges
builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted)
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, ranges.Data);
All your strings needs to use UTF-8 encoding. In C++11 you can encode a string literal in UTF-8
by using the u8"hello" syntax. Specifying literal in your source code using a local code page
(such as CP-923 for Japanese or CP-1251 for Cyrillic) will NOT work!
Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8.
Text input: it is up to your application to pass the right character code by calling io.AddInputCharacter().
The applications in examples/ are doing that.
Windows: you can use the WM_CHAR or WM_UNICHAR or WM_IME_CHAR message (depending if your app is built using Unicode or MultiByte mode).
You may also use MultiByteToWideChar() or ToUnicode() to retrieve Unicode codepoints from MultiByte characters or keyboard state.
Windows: if your language is relying on an Input Method Editor (IME), you copy the HWND of your window to io.ImeWindowHandle in order for
the default implementation of io.ImeSetInputScreenPosFn() to set your Microsoft IME position correctly.
Q: How can I interact with standard C++ types (such as std::string and std::vector)?
A: - Being highly portable (bindings for several languages, frameworks, programming style, obscure or older platforms/compilers),
and aiming for compatibility & performance suitable for every modern real-time game engines, dear imgui does not use
any of std C++ types. We use raw types (e.g. char* instead of std::string) because they adapt to more use cases.
- To use ImGui::InputText() with a std::string or any resizable string class, see misc/cpp/imgui_stdlib.h.
- To use combo boxes and list boxes with std::vector or any other data structure: the BeginCombo()/EndCombo() API
lets you iterate and submit items yourself, so does the ListBoxHeader()/ListBoxFooter() API.
Prefer using them over the old and awkward Combo()/ListBox() api.
- Generally for most high-level types you should be able to access the underlying data type.
You may write your own one-liner wrappers to facilitate user code (tip: add new functions in ImGui:: namespace from your code).
- Dear ImGui applications often need to make intensive use of strings. It is expected that many of the strings you will pass
to the API are raw literals (free in C/C++) or allocated in a manner that won't incur a large cost on your application.
Please bear in mind that using std::string on applications with large amount of UI may incur unsatisfactory performances.
Modern implementations of std::string often include small-string optimization (which is often a local buffer) but those
are not configurable and not the same across implementations.
- If you are finding your UI traversal cost to be too large, make sure your string usage is not leading to excessive amount
of heap allocations. Consider using literals, statically sized buffers and your own helper functions. A common pattern
is that you will need to build lots of strings on the fly, and their maximum length can be easily be scoped ahead.
One possible implementation of a helper to facilitate printf-style building of strings: https://github.com/ocornut/Str
This is a small helper where you can instance strings with configurable local buffers length. Many game engines will
provide similar or better string helpers.
Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
A: - You can create a dummy window. Call Begin() with the NoBackground | NoDecoration | NoSavedSettings | NoInputs flags.
(The ImGuiWindowFlags_NoDecoration flag itself is a shortcut for NoTitleBar | NoResize | NoScrollbar | NoCollapse)
Then you can retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like.
- You can call ImGui::GetBackgroundDrawList() or ImGui::GetForegroundDrawList() and use those draw list to display
contents behind or over every other imgui windows (one bg/fg drawlist per viewport).
- You can create your own ImDrawList instance. You'll need to initialize them ImGui::GetDrawListSharedData(), or create
your own ImDrawListSharedData, and then call your rendered code with your own ImDrawList or ImDrawData data.
Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
A: - You can control Dear ImGui with a gamepad. Read about navigation in "Using gamepad/keyboard navigation controls".
(short version: map gamepad inputs into the io.NavInputs[] array + set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad)
- You can share your computer mouse seamlessly with your console/tablet/phone using Synergy (https://symless.com/synergy)
This is the preferred solution for developer productivity.
In particular, the "micro-synergy-client" repository (https://github.com/symless/micro-synergy-client) has simple
and portable source code (uSynergy.c/.h) for a small embeddable client that you can use on any platform to connect
to your host computer, based on the Synergy 1.x protocol. Make sure you download the Synergy 1 server on your computer.
Console SDK also sometimes provide equivalent tooling or wrapper for Synergy-like protocols.
- You may also use a third party solution such as Remote ImGui (https://github.com/JordiRos/remoteimgui) which sends
the vertices to render over the local network, allowing you to use Dear ImGui even on a screen-less machine.
- For touch inputs, you can increase the hit box of widgets (via the style.TouchPadding setting) to accommodate
for the lack of precision of touch inputs, but it is recommended you use a mouse or gamepad to allow optimizing
for screen real-estate and precision.
Q: I integrated Dear ImGui in my engine and the text or lines are blurry..
A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f).
Also make sure your orthographic projection matrix and io.DisplaySize matches your actual framebuffer dimension.
Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
A: You are probably mishandling the clipping rectangles in your render function.
Rectangles provided by ImGui are defined as (x1=left,y1=top,x2=right,y2=bottom) and NOT as (x1,y1,width,height).
Q: How can I help?
A: - If you are experienced with Dear ImGui and C++, look at the github issues, look at the Wiki, read docs/TODO.txt
and see how you want to help and can help!
- Businesses: convince your company to fund development via support contracts/sponsoring! This is among the most useful thing you can do for dear imgui.
- Individuals: you can also become a Patron (http://www.patreon.com/imgui) or donate on PayPal! See README.
- Disclose your usage of dear imgui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
You may post screenshot or links in the gallery threads (github.com/ocornut/imgui/issues/1902). Visuals are ideal as they inspire other programmers.
But even without visuals, disclosing your use of dear imgui help the library grow credibility, and help other teams and programmers with taking decisions.
- If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on github or privately).
- tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window.
this is also useful to set yourself in the context of another window (to get/set other settings)
- tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug".
- tip: the ImGuiOnceUponAFrame helper will allow run the block of code only once a frame. You can use it to quickly add custom UI in the middle
of a deep nested inner loop in your code.
- tip: you can call Render() multiple times (e.g for VR renders).
- tip: call and read the ShowDemoWindow() code in imgui_demo.cpp for more example of how to use ImGui!
*/
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "imgui.h"
#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif
#include "imgui_internal.h"
#include <ctype.h> // toupper
#include <stdio.h> // vsnprintf, sscanf, printf
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include <stddef.h> // intptr_t
#else
#include <stdint.h> // intptr_t
#endif
// Debug options
#define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
#define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
// Visual Studio warnings
#ifdef _MSC_VER
#pragma warning (disable: 4127) // condition expression is constant
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
#endif
// Clang/GCC warnings with -Weverything
#ifdef __clang__
#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning : unknown warning group '-Wformat-pedantic *' // not all warnings are known by all clang versions.. so ignoring warnings triggers new warnings on some configuration. great!
#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
#pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
#pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference is.
#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness //
#pragma clang diagnostic ignored "-Wformat-pedantic" // warning : format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int'
#if __has_warning("-Wzero-as-null-pointer-constant")
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning : zero as null pointer constant // some standard header variations use #define NULL 0
#endif
#if __has_warning("-Wdouble-promotion")
#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
#endif
#elif defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
#if __GNUC__ >= 8
#pragma GCC diagnostic ignored "-Wclass-memaccess" // warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
#endif
#endif
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by back-end)
static const float WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS = 4.0f; // Extend outside and inside windows. Affect FindHoveredWindow().
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
//-------------------------------------------------------------------------
// [SECTION] FORWARD DECLARATIONS
//-------------------------------------------------------------------------
static void SetCurrentWindow(ImGuiWindow* window);
static void FindHoveredWindow();
static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags);
static void CheckStacksSize(ImGuiWindow* window, bool write);
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges);
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
static ImRect GetViewportRect();
// Settings
static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
// Platform Dependents default implementation for IO functions
static const char* GetClipboardTextFn_DefaultImpl(void* user_data);
static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text);
static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y);
namespace ImGui
{
static bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags);
// Navigation
static void NavUpdate();
static void NavUpdateWindowing();
static void NavUpdateWindowingList();
static void NavUpdateMoveResult();
static float NavUpdatePageUpPageDown(int allowed_dir_flags);
static inline void NavUpdateAnyRequestFlag();
static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, ImGuiID id);
static ImVec2 NavCalcPreferredRefPos();
static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
static int FindWindowFocusIndex(ImGuiWindow* window);
// Misc
static void UpdateMouseInputs();
static void UpdateMouseWheel();
static void UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]);
static void RenderWindowOuterBorders(ImGuiWindow* window);
static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
}
//-----------------------------------------------------------------------------
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
//-----------------------------------------------------------------------------
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
// ImGui::CreateContext() will automatically set this pointer if it is NULL. Change to a different context by calling ImGui::SetCurrentContext().
// 1) Important: globals are not shared across DLL boundaries! If you use DLLs or any form of hot-reloading: you will need to call
// SetCurrentContext() (with the pointer you got from CreateContext) from each unique static/DLL boundary, and after each hot-reloading.
// In your debugger, add GImGui to your watch window and notice how its value changes depending on which location you are currently stepping into.
// 2) Important: Dear ImGui functions are not thread-safe because of this pointer.
// If you want thread-safety to allow N threads to access N different contexts, you can:
// - Change this variable to use thread local storage so each thread can refer to a different context, in imconfig.h:
// struct ImGuiContext;
// extern thread_local ImGuiContext* MyImGuiTLS;
// #define GImGui MyImGuiTLS
// And then define MyImGuiTLS in one of your cpp file. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
// - Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
// - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from different namespace.
#ifndef GImGui
ImGuiContext* GImGui = NULL;
#endif
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
// If you use DLL hotreloading you might need to call SetAllocatorFunctions() after reloading code from this file.
// Otherwise, you probably don't want to modify them mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size); }
static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr); }
#else
static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
#endif
static void* (*GImAllocatorAllocFunc)(size_t size, void* user_data) = MallocWrapper;
static void (*GImAllocatorFreeFunc)(void* ptr, void* user_data) = FreeWrapper;
static void* GImAllocatorUserData = NULL;
//-----------------------------------------------------------------------------
// [SECTION] MAIN USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
//-----------------------------------------------------------------------------
ImGuiStyle::ImGuiStyle()
{
Alpha = 1.0f; // Global alpha applies to everything in ImGui
WindowPadding = ImVec2(8,8); // Padding within a window
WindowRounding = 7.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows
WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
WindowMinSize = ImVec2(32,32); // Minimum window size
WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns. Preferably > (FramePadding.x + 1).
ScrollbarSize = 16.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar
GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
TabBorderSize = 0.0f; // Thickness of border around tabs.
ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text when button is larger than text.
DisplayWindowPadding = ImVec2(19,19); // Window position are clamped to be visible within the display area by at least this amount. Only applies to regular windows.
DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU.
AntiAliasedFill = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
// Default theme
ImGui::StyleColorsDark(this);
}
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
void ImGuiStyle::ScaleAllSizes(float scale_factor)
{
WindowPadding = ImFloor(WindowPadding * scale_factor);
WindowRounding = ImFloor(WindowRounding * scale_factor);
WindowMinSize = ImFloor(WindowMinSize * scale_factor);
ChildRounding = ImFloor(ChildRounding * scale_factor);
PopupRounding = ImFloor(PopupRounding * scale_factor);
FramePadding = ImFloor(FramePadding * scale_factor);
FrameRounding = ImFloor(FrameRounding * scale_factor);
ItemSpacing = ImFloor(ItemSpacing * scale_factor);
ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
IndentSpacing = ImFloor(IndentSpacing * scale_factor);
ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);
ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
GrabMinSize = ImFloor(GrabMinSize * scale_factor);
GrabRounding = ImFloor(GrabRounding * scale_factor);
TabRounding = ImFloor(TabRounding * scale_factor);
DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
}
ImGuiIO::ImGuiIO()
{
// Most fields are initialized with zero
memset(this, 0, sizeof(*this));
// Settings
ConfigFlags = ImGuiConfigFlags_None;
BackendFlags = ImGuiBackendFlags_None;
DisplaySize = ImVec2(-1.0f, -1.0f);
DeltaTime = 1.0f/60.0f;
IniSavingRate = 5.0f;
IniFilename = "imgui.ini";
LogFilename = "imgui_log.txt";
MouseDoubleClickTime = 0.30f;
MouseDoubleClickMaxDist = 6.0f;
for (int i = 0; i < ImGuiKey_COUNT; i++)
KeyMap[i] = -1;
KeyRepeatDelay = 0.250f;
KeyRepeatRate = 0.050f;
UserData = NULL;
Fonts = NULL;
FontGlobalScale = 1.0f;
FontDefault = NULL;
FontAllowUserScaling = false;
DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
// Miscellaneous options
MouseDrawCursor = false;
#ifdef __APPLE__
ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
#else
ConfigMacOSXBehaviors = false;
#endif
ConfigInputTextCursorBlink = true;
ConfigWindowsResizeFromEdges = true;
ConfigWindowsMoveFromTitleBarOnly = false;
// Platform Functions
BackendPlatformName = BackendRendererName = NULL;
BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
ClipboardUserData = NULL;
ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl;
ImeWindowHandle = NULL;
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
RenderDrawListsFn = NULL;
#endif
// Input (NB: we already have memset zero the entire structure!)
MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
MouseDragThreshold = 6.0f;
for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f;
for (int i = 0; i < IM_ARRAYSIZE(NavInputsDownDuration); i++) NavInputsDownDuration[i] = -1.0f;
}
// Pass in translated ASCII characters for text input.
// - with glfw you can get those from the callback set in glfwSetCharCallback()
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
void ImGuiIO::AddInputCharacter(unsigned int c)
{
if (c > 0 && c < 0x10000)
InputQueueCharacters.push_back((ImWchar)c);
}
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
{
while (*utf8_chars != 0)
{
unsigned int c = 0;
utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
if (c > 0 && c < 0x10000)
InputQueueCharacters.push_back((ImWchar)c);
}
}
void ImGuiIO::ClearInputCharacters()
{
InputQueueCharacters.resize(0);
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (Maths, String, Format, Hash, File functions)
//-----------------------------------------------------------------------------
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
{
ImVec2 ap = p - a;
ImVec2 ab_dir = b - a;
float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
if (dot < 0.0f)
return a;
float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
if (dot > ab_len_sqr)
return b;
return a + ab_dir * dot / ab_len_sqr;
}
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
{
bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
return ((b1 == b2) && (b2 == b3));
}
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
{
ImVec2 v0 = b - a;
ImVec2 v1 = c - a;
ImVec2 v2 = p - a;
const float denom = v0.x * v1.y - v1.x * v0.y;
out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
out_u = 1.0f - out_v - out_w;
}
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
{
ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
float dist2_ab = ImLengthSqr(p - proj_ab);
float dist2_bc = ImLengthSqr(p - proj_bc);
float dist2_ca = ImLengthSqr(p - proj_ca);
float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
if (m == dist2_ab)
return proj_ab;
if (m == dist2_bc)
return proj_bc;
return proj_ca;
}
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
int ImStricmp(const char* str1, const char* str2)
{
int d;
while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; }
return d;
}
int ImStrnicmp(const char* str1, const char* str2, size_t count)
{
int d = 0;
while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
return d;
}
void ImStrncpy(char* dst, const char* src, size_t count)
{
if (count < 1)
return;
if (count > 1)
strncpy(dst, src, count - 1);
dst[count - 1] = 0;
}
char* ImStrdup(const char* str)
{
size_t len = strlen(str);
void* buf = IM_ALLOC(len + 1);
return (char*)memcpy(buf, (const void*)str, len + 1);
}
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
{
size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
size_t src_size = strlen(src) + 1;
if (dst_buf_size < src_size)
{
IM_FREE(dst);
dst = (char*)IM_ALLOC(src_size);
if (p_dst_size)
*p_dst_size = src_size;
}
return (char*)memcpy(dst, (const void*)src, src_size);
}
const char* ImStrchrRange(const char* str, const char* str_end, char c)
{
const char* p = (const char*)memchr(str, (int)c, str_end - str);
return p;
}
int ImStrlenW(const ImWchar* str)
{
//return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bits
int n = 0;
while (*str++) n++;
return n;
}
// Find end-of-line. Return pointer will point to either first \n, either str_end.
const char* ImStreolRange(const char* str, const char* str_end)
{
const char* p = (const char*)memchr(str, '\n', str_end - str);
return p ? p : str_end;
}
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
{
while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
buf_mid_line--;
return buf_mid_line;
}
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
{
if (!needle_end)
needle_end = needle + strlen(needle);
const char un0 = (char)toupper(*needle);
while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
{
if (toupper(*haystack) == un0)
{
const char* b = needle + 1;
for (const char* a = haystack + 1; b < needle_end; a++, b++)
if (toupper(*a) != toupper(*b))
break;
if (b == needle_end)
return haystack;
}
haystack++;
}
return NULL;
}
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
void ImStrTrimBlanks(char* buf)
{
char* p = buf;
while (p[0] == ' ' || p[0] == '\t') // Leading blanks
p++;
char* p_start = p;
while (*p != 0) // Find end of string
p++;
while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks
p--;
if (p_start != buf) // Copy memory if we had leading blanks
memmove(buf, p_start, p - p_start);
buf[p - p_start] = 0; // Zero terminate
}
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
// B) When buf==NULL vsnprintf() will return the output size.
#ifndef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
//#define IMGUI_USE_STB_SPRINTF
#ifdef IMGUI_USE_STB_SPRINTF
#define STB_SPRINTF_IMPLEMENTATION
#include "imstb_sprintf.h"
#endif
#if defined(_MSC_VER) && !defined(vsnprintf)
#define vsnprintf _vsnprintf
#endif
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
#ifdef IMGUI_USE_STB_SPRINTF
int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
#else
int w = vsnprintf(buf, buf_size, fmt, args);
#endif
va_end(args);
if (buf == NULL)
return w;
if (w == -1 || w >= (int)buf_size)
w = (int)buf_size - 1;
buf[w] = 0;
return w;
}
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
{
#ifdef IMGUI_USE_STB_SPRINTF
int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
#else
int w = vsnprintf(buf, buf_size, fmt, args);
#endif
if (buf == NULL)
return w;
if (w == -1 || w >= (int)buf_size)
w = (int)buf_size - 1;
buf[w] = 0;
return w;
}
#endif // #ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
// CRC32 needs a 1KB lookup table (not cache friendly)
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
static const ImU32 GCrc32LookupTable[256] =
{
0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
};
// Known size hash
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
ImU32 ImHashData(const void* data_p, size_t data_size, ImU32 seed)
{
ImU32 crc = ~seed;
const unsigned char* data = (const unsigned char*)data_p;
const ImU32* crc32_lut = GCrc32LookupTable;
while (data_size-- != 0)
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
return ~crc;
}
// Zero-terminated string hash, with support for ### to reset back to seed value
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
// Because this syntax is rarely used we are optimizing for the common case.
// - If we reach ### in the string we discard the hash so far and reset to the seed.
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
ImU32 ImHashStr(const char* data_p, size_t data_size, ImU32 seed)
{
seed = ~seed;
ImU32 crc = seed;
const unsigned char* data = (const unsigned char*)data_p;
const ImU32* crc32_lut = GCrc32LookupTable;
if (data_size != 0)
{
while (data_size-- != 0)
{
unsigned char c = *data++;
if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
crc = seed;
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
}
}
else
{
while (unsigned char c = *data++)
{
if (c == '#' && data[0] == '#' && data[1] == '#')
crc = seed;
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
}
}
return ~crc;
}
FILE* ImFileOpen(const char* filename, const char* mode)
{
#if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__GNUC__)
// We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames. Converting both strings from UTF-8 to wchar format (using a single allocation, because we can)
const int filename_wsize = ImTextCountCharsFromUtf8(filename, NULL) + 1;
const int mode_wsize = ImTextCountCharsFromUtf8(mode, NULL) + 1;
ImVector<ImWchar> buf;
buf.resize(filename_wsize + mode_wsize);
ImTextStrFromUtf8(&buf[0], filename_wsize, filename, NULL);
ImTextStrFromUtf8(&buf[filename_wsize], mode_wsize, mode, NULL);
return _wfopen((wchar_t*)&buf[0], (wchar_t*)&buf[filename_wsize]);
#else
return fopen(filename, mode);
#endif
}
// Load file content into memory
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, size_t* out_file_size, int padding_bytes)
{
IM_ASSERT(filename && file_open_mode);
if (out_file_size)
*out_file_size = 0;
FILE* f;
if ((f = ImFileOpen(filename, file_open_mode)) == NULL)
return NULL;
long file_size_signed;
if (fseek(f, 0, SEEK_END) || (file_size_signed = ftell(f)) == -1 || fseek(f, 0, SEEK_SET))
{
fclose(f);
return NULL;
}
size_t file_size = (size_t)file_size_signed;
void* file_data = IM_ALLOC(file_size + padding_bytes);
if (file_data == NULL)
{
fclose(f);
return NULL;
}
if (fread(file_data, 1, file_size, f) != file_size)
{
fclose(f);
IM_FREE(file_data);
return NULL;
}
if (padding_bytes > 0)
memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
fclose(f);
if (out_file_size)
*out_file_size = file_size;
return file_data;
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
//-----------------------------------------------------------------------------
// Convert UTF-8 to 32-bits character, process single character input.
// Based on stb_from_utf8() from github.com/nothings/stb/
// We handle UTF-8 decoding error by skipping forward.
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
{
unsigned int c = (unsigned int)-1;
const unsigned char* str = (const unsigned char*)in_text;
if (!(*str & 0x80))
{
c = (unsigned int)(*str++);
*out_char = c;
return 1;
}
if ((*str & 0xe0) == 0xc0)
{
*out_char = 0xFFFD; // will be invalid but not end of string
if (in_text_end && in_text_end - (const char*)str < 2) return 1;
if (*str < 0xc2) return 2;
c = (unsigned int)((*str++ & 0x1f) << 6);
if ((*str & 0xc0) != 0x80) return 2;
c += (*str++ & 0x3f);
*out_char = c;
return 2;
}
if ((*str & 0xf0) == 0xe0)
{
*out_char = 0xFFFD; // will be invalid but not end of string
if (in_text_end && in_text_end - (const char*)str < 3) return 1;
if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3;
if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below
c = (unsigned int)((*str++ & 0x0f) << 12);
if ((*str & 0xc0) != 0x80) return 3;
c += (unsigned int)((*str++ & 0x3f) << 6);
if ((*str & 0xc0) != 0x80) return 3;
c += (*str++ & 0x3f);
*out_char = c;
return 3;
}
if ((*str & 0xf8) == 0xf0)
{
*out_char = 0xFFFD; // will be invalid but not end of string
if (in_text_end && in_text_end - (const char*)str < 4) return 1;
if (*str > 0xf4) return 4;
if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4;
if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below
c = (unsigned int)((*str++ & 0x07) << 18);
if ((*str & 0xc0) != 0x80) return 4;
c += (unsigned int)((*str++ & 0x3f) << 12);
if ((*str & 0xc0) != 0x80) return 4;
c += (unsigned int)((*str++ & 0x3f) << 6);
if ((*str & 0xc0) != 0x80) return 4;
c += (*str++ & 0x3f);
// utf-8 encodings of values used in surrogate pairs are invalid
if ((c & 0xFFFFF800) == 0xD800) return 4;
*out_char = c;
return 4;
}
*out_char = 0;
return 0;
}
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
{
ImWchar* buf_out = buf;
ImWchar* buf_end = buf + buf_size;
while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c;
in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
if (c == 0)
break;
if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes
*buf_out++ = (ImWchar)c;
}
*buf_out = 0;
if (in_text_remaining)
*in_text_remaining = in_text;
return (int)(buf_out - buf);
}
int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
{
int char_count = 0;
while ((!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c;
in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
if (c == 0)
break;
if (c < 0x10000)
char_count++;
}
return char_count;
}
// Based on stb_to_utf8() from github.com/nothings/stb/
static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c)
{
if (c < 0x80)
{
buf[0] = (char)c;
return 1;
}
if (c < 0x800)
{
if (buf_size < 2) return 0;
buf[0] = (char)(0xc0 + (c >> 6));
buf[1] = (char)(0x80 + (c & 0x3f));
return 2;
}
if (c >= 0xdc00 && c < 0xe000)
{
return 0;
}
if (c >= 0xd800 && c < 0xdc00)
{
if (buf_size < 4) return 0;
buf[0] = (char)(0xf0 + (c >> 18));
buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
buf[3] = (char)(0x80 + ((c ) & 0x3f));
return 4;
}
//else if (c < 0x10000)
{
if (buf_size < 3) return 0;
buf[0] = (char)(0xe0 + (c >> 12));
buf[1] = (char)(0x80 + ((c>> 6) & 0x3f));
buf[2] = (char)(0x80 + ((c ) & 0x3f));
return 3;
}
}
// Not optimal but we very rarely use this function.
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
{
unsigned int dummy = 0;
return ImTextCharFromUtf8(&dummy, in_text, in_text_end);
}
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
{
if (c < 0x80) return 1;
if (c < 0x800) return 2;
if (c >= 0xdc00 && c < 0xe000) return 0;
if (c >= 0xd800 && c < 0xdc00) return 4;
return 3;
}
int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
{
char* buf_out = buf;
const char* buf_end = buf + buf_size;
while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c = (unsigned int)(*in_text++);
if (c < 0x80)
*buf_out++ = (char)c;
else
buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end-buf_out-1), c);
}
*buf_out = 0;
return (int)(buf_out - buf);
}
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
{
int bytes_count = 0;
while ((!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c = (unsigned int)(*in_text++);
if (c < 0x80)
bytes_count++;
else
bytes_count += ImTextCountUtf8BytesFromChar(c);
}
return bytes_count;
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILTIES (Color functions)
// Note: The Convert functions are early design which are not consistent with other API.
//-----------------------------------------------------------------------------
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
{
float s = 1.0f/255.0f;
return ImVec4(
((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
}
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
{
ImU32 out;
out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
return out;
}
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
{
float K = 0.f;
if (g < b)
{
ImSwap(g, b);
K = -1.f;
}
if (r < g)
{
ImSwap(r, g);
K = -2.f / 6.f - K;
}
const float chroma = r - (g < b ? g : b);
out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
out_s = chroma / (r + 1e-20f);
out_v = r;
}
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
// also http://en.wikipedia.org/wiki/HSL_and_HSV
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
{
if (s == 0.0f)
{
// gray
out_r = out_g = out_b = v;
return;
}
h = ImFmod(h, 1.0f) / (60.0f/360.0f);
int i = (int)h;
float f = h - (float)i;
float p = v * (1.0f - s);
float q = v * (1.0f - s * f);
float t = v * (1.0f - s * (1.0f - f));
switch (i)
{
case 0: out_r = v; out_g = t; out_b = p; break;
case 1: out_r = q; out_g = v; out_b = p; break;
case 2: out_r = p; out_g = v; out_b = t; break;
case 3: out_r = p; out_g = q; out_b = v; break;
case 4: out_r = t; out_g = p; out_b = v; break;
case 5: default: out_r = v; out_g = p; out_b = q; break;
}
}
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
{
ImGuiStyle& style = GImGui->Style;
ImVec4 c = style.Colors[idx];
c.w *= style.Alpha * alpha_mul;
return ColorConvertFloat4ToU32(c);
}
ImU32 ImGui::GetColorU32(const ImVec4& col)
{
ImGuiStyle& style = GImGui->Style;
ImVec4 c = col;
c.w *= style.Alpha;
return ColorConvertFloat4ToU32(c);
}
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
{
ImGuiStyle& style = GImGui->Style;
return style.Colors[idx];
}
ImU32 ImGui::GetColorU32(ImU32 col)
{
float style_alpha = GImGui->Style.Alpha;
if (style_alpha >= 1.0f)
return col;
ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
a = (ImU32)(a * style_alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiStorage
// Helper: Key->value storage
//-----------------------------------------------------------------------------
// std::lower_bound but without the bullshit
static ImGuiStorage::Pair* LowerBound(ImVector<ImGuiStorage::Pair>& data, ImGuiID key)
{
ImGuiStorage::Pair* first = data.Data;
ImGuiStorage::Pair* last = data.Data + data.Size;
size_t count = (size_t)(last - first);
while (count > 0)
{
size_t count2 = count >> 1;
ImGuiStorage::Pair* mid = first + count2;
if (mid->key < key)
{
first = ++mid;
count -= count2 + 1;
}
else
{
count = count2;
}
}
return first;
}
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
void ImGuiStorage::BuildSortByKey()
{
struct StaticFunc
{
static int IMGUI_CDECL PairCompareByID(const void* lhs, const void* rhs)
{
// We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
if (((const Pair*)lhs)->key > ((const Pair*)rhs)->key) return +1;
if (((const Pair*)lhs)->key < ((const Pair*)rhs)->key) return -1;
return 0;
}
};
if (Data.Size > 1)
ImQsort(Data.Data, (size_t)Data.Size, sizeof(Pair), StaticFunc::PairCompareByID);
}
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
{
ImGuiStorage::Pair* it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
if (it == Data.end() || it->key != key)
return default_val;
return it->val_i;
}
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
{
return GetInt(key, default_val ? 1 : 0) != 0;
}
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
{
ImGuiStorage::Pair* it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
if (it == Data.end() || it->key != key)
return default_val;
return it->val_f;
}
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
{
ImGuiStorage::Pair* it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
if (it == Data.end() || it->key != key)
return NULL;
return it->val_p;
}
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
{
ImGuiStorage::Pair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, Pair(key, default_val));
return &it->val_i;
}
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
{
return (bool*)GetIntRef(key, default_val ? 1 : 0);
}
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
{
ImGuiStorage::Pair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, Pair(key, default_val));
return &it->val_f;
}
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
{
ImGuiStorage::Pair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, Pair(key, default_val));
return &it->val_p;
}
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
void ImGuiStorage::SetInt(ImGuiID key, int val)
{
ImGuiStorage::Pair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, Pair(key, val));
return;
}
it->val_i = val;
}
void ImGuiStorage::SetBool(ImGuiID key, bool val)
{
SetInt(key, val ? 1 : 0);
}
void ImGuiStorage::SetFloat(ImGuiID key, float val)
{
ImGuiStorage::Pair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, Pair(key, val));
return;
}
it->val_f = val;
}
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
{
ImGuiStorage::Pair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, Pair(key, val));
return;
}
it->val_p = val;
}
void ImGuiStorage::SetAllInt(int v)
{
for (int i = 0; i < Data.Size; i++)
Data[i].val_i = v;
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiTextFilter
//-----------------------------------------------------------------------------
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter)
{
if (default_filter)
{
ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
Build();
}
else
{
InputBuf[0] = 0;
CountGrep = 0;
}
}
bool ImGuiTextFilter::Draw(const char* label, float width)
{
if (width != 0.0f)
ImGui::SetNextItemWidth(width);
bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
if (value_changed)
Build();
return value_changed;
}
void ImGuiTextFilter::TextRange::split(char separator, ImVector<TextRange>* out) const
{
out->resize(0);
const char* wb = b;
const char* we = wb;
while (we < e)
{
if (*we == separator)
{
out->push_back(TextRange(wb, we));
wb = we + 1;
}
we++;
}
if (wb != we)
out->push_back(TextRange(wb, we));
}
void ImGuiTextFilter::Build()
{
Filters.resize(0);
TextRange input_range(InputBuf, InputBuf+strlen(InputBuf));
input_range.split(',', &Filters);
CountGrep = 0;
for (int i = 0; i != Filters.Size; i++)
{
TextRange& f = Filters[i];
while (f.b < f.e && ImCharIsBlankA(f.b[0]))
f.b++;
while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
f.e--;
if (f.empty())
continue;
if (Filters[i].b[0] != '-')
CountGrep += 1;
}
}
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
{
if (Filters.empty())
return true;
if (text == NULL)
text = "";
for (int i = 0; i != Filters.Size; i++)
{
const TextRange& f = Filters[i];
if (f.empty())
continue;
if (f.b[0] == '-')
{
// Subtract
if (ImStristr(text, text_end, f.begin()+1, f.end()) != NULL)
return false;
}
else
{
// Grep
if (ImStristr(text, text_end, f.begin(), f.end()) != NULL)
return true;
}
}
// Implicit * grep
if (CountGrep == 0)
return true;
return false;
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiTextBuffer
//-----------------------------------------------------------------------------
// On some platform vsnprintf() takes va_list by reference and modifies it.
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
#ifndef va_copy
#if defined(__GNUC__) || defined(__clang__)
#define va_copy(dest, src) __builtin_va_copy(dest, src)
#else
#define va_copy(dest, src) (dest = src)
#endif
#endif
char ImGuiTextBuffer::EmptyString[1] = { 0 };
void ImGuiTextBuffer::append(const char* str, const char* str_end)
{
int len = str_end ? (int)(str_end - str) : (int)strlen(str);
// Add zero-terminator the first time
const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
const int needed_sz = write_off + len;
if (write_off + len >= Buf.Capacity)
{
int new_capacity = Buf.Capacity * 2;
Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
}
Buf.resize(needed_sz);
memcpy(&Buf[write_off - 1], str, (size_t)len);
Buf[write_off - 1 + len] = 0;
}
void ImGuiTextBuffer::appendf(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
appendfv(fmt, args);
va_end(args);
}
// Helper: Text buffer for logging/accumulating text
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
{
va_list args_copy;
va_copy(args_copy, args);
int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
if (len <= 0)
{
va_end(args_copy);
return;
}
// Add zero-terminator the first time
const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
const int needed_sz = write_off + len;
if (write_off + len >= Buf.Capacity)
{
int new_capacity = Buf.Capacity * 2;
Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
}
Buf.resize(needed_sz);
ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
va_end(args_copy);
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiListClipper
// This is currently not as flexible/powerful as it should be, needs some rework (see TODO)
//-----------------------------------------------------------------------------
static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height)
{
// Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
// FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
// The clipper should probably have a 4th step to display the last item in a regular manner.
ImGui::SetCursorPosY(pos_y);
ImGuiWindow* window = ImGui::GetCurrentWindow();
window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
window->DC.PrevLineSize.y = (line_height - GImGui->Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
if (window->DC.CurrentColumns)
window->DC.CurrentColumns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
}
// Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1
// Use case B: Begin() called from constructor with items_height>0
// FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style.
void ImGuiListClipper::Begin(int count, float items_height)
{
StartPosY = ImGui::GetCursorPosY();
ItemsHeight = items_height;
ItemsCount = count;
StepNo = 0;
DisplayEnd = DisplayStart = -1;
if (ItemsHeight > 0.0f)
{
ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display
if (DisplayStart > 0)
SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor
StepNo = 2;
}
}
void ImGuiListClipper::End()
{
if (ItemsCount < 0)
return;
// In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user.
if (ItemsCount < INT_MAX)
SetCursorPosYAndSetupDummyPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor
ItemsCount = -1;
StepNo = 3;
}
bool ImGuiListClipper::Step()
{
if (ItemsCount == 0 || ImGui::GetCurrentWindowRead()->SkipItems)
{
ItemsCount = -1;
return false;
}
if (StepNo == 0) // Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height.
{
DisplayStart = 0;
DisplayEnd = 1;
StartPosY = ImGui::GetCursorPosY();
StepNo = 1;
return true;
}
if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element.
{
if (ItemsCount == 1) { ItemsCount = -1; return false; }
float items_height = ImGui::GetCursorPosY() - StartPosY;
IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically
Begin(ItemsCount-1, items_height);
DisplayStart++;
DisplayEnd++;
StepNo = 3;
return true;
}
if (StepNo == 2) // Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3.
{
IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0);
StepNo = 3;
return true;
}
if (StepNo == 3) // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop.
End();
return false;
}
//-----------------------------------------------------------------------------
// [SECTION] RENDER HELPERS
// Those (internal) functions are currently quite a legacy mess - their signature and behavior will change.
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: state.
//-----------------------------------------------------------------------------
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
{
const char* text_display_end = text;
if (!text_end)
text_end = (const char*)-1;
while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
text_display_end++;
return text_display_end;
}
// Internal ImGui functions to render text
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
// Hide anything after a '##' string
const char* text_display_end;
if (hide_text_after_hash)
{
text_display_end = FindRenderedTextEnd(text, text_end);
}
else
{
if (!text_end)
text_end = text + strlen(text); // FIXME-OPT
text_display_end = text_end;
}
if (text != text_display_end)
{
window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
if (g.LogEnabled)
LogRenderedText(&pos, text, text_display_end);
}
}
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!text_end)
text_end = text + strlen(text); // FIXME-OPT
if (text != text_end)
{
window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
if (g.LogEnabled)
LogRenderedText(&pos, text, text_end);
}
}
// Default clip_rect uses (pos_min,pos_max)
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
{
// Perform CPU side clipping for single clipped element to avoid using scissor state
ImVec2 pos = pos_min;
const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
// Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
// Render
if (need_clipping)
{
ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
}
else
{
draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
}
}
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
{
// Hide anything after a '##' string
const char* text_display_end = FindRenderedTextEnd(text, text_end);
const int text_len = (int)(text_display_end - text);
if (text_len == 0)
return;
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
if (g.LogEnabled)
LogRenderedText(&pos_min, text, text_display_end);
}
// Render a rectangle shaped with optional rounding and borders
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
const float border_size = g.Style.FrameBorderSize;
if (border && border_size > 0.0f)
{
window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
}
}
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const float border_size = g.Style.FrameBorderSize;
if (border_size > 0.0f)
{
window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
}
}
// Render an arrow aimed to be aligned with text (p_min is a position in the same space text would be positioned). To e.g. denote expanded/collapsed state
void ImGui::RenderArrow(ImVec2 p_min, ImGuiDir dir, float scale)
{
ImGuiContext& g = *GImGui;
const float h = g.FontSize * 1.00f;
float r = h * 0.40f * scale;
ImVec2 center = p_min + ImVec2(h * 0.50f, h * 0.50f * scale);
ImVec2 a, b, c;
switch (dir)
{
case ImGuiDir_Up:
case ImGuiDir_Down:
if (dir == ImGuiDir_Up) r = -r;
a = ImVec2(+0.000f,+0.750f) * r;
b = ImVec2(-0.866f,-0.750f) * r;
c = ImVec2(+0.866f,-0.750f) * r;
break;
case ImGuiDir_Left:
case ImGuiDir_Right:
if (dir == ImGuiDir_Left) r = -r;
a = ImVec2(+0.750f,+0.000f) * r;
b = ImVec2(-0.750f,+0.866f) * r;
c = ImVec2(-0.750f,-0.866f) * r;
break;
case ImGuiDir_None:
case ImGuiDir_COUNT:
IM_ASSERT(0);
break;
}
g.CurrentWindow->DrawList->AddTriangleFilled(center + a, center + b, center + c, GetColorU32(ImGuiCol_Text));
}
void ImGui::RenderBullet(ImVec2 pos)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->DrawList->AddCircleFilled(pos, g.FontSize*0.20f, GetColorU32(ImGuiCol_Text), 8);
}
void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col, float sz)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
float thickness = ImMax(sz / 5.0f, 1.0f);
sz -= thickness*0.5f;
pos += ImVec2(thickness*0.25f, thickness*0.25f);
float third = sz / 3.0f;
float bx = pos.x + third;
float by = pos.y + sz - third*0.5f;
window->DrawList->PathLineTo(ImVec2(bx - third, by - third));
window->DrawList->PathLineTo(ImVec2(bx, by));
window->DrawList->PathLineTo(ImVec2(bx + third*2, by - third*2));
window->DrawList->PathStroke(col, false, thickness);
}
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
{
ImGuiContext& g = *GImGui;
if (id != g.NavId)
return;
if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
return;
ImGuiWindow* window = g.CurrentWindow;
if (window->DC.NavHideHighlightOneFrame)
return;
float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
ImRect display_rect = bb;
display_rect.ClipWith(window->ClipRect);
if (flags & ImGuiNavHighlightFlags_TypeDefault)
{
const float THICKNESS = 2.0f;
const float DISTANCE = 3.0f + THICKNESS * 0.5f;
display_rect.Expand(ImVec2(DISTANCE,DISTANCE));
bool fully_visible = window->ClipRect.Contains(display_rect);
if (!fully_visible)
window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), display_rect.Max - ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, ImDrawCornerFlags_All, THICKNESS);
if (!fully_visible)
window->DrawList->PopClipRect();
}
if (flags & ImGuiNavHighlightFlags_TypeThin)
{
window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, ~0, 1.0f);
}
}
//-----------------------------------------------------------------------------
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
//-----------------------------------------------------------------------------
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name)
: DrawListInst(&context->DrawListSharedData)
{
Name = ImStrdup(name);
ID = ImHashStr(name);
IDStack.push_back(ID);
Flags = ImGuiWindowFlags_None;
Pos = ImVec2(0.0f, 0.0f);
Size = SizeFull = ImVec2(0.0f, 0.0f);
SizeContents = SizeContentsExplicit = ImVec2(0.0f, 0.0f);
WindowPadding = ImVec2(0.0f, 0.0f);
WindowRounding = 0.0f;
WindowBorderSize = 0.0f;
NameBufLen = (int)strlen(name) + 1;
MoveId = GetID("#MOVE");
ChildId = 0;
Scroll = ImVec2(0.0f, 0.0f);
ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
ScrollbarSizes = ImVec2(0.0f, 0.0f);
ScrollbarX = ScrollbarY = false;
Active = WasActive = false;
WriteAccessed = false;
Collapsed = false;
WantCollapseToggle = false;
SkipItems = false;
Appearing = false;
Hidden = false;
HasCloseButton = false;
ResizeBorderHeld = -1;
BeginCount = 0;
BeginOrderWithinParent = -1;
BeginOrderWithinContext = -1;
PopupId = 0;
AutoFitFramesX = AutoFitFramesY = -1;
AutoFitOnlyGrows = false;
AutoFitChildAxises = 0x00;
AutoPosLastDirection = ImGuiDir_None;
HiddenFramesCanSkipItems = HiddenFramesCannotSkipItems = 0;
SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
LastFrameActive = -1;
ItemWidthDefault = 0.0f;
FontWindowScale = 1.0f;
SettingsIdx = -1;
DrawList = &DrawListInst;
DrawList->_OwnerName = Name;
ParentWindow = NULL;
RootWindow = NULL;
RootWindowForTitleBarHighlight = NULL;
RootWindowForNav = NULL;
NavLastIds[0] = NavLastIds[1] = 0;
NavRectRel[0] = NavRectRel[1] = ImRect();
NavLastChildNavWindow = NULL;
}
ImGuiWindow::~ImGuiWindow()
{
IM_ASSERT(DrawList == &DrawListInst);
IM_DELETE(Name);
for (int i = 0; i != ColumnsStorage.Size; i++)
ColumnsStorage[i].~ImGuiColumns();
}
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
ImGui::KeepAliveID(id);
return id;
}
ImGuiID ImGuiWindow::GetID(const void* ptr)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
ImGui::KeepAliveID(id);
return id;
}
ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end)
{
ImGuiID seed = IDStack.back();
return ImHashStr(str, str_end ? (str_end - str) : 0, seed);
}
ImGuiID ImGuiWindow::GetIDNoKeepAlive(const void* ptr)
{
ImGuiID seed = IDStack.back();
return ImHashData(&ptr, sizeof(void*), seed);
}
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
{
ImGuiID seed = IDStack.back();
const int r_rel[4] = { (int)(r_abs.Min.x - Pos.x), (int)(r_abs.Min.y - Pos.y), (int)(r_abs.Max.x - Pos.x), (int)(r_abs.Max.y - Pos.y) };
ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
ImGui::KeepAliveID(id);
return id;
}
static void SetCurrentWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
g.CurrentWindow = window;
if (window)
g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
}
void ImGui::SetNavID(ImGuiID id, int nav_layer)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavWindow);
IM_ASSERT(nav_layer == 0 || nav_layer == 1);
g.NavId = id;
g.NavWindow->NavLastIds[nav_layer] = id;
}
void ImGui::SetNavIDWithRectRel(ImGuiID id, int nav_layer, const ImRect& rect_rel)
{
ImGuiContext& g = *GImGui;
SetNavID(id, nav_layer);
g.NavWindow->NavRectRel[nav_layer] = rect_rel;
g.NavMousePosDirty = true;
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
}
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
g.ActiveIdIsJustActivated = (g.ActiveId != id);
if (g.ActiveIdIsJustActivated)
{
g.ActiveIdTimer = 0.0f;
g.ActiveIdHasBeenPressed = false;
g.ActiveIdHasBeenEdited = false;
if (id != 0)
{
g.LastActiveId = id;
g.LastActiveIdTimer = 0.0f;
}
}
g.ActiveId = id;
g.ActiveIdAllowNavDirFlags = 0;
g.ActiveIdBlockNavInputFlags = 0;
g.ActiveIdAllowOverlap = false;
g.ActiveIdWindow = window;
if (id)
{
g.ActiveIdIsAlive = id;
g.ActiveIdSource = (g.NavActivateId == id || g.NavInputId == id || g.NavJustTabbedId == id || g.NavJustMovedToId == id) ? ImGuiInputSource_Nav : ImGuiInputSource_Mouse;
}
}
// FIXME-NAV: The existence of SetNavID/SetNavIDWithRectRel/SetFocusID is incredibly messy and confusing and needs some explanation or refactoring.
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(id != 0);
// Assume that SetFocusID() is called in the context where its NavLayer is the current layer, which is the case everywhere we call it.
const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
if (g.NavWindow != window)
g.NavInitRequest = false;
g.NavId = id;
g.NavWindow = window;
g.NavLayer = nav_layer;
window->NavLastIds[nav_layer] = id;
if (window->DC.LastItemId == id)
window->NavRectRel[nav_layer] = ImRect(window->DC.LastItemRect.Min - window->Pos, window->DC.LastItemRect.Max - window->Pos);
if (g.ActiveIdSource == ImGuiInputSource_Nav)
g.NavDisableMouseHover = true;
else
g.NavDisableHighlight = true;
}
void ImGui::ClearActiveID()
{
SetActiveID(0, NULL);
}
void ImGui::SetHoveredID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
g.HoveredId = id;
g.HoveredIdAllowOverlap = false;
if (id != 0 && g.HoveredIdPreviousFrame != id)
g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
}
ImGuiID ImGui::GetHoveredID()
{
ImGuiContext& g = *GImGui;
return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
}
void ImGui::KeepAliveID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
if (g.ActiveId == id)
g.ActiveIdIsAlive = id;
if (g.ActiveIdPreviousFrame == id)
g.ActiveIdPreviousFrameIsAlive = true;
}
void ImGui::MarkItemEdited(ImGuiID id)
{
// This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
// ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need need to fill the data.
ImGuiContext& g = *GImGui;
IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive);
IM_UNUSED(id); // Avoid unused variable warnings when asserts are compiled out.
//IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
g.ActiveIdHasBeenEdited = true;
g.CurrentWindow->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited;
}
static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
{
// An active popup disable hovering on other windows (apart from its own children)
// FIXME-OPT: This could be cached/stored within the window.
ImGuiContext& g = *GImGui;
if (g.NavWindow)
if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow)
if (focused_root_window->WasActive && focused_root_window != window->RootWindow)
{
// For the purpose of those flags we differentiate "standard popup" from "modal popup"
// NB: The order of those two tests is important because Modal windows are also Popups.
if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
return false;
if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
return false;
}
return true;
}
// Advance cursor given item size for layout.
void ImGui::ItemSize(const ImVec2& size, float text_offset_y)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return;
// Always align ourselves on pixel boundaries
const float line_height = ImMax(window->DC.CurrentLineSize.y, size.y);
const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y);
//if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y);
window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
window->DC.CursorPos.y = (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y);
window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
//if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
window->DC.PrevLineSize.y = line_height;
window->DC.PrevLineTextBaseOffset = text_base_offset;
window->DC.CurrentLineSize.y = window->DC.CurrentLineTextBaseOffset = 0.0f;
// Horizontal layout mode
if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
SameLine();
}
void ImGui::ItemSize(const ImRect& bb, float text_offset_y)
{
ItemSize(bb.GetSize(), text_offset_y);
}
// Declare item bounding box for clipping and interaction.
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
// declare their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd().
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (id != 0)
{
// Navigation processing runs prior to clipping early-out
// (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
// (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests unfortunately, but it is still limited to one window.
// it may not scale very well for windows with ten of thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
// We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick)
window->DC.NavLayerActiveMaskNext |= window->DC.NavLayerCurrentMask;
if (g.NavId == id || g.NavAnyRequest)
if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
NavProcessItem(window, nav_bb_arg ? *nav_bb_arg : bb, id);
}
window->DC.LastItemId = id;
window->DC.LastItemRect = bb;
window->DC.LastItemStatusFlags = ImGuiItemStatusFlags_None;
#ifdef IMGUI_ENABLE_TEST_ENGINE
if (id != 0)
IMGUI_TEST_ENGINE_ITEM_ADD(nav_bb_arg ? *nav_bb_arg : bb, id);
#endif
// Clipping test
const bool is_clipped = IsClippedEx(bb, id, false);
if (is_clipped)
return false;
//if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
// We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
if (IsMouseHoveringRect(bb.Min, bb.Max))
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HoveredRect;
return true;
}
// This is roughly matching the behavior of internal-facing ItemHoverable()
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavDisableMouseHover && !g.NavDisableHighlight)
return IsItemFocused();
// Test for bounding box overlap, as updated as ItemAdd()
if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
return false;
IM_ASSERT((flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows)) == 0); // Flags not supported by this function
// Test if we are hovering the right window (our window could be behind another window)
// [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable to use IsItemHovered() after EndChild() itself.
// Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was the test that has been running for a long while.
//if (g.HoveredWindow != window)
// return false;
if (g.HoveredRootWindow != window->RootWindow && !(flags & ImGuiHoveredFlags_AllowWhenOverlapped))
return false;
// Test if another item is active (e.g. being dragged)
if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
if (g.ActiveId != 0 && g.ActiveId != window->DC.LastItemId && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId)
return false;
// Test if interactions on this window are blocked by an active popup or modal.
// The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
if (!IsWindowContentHoverable(window, flags))
return false;
// Test if the item is disabled
if ((window->DC.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
return false;
// Special handling for the dummy item after Begin() which represent the title bar or tab.
// When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
if (window->DC.LastItemId == window->MoveId && window->WriteAccessed)
return false;
return true;
}
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
{
ImGuiContext& g = *GImGui;
if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
return false;
ImGuiWindow* window = g.CurrentWindow;
if (g.HoveredWindow != window)
return false;
if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
return false;
if (!IsMouseHoveringRect(bb.Min, bb.Max))
return false;
if (g.NavDisableMouseHover || !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
return false;
if (window->DC.ItemFlags & ImGuiItemFlags_Disabled)
return false;
SetHoveredID(id);
return true;
}
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!bb.Overlaps(window->ClipRect))
if (id == 0 || id != g.ActiveId)
if (clip_even_when_logged || !g.LogEnabled)
return true;
return false;
}
// Process TAB/Shift+TAB. Be mindful that this function may _clear_ the ActiveID when tabbing out.
bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id)
{
ImGuiContext& g = *GImGui;
// Increment counters
const bool is_tab_stop = (window->DC.ItemFlags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0;
window->DC.FocusCounterAll++;
if (is_tab_stop)
window->DC.FocusCounterTab++;
// Process TAB/Shift-TAB to tab *OUT* of the currently focused item.
// (Note that we can always TAB out of a widget that doesn't allow tabbing in)
if (g.ActiveId == id && g.FocusTabPressed && !(g.ActiveIdBlockNavInputFlags & (1 << ImGuiNavInput_KeyTab_)) && g.FocusRequestNextWindow == NULL)
{
g.FocusRequestNextWindow = window;
g.FocusRequestNextCounterTab = window->DC.FocusCounterTab + (g.IO.KeyShift ? (is_tab_stop ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items.
}
// Handle focus requests
if (g.FocusRequestCurrWindow == window)
{
if (window->DC.FocusCounterAll == g.FocusRequestCurrCounterAll)
return true;
if (is_tab_stop && window->DC.FocusCounterTab == g.FocusRequestCurrCounterTab)
{
g.NavJustTabbedId = id;
return true;
}
// If another item is about to be focused, we clear our own active id
if (g.ActiveId == id)
ClearActiveID();
}
return false;
}
void ImGui::FocusableItemUnregister(ImGuiWindow* window)
{
window->DC.FocusCounterAll--;
window->DC.FocusCounterTab--;
}
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
{
if (wrap_pos_x < 0.0f)
return 0.0f;
ImGuiWindow* window = GImGui->CurrentWindow;
if (wrap_pos_x == 0.0f)
wrap_pos_x = GetWorkRectMax().x;
else if (wrap_pos_x > 0.0f)
wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
return ImMax(wrap_pos_x - pos.x, 1.0f);
}
// IM_ALLOC() == ImGui::MemAlloc()
void* ImGui::MemAlloc(size_t size)
{
if (ImGuiContext* ctx = GImGui)
ctx->IO.MetricsActiveAllocations++;
return GImAllocatorAllocFunc(size, GImAllocatorUserData);
}
// IM_FREE() == ImGui::MemFree()
void ImGui::MemFree(void* ptr)
{
if (ptr)
if (ImGuiContext* ctx = GImGui)
ctx->IO.MetricsActiveAllocations--;
return GImAllocatorFreeFunc(ptr, GImAllocatorUserData);
}
const char* ImGui::GetClipboardText()
{
return GImGui->IO.GetClipboardTextFn ? GImGui->IO.GetClipboardTextFn(GImGui->IO.ClipboardUserData) : "";
}
void ImGui::SetClipboardText(const char* text)
{
if (GImGui->IO.SetClipboardTextFn)
GImGui->IO.SetClipboardTextFn(GImGui->IO.ClipboardUserData, text);
}
const char* ImGui::GetVersion()
{
return IMGUI_VERSION;
}
// Internal state access - if you want to share ImGui state between modules (e.g. DLL) or allocate it yourself
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
ImGuiContext* ImGui::GetCurrentContext()
{
return GImGui;
}
void ImGui::SetCurrentContext(ImGuiContext* ctx)
{
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
#else
GImGui = ctx;
#endif
}
// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
// If the user has inconsistent compilation settings, imgui configuration #define, packing pragma, etc. your user code
// may see different structures thanwhat imgui.cpp sees, which is problematic.
// We usually require settings to be in imconfig.h to make sure that they are accessible to all compilation units involved with Dear ImGui.
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
{
bool error = false;
if (strcmp(version, IMGUI_VERSION)!=0) { error = true; IM_ASSERT(strcmp(version,IMGUI_VERSION)==0 && "Mismatched version string!"); }
if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
return !error;
}
void ImGui::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data)
{
GImAllocatorAllocFunc = alloc_func;
GImAllocatorFreeFunc = free_func;
GImAllocatorUserData = user_data;
}
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
{
ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
if (GImGui == NULL)
SetCurrentContext(ctx);
Initialize(ctx);
return ctx;
}
void ImGui::DestroyContext(ImGuiContext* ctx)
{
if (ctx == NULL)
ctx = GImGui;
Shutdown(ctx);
if (GImGui == ctx)
SetCurrentContext(NULL);
IM_DELETE(ctx);
}
ImGuiIO& ImGui::GetIO()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
return GImGui->IO;
}
ImGuiStyle& ImGui::GetStyle()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
return GImGui->Style;
}
// Same value as passed to the old io.RenderDrawListsFn function. Valid after Render() and until the next call to NewFrame()
ImDrawData* ImGui::GetDrawData()
{
ImGuiContext& g = *GImGui;
return g.DrawData.Valid ? &g.DrawData : NULL;
}
double ImGui::GetTime()
{
return GImGui->Time;
}
int ImGui::GetFrameCount()
{
return GImGui->FrameCount;
}
ImDrawList* ImGui::GetBackgroundDrawList()
{
return &GImGui->BackgroundDrawList;
}
static ImDrawList* GetForegroundDrawList(ImGuiWindow*)
{
// This seemingly unnecessary wrapper simplifies compatibility between the 'master' and 'docking' branches.
return &GImGui->ForegroundDrawList;
}
ImDrawList* ImGui::GetForegroundDrawList()
{
return &GImGui->ForegroundDrawList;
}
ImDrawListSharedData* ImGui::GetDrawListSharedData()
{
return &GImGui->DrawListSharedData;
}
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
{
// Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
// We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
// This is because we want ActiveId to be set even when the window is not permitted to move.
ImGuiContext& g = *GImGui;
FocusWindow(window);
SetActiveID(window->MoveId, window);
g.NavDisableHighlight = true;
g.ActiveIdClickOffset = g.IO.MousePos - window->RootWindow->Pos;
bool can_move_window = true;
if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindow->Flags & ImGuiWindowFlags_NoMove))
can_move_window = false;
if (can_move_window)
g.MovingWindow = window;
}
// Handle mouse moving window
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
void ImGui::UpdateMouseMovingWindowNewFrame()
{
ImGuiContext& g = *GImGui;
if (g.MovingWindow != NULL)
{
// We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
// We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
KeepAliveID(g.ActiveId);
IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow);
ImGuiWindow* moving_window = g.MovingWindow->RootWindow;
if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos))
{
ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
{
MarkIniSettingsDirty(moving_window);
SetWindowPos(moving_window, pos, ImGuiCond_Always);
}
FocusWindow(g.MovingWindow);
}
else
{
ClearActiveID();
g.MovingWindow = NULL;
}
}
else
{
// When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
{
KeepAliveID(g.ActiveId);
if (!g.IO.MouseDown[0])
ClearActiveID();
}
}
}
// Initiate moving window, handle left-click and right-click focus
void ImGui::UpdateMouseMovingWindowEndFrame()
{
// Initiate moving window
ImGuiContext& g = *GImGui;
if (g.ActiveId != 0 || g.HoveredId != 0)
return;
// Unless we just made a window/popup appear
if (g.NavWindow && g.NavWindow->Appearing)
return;
// Click to focus window and start moving (after we're done with all our widgets)
if (g.IO.MouseClicked[0])
{
if (g.HoveredRootWindow != NULL)
{
StartMouseMovingWindow(g.HoveredWindow);
if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(g.HoveredRootWindow->Flags & ImGuiWindowFlags_NoTitleBar))
if (!g.HoveredRootWindow->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
g.MovingWindow = NULL;
}
else if (g.NavWindow != NULL && GetFrontMostPopupModal() == NULL)
{
// Clicking on void disable focus
FocusWindow(NULL);
}
}
// With right mouse button we close popups without changing focus based on where the mouse is aimed
// Instead, focus will be restored to the window under the bottom-most closed popup.
// (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
if (g.IO.MouseClicked[1])
{
// Find the top-most window between HoveredWindow and the front most Modal Window.
// This is where we can trim the popup stack.
ImGuiWindow* modal = GetFrontMostPopupModal();
bool hovered_window_above_modal = false;
if (modal == NULL)
hovered_window_above_modal = true;
for (int i = g.Windows.Size - 1; i >= 0 && hovered_window_above_modal == false; i--)
{
ImGuiWindow* window = g.Windows[i];
if (window == modal)
break;
if (window == g.HoveredWindow)
hovered_window_above_modal = true;
}
ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
}
}
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
{
return (window->Active) && (!window->Hidden);
}
static void ImGui::UpdateMouseInputs()
{
ImGuiContext& g = *GImGui;
// Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
if (IsMousePosValid(&g.IO.MousePos))
g.IO.MousePos = g.LastValidMousePos = ImFloor(g.IO.MousePos);
// If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MousePosPrev))
g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev;
else
g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
if (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f)
g.NavDisableMouseHover = false;
g.IO.MousePosPrev = g.IO.MousePos;
for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
{
g.IO.MouseClicked[i] = g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] < 0.0f;
g.IO.MouseReleased[i] = !g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] >= 0.0f;
g.IO.MouseDownDurationPrev[i] = g.IO.MouseDownDuration[i];
g.IO.MouseDownDuration[i] = g.IO.MouseDown[i] ? (g.IO.MouseDownDuration[i] < 0.0f ? 0.0f : g.IO.MouseDownDuration[i] + g.IO.DeltaTime) : -1.0f;
g.IO.MouseDoubleClicked[i] = false;
if (g.IO.MouseClicked[i])
{
if ((float)(g.Time - g.IO.MouseClickedTime[i]) < g.IO.MouseDoubleClickTime)
{
ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
if (ImLengthSqr(delta_from_click_pos) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist)
g.IO.MouseDoubleClicked[i] = true;
g.IO.MouseClickedTime[i] = -FLT_MAX; // so the third click isn't turned into a double-click
}
else
{
g.IO.MouseClickedTime[i] = g.Time;
}
g.IO.MouseClickedPos[i] = g.IO.MousePos;
g.IO.MouseDownWasDoubleClick[i] = g.IO.MouseDoubleClicked[i];
g.IO.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
g.IO.MouseDragMaxDistanceSqr[i] = 0.0f;
}
else if (g.IO.MouseDown[i])
{
// Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
g.IO.MouseDragMaxDistanceAbs[i].x = ImMax(g.IO.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
g.IO.MouseDragMaxDistanceAbs[i].y = ImMax(g.IO.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
}
if (!g.IO.MouseDown[i] && !g.IO.MouseReleased[i])
g.IO.MouseDownWasDoubleClick[i] = false;
if (g.IO.MouseClicked[i]) // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
g.NavDisableMouseHover = false;
}
}
void ImGui::UpdateMouseWheel()
{
ImGuiContext& g = *GImGui;
if (!g.HoveredWindow || g.HoveredWindow->Collapsed)
return;
if (g.IO.MouseWheel == 0.0f && g.IO.MouseWheelH == 0.0f)
return;
ImGuiWindow* window = g.HoveredWindow;
// Zoom / Scale window
// FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
if (g.IO.MouseWheel != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
{
const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
const float scale = new_font_scale / window->FontWindowScale;
window->FontWindowScale = new_font_scale;
if (!(window->Flags & ImGuiWindowFlags_ChildWindow))
{
const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
window->Pos = ImFloor(window->Pos + offset);
window->Size = ImFloor(window->Size * scale);
window->SizeFull = ImFloor(window->SizeFull * scale);
}
return;
}
// Mouse wheel scrolling
// If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent (unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set).
while ((window->Flags & ImGuiWindowFlags_ChildWindow) && (window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs) && window->ParentWindow)
window = window->ParentWindow;
const bool scroll_allowed = !(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs);
if (scroll_allowed && (g.IO.MouseWheel != 0.0f || g.IO.MouseWheelH != 0.0f) && !g.IO.KeyCtrl)
{
ImVec2 max_step = (window->ContentsRegionRect.GetSize() + window->WindowPadding * 2.0f) * 0.67f;
// Vertical Mouse Wheel Scrolling (hold Shift to scroll horizontally)
if (g.IO.MouseWheel != 0.0f && !g.IO.KeyShift)
{
float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step.y));
SetWindowScrollY(window, window->Scroll.y - g.IO.MouseWheel * scroll_step);
}
else if (g.IO.MouseWheel != 0.0f && g.IO.KeyShift)
{
float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step.x));
SetWindowScrollX(window, window->Scroll.x - g.IO.MouseWheel * scroll_step);
}
// Horizontal Mouse Wheel Scrolling (for hardware that supports it)
if (g.IO.MouseWheelH != 0.0f && !g.IO.KeyShift)
{
float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step.x));
SetWindowScrollX(window, window->Scroll.x - g.IO.MouseWheelH * scroll_step);
}
}
}
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
void ImGui::UpdateHoveredWindowAndCaptureFlags()
{
ImGuiContext& g = *GImGui;
// Find the window hovered by mouse:
// - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
// - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
// - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
FindHoveredWindow();
// Modal windows prevents cursor from hovering behind them.
ImGuiWindow* modal_window = GetFrontMostPopupModal();
if (modal_window)
if (g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window))
g.HoveredRootWindow = g.HoveredWindow = NULL;
// Disabled mouse?
if (g.IO.ConfigFlags & ImGuiConfigFlags_NoMouse)
g.HoveredWindow = g.HoveredRootWindow = NULL;
// We track click ownership. When clicked outside of a window the click is owned by the application and won't report hovering nor request capture even while dragging over our windows afterward.
int mouse_earliest_button_down = -1;
bool mouse_any_down = false;
for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
{
if (g.IO.MouseClicked[i])
g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (!g.OpenPopupStack.empty());
mouse_any_down |= g.IO.MouseDown[i];
if (g.IO.MouseDown[i])
if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[i] < g.IO.MouseClickedTime[mouse_earliest_button_down])
mouse_earliest_button_down = i;
}
const bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down];
// If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
// FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload)
g.HoveredWindow = g.HoveredRootWindow = NULL;
// Update io.WantCaptureMouse for the user application (true = dispatch mouse info to imgui, false = dispatch mouse info to imgui + app)
if (g.WantCaptureMouseNextFrame != -1)
g.IO.WantCaptureMouse = (g.WantCaptureMouseNextFrame != 0);
else
g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (!g.OpenPopupStack.empty());
// Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to imgui, false = dispatch keyboard info to imgui + app)
if (g.WantCaptureKeyboardNextFrame != -1)
g.IO.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
else
g.IO.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
if (g.IO.NavActive && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
g.IO.WantCaptureKeyboard = true;
// Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
g.IO.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
}
void ImGui::NewFrame()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
ImGuiContext& g = *GImGui;
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiTestEngineHook_PreNewFrame(&g);
#endif
// Check user data
// (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
IM_ASSERT(g.Initialized);
IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!");
IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!");
IM_ASSERT(g.IO.Fonts->Fonts.Size > 0 && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!");
IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)!");
IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
for (int n = 0; n < ImGuiKey_COUNT; n++)
IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && "io.KeyMap[] contains an out of bound value (need to be 0..512, or -1 for unmapped key)");
// Perform simple check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only recently added in 1.60 WIP)
if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard)
IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
// Perform simple check: the beta io.ConfigWindowsResizeFromEdges option requires back-end to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
g.IO.ConfigWindowsResizeFromEdges = false;
// Load settings on first frame (if not explicitly loaded manually before)
if (!g.SettingsLoaded)
{
IM_ASSERT(g.SettingsWindows.empty());
if (g.IO.IniFilename)
LoadIniSettingsFromDisk(g.IO.IniFilename);
g.SettingsLoaded = true;
}
// Save settings (with a delay after the last modification, so we don't spam disk too much)
if (g.SettingsDirtyTimer > 0.0f)
{
g.SettingsDirtyTimer -= g.IO.DeltaTime;
if (g.SettingsDirtyTimer <= 0.0f)
{
if (g.IO.IniFilename != NULL)
SaveIniSettingsToDisk(g.IO.IniFilename);
else
g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
g.SettingsDirtyTimer = 0.0f;
}
}
g.Time += g.IO.DeltaTime;
g.FrameScopeActive = true;
g.FrameCount += 1;
g.TooltipOverrideCount = 0;
g.WindowsActiveCount = 0;
// Setup current font and draw list shared data
g.IO.Fonts->Locked = true;
SetCurrentFont(GetDefaultFont());
IM_ASSERT(g.Font->IsLoaded());
g.DrawListSharedData.ClipRectFullscreen = ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
g.BackgroundDrawList.Clear();
g.BackgroundDrawList.PushTextureID(g.IO.Fonts->TexID);
g.BackgroundDrawList.PushClipRectFullScreen();
g.BackgroundDrawList.Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0);
g.ForegroundDrawList.Clear();
g.ForegroundDrawList.PushTextureID(g.IO.Fonts->TexID);
g.ForegroundDrawList.PushClipRectFullScreen();
g.ForegroundDrawList.Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0);
// Mark rendering data as invalid to prevent user who may have a handle on it to use it.
g.DrawData.Clear();
// Drag and drop keep the source ID alive so even if the source disappear our state is consistent
if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
KeepAliveID(g.DragDropPayload.SourceId);
// Clear reference to active widget if the widget isn't alive anymore
if (!g.HoveredIdPreviousFrame)
g.HoveredIdTimer = 0.0f;
if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
g.HoveredIdNotActiveTimer = 0.0f;
if (g.HoveredId)
g.HoveredIdTimer += g.IO.DeltaTime;
if (g.HoveredId && g.ActiveId != g.HoveredId)
g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
g.HoveredIdPreviousFrame = g.HoveredId;
g.HoveredId = 0;
g.HoveredIdAllowOverlap = false;
if (g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)
ClearActiveID();
if (g.ActiveId)
g.ActiveIdTimer += g.IO.DeltaTime;
g.LastActiveIdTimer += g.IO.DeltaTime;
g.ActiveIdPreviousFrame = g.ActiveId;
g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
g.ActiveIdPreviousFrameHasBeenEdited = g.ActiveIdHasBeenEdited;
g.ActiveIdIsAlive = 0;
g.ActiveIdPreviousFrameIsAlive = false;
g.ActiveIdIsJustActivated = false;
if (g.TempInputTextId != 0 && g.ActiveId != g.TempInputTextId)
g.TempInputTextId = 0;
// Drag and drop
g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
g.DragDropAcceptIdCurr = 0;
g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
g.DragDropWithinSourceOrTarget = false;
// Update keyboard input state
memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration));
for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++)
g.IO.KeysDownDuration[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownDuration[i] < 0.0f ? 0.0f : g.IO.KeysDownDuration[i] + g.IO.DeltaTime) : -1.0f;
// Update gamepad/keyboard directional navigation
NavUpdate();
// Update mouse input state
UpdateMouseInputs();
// Calculate frame-rate for the user, as a purely luxurious feature
g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame))) : FLT_MAX;
// Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
UpdateMouseMovingWindowNewFrame();
UpdateHoveredWindowAndCaptureFlags();
// Background darkening/whitening
if (GetFrontMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
else
g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
g.MouseCursor = ImGuiMouseCursor_Arrow;
g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
g.PlatformImePos = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default
// Mouse wheel scrolling, scale
UpdateMouseWheel();
// Pressing TAB activate widget focus
g.FocusTabPressed = (g.NavWindow && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab));
if (g.ActiveId == 0 && g.FocusTabPressed)
{
// Note that SetKeyboardFocusHere() sets the Next fields mid-frame. To be consistent we also
// manipulate the Next fields even, even though they will be turned into Curr fields by the code below.
g.FocusRequestNextWindow = g.NavWindow;
g.FocusRequestNextCounterAll = INT_MAX;
if (g.NavId != 0 && g.NavIdTabCounter != INT_MAX)
g.FocusRequestNextCounterTab = g.NavIdTabCounter + 1 + (g.IO.KeyShift ? -1 : 1);
else
g.FocusRequestNextCounterTab = g.IO.KeyShift ? -1 : 0;
}
// Turn queued focus request into current one
g.FocusRequestCurrWindow = NULL;
g.FocusRequestCurrCounterAll = g.FocusRequestCurrCounterTab = INT_MAX;
if (g.FocusRequestNextWindow != NULL)
{
ImGuiWindow* window = g.FocusRequestNextWindow;
g.FocusRequestCurrWindow = window;
if (g.FocusRequestNextCounterAll != INT_MAX && window->DC.FocusCounterAll != -1)
g.FocusRequestCurrCounterAll = ImModPositive(g.FocusRequestNextCounterAll, window->DC.FocusCounterAll + 1);
if (g.FocusRequestNextCounterTab != INT_MAX && window->DC.FocusCounterTab != -1)
g.FocusRequestCurrCounterTab = ImModPositive(g.FocusRequestNextCounterTab, window->DC.FocusCounterTab + 1);
g.FocusRequestNextWindow = NULL;
g.FocusRequestNextCounterAll = g.FocusRequestNextCounterTab = INT_MAX;
}
g.NavIdTabCounter = INT_MAX;
// Mark all windows as not visible
IM_ASSERT(g.WindowsFocusOrder.Size == g.Windows.Size);
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
window->WasActive = window->Active;
window->BeginCount = 0;
window->Active = false;
window->WriteAccessed = false;
}
// Closing the focused window restore focus to the first active root window in descending z-order
if (g.NavWindow && !g.NavWindow->WasActive)
FocusTopMostWindowUnderOne(NULL, NULL);
// No window should be open at the beginning of the frame.
// But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
g.CurrentWindowStack.resize(0);
g.BeginPopupStack.resize(0);
ClosePopupsOverWindow(g.NavWindow, false);
// Create implicit/fallback window - which we will only render it if the user has added something to it.
// We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
// This fallback is particularly important as it avoid ImGui:: calls from crashing.
SetNextWindowSize(ImVec2(400,400), ImGuiCond_FirstUseEver);
Begin("Debug##Default");
g.FrameScopePushedImplicitWindow = true;
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiTestEngineHook_PostNewFrame(&g);
#endif
}
void ImGui::Initialize(ImGuiContext* context)
{
ImGuiContext& g = *context;
IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
// Add .ini handle for ImGuiWindow type
ImGuiSettingsHandler ini_handler;
ini_handler.TypeName = "Window";
ini_handler.TypeHash = ImHashStr("Window");
ini_handler.ReadOpenFn = SettingsHandlerWindow_ReadOpen;
ini_handler.ReadLineFn = SettingsHandlerWindow_ReadLine;
ini_handler.WriteAllFn = SettingsHandlerWindow_WriteAll;
g.SettingsHandlers.push_back(ini_handler);
g.Initialized = true;
}
// This function is merely here to free heap allocations.
void ImGui::Shutdown(ImGuiContext* context)
{
// The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
ImGuiContext& g = *context;
if (g.IO.Fonts && g.FontAtlasOwnedByContext)
{
g.IO.Fonts->Locked = false;
IM_DELETE(g.IO.Fonts);
}
g.IO.Fonts = NULL;
// Cleanup of other data are conditional on actually having initialized ImGui.
if (!g.Initialized)
return;
// Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
if (g.SettingsLoaded && g.IO.IniFilename != NULL)
{
ImGuiContext* backup_context = GImGui;
SetCurrentContext(context);
SaveIniSettingsToDisk(g.IO.IniFilename);
SetCurrentContext(backup_context);
}
// Clear everything else
for (int i = 0; i < g.Windows.Size; i++)
IM_DELETE(g.Windows[i]);
g.Windows.clear();
g.WindowsFocusOrder.clear();
g.WindowsSortBuffer.clear();
g.CurrentWindow = NULL;
g.CurrentWindowStack.clear();
g.WindowsById.Clear();
g.NavWindow = NULL;
g.HoveredWindow = g.HoveredRootWindow = NULL;
g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
g.MovingWindow = NULL;
g.ColorModifiers.clear();
g.StyleModifiers.clear();
g.FontStack.clear();
g.OpenPopupStack.clear();
g.BeginPopupStack.clear();
g.DrawDataBuilder.ClearFreeMemory();
g.BackgroundDrawList.ClearFreeMemory();
g.ForegroundDrawList.ClearFreeMemory();
g.PrivateClipboard.clear();
g.InputTextState.ClearFreeMemory();
for (int i = 0; i < g.SettingsWindows.Size; i++)
IM_DELETE(g.SettingsWindows[i].Name);
g.SettingsWindows.clear();
g.SettingsHandlers.clear();
if (g.LogFile && g.LogFile != stdout)
{
fclose(g.LogFile);
g.LogFile = NULL;
}
g.LogBuffer.clear();
g.Initialized = false;
}
// FIXME: Add a more explicit sort order in the window structure.
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
{
const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
return d;
if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
return d;
return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
}
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
{
out_sorted_windows->push_back(window);
if (window->Active)
{
int count = window->DC.ChildWindows.Size;
if (count > 1)
ImQsort(window->DC.ChildWindows.begin(), (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
for (int i = 0; i < count; i++)
{
ImGuiWindow* child = window->DC.ChildWindows[i];
if (child->Active)
AddWindowToSortBuffer(out_sorted_windows, child);
}
}
}
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list)
{
if (draw_list->CmdBuffer.empty())
return;
// Remove trailing command if unused
ImDrawCmd& last_cmd = draw_list->CmdBuffer.back();
if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL)
{
draw_list->CmdBuffer.pop_back();
if (draw_list->CmdBuffer.empty())
return;
}
// Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. May trigger for you if you are using PrimXXX functions incorrectly.
IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
// Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
// If this assert triggers because you are drawing lots of stuff manually:
// A) Make sure you are coarse clipping, because ImDrawList let all your vertices pass. You can use the Metrics window to inspect draw list contents.
// B) If you need/want meshes with more than 64K vertices, uncomment the '#define ImDrawIdx unsigned int' line in imconfig.h to set the index size to 4 bytes.
// You'll need to handle the 4-bytes indices to your renderer. For example, the OpenGL example code detect index size at compile-time by doing:
// glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
// Your own engine or render API may use different parameters or function calls to specify index sizes. 2 and 4 bytes indices are generally supported by most API.
// C) If for some reason you cannot use 4 bytes indices or don't want to, a workaround is to call BeginChild()/EndChild() before reaching the 64K limit to split your draw commands in multiple draw lists.
if (sizeof(ImDrawIdx) == 2)
IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
out_list->push_back(draw_list);
}
static void AddWindowToDrawData(ImVector<ImDrawList*>* out_render_list, ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
g.IO.MetricsRenderWindows++;
AddDrawListToDrawData(out_render_list, window->DrawList);
for (int i = 0; i < window->DC.ChildWindows.Size; i++)
{
ImGuiWindow* child = window->DC.ChildWindows[i];
if (IsWindowActiveAndVisible(child)) // clipped children may have been marked not active
AddWindowToDrawData(out_render_list, child);
}
}
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
static void AddRootWindowToDrawData(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (window->Flags & ImGuiWindowFlags_Tooltip)
AddWindowToDrawData(&g.DrawDataBuilder.Layers[1], window);
else
AddWindowToDrawData(&g.DrawDataBuilder.Layers[0], window);
}
void ImDrawDataBuilder::FlattenIntoSingleLayer()
{
int n = Layers[0].Size;
int size = n;
for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)
size += Layers[i].Size;
Layers[0].resize(size);
for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)
{
ImVector<ImDrawList*>& layer = Layers[layer_n];
if (layer.empty())
continue;
memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
n += layer.Size;
layer.resize(0);
}
}
static void SetupDrawData(ImVector<ImDrawList*>* draw_lists, ImDrawData* draw_data)
{
ImGuiIO& io = ImGui::GetIO();
draw_data->Valid = true;
draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
draw_data->CmdListsCount = draw_lists->Size;
draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
draw_data->DisplayPos = ImVec2(0.0f, 0.0f);
draw_data->DisplaySize = io.DisplaySize;
draw_data->FramebufferScale = io.DisplayFramebufferScale;
for (int n = 0; n < draw_lists->Size; n++)
{
draw_data->TotalVtxCount += draw_lists->Data[n]->VtxBuffer.Size;
draw_data->TotalIdxCount += draw_lists->Data[n]->IdxBuffer.Size;
}
}
// When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result.
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
{
ImGuiWindow* window = GetCurrentWindow();
window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
window->ClipRect = window->DrawList->_ClipRectStack.back();
}
void ImGui::PopClipRect()
{
ImGuiWindow* window = GetCurrentWindow();
window->DrawList->PopClipRect();
window->ClipRect = window->DrawList->_ClipRectStack.back();
}
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
void ImGui::EndFrame()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized);
if (g.FrameCountEnded == g.FrameCount) // Don't process EndFrame() multiple times.
return;
IM_ASSERT(g.FrameScopeActive && "Forgot to call ImGui::NewFrame()?");
// Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
if (g.IO.ImeSetInputScreenPosFn && (g.PlatformImeLastPos.x == FLT_MAX || ImLengthSqr(g.PlatformImeLastPos - g.PlatformImePos) > 0.0001f))
{
g.IO.ImeSetInputScreenPosFn((int)g.PlatformImePos.x, (int)g.PlatformImePos.y);
g.PlatformImeLastPos = g.PlatformImePos;
}
// Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
// to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
if (g.CurrentWindowStack.Size != 1)
{
if (g.CurrentWindowStack.Size > 1)
{
IM_ASSERT(g.CurrentWindowStack.Size == 1 && "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
while (g.CurrentWindowStack.Size > 1) // FIXME-ERRORHANDLING
End();
}
else
{
IM_ASSERT(g.CurrentWindowStack.Size == 1 && "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
}
}
// Hide implicit/fallback "Debug" window if it hasn't been used
g.FrameScopePushedImplicitWindow = false;
if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
g.CurrentWindow->Active = false;
End();
// Show CTRL+TAB list window
if (g.NavWindowingTarget)
NavUpdateWindowingList();
// Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
if (g.DragDropActive)
{
bool is_delivered = g.DragDropPayload.Delivery;
bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
if (is_delivered || is_elapsed)
ClearDragDrop();
}
// Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount)
{
g.DragDropWithinSourceOrTarget = true;
SetTooltip("...");
g.DragDropWithinSourceOrTarget = false;
}
// End frame
g.FrameScopeActive = false;
g.FrameCountEnded = g.FrameCount;
// Initiate moving window + handle left-click and right-click focus
UpdateMouseMovingWindowEndFrame();
// Sort the window list so that all child windows are after their parent
// We cannot do that on FocusWindow() because childs may not exist yet
g.WindowsSortBuffer.resize(0);
g.WindowsSortBuffer.reserve(g.Windows.Size);
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
continue;
AddWindowToSortBuffer(&g.WindowsSortBuffer, window);
}
// This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size);
g.Windows.swap(g.WindowsSortBuffer);
g.IO.MetricsActiveWindows = g.WindowsActiveCount;
// Unlock font atlas
g.IO.Fonts->Locked = false;
// Clear Input data for next frame
g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
g.IO.InputQueueCharacters.resize(0);
memset(g.IO.NavInputs, 0, sizeof(g.IO.NavInputs));
}
void ImGui::Render()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized);
if (g.FrameCountEnded != g.FrameCount)
EndFrame();
g.FrameCountRendered = g.FrameCount;
// Gather ImDrawList to render (for each active window)
g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsRenderWindows = 0;
g.DrawDataBuilder.Clear();
if (!g.BackgroundDrawList.VtxBuffer.empty())
AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.BackgroundDrawList);
ImGuiWindow* windows_to_render_front_most[2];
windows_to_render_front_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL;
windows_to_render_front_most[1] = g.NavWindowingTarget ? g.NavWindowingList : NULL;
for (int n = 0; n != g.Windows.Size; n++)
{
ImGuiWindow* window = g.Windows[n];
if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_front_most[0] && window != windows_to_render_front_most[1])
AddRootWindowToDrawData(window);
}
for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_front_most); n++)
if (windows_to_render_front_most[n] && IsWindowActiveAndVisible(windows_to_render_front_most[n])) // NavWindowingTarget is always temporarily displayed as the front-most window
AddRootWindowToDrawData(windows_to_render_front_most[n]);
g.DrawDataBuilder.FlattenIntoSingleLayer();
// Draw software mouse cursor if requested
if (g.IO.MouseDrawCursor)
RenderMouseCursor(&g.ForegroundDrawList, g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor);
if (!g.ForegroundDrawList.VtxBuffer.empty())
AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.ForegroundDrawList);
// Setup ImDrawData structure for end-user
SetupDrawData(&g.DrawDataBuilder.Layers[0], &g.DrawData);
g.IO.MetricsRenderVertices = g.DrawData.TotalVtxCount;
g.IO.MetricsRenderIndices = g.DrawData.TotalIdxCount;
// (Legacy) Call the Render callback function. The current prefer way is to let the user retrieve GetDrawData() and call the render function themselves.
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
if (g.DrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL)
g.IO.RenderDrawListsFn(&g.DrawData);
#endif
}
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
// CalcTextSize("") should return ImVec2(0.0f, GImGui->FontSize)
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
{
ImGuiContext& g = *GImGui;
const char* text_display_end;
if (hide_text_after_double_hash)
text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
else
text_display_end = text_end;
ImFont* font = g.Font;
const float font_size = g.FontSize;
if (text == text_display_end)
return ImVec2(0.0f, font_size);
ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
// Round
text_size.x = (float)(int)(text_size.x + 0.95f);
return text_size;
}
// Helper to calculate coarse clipping of large list of evenly sized items.
// NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern.
// NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX
void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.LogEnabled)
{
// If logging is active, do not perform any clipping
*out_items_display_start = 0;
*out_items_display_end = items_count;
return;
}
if (window->SkipItems)
{
*out_items_display_start = *out_items_display_end = 0;
return;
}
// We create the union of the ClipRect and the NavScoringRect which at worst should be 1 page away from ClipRect
ImRect unclipped_rect = window->ClipRect;
if (g.NavMoveRequest)
unclipped_rect.Add(g.NavScoringRectScreen);
const ImVec2 pos = window->DC.CursorPos;
int start = (int)((unclipped_rect.Min.y - pos.y) / items_height);
int end = (int)((unclipped_rect.Max.y - pos.y) / items_height);
// When performing a navigation request, ensure we have one item extra in the direction we are moving to
if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Up)
start--;
if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Down)
end++;
start = ImClamp(start, 0, items_count);
end = ImClamp(end + 1, start, items_count);
*out_items_display_start = start;
*out_items_display_end = end;
}
// Find window given position, search front-to-back
// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programatically
// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
// called, aka before the next Begin(). Moving window isn't affected.
static void FindHoveredWindow()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* hovered_window = NULL;
if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
hovered_window = g.MovingWindow;
ImVec2 padding_regular = g.Style.TouchExtraPadding;
ImVec2 padding_for_resize_from_edges = g.IO.ConfigWindowsResizeFromEdges ? ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS)) : padding_regular;
for (int i = g.Windows.Size - 1; i >= 0; i--)
{
ImGuiWindow* window = g.Windows[i];
if (!window->Active || window->Hidden)
continue;
if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
continue;
// Using the clipped AABB, a child window will typically be clipped by its parent (not always)
ImRect bb(window->OuterRectClipped);
if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize))
bb.Expand(padding_regular);
else
bb.Expand(padding_for_resize_from_edges);
if (!bb.Contains(g.IO.MousePos))
continue;
// Those seemingly unnecessary extra tests are because the code here is a little different in viewport/docking branches.
if (hovered_window == NULL)
hovered_window = window;
if (hovered_window)
break;
}
g.HoveredWindow = hovered_window;
g.HoveredRootWindow = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
}
// Test if mouse cursor is hovering given rectangle
// NB- Rectangle is clipped by our current clip setting
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
{
ImGuiContext& g = *GImGui;
// Clip
ImRect rect_clipped(r_min, r_max);
if (clip)
rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
// Expand for touch input
const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
if (!rect_for_touch.Contains(g.IO.MousePos))
return false;
return true;
}
int ImGui::GetKeyIndex(ImGuiKey imgui_key)
{
IM_ASSERT(imgui_key >= 0 && imgui_key < ImGuiKey_COUNT);
return GImGui->IO.KeyMap[imgui_key];
}
// Note that imgui doesn't know the semantic of each entry of io.KeysDown[]. Use your own indices/enums according to how your back-end/engine stored them into io.KeysDown[]!
bool ImGui::IsKeyDown(int user_key_index)
{
if (user_key_index < 0) return false;
IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(GImGui->IO.KeysDown));
return GImGui->IO.KeysDown[user_key_index];
}
int ImGui::CalcTypematicPressedRepeatAmount(float t, float t_prev, float repeat_delay, float repeat_rate)
{
if (t == 0.0f)
return 1;
if (t <= repeat_delay || repeat_rate <= 0.0f)
return 0;
const int count = (int)((t - repeat_delay) / repeat_rate) - (int)((t_prev - repeat_delay) / repeat_rate);
return (count > 0) ? count : 0;
}
int ImGui::GetKeyPressedAmount(int key_index, float repeat_delay, float repeat_rate)
{
ImGuiContext& g = *GImGui;
if (key_index < 0)
return 0;
IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown));
const float t = g.IO.KeysDownDuration[key_index];
return CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, repeat_delay, repeat_rate);
}
bool ImGui::IsKeyPressed(int user_key_index, bool repeat)
{
ImGuiContext& g = *GImGui;
if (user_key_index < 0)<|fim▁hole|> IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
const float t = g.IO.KeysDownDuration[user_key_index];
if (t == 0.0f)
return true;
if (repeat && t > g.IO.KeyRepeatDelay)
return GetKeyPressedAmount(user_key_index, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0;
return false;
}
bool ImGui::IsKeyReleased(int user_key_index)
{
ImGuiContext& g = *GImGui;
if (user_key_index < 0) return false;
IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
return g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index];
}
bool ImGui::IsMouseDown(int button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseDown[button];
}
bool ImGui::IsAnyMouseDown()
{
ImGuiContext& g = *GImGui;
for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
if (g.IO.MouseDown[n])
return true;
return false;
}
bool ImGui::IsMouseClicked(int button, bool repeat)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
const float t = g.IO.MouseDownDuration[button];
if (t == 0.0f)
return true;
if (repeat && t > g.IO.KeyRepeatDelay)
{
// FIXME: 2019/05/03: Our old repeat code was wrong here and led to doubling the repeat rate, which made it an ok rate for repeat on mouse hold.
int amount = CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate * 0.5f);
if (amount > 0)
return true;
}
return false;
}
bool ImGui::IsMouseReleased(int button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseReleased[button];
}
bool ImGui::IsMouseDoubleClicked(int button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseDoubleClicked[button];
}
bool ImGui::IsMouseDragging(int button, float lock_threshold)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
if (!g.IO.MouseDown[button])
return false;
if (lock_threshold < 0.0f)
lock_threshold = g.IO.MouseDragThreshold;
return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
}
ImVec2 ImGui::GetMousePos()
{
return GImGui->IO.MousePos;
}
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
{
ImGuiContext& g = *GImGui;
if (g.BeginPopupStack.Size > 0)
return g.OpenPopupStack[g.BeginPopupStack.Size-1].OpenMousePos;
return g.IO.MousePos;
}
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
{
// The assert is only to silence a false-positive in XCode Static Analysis.
// Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
IM_ASSERT(GImGui != NULL);
const float MOUSE_INVALID = -256000.0f;
ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
}
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
// NB: This is only valid if IsMousePosValid(). Back-ends in theory should always keep mouse position valid when dragging even outside the client window.
ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
if (lock_threshold < 0.0f)
lock_threshold = g.IO.MouseDragThreshold;
if (g.IO.MouseDown[button] || g.IO.MouseReleased[button])
if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
return g.IO.MousePos - g.IO.MouseClickedPos[button];
return ImVec2(0.0f, 0.0f);
}
void ImGui::ResetMouseDragDelta(int button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
// NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
g.IO.MouseClickedPos[button] = g.IO.MousePos;
}
ImGuiMouseCursor ImGui::GetMouseCursor()
{
return GImGui->MouseCursor;
}
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
{
GImGui->MouseCursor = cursor_type;
}
void ImGui::CaptureKeyboardFromApp(bool capture)
{
GImGui->WantCaptureKeyboardNextFrame = capture ? 1 : 0;
}
void ImGui::CaptureMouseFromApp(bool capture)
{
GImGui->WantCaptureMouseNextFrame = capture ? 1 : 0;
}
bool ImGui::IsItemActive()
{
ImGuiContext& g = *GImGui;
if (g.ActiveId)
{
ImGuiWindow* window = g.CurrentWindow;
return g.ActiveId == window->DC.LastItemId;
}
return false;
}
bool ImGui::IsItemActivated()
{
ImGuiContext& g = *GImGui;
if (g.ActiveId)
{
ImGuiWindow* window = g.CurrentWindow;
if (g.ActiveId == window->DC.LastItemId && g.ActiveIdPreviousFrame != window->DC.LastItemId)
return true;
}
return false;
}
bool ImGui::IsItemDeactivated()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
return (g.ActiveIdPreviousFrame == window->DC.LastItemId && g.ActiveIdPreviousFrame != 0 && g.ActiveId != window->DC.LastItemId);
}
bool ImGui::IsItemDeactivatedAfterEdit()
{
ImGuiContext& g = *GImGui;
return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEdited || (g.ActiveId == 0 && g.ActiveIdHasBeenEdited));
}
bool ImGui::IsItemFocused()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavId == 0 || g.NavDisableHighlight || g.NavId != window->DC.LastItemId)
return false;
return true;
}
bool ImGui::IsItemClicked(int mouse_button)
{
return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
}
bool ImGui::IsItemToggledSelection()
{
ImGuiContext& g = *GImGui;
return (g.CurrentWindow->DC.LastItemStatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
}
bool ImGui::IsAnyItemHovered()
{
ImGuiContext& g = *GImGui;
return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
}
bool ImGui::IsAnyItemActive()
{
ImGuiContext& g = *GImGui;
return g.ActiveId != 0;
}
bool ImGui::IsAnyItemFocused()
{
ImGuiContext& g = *GImGui;
return g.NavId != 0 && !g.NavDisableHighlight;
}
bool ImGui::IsItemVisible()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->ClipRect.Overlaps(window->DC.LastItemRect);
}
bool ImGui::IsItemEdited()
{
ImGuiWindow* window = GetCurrentWindowRead();
return (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_Edited) != 0;
}
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
void ImGui::SetItemAllowOverlap()
{
ImGuiContext& g = *GImGui;
if (g.HoveredId == g.CurrentWindow->DC.LastItemId)
g.HoveredIdAllowOverlap = true;
if (g.ActiveId == g.CurrentWindow->DC.LastItemId)
g.ActiveIdAllowOverlap = true;
}
ImVec2 ImGui::GetItemRectMin()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.LastItemRect.Min;
}
ImVec2 ImGui::GetItemRectMax()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.LastItemRect.Max;
}
ImVec2 ImGui::GetItemRectSize()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.LastItemRect.GetSize();
}
static ImRect GetViewportRect()
{
ImGuiContext& g = *GImGui;
return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
}
static bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* parent_window = g.CurrentWindow;
flags |= ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow;
flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
// Size
const ImVec2 content_avail = GetContentRegionAvail();
ImVec2 size = ImFloor(size_arg);
const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);
if (size.x <= 0.0f)
size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
if (size.y <= 0.0f)
size.y = ImMax(content_avail.y + size.y, 4.0f);
SetNextWindowSize(size);
// Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
char title[256];
if (name)
ImFormatString(title, IM_ARRAYSIZE(title), "%s/%s_%08X", parent_window->Name, name, id);
else
ImFormatString(title, IM_ARRAYSIZE(title), "%s/%08X", parent_window->Name, id);
const float backup_border_size = g.Style.ChildBorderSize;
if (!border)
g.Style.ChildBorderSize = 0.0f;
bool ret = Begin(title, NULL, flags);
g.Style.ChildBorderSize = backup_border_size;
ImGuiWindow* child_window = g.CurrentWindow;
child_window->ChildId = id;
child_window->AutoFitChildAxises = auto_fit_axises;
// Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
// While this is not really documented/defined, it seems that the expected thing to do.
if (child_window->BeginCount == 1)
parent_window->DC.CursorPos = child_window->Pos;
// Process navigation-in immediately so NavInit can run on first frame
if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayerActiveMask != 0 || child_window->DC.NavHasScroll))
{
FocusWindow(child_window);
NavInitWindow(child_window, false);
SetActiveID(id+1, child_window); // Steal ActiveId with a dummy id so that key-press won't activate child item
g.ActiveIdSource = ImGuiInputSource_Nav;
}
return ret;
}
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
{
ImGuiWindow* window = GetCurrentWindow();
return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
}
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
{
IM_ASSERT(id != 0);
return BeginChildEx(NULL, id, size_arg, border, extra_flags);
}
void ImGui::EndChild()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss
if (window->BeginCount > 1)
{
End();
}
else
{
ImVec2 sz = window->Size;
if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
sz.x = ImMax(4.0f, sz.x);
if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
sz.y = ImMax(4.0f, sz.y);
End();
ImGuiWindow* parent_window = g.CurrentWindow;
ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
ItemSize(sz);
if ((window->DC.NavLayerActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened))
{
ItemAdd(bb, window->ChildId);
RenderNavHighlight(bb, window->ChildId);
// When browsing a window that has no activable items (scroll only) we keep a highlight on the child
if (window->DC.NavLayerActiveMask == 0 && window == g.NavWindow)
RenderNavHighlight(ImRect(bb.Min - ImVec2(2,2), bb.Max + ImVec2(2,2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
}
else
{
// Not navigable into
ItemAdd(bb, 0);
}
}
}
// Helper to create a child window / scrolling region that looks like a normal widget frame.
bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
{
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
PopStyleVar(3);
PopStyleColor();
return ret;
}
void ImGui::EndChildFrame()
{
EndChild();
}
// Save and compare stack sizes on Begin()/End() to detect usage errors
static void CheckStacksSize(ImGuiWindow* window, bool write)
{
// NOT checking: DC.ItemWidth, DC.AllowKeyboardFocus, DC.ButtonRepeat, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
ImGuiContext& g = *GImGui;
short* p_backup = &window->DC.StackSizesBackup[0];
{ int current = window->IDStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "PushID/PopID or TreeNode/TreePop Mismatch!"); p_backup++; } // Too few or too many PopID()/TreePop()
{ int current = window->DC.GroupStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // Too few or too many EndGroup()
{ int current = g.BeginPopupStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch"); p_backup++;}// Too few or too many EndMenu()/EndPopup()
// For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
{ int current = g.ColorModifiers.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // Too few or too many PopStyleColor()
{ int current = g.StyleModifiers.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // Too few or too many PopStyleVar()
{ int current = g.FontStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushFont/PopFont Mismatch!"); p_backup++; } // Too few or too many PopFont()
IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup));
}
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
{
window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags);
window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
}
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
}
ImGuiWindow* ImGui::FindWindowByName(const char* name)
{
ImGuiID id = ImHashStr(name);
return FindWindowByID(id);
}
static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
// Create window the first time
ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
window->Flags = flags;
g.WindowsById.SetVoidPtr(window->ID, window);
// Default/arbitrary window position. Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
window->Pos = ImVec2(60, 60);
// User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
if (!(flags & ImGuiWindowFlags_NoSavedSettings))
if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID))
{
// Retrieve settings from .ini file
window->SettingsIdx = g.SettingsWindows.index_from_ptr(settings);
SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
window->Pos = ImFloor(settings->Pos);
window->Collapsed = settings->Collapsed;
if (ImLengthSqr(settings->Size) > 0.00001f)
size = ImFloor(settings->Size);
}
window->Size = window->SizeFull = window->SizeFullAtLastBegin = ImFloor(size);
window->DC.CursorMaxPos = window->Pos; // So first call to CalcSizeContents() doesn't return crazy values
if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
{
window->AutoFitFramesX = window->AutoFitFramesY = 2;
window->AutoFitOnlyGrows = false;
}
else
{
if (window->Size.x <= 0.0f)
window->AutoFitFramesX = 2;
if (window->Size.y <= 0.0f)
window->AutoFitFramesY = 2;
window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
}
g.WindowsFocusOrder.push_back(window);
if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
g.Windows.push_front(window); // Quite slow but rare and only once
else
g.Windows.push_back(window);
return window;
}
static ImVec2 CalcSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size)
{
ImGuiContext& g = *GImGui;
if (g.NextWindowData.SizeConstraintCond != 0)
{
// Using -1,-1 on either X/Y axis to preserve the current size.
ImRect cr = g.NextWindowData.SizeConstraintRect;
new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
if (g.NextWindowData.SizeCallback)
{
ImGuiSizeCallbackData data;
data.UserData = g.NextWindowData.SizeCallbackUserData;
data.Pos = window->Pos;
data.CurrentSize = window->SizeFull;
data.DesiredSize = new_size;
g.NextWindowData.SizeCallback(&data);
new_size = data.DesiredSize;
}
new_size.x = ImFloor(new_size.x);
new_size.y = ImFloor(new_size.y);
}
// Minimum size
if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
{
new_size = ImMax(new_size, g.Style.WindowMinSize);
new_size.y = ImMax(new_size.y, window->TitleBarHeight() + window->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows
}
return new_size;
}
static ImVec2 CalcSizeContents(ImGuiWindow* window)
{
if (window->Collapsed)
if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
return window->SizeContents;
if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
return window->SizeContents;
ImVec2 sz;
sz.x = (float)(int)((window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : (window->DC.CursorMaxPos.x - window->Pos.x + window->Scroll.x));
sz.y = (float)(int)((window->SizeContentsExplicit.y != 0.0f) ? window->SizeContentsExplicit.y : (window->DC.CursorMaxPos.y - window->Pos.y + window->Scroll.y));
return sz + window->WindowPadding;
}
static ImVec2 CalcSizeAutoFit(ImGuiWindow* window, const ImVec2& size_contents)
{
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
if (window->Flags & ImGuiWindowFlags_Tooltip)
{
// Tooltip always resize
return size_contents;
}
else
{
// Maximum window size is determined by the display size
const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0;
const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0;
ImVec2 size_min = style.WindowMinSize;
if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
size_min = ImMin(size_min, ImVec2(4.0f, 4.0f));
ImVec2 size_auto_fit = ImClamp(size_contents, size_min, ImMax(size_min, g.IO.DisplaySize - style.DisplaySafeAreaPadding * 2.0f));
// When the window cannot fit all contents (either because of constraints, either because screen is too small),
// we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
ImVec2 size_auto_fit_after_constraint = CalcSizeAfterConstraint(window, size_auto_fit);
if (size_auto_fit_after_constraint.x < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar))
size_auto_fit.y += style.ScrollbarSize;
if (size_auto_fit_after_constraint.y < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar))
size_auto_fit.x += style.ScrollbarSize;
return size_auto_fit;
}
}
ImVec2 ImGui::CalcWindowExpectedSize(ImGuiWindow* window)
{
ImVec2 size_contents = CalcSizeContents(window);
return CalcSizeAfterConstraint(window, CalcSizeAutoFit(window, size_contents));
}
float ImGui::GetWindowScrollMaxX(ImGuiWindow* window)
{
return ImMax(0.0f, window->SizeContents.x - (window->SizeFull.x - window->ScrollbarSizes.x));
}
float ImGui::GetWindowScrollMaxY(ImGuiWindow* window)
{
return ImMax(0.0f, window->SizeContents.y - (window->SizeFull.y - window->ScrollbarSizes.y));
}
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges)
{
ImGuiContext& g = *GImGui;
ImVec2 scroll = window->Scroll;
if (window->ScrollTarget.x < FLT_MAX)
{
float cr_x = window->ScrollTargetCenterRatio.x;
scroll.x = window->ScrollTarget.x - cr_x * (window->SizeFull.x - window->ScrollbarSizes.x);
}
if (window->ScrollTarget.y < FLT_MAX)
{
// 'snap_on_edges' allows for a discontinuity at the edge of scrolling limits to take account of WindowPadding so that scrolling to make the last item visible scroll far enough to see the padding.
float cr_y = window->ScrollTargetCenterRatio.y;
float target_y = window->ScrollTarget.y;
if (snap_on_edges && cr_y <= 0.0f && target_y <= window->WindowPadding.y)
target_y = 0.0f;
if (snap_on_edges && cr_y >= 1.0f && target_y >= window->SizeContents.y - window->WindowPadding.y + g.Style.ItemSpacing.y)
target_y = window->SizeContents.y;
scroll.y = target_y - (1.0f - cr_y) * (window->TitleBarHeight() + window->MenuBarHeight()) - cr_y * (window->SizeFull.y - window->ScrollbarSizes.y);
}
scroll = ImMax(scroll, ImVec2(0.0f, 0.0f));
if (!window->Collapsed && !window->SkipItems)
{
scroll.x = ImMin(scroll.x, ImGui::GetWindowScrollMaxX(window));
scroll.y = ImMin(scroll.y, ImGui::GetWindowScrollMaxY(window));
}
return scroll;
}
static ImGuiCol GetWindowBgColorIdxFromFlags(ImGuiWindowFlags flags)
{
if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
return ImGuiCol_PopupBg;
if (flags & ImGuiWindowFlags_ChildWindow)
return ImGuiCol_ChildBg;
return ImGuiCol_WindowBg;
}
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
{
ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left
ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
ImVec2 size_expected = pos_max - pos_min;
ImVec2 size_constrained = CalcSizeAfterConstraint(window, size_expected);
*out_pos = pos_min;
if (corner_norm.x == 0.0f)
out_pos->x -= (size_constrained.x - size_expected.x);
if (corner_norm.y == 0.0f)
out_pos->y -= (size_constrained.y - size_expected.y);
*out_size = size_constrained;
}
struct ImGuiResizeGripDef
{
ImVec2 CornerPosN;
ImVec2 InnerDir;
int AngleMin12, AngleMax12;
};
static const ImGuiResizeGripDef resize_grip_def[4] =
{
{ ImVec2(1,1), ImVec2(-1,-1), 0, 3 }, // Lower right
{ ImVec2(0,1), ImVec2(+1,-1), 3, 6 }, // Lower left
{ ImVec2(0,0), ImVec2(+1,+1), 6, 9 }, // Upper left
{ ImVec2(1,0), ImVec2(-1,+1), 9,12 }, // Upper right
};
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
{
ImRect rect = window->Rect();
if (thickness == 0.0f) rect.Max -= ImVec2(1,1);
if (border_n == 0) return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); // Top
if (border_n == 1) return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); // Right
if (border_n == 2) return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); // Bottom
if (border_n == 3) return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); // Left
IM_ASSERT(0);
return ImRect();
}
// Handle resize for: Resize Grips, Borders, Gamepad
static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4])
{
ImGuiContext& g = *GImGui;
ImGuiWindowFlags flags = window->Flags;
if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
return;
if (window->WasActive == false) // Early out to avoid running this code for e.g. an hidden implicit/fallback Debug window.
return;
const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0;
const float grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f);
const float grip_hover_inner_size = (float)(int)(grip_draw_size * 0.75f);
const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS : 0.0f;
ImVec2 pos_target(FLT_MAX, FLT_MAX);
ImVec2 size_target(FLT_MAX, FLT_MAX);
// Resize grips and borders are on layer 1
window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu);
// Manual resize grips
PushID("#RESIZE");
for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
{
const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
// Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
ImRect resize_rect(corner - grip.InnerDir * grip_hover_outer_size, corner + grip.InnerDir * grip_hover_inner_size);
if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
bool hovered, held;
ButtonBehavior(resize_rect, window->GetID((void*)(intptr_t)resize_grip_n), &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
//GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
if (hovered || held)
g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
if (held && g.IO.MouseDoubleClicked[0] && resize_grip_n == 0)
{
// Manual auto-fit when double-clicking
size_target = CalcSizeAfterConstraint(window, size_auto_fit);
ClearActiveID();
}
else if (held)
{
// Resize from any of the four corners
// We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(grip.InnerDir * grip_hover_outer_size, grip.InnerDir * -grip_hover_inner_size, grip.CornerPosN); // Corner of the window corresponding to our corner grip
CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPosN, &pos_target, &size_target);
}
if (resize_grip_n == 0 || held || hovered)
resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
}
for (int border_n = 0; border_n < resize_border_count; border_n++)
{
bool hovered, held;
ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS);
ButtonBehavior(border_rect, window->GetID((void*)(intptr_t)(border_n + 4)), &hovered, &held, ImGuiButtonFlags_FlattenChildren);
//GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held)
{
g.MouseCursor = (border_n & 1) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
if (held)
*border_held = border_n;
}
if (held)
{
ImVec2 border_target = window->Pos;
ImVec2 border_posn;
if (border_n == 0) { border_posn = ImVec2(0, 0); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Top
if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Right
if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Bottom
if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Left
CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target);
}
}
PopID();
// Navigation resize (keyboard/gamepad)
if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindow == window)
{
ImVec2 nav_resize_delta;
if (g.NavInputSource == ImGuiInputSource_NavKeyboard && g.IO.KeyShift)
nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
if (g.NavInputSource == ImGuiInputSource_NavGamepad)
nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_Down);
if (nav_resize_delta.x != 0.0f || nav_resize_delta.y != 0.0f)
{
const float NAV_RESIZE_SPEED = 600.0f;
nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y));
g.NavWindowingToggleLayer = false;
g.NavDisableMouseHover = true;
resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
// FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
size_target = CalcSizeAfterConstraint(window, window->SizeFull + nav_resize_delta);
}
}
// Apply back modified position/size to window
if (size_target.x != FLT_MAX)
{
window->SizeFull = size_target;
MarkIniSettingsDirty(window);
}
if (pos_target.x != FLT_MAX)
{
window->Pos = ImFloor(pos_target);
MarkIniSettingsDirty(window);
}
// Resize nav layer
window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
window->Size = window->SizeFull;
}
static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& rect, const ImVec2& padding)
{
ImGuiContext& g = *GImGui;
ImVec2 size_for_clamping = (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) ? ImVec2(window->Size.x, window->TitleBarHeight()) : window->Size;
window->Pos = ImMin(rect.Max - padding, ImMax(window->Pos + size_for_clamping, rect.Min + padding) - size_for_clamping);
}
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
float rounding = window->WindowRounding;
float border_size = window->WindowBorderSize;
if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))
window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
int border_held = window->ResizeBorderHeld;
if (border_held != -1)
{
struct ImGuiResizeBorderDef
{
ImVec2 InnerDir;
ImVec2 CornerPosN1, CornerPosN2;
float OuterAngle;
};
static const ImGuiResizeBorderDef resize_border_def[4] =
{
{ ImVec2(0,+1), ImVec2(0,0), ImVec2(1,0), IM_PI*1.50f }, // Top
{ ImVec2(-1,0), ImVec2(1,0), ImVec2(1,1), IM_PI*0.00f }, // Right
{ ImVec2(0,-1), ImVec2(1,1), ImVec2(0,1), IM_PI*0.50f }, // Bottom
{ ImVec2(+1,0), ImVec2(0,1), ImVec2(0,0), IM_PI*1.00f } // Left
};
const ImGuiResizeBorderDef& def = resize_border_def[border_held];
ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f);
window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI*0.25f, def.OuterAngle);
window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI*0.25f);
window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), false, ImMax(2.0f, border_size)); // Thicker than usual
}
if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
{
float y = window->Pos.y + window->TitleBarHeight() - 1;
window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize);
}
}
void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
{
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
ImGuiWindowFlags flags = window->Flags;
// Draw window + handle manual resize
// As we highlight the title bar when want_focus is set, multiple reappearing windows will have have their title bar highlighted on their reappearing frame.
const float window_rounding = window->WindowRounding;
const float window_border_size = window->WindowBorderSize;
if (window->Collapsed)
{
// Title bar only
float backup_border_size = style.FrameBorderSize;
g.Style.FrameBorderSize = window->WindowBorderSize;
ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
g.Style.FrameBorderSize = backup_border_size;
}
else
{
// Window background
if (!(flags & ImGuiWindowFlags_NoBackground))
{
ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags));
float alpha = 1.0f;
if (g.NextWindowData.BgAlphaCond != 0)
alpha = g.NextWindowData.BgAlphaVal;
if (alpha != 1.0f)
bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Bot);
}
g.NextWindowData.BgAlphaCond = 0;
// Title bar
if (!(flags & ImGuiWindowFlags_NoTitleBar))
{
ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawCornerFlags_Top);
}
// Menu bar
if (flags & ImGuiWindowFlags_MenuBar)
{
ImRect menu_bar_rect = window->MenuBarRect();
menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
window->DrawList->AddRectFilled(menu_bar_rect.Min + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawCornerFlags_Top);
if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
}
// Scrollbars
if (window->ScrollbarX)
Scrollbar(ImGuiAxis_X);
if (window->ScrollbarY)
Scrollbar(ImGuiAxis_Y);
// Render resize grips (after their input handling so we don't have a frame of latency)
if (!(flags & ImGuiWindowFlags_NoResize))
{
for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
{
const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_grip_draw_size)));
window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]);
}
}
// Borders
RenderWindowOuterBorders(window);
}
}
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
{
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
ImGuiWindowFlags flags = window->Flags;
// Close & collapse button are on layer 1 (same as menus) and don't default focus
const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags;
window->DC.ItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu);
// Collapse button
if (!(flags & ImGuiWindowFlags_NoCollapse))
if (CollapseButton(window->GetID("#COLLAPSE"), window->Pos))
window->WantCollapseToggle = true; // Defer collapsing to next frame as we are too far in the Begin() function
// Close button
if (p_open != NULL)
{
const float rad = g.FontSize * 0.5f;
if (CloseButton(window->GetID("#CLOSE"), ImVec2(window->Pos.x + window->Size.x - style.FramePadding.x - rad, window->Pos.y + style.FramePadding.y + rad), rad + 1))
*p_open = false;
}
window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
window->DC.ItemFlags = item_flags_backup;
// Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
// FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
const char* UNSAVED_DOCUMENT_MARKER = "*";
const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? CalcTextSize(UNSAVED_DOCUMENT_MARKER, NULL, false).x : 0.0f;
const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
ImRect text_r = title_bar_rect;
float pad_left = (flags & ImGuiWindowFlags_NoCollapse) ? style.FramePadding.x : (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x);
float pad_right = (p_open == NULL) ? style.FramePadding.x : (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x);
if (style.WindowTitleAlign.x > 0.0f)
pad_right = ImLerp(pad_right, pad_left, style.WindowTitleAlign.x);
text_r.Min.x += pad_left;
text_r.Max.x -= pad_right;
ImRect clip_rect = text_r;
clip_rect.Max.x = window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x); // Match the size of CloseButton()
RenderTextClipped(text_r.Min, text_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_rect);
if (flags & ImGuiWindowFlags_UnsavedDocument)
{
ImVec2 marker_pos = ImVec2(ImMax(text_r.Min.x, text_r.Min.x + (text_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x) + text_size.x, text_r.Min.y) + ImVec2(2 - marker_size_x, 0.0f);
ImVec2 off = ImVec2(0.0f, (float)(int)(-g.FontSize * 0.25f));
RenderTextClipped(marker_pos + off, text_r.Max + off, UNSAVED_DOCUMENT_MARKER, NULL, NULL, ImVec2(0, style.WindowTitleAlign.y), &clip_rect);
}
}
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
{
window->ParentWindow = parent_window;
window->RootWindow = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
window->RootWindow = parent_window->RootWindow;
if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
{
IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
}
}
// Push a new Dear ImGui window to add widgets to.
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
// - Begin/End can be called multiple times during the frame with the same window name to append content.
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
// You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required
IM_ASSERT(g.FrameScopeActive); // Forgot to call ImGui::NewFrame()
IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
// Find or create
ImGuiWindow* window = FindWindowByName(name);
const bool window_just_created = (window == NULL);
if (window_just_created)
{
ImVec2 size_on_first_use = (g.NextWindowData.SizeCond != 0) ? g.NextWindowData.SizeVal : ImVec2(0.0f, 0.0f); // Any condition flag will do since we are creating a new window here.
window = CreateNewWindow(name, size_on_first_use, flags);
}
// Automatically disable manual moving/resizing when NoInputs is set
if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
if (flags & ImGuiWindowFlags_NavFlattened)
IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
const int current_frame = g.FrameCount;
const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
// Update the Appearing flag
bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
if (flags & ImGuiWindowFlags_Popup)
{
ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
window_just_activated_by_user |= (window != popup_ref.Window);
}
window->Appearing = (window_just_activated_by_user || window_just_appearing_after_hidden_for_resize);
if (window->Appearing)
SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
// Update Flags, LastFrameActive, BeginOrderXXX fields
if (first_begin_of_the_frame)
{
window->Flags = (ImGuiWindowFlags)flags;
window->LastFrameActive = current_frame;
window->BeginOrderWithinParent = 0;
window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
}
else
{
flags = window->Flags;
}
// Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back();
ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
// Add to stack
// We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
g.CurrentWindowStack.push_back(window);
g.CurrentWindow = NULL;
CheckStacksSize(window, true);
if (flags & ImGuiWindowFlags_Popup)
{
ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
popup_ref.Window = window;
g.BeginPopupStack.push_back(popup_ref);
window->PopupId = popup_ref.PopupId;
}
if (window_just_appearing_after_hidden_for_resize && !(flags & ImGuiWindowFlags_ChildWindow))
window->NavLastIds[0] = 0;
// Process SetNextWindow***() calls
bool window_pos_set_by_api = false;
bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
if (g.NextWindowData.PosCond)
{
window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
{
// May be processed on the next frame if this is our first frame and we are measuring size
// FIXME: Look into removing the branch so everything can go through this same code path for consistency.
window->SetWindowPosVal = g.NextWindowData.PosVal;
window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
}
else
{
SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
}
}
if (g.NextWindowData.SizeCond)
{
window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
}
if (g.NextWindowData.ContentSizeCond)
{
// Adjust passed "client size" to become a "window size"
window->SizeContentsExplicit = g.NextWindowData.ContentSizeVal;
if (window->SizeContentsExplicit.y != 0.0f)
window->SizeContentsExplicit.y += window->TitleBarHeight() + window->MenuBarHeight();
}
else if (first_begin_of_the_frame)
{
window->SizeContentsExplicit = ImVec2(0.0f, 0.0f);
}
if (g.NextWindowData.CollapsedCond)
SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
if (g.NextWindowData.FocusCond)
FocusWindow(window);
if (window->Appearing)
SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
// When reusing window again multiple times a frame, just append content (don't need to setup again)
if (first_begin_of_the_frame)
{
// Initialize
const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
UpdateWindowParentAndRootLinks(window, flags, parent_window);
window->Active = true;
window->HasCloseButton = (p_open != NULL);
window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX);
window->IDStack.resize(1);
// Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
// The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
bool window_title_visible_elsewhere = false;
if (g.NavWindowingList != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
window_title_visible_elsewhere = true;
if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
{
size_t buf_len = (size_t)window->NameBufLen;
window->Name = ImStrdupcpy(window->Name, &buf_len, name);
window->NameBufLen = (int)buf_len;
}
// UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
// Update contents size from last frame for auto-fitting (or use explicit size)
window->SizeContents = CalcSizeContents(window);
if (window->HiddenFramesCanSkipItems > 0)
window->HiddenFramesCanSkipItems--;
if (window->HiddenFramesCannotSkipItems > 0)
window->HiddenFramesCannotSkipItems--;
// Hide new windows for one frame until they calculate their size
if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
window->HiddenFramesCannotSkipItems = 1;
// Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
// We reset Size/SizeContents for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
{
window->HiddenFramesCannotSkipItems = 1;
if (flags & ImGuiWindowFlags_AlwaysAutoResize)
{
if (!window_size_x_set_by_api)
window->Size.x = window->SizeFull.x = 0.f;
if (!window_size_y_set_by_api)
window->Size.y = window->SizeFull.y = 0.f;
window->SizeContents = ImVec2(0.f, 0.f);
}
}
SetCurrentWindow(window);
// Lock border size and padding for the frame (so that altering them doesn't cause inconsistencies)
if (flags & ImGuiWindowFlags_ChildWindow)
window->WindowBorderSize = style.ChildBorderSize;
else
window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
window->WindowPadding = style.WindowPadding;
if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
// Collapse window by double-clicking on title bar
// At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse))
{
// We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
ImRect title_bar_rect = window->TitleBarRect();
if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0])
window->WantCollapseToggle = true;
if (window->WantCollapseToggle)
{
window->Collapsed = !window->Collapsed;
MarkIniSettingsDirty(window);
FocusWindow(window);
}
}
else
{
window->Collapsed = false;
}
window->WantCollapseToggle = false;
// SIZE
// Calculate auto-fit size, handle automatic resize
const ImVec2 size_auto_fit = CalcSizeAutoFit(window, window->SizeContents);
ImVec2 size_full_modified(FLT_MAX, FLT_MAX);
if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
{
// Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
if (!window_size_x_set_by_api)
window->SizeFull.x = size_full_modified.x = size_auto_fit.x;
if (!window_size_y_set_by_api)
window->SizeFull.y = size_full_modified.y = size_auto_fit.y;
}
else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
{
// Auto-fit may only grow window during the first few frames
// We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
window->SizeFull.x = size_full_modified.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
window->SizeFull.y = size_full_modified.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
if (!window->Collapsed)
MarkIniSettingsDirty(window);
}
// Apply minimum/maximum window size constraints and final size
window->SizeFull = CalcSizeAfterConstraint(window, window->SizeFull);
window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
// SCROLLBAR STATUS
// Update scrollbar status (based on the Size that was effective during last frame or the auto-resized Size).
if (!window->Collapsed)
{
// When reading the current size we need to read it after size constraints have been applied
float size_x_for_scrollbars = size_full_modified.x != FLT_MAX ? window->SizeFull.x : window->SizeFullAtLastBegin.x;
float size_y_for_scrollbars = size_full_modified.y != FLT_MAX ? window->SizeFull.y : window->SizeFullAtLastBegin.y;
window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
if (window->ScrollbarX && !window->ScrollbarY)
window->ScrollbarY = (window->SizeContents.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar);
window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
}
// POSITION
// Popup latch its initial position, will position itself when it appears next frame
if (window_just_activated_by_user)
{
window->AutoPosLastDirection = ImGuiDir_None;
if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api)
window->Pos = g.BeginPopupStack.back().OpenPopupPos;
}
// Position child window
if (flags & ImGuiWindowFlags_ChildWindow)
{
IM_ASSERT(parent_window && parent_window->Active);
window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
parent_window->DC.ChildWindows.push_back(window);
if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
window->Pos = parent_window->DC.CursorPos;
}
const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
if (window_pos_with_pivot)
SetWindowPos(window, ImMax(style.DisplaySafeAreaPadding, window->SetWindowPosVal - window->SizeFull * window->SetWindowPosPivot), 0); // Position given a pivot (e.g. for centering)
else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
window->Pos = FindBestWindowPosForPopup(window);
else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
window->Pos = FindBestWindowPosForPopup(window);
else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
window->Pos = FindBestWindowPosForPopup(window);
// Clamp position so it stays visible
// Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
ImRect viewport_rect(GetViewportRect());
if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
{
if (g.IO.DisplaySize.x > 0.0f && g.IO.DisplaySize.y > 0.0f) // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
{
ImVec2 clamp_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
ClampWindowRect(window, viewport_rect, clamp_padding);
}
}
window->Pos = ImFloor(window->Pos);
// Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
// Apply scrolling
window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window, true);
window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
// Apply window focus (new and reactivated windows are moved to front)
bool want_focus = false;
if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
{
if (flags & ImGuiWindowFlags_Popup)
want_focus = true;
else if ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) == 0)
want_focus = true;
}
// Handle manual resize: Resize Grips, Borders, Gamepad
int border_held = -1;
ImU32 resize_grip_col[4] = { 0 };
const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // 4
const float resize_grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f);
if (!window->Collapsed)
UpdateManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0]);
window->ResizeBorderHeld = (signed char)border_held;
// Default item width. Make it proportional to window size if window manually resizes
if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
window->ItemWidthDefault = (float)(int)(window->Size.x * 0.65f);
else
window->ItemWidthDefault = (float)(int)(g.FontSize * 16.0f);
// Store a backup of SizeFull which we will use next frame to decide if we need scrollbars.
window->SizeFullAtLastBegin = window->SizeFull;
// UPDATE RECTANGLES
// Update various regions. Variables they depends on are set above in this function.
// FIXME: window->ContentsRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
// NB: WindowBorderSize is included in WindowPadding _and_ ScrollbarSizes so we need to cancel one out.
window->ContentsRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x;
window->ContentsRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight();
window->ContentsRegionRect.Max.x = window->Pos.x - window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x + ImMin(window->ScrollbarSizes.x, window->WindowBorderSize)));
window->ContentsRegionRect.Max.y = window->Pos.y - window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y + ImMin(window->ScrollbarSizes.y, window->WindowBorderSize)));
// Save clipped aabb so we can access it in constant-time in FindHoveredWindow()
window->OuterRectClipped = window->Rect();
window->OuterRectClipped.ClipWith(window->ClipRect);
// Inner rectangle
// We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame
// Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
const ImRect title_bar_rect = window->TitleBarRect();
window->InnerMainRect.Min.x = title_bar_rect.Min.x + window->WindowBorderSize;
window->InnerMainRect.Min.y = title_bar_rect.Max.y + window->MenuBarHeight() + (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
window->InnerMainRect.Max.x = window->Pos.x + window->Size.x - ImMax(window->ScrollbarSizes.x, window->WindowBorderSize);
window->InnerMainRect.Max.y = window->Pos.y + window->Size.y - ImMax(window->ScrollbarSizes.y, window->WindowBorderSize);
// Inner clipping rectangle will extend a little bit outside the work region.
// This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
// Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerMainRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize)));
window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerMainRect.Min.y);
window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerMainRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x * 0.5f - window->WindowBorderSize)));
window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerMainRect.Max.y);
// DRAWING
// Setup draw list and outer clipping rectangle
window->DrawList->Clear();
window->DrawList->Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0);
window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true);
else
PushClipRect(viewport_rect.Min, viewport_rect.Max, true);
// Draw modal window background (darkens what is behind them, all viewports)
const bool dim_bg_for_modal = (flags & ImGuiWindowFlags_Modal) && window == GetFrontMostPopupModal() && window->HiddenFramesCannotSkipItems <= 0;
const bool dim_bg_for_window_list = g.NavWindowingTargetAnim && (window == g.NavWindowingTargetAnim->RootWindow);
if (dim_bg_for_modal || dim_bg_for_window_list)
{
const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
window->DrawList->AddRectFilled(viewport_rect.Min, viewport_rect.Max, dim_bg_col);
}
// Draw navigation selection/windowing rectangle background
if (dim_bg_for_window_list && window == g.NavWindowingTargetAnim)
{
ImRect bb = window->Rect();
bb.Expand(g.FontSize);
if (!bb.Contains(viewport_rect)) // Avoid drawing if the window covers all the viewport anyway
window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha * 0.25f), g.Style.WindowRounding);
}
const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight);
RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, resize_grip_count, resize_grip_col, resize_grip_draw_size);
// Draw navigation selection/windowing rectangle border
if (g.NavWindowingTargetAnim == window)
{
float rounding = ImMax(window->WindowRounding, g.Style.WindowRounding);
ImRect bb = window->Rect();
bb.Expand(g.FontSize);
if (bb.Contains(viewport_rect)) // If a window fits the entire viewport, adjust its highlight inward
{
bb.Expand(-g.FontSize - 1.0f);
rounding = window->WindowRounding;
}
window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), rounding, ~0, 3.0f);
}
// Setup drawing context
// (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
window->DC.Indent.x = 0.0f + window->WindowPadding.x - window->Scroll.x;
window->DC.GroupOffset.x = 0.0f;
window->DC.ColumnsOffset.x = 0.0f;
window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.Indent.x + window->DC.ColumnsOffset.x, window->TitleBarHeight() + window->MenuBarHeight() + window->WindowPadding.y - window->Scroll.y);
window->DC.CursorPos = window->DC.CursorStartPos;
window->DC.CursorPosPrevLine = window->DC.CursorPos;
window->DC.CursorMaxPos = window->DC.CursorStartPos;
window->DC.CurrentLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
window->DC.NavHideHighlightOneFrame = false;
window->DC.NavHasScroll = (GetWindowScrollMaxY(window) > 0.0f);
window->DC.NavLayerActiveMask = window->DC.NavLayerActiveMaskNext;
window->DC.NavLayerActiveMaskNext = 0x00;
window->DC.MenuBarAppending = false;
window->DC.ChildWindows.resize(0);
window->DC.LayoutType = ImGuiLayoutType_Vertical;
window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
window->DC.FocusCounterAll = window->DC.FocusCounterTab = -1;
window->DC.ItemFlags = parent_window ? parent_window->DC.ItemFlags : ImGuiItemFlags_Default_;
window->DC.ItemWidth = window->ItemWidthDefault;
window->DC.TextWrapPos = -1.0f; // disabled
window->DC.ItemFlagsStack.resize(0);
window->DC.ItemWidthStack.resize(0);
window->DC.TextWrapPosStack.resize(0);
window->DC.CurrentColumns = NULL;
window->DC.TreeDepth = 0;
window->DC.TreeStoreMayJumpToParentOnPop = 0x00;
window->DC.StateStorage = &window->StateStorage;
window->DC.GroupStack.resize(0);
window->MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user);
if ((flags & ImGuiWindowFlags_ChildWindow) && (window->DC.ItemFlags != parent_window->DC.ItemFlags))
{
window->DC.ItemFlags = parent_window->DC.ItemFlags;
window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
}
if (window->AutoFitFramesX > 0)
window->AutoFitFramesX--;
if (window->AutoFitFramesY > 0)
window->AutoFitFramesY--;
// Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
if (want_focus)
{
FocusWindow(window);
NavInitWindow(window, false);
}
// Title bar
if (!(flags & ImGuiWindowFlags_NoTitleBar))
RenderWindowTitleBarContents(window, title_bar_rect, name, p_open);
// Pressing CTRL+C while holding on a window copy its content to the clipboard
// This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
// Maybe we can support CTRL+C on every element?
/*
if (g.ActiveId == move_id)
if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C))
LogToClipboard();
*/
// We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
// This is useful to allow creating context menus on title bar only, etc.
window->DC.LastItemId = window->MoveId;
window->DC.LastItemStatusFlags = IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0;
window->DC.LastItemRect = title_bar_rect;
#ifdef IMGUI_ENABLE_TEST_ENGINE
if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
IMGUI_TEST_ENGINE_ITEM_ADD(window->DC.LastItemRect, window->DC.LastItemId);
#endif
}
else
{
// Append
SetCurrentWindow(window);
}
PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
// Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
if (first_begin_of_the_frame)
window->WriteAccessed = false;
window->BeginCount++;
g.NextWindowData.Clear();
if (flags & ImGuiWindowFlags_ChildWindow)
{
// Child window can be out of sight and have "negative" clip windows.
// Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0);
if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
window->HiddenFramesCanSkipItems = 1;
// Completely hide along with parent or if parent is collapsed
if (parent_window && (parent_window->Collapsed || parent_window->Hidden))
window->HiddenFramesCanSkipItems = 1;
}
// Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
if (style.Alpha <= 0.0f)
window->HiddenFramesCanSkipItems = 1;
// Update the Hidden flag
window->Hidden = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0);
// Update the SkipItems flag, used to early out of all items functions (no layout required)
bool skip_items = false;
if (window->Collapsed || !window->Active || window->Hidden)
if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
skip_items = true;
window->SkipItems = skip_items;
return !skip_items;
}
// Old Begin() API with 5 parameters, avoid calling this version directly! Use SetNextWindowSize()/SetNextWindowBgAlpha() + Begin() instead.
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_first_use, float bg_alpha_override, ImGuiWindowFlags flags)
{
// Old API feature: we could pass the initial window size as a parameter. This was misleading because it only had an effect if the window didn't have data in the .ini file.
if (size_first_use.x != 0.0f || size_first_use.y != 0.0f)
SetNextWindowSize(size_first_use, ImGuiCond_FirstUseEver);
// Old API feature: override the window background alpha with a parameter.
if (bg_alpha_override >= 0.0f)
SetNextWindowBgAlpha(bg_alpha_override);
return Begin(name, p_open, flags);
}
#endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS
void ImGui::End()
{
ImGuiContext& g = *GImGui;
if (g.CurrentWindowStack.Size <= 1 && g.FrameScopePushedImplicitWindow)
{
IM_ASSERT(g.CurrentWindowStack.Size > 1 && "Calling End() too many times!");
return; // FIXME-ERRORHANDLING
}
IM_ASSERT(g.CurrentWindowStack.Size > 0);
ImGuiWindow* window = g.CurrentWindow;
if (window->DC.CurrentColumns != NULL)
EndColumns();
PopClipRect(); // Inner window clip rectangle
// Stop logging
if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging
LogFinish();
// Pop from window stack
g.CurrentWindowStack.pop_back();
if (window->Flags & ImGuiWindowFlags_Popup)
g.BeginPopupStack.pop_back();
CheckStacksSize(window, false);
SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back());
}
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.WindowsFocusOrder.back() == window)
return;
for (int i = g.WindowsFocusOrder.Size - 2; i >= 0; i--) // We can ignore the front most window
if (g.WindowsFocusOrder[i] == window)
{
memmove(&g.WindowsFocusOrder[i], &g.WindowsFocusOrder[i + 1], (size_t)(g.WindowsFocusOrder.Size - i - 1) * sizeof(ImGuiWindow*));
g.WindowsFocusOrder[g.WindowsFocusOrder.Size - 1] = window;
break;
}
}
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* current_front_window = g.Windows.back();
if (current_front_window == window || current_front_window->RootWindow == window)
return;
for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the front most window
if (g.Windows[i] == window)
{
memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
g.Windows[g.Windows.Size - 1] = window;
break;
}
}
void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.Windows[0] == window)
return;
for (int i = 0; i < g.Windows.Size; i++)
if (g.Windows[i] == window)
{
memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
g.Windows[0] = window;
break;
}
}
// Moving window to front of display and set focus (which happens to be back of our sorted list)
void ImGui::FocusWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.NavWindow != window)
{
g.NavWindow = window;
if (window && g.NavDisableMouseHover)
g.NavMousePosDirty = true;
g.NavInitRequest = false;
g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
g.NavIdIsAlive = false;
g.NavLayer = ImGuiNavLayer_Main;
//IMGUI_DEBUG_LOG("FocusWindow(\"%s\")\n", window ? window->Name : NULL);
}
// Close popups if any
ClosePopupsOverWindow(window, false);
// Passing NULL allow to disable keyboard focus
if (!window)
return;
// Move the root window to the top of the pile
if (window->RootWindow)
window = window->RootWindow;
// Steal focus on active widgets
if (window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement should be unnecessary. Need further testing before removing it..
if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != window)
ClearActiveID();
// Bring to front
BringWindowToFocusFront(window);
if (!(window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus))
BringWindowToDisplayFront(window);
}
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window)
{
ImGuiContext& g = *GImGui;
int start_idx = g.WindowsFocusOrder.Size - 1;
if (under_this_window != NULL)
{
int under_this_window_idx = FindWindowFocusIndex(under_this_window);
if (under_this_window_idx != -1)
start_idx = under_this_window_idx - 1;
}
for (int i = start_idx; i >= 0; i--)
{
// We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
ImGuiWindow* window = g.WindowsFocusOrder[i];
if (window != ignore_window && window->WasActive && !(window->Flags & ImGuiWindowFlags_ChildWindow))
if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
{
ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window);
FocusWindow(focus_window);
return;
}
}
FocusWindow(NULL);
}
void ImGui::SetNextItemWidth(float item_width)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.NextItemWidth = item_width;
}
void ImGui::PushItemWidth(float item_width)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
window->DC.ItemWidthStack.push_back(window->DC.ItemWidth);
}
void ImGui::PushMultiItemsWidths(int components, float w_full)
{
ImGuiWindow* window = GetCurrentWindow();
const ImGuiStyle& style = GImGui->Style;
const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
window->DC.ItemWidthStack.push_back(w_item_last);
for (int i = 0; i < components-1; i++)
window->DC.ItemWidthStack.push_back(w_item_one);
window->DC.ItemWidth = window->DC.ItemWidthStack.back();
}
void ImGui::PopItemWidth()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.ItemWidthStack.pop_back();
window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back();
}
// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth(),
// Then consume the
float ImGui::GetNextItemWidth()
{
ImGuiWindow* window = GImGui->CurrentWindow;
float w;
if (window->DC.NextItemWidth != FLT_MAX)
{
w = window->DC.NextItemWidth;
window->DC.NextItemWidth = FLT_MAX;
}
else
{
w = window->DC.ItemWidth;
}
if (w < 0.0f)
{
float region_max_x = GetWorkRectMax().x;
w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
}
w = (float)(int)w;
return w;
}
// Calculate item width *without* popping/consuming NextItemWidth if it was set.
// (rarely used, which is why we avoid calling this from GetNextItemWidth() and instead do a backup/restore here)
float ImGui::CalcItemWidth()
{
ImGuiWindow* window = GImGui->CurrentWindow;
float backup_next_item_width = window->DC.NextItemWidth;
float w = GetNextItemWidth();
window->DC.NextItemWidth = backup_next_item_width;
return w;
}
// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == GetNextItemWidth().
// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
// Note that only CalcItemWidth() is publicly exposed.
// The 4.0f here may be changed to match GetNextItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
{
ImGuiWindow* window = GImGui->CurrentWindow;
ImVec2 region_max;
if (size.x < 0.0f || size.y < 0.0f)
region_max = GetWorkRectMax();
if (size.x == 0.0f)
size.x = default_w;
else if (size.x < 0.0f)
size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
if (size.y == 0.0f)
size.y = default_h;
else if (size.y < 0.0f)
size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
return size;
}
void ImGui::SetCurrentFont(ImFont* font)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
IM_ASSERT(font->Scale > 0.0f);
g.Font = font;
g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
ImFontAtlas* atlas = g.Font->ContainerAtlas;
g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
g.DrawListSharedData.Font = g.Font;
g.DrawListSharedData.FontSize = g.FontSize;
}
void ImGui::PushFont(ImFont* font)
{
ImGuiContext& g = *GImGui;
if (!font)
font = GetDefaultFont();
SetCurrentFont(font);
g.FontStack.push_back(font);
g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
}
void ImGui::PopFont()
{
ImGuiContext& g = *GImGui;
g.CurrentWindow->DrawList->PopTextureID();
g.FontStack.pop_back();
SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
}
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
{
ImGuiWindow* window = GetCurrentWindow();
if (enabled)
window->DC.ItemFlags |= option;
else
window->DC.ItemFlags &= ~option;
window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
}
void ImGui::PopItemFlag()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.ItemFlagsStack.pop_back();
window->DC.ItemFlags = window->DC.ItemFlagsStack.empty() ? ImGuiItemFlags_Default_ : window->DC.ItemFlagsStack.back();
}
// FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system.
void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
{
PushItemFlag(ImGuiItemFlags_NoTabStop, !allow_keyboard_focus);
}
void ImGui::PopAllowKeyboardFocus()
{
PopItemFlag();
}
void ImGui::PushButtonRepeat(bool repeat)
{
PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
}
void ImGui::PopButtonRepeat()
{
PopItemFlag();
}
void ImGui::PushTextWrapPos(float wrap_pos_x)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.TextWrapPos = wrap_pos_x;
window->DC.TextWrapPosStack.push_back(wrap_pos_x);
}
void ImGui::PopTextWrapPos()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.TextWrapPosStack.pop_back();
window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back();
}
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
{
ImGuiContext& g = *GImGui;
ImGuiColorMod backup;
backup.Col = idx;
backup.BackupValue = g.Style.Colors[idx];
g.ColorModifiers.push_back(backup);
g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
}
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
{
ImGuiContext& g = *GImGui;
ImGuiColorMod backup;
backup.Col = idx;
backup.BackupValue = g.Style.Colors[idx];
g.ColorModifiers.push_back(backup);
g.Style.Colors[idx] = col;
}
void ImGui::PopStyleColor(int count)
{
ImGuiContext& g = *GImGui;
while (count > 0)
{
ImGuiColorMod& backup = g.ColorModifiers.back();
g.Style.Colors[backup.Col] = backup.BackupValue;
g.ColorModifiers.pop_back();
count--;
}
}
struct ImGuiStyleVarInfo
{
ImGuiDataType Type;
ImU32 Count;
ImU32 Offset;
void* GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); }
};
static const ImGuiStyleVarInfo GStyleVarInfo[] =
{
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
};
static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
{
IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
return &GStyleVarInfo[idx];
}
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
{
const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
{
ImGuiContext& g = *GImGui;
float* pvar = (float*)var_info->GetVarPtr(&g.Style);
g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
*pvar = val;
return;
}
IM_ASSERT(0 && "Called PushStyleVar() float variant but variable is not a float!");
}
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
{
const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
{
ImGuiContext& g = *GImGui;
ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
*pvar = val;
return;
}
IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but variable is not a ImVec2!");
}
void ImGui::PopStyleVar(int count)
{
ImGuiContext& g = *GImGui;
while (count > 0)
{
// We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
ImGuiStyleMod& backup = g.StyleModifiers.back();
const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx);
void* data = info->GetVarPtr(&g.Style);
if (info->Type == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; }
else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
g.StyleModifiers.pop_back();
count--;
}
}
const char* ImGui::GetStyleColorName(ImGuiCol idx)
{
// Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
switch (idx)
{
case ImGuiCol_Text: return "Text";
case ImGuiCol_TextDisabled: return "TextDisabled";
case ImGuiCol_WindowBg: return "WindowBg";
case ImGuiCol_ChildBg: return "ChildBg";
case ImGuiCol_PopupBg: return "PopupBg";
case ImGuiCol_Border: return "Border";
case ImGuiCol_BorderShadow: return "BorderShadow";
case ImGuiCol_FrameBg: return "FrameBg";
case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
case ImGuiCol_FrameBgActive: return "FrameBgActive";
case ImGuiCol_TitleBg: return "TitleBg";
case ImGuiCol_TitleBgActive: return "TitleBgActive";
case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
case ImGuiCol_MenuBarBg: return "MenuBarBg";
case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
case ImGuiCol_CheckMark: return "CheckMark";
case ImGuiCol_SliderGrab: return "SliderGrab";
case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
case ImGuiCol_Button: return "Button";
case ImGuiCol_ButtonHovered: return "ButtonHovered";
case ImGuiCol_ButtonActive: return "ButtonActive";
case ImGuiCol_Header: return "Header";
case ImGuiCol_HeaderHovered: return "HeaderHovered";
case ImGuiCol_HeaderActive: return "HeaderActive";
case ImGuiCol_Separator: return "Separator";
case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
case ImGuiCol_SeparatorActive: return "SeparatorActive";
case ImGuiCol_ResizeGrip: return "ResizeGrip";
case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
case ImGuiCol_Tab: return "Tab";
case ImGuiCol_TabHovered: return "TabHovered";
case ImGuiCol_TabActive: return "TabActive";
case ImGuiCol_TabUnfocused: return "TabUnfocused";
case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
case ImGuiCol_PlotLines: return "PlotLines";
case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
case ImGuiCol_PlotHistogram: return "PlotHistogram";
case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
case ImGuiCol_DragDropTarget: return "DragDropTarget";
case ImGuiCol_NavHighlight: return "NavHighlight";
case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
}
IM_ASSERT(0);
return "Unknown";
}
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
{
if (window->RootWindow == potential_parent)
return true;
while (window != NULL)
{
if (window == potential_parent)
return true;
window = window->ParentWindow;
}
return false;
}
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
{
IM_ASSERT((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0); // Flags not supported by this function
ImGuiContext& g = *GImGui;
if (flags & ImGuiHoveredFlags_AnyWindow)
{
if (g.HoveredWindow == NULL)
return false;
}
else
{
switch (flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows))
{
case ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows:
if (g.HoveredRootWindow != g.CurrentWindow->RootWindow)
return false;
break;
case ImGuiHoveredFlags_RootWindow:
if (g.HoveredWindow != g.CurrentWindow->RootWindow)
return false;
break;
case ImGuiHoveredFlags_ChildWindows:
if (g.HoveredWindow == NULL || !IsWindowChildOf(g.HoveredWindow, g.CurrentWindow))
return false;
break;
default:
if (g.HoveredWindow != g.CurrentWindow)
return false;
break;
}
}
if (!IsWindowContentHoverable(g.HoveredWindow, flags))
return false;
if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != g.HoveredWindow->MoveId)
return false;
return true;
}
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
{
ImGuiContext& g = *GImGui;
if (flags & ImGuiFocusedFlags_AnyWindow)
return g.NavWindow != NULL;
IM_ASSERT(g.CurrentWindow); // Not inside a Begin()/End()
switch (flags & (ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows))
{
case ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows:
return g.NavWindow && g.NavWindow->RootWindow == g.CurrentWindow->RootWindow;
case ImGuiFocusedFlags_RootWindow:
return g.NavWindow == g.CurrentWindow->RootWindow;
case ImGuiFocusedFlags_ChildWindows:
return g.NavWindow && IsWindowChildOf(g.NavWindow, g.CurrentWindow);
default:
return g.NavWindow == g.CurrentWindow;
}
}
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmaticaly.
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
{
return window->Active && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
}
float ImGui::GetWindowWidth()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->Size.x;
}
float ImGui::GetWindowHeight()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->Size.y;
}
ImVec2 ImGui::GetWindowPos()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
return window->Pos;
}
void ImGui::SetWindowScrollX(ImGuiWindow* window, float new_scroll_x)
{
window->DC.CursorMaxPos.x += window->Scroll.x; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it.
window->Scroll.x = new_scroll_x;
window->DC.CursorMaxPos.x -= window->Scroll.x;
}
void ImGui::SetWindowScrollY(ImGuiWindow* window, float new_scroll_y)
{
window->DC.CursorMaxPos.y += window->Scroll.y; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it.
window->Scroll.y = new_scroll_y;
window->DC.CursorMaxPos.y -= window->Scroll.y;
}
void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
return;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
// Set
const ImVec2 old_pos = window->Pos;
window->Pos = ImFloor(pos);
window->DC.CursorPos += (window->Pos - old_pos); // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
window->DC.CursorMaxPos += (window->Pos - old_pos); // And more importantly we need to adjust this so size calculation doesn't get affected.
}
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
{
ImGuiWindow* window = GetCurrentWindowRead();
SetWindowPos(window, pos, cond);
}
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
{
if (ImGuiWindow* window = FindWindowByName(name))
SetWindowPos(window, pos, cond);
}
ImVec2 ImGui::GetWindowSize()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->Size;
}
void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
return;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
// Set
if (size.x > 0.0f)
{
window->AutoFitFramesX = 0;
window->SizeFull.x = ImFloor(size.x);
}
else
{
window->AutoFitFramesX = 2;
window->AutoFitOnlyGrows = false;
}
if (size.y > 0.0f)
{
window->AutoFitFramesY = 0;
window->SizeFull.y = ImFloor(size.y);
}
else
{
window->AutoFitFramesY = 2;
window->AutoFitOnlyGrows = false;
}
}
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
{
SetWindowSize(GImGui->CurrentWindow, size, cond);
}
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
{
if (ImGuiWindow* window = FindWindowByName(name))
SetWindowSize(window, size, cond);
}
void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
return;
window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
// Set
window->Collapsed = collapsed;
}
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
{
SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
}
bool ImGui::IsWindowCollapsed()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->Collapsed;
}
bool ImGui::IsWindowAppearing()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->Appearing;
}
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
{
if (ImGuiWindow* window = FindWindowByName(name))
SetWindowCollapsed(window, collapsed, cond);
}
void ImGui::SetWindowFocus()
{
FocusWindow(GImGui->CurrentWindow);
}
void ImGui::SetWindowFocus(const char* name)
{
if (name)
{
if (ImGuiWindow* window = FindWindowByName(name))
FocusWindow(window);
}
else
{
FocusWindow(NULL);
}
}
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
g.NextWindowData.PosVal = pos;
g.NextWindowData.PosPivotVal = pivot;
g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
g.NextWindowData.SizeVal = size;
g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.SizeConstraintCond = ImGuiCond_Always;
g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
g.NextWindowData.SizeCallback = custom_callback;
g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
}
void ImGui::SetNextWindowContentSize(const ImVec2& size)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.ContentSizeVal = size; // In Begin() we will add the size of window decorations (title bar, menu etc.) to that to form a SizeContents value.
g.NextWindowData.ContentSizeCond = ImGuiCond_Always;
}
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
g.NextWindowData.CollapsedVal = collapsed;
g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::SetNextWindowFocus()
{
ImGuiContext& g = *GImGui;
g.NextWindowData.FocusCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op)
}
void ImGui::SetNextWindowBgAlpha(float alpha)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.BgAlphaVal = alpha;
g.NextWindowData.BgAlphaCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op)
}
// FIXME: This is in window space (not screen space!). We should try to obsolete all those functions.
ImVec2 ImGui::GetContentRegionMax()
{
ImGuiWindow* window = GImGui->CurrentWindow;
ImVec2 mx = window->ContentsRegionRect.Max - window->Pos;
if (window->DC.CurrentColumns)
mx.x = GetColumnOffset(window->DC.CurrentColumns->Current + 1) - window->WindowPadding.x;
return mx;
}
// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
ImVec2 ImGui::GetWorkRectMax()
{
ImGuiWindow* window = GImGui->CurrentWindow;
ImVec2 mx = window->ContentsRegionRect.Max;
if (window->DC.CurrentColumns)
mx.x = window->Pos.x + GetColumnOffset(window->DC.CurrentColumns->Current + 1) - window->WindowPadding.x;
return mx;
}
ImVec2 ImGui::GetContentRegionAvail()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return GetWorkRectMax() - window->DC.CursorPos;
}
// In window space (not screen space!)
ImVec2 ImGui::GetWindowContentRegionMin()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->ContentsRegionRect.Min - window->Pos;
}
ImVec2 ImGui::GetWindowContentRegionMax()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->ContentsRegionRect.Max - window->Pos;
}
float ImGui::GetWindowContentRegionWidth()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->ContentsRegionRect.GetWidth();
}
float ImGui::GetTextLineHeight()
{
ImGuiContext& g = *GImGui;
return g.FontSize;
}
float ImGui::GetTextLineHeightWithSpacing()
{
ImGuiContext& g = *GImGui;
return g.FontSize + g.Style.ItemSpacing.y;
}
float ImGui::GetFrameHeight()
{
ImGuiContext& g = *GImGui;
return g.FontSize + g.Style.FramePadding.y * 2.0f;
}
float ImGui::GetFrameHeightWithSpacing()
{
ImGuiContext& g = *GImGui;
return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
}
ImDrawList* ImGui::GetWindowDrawList()
{
ImGuiWindow* window = GetCurrentWindow();
return window->DrawList;
}
ImFont* ImGui::GetFont()
{
return GImGui->Font;
}
float ImGui::GetFontSize()
{
return GImGui->FontSize;
}
ImVec2 ImGui::GetFontTexUvWhitePixel()
{
return GImGui->DrawListSharedData.TexUvWhitePixel;
}
void ImGui::SetWindowFontScale(float scale)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->FontWindowScale = scale;
g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
}
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
ImVec2 ImGui::GetCursorPos()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos - window->Pos + window->Scroll;
}
float ImGui::GetCursorPosX()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
}
float ImGui::GetCursorPosY()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
}
void ImGui::SetCursorPos(const ImVec2& local_pos)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
}
void ImGui::SetCursorPosX(float x)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
}
void ImGui::SetCursorPosY(float y)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
}
ImVec2 ImGui::GetCursorStartPos()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorStartPos - window->Pos;
}
ImVec2 ImGui::GetCursorScreenPos()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos;
}
void ImGui::SetCursorScreenPos(const ImVec2& pos)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos = pos;
window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
}
float ImGui::GetScrollX()
{
return GImGui->CurrentWindow->Scroll.x;
}
float ImGui::GetScrollY()
{
return GImGui->CurrentWindow->Scroll.y;
}
float ImGui::GetScrollMaxX()
{
return GetWindowScrollMaxX(GImGui->CurrentWindow);
}
float ImGui::GetScrollMaxY()
{
return GetWindowScrollMaxY(GImGui->CurrentWindow);
}
void ImGui::SetScrollX(float scroll_x)
{
ImGuiWindow* window = GetCurrentWindow();
window->ScrollTarget.x = scroll_x;
window->ScrollTargetCenterRatio.x = 0.0f;
}
void ImGui::SetScrollY(float scroll_y)
{
ImGuiWindow* window = GetCurrentWindow();
window->ScrollTarget.y = scroll_y + window->TitleBarHeight() + window->MenuBarHeight(); // title bar height canceled out when using ScrollTargetRelY
window->ScrollTargetCenterRatio.y = 0.0f;
}
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
{
// We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
window->ScrollTarget.y = (float)(int)(local_y + window->Scroll.y);
window->ScrollTargetCenterRatio.y = center_y_ratio;
}
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
void ImGui::SetScrollHereY(float center_y_ratio)
{
ImGuiWindow* window = GetCurrentWindow();
float target_y = window->DC.CursorPosPrevLine.y - window->Pos.y; // Top of last item, in window space
target_y += (window->DC.PrevLineSize.y * center_y_ratio) + (GImGui->Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line.
SetScrollFromPosY(target_y, center_y_ratio);
}
void ImGui::ActivateItem(ImGuiID id)
{
ImGuiContext& g = *GImGui;
g.NavNextActivateId = id;
}
void ImGui::SetKeyboardFocusHere(int offset)
{
IM_ASSERT(offset >= -1); // -1 is allowed but not below
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
g.FocusRequestNextWindow = window;
g.FocusRequestNextCounterAll = window->DC.FocusCounterAll + 1 + offset;
g.FocusRequestNextCounterTab = INT_MAX;
}
void ImGui::SetItemDefaultFocus()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!window->Appearing)
return;
if (g.NavWindow == window->RootWindowForNav && (g.NavInitRequest || g.NavInitResultId != 0) && g.NavLayer == g.NavWindow->DC.NavLayerCurrent)
{
g.NavInitRequest = false;
g.NavInitResultId = g.NavWindow->DC.LastItemId;
g.NavInitResultRectRel = ImRect(g.NavWindow->DC.LastItemRect.Min - g.NavWindow->Pos, g.NavWindow->DC.LastItemRect.Max - g.NavWindow->Pos);
NavUpdateAnyRequestFlag();
if (!IsItemVisible())
SetScrollHereY();
}
}
void ImGui::SetStateStorage(ImGuiStorage* tree)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->DC.StateStorage = tree ? tree : &window->StateStorage;
}
ImGuiStorage* ImGui::GetStateStorage()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->DC.StateStorage;
}
void ImGui::PushID(const char* str_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(window->GetIDNoKeepAlive(str_id));
}
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(window->GetIDNoKeepAlive(str_id_begin, str_id_end));
}
void ImGui::PushID(const void* ptr_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(window->GetIDNoKeepAlive(ptr_id));
}
void ImGui::PushID(int int_id)
{
const void* ptr_id = (void*)(intptr_t)int_id;
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(window->GetIDNoKeepAlive(ptr_id));
}
// Push a given id value ignoring the ID stack as a seed.
void ImGui::PushOverrideID(ImGuiID id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(id);
}
void ImGui::PopID()
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.pop_back();
}
ImGuiID ImGui::GetID(const char* str_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->GetID(str_id);
}
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->GetID(str_id_begin, str_id_end);
}
ImGuiID ImGui::GetID(const void* ptr_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->GetID(ptr_id);
}
bool ImGui::IsRectVisible(const ImVec2& size)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
}
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
}
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
void ImGui::BeginGroup()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1);
ImGuiGroupData& group_data = window->DC.GroupStack.back();
group_data.BackupCursorPos = window->DC.CursorPos;
group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
group_data.BackupIndent = window->DC.Indent;
group_data.BackupGroupOffset = window->DC.GroupOffset;
group_data.BackupCurrentLineSize = window->DC.CurrentLineSize;
group_data.BackupCurrentLineTextBaseOffset = window->DC.CurrentLineTextBaseOffset;
group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
group_data.AdvanceCursor = true;
window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
window->DC.Indent = window->DC.GroupOffset;
window->DC.CursorMaxPos = window->DC.CursorPos;
window->DC.CurrentLineSize = ImVec2(0.0f, 0.0f);
if (g.LogEnabled)
g.LogLinePosY = -FLT_MAX; // To enforce Log carriage return
}
void ImGui::EndGroup()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls
ImGuiGroupData& group_data = window->DC.GroupStack.back();
ImRect group_bb(group_data.BackupCursorPos, window->DC.CursorMaxPos);
group_bb.Max = ImMax(group_bb.Min, group_bb.Max);
window->DC.CursorPos = group_data.BackupCursorPos;
window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
window->DC.Indent = group_data.BackupIndent;
window->DC.GroupOffset = group_data.BackupGroupOffset;
window->DC.CurrentLineSize = group_data.BackupCurrentLineSize;
window->DC.CurrentLineTextBaseOffset = group_data.BackupCurrentLineTextBaseOffset;
if (g.LogEnabled)
g.LogLinePosY = -FLT_MAX; // To enforce Log carriage return
if (group_data.AdvanceCursor)
{
window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrentLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
ItemSize(group_bb.GetSize(), 0.0f);
ItemAdd(group_bb, 0);
}
// If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
// It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
// (and if you grep for LastItemId you'll notice it is only used in that context.
if ((group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId) // && g.ActiveIdWindow->RootWindow == window->RootWindow)
window->DC.LastItemId = g.ActiveId;
else if (!group_data.BackupActiveIdPreviousFrameIsAlive && g.ActiveIdPreviousFrameIsAlive) // && g.ActiveIdPreviousFrameWindow->RootWindow == window->RootWindow)
window->DC.LastItemId = g.ActiveIdPreviousFrame;
window->DC.LastItemRect = group_bb;
window->DC.GroupStack.pop_back();
//window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
}
// Gets back to previous line and continue with horizontal layout
// offset_from_start_x == 0 : follow right after previous item
// offset_from_start_x != 0 : align to specified x position (relative to window/group left)
// spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0
// spacing_w >= 0 : enforce spacing amount
void ImGui::SameLine(float offset_from_start_x, float spacing_w)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
if (offset_from_start_x != 0.0f)
{
if (spacing_w < 0.0f) spacing_w = 0.0f;
window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
}
else
{
if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x;
window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
}
window->DC.CurrentLineSize = window->DC.PrevLineSize;
window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
}
void ImGui::Indent(float indent_w)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
}
void ImGui::Unindent(float indent_w)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
}
//-----------------------------------------------------------------------------
// [SECTION] TOOLTIPS
//-----------------------------------------------------------------------------
void ImGui::BeginTooltip()
{
ImGuiContext& g = *GImGui;
if (g.DragDropWithinSourceOrTarget)
{
// The default tooltip position is a little offset to give space to see the context menu (it's also clamped within the current viewport/monitor)
// In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor.
// Whatever we do we want to call SetNextWindowPos() to enforce a tooltip position and disable clipping the tooltip without our display area, like regular tooltip do.
//ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale);
SetNextWindowPos(tooltip_pos);
SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
//PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
BeginTooltipEx(0, true);
}
else
{
BeginTooltipEx(0, false);
}
}
// Not exposed publicly as BeginTooltip() because bool parameters are evil. Let's see if other needs arise first.
void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_tooltip)
{
ImGuiContext& g = *GImGui;
char window_name[16];
ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
if (override_previous_tooltip)
if (ImGuiWindow* window = FindWindowByName(window_name))
if (window->Active)
{
// Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
window->Hidden = true;
window->HiddenFramesCanSkipItems = 1;
ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
}
ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoInputs|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize;
Begin(window_name, NULL, flags | extra_flags);
}
void ImGui::EndTooltip()
{
IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
End();
}
void ImGui::SetTooltipV(const char* fmt, va_list args)
{
ImGuiContext& g = *GImGui;
if (g.DragDropWithinSourceOrTarget)
BeginTooltip();
else
BeginTooltipEx(0, true);
TextV(fmt, args);
EndTooltip();
}
void ImGui::SetTooltip(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
SetTooltipV(fmt, args);
va_end(args);
}
//-----------------------------------------------------------------------------
// [SECTION] POPUPS
//-----------------------------------------------------------------------------
bool ImGui::IsPopupOpen(ImGuiID id)
{
ImGuiContext& g = *GImGui;
return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
}
bool ImGui::IsPopupOpen(const char* str_id)
{
ImGuiContext& g = *GImGui;
return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == g.CurrentWindow->GetID(str_id);
}
ImGuiWindow* ImGui::GetFrontMostPopupModal()
{
ImGuiContext& g = *GImGui;
for (int n = g.OpenPopupStack.Size-1; n >= 0; n--)
if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
if (popup->Flags & ImGuiWindowFlags_Modal)
return popup;
return NULL;
}
void ImGui::OpenPopup(const char* str_id)
{
ImGuiContext& g = *GImGui;
OpenPopupEx(g.CurrentWindow->GetID(str_id));
}
// Mark popup as open (toggle toward open state).
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
void ImGui::OpenPopupEx(ImGuiID id)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* parent_window = g.CurrentWindow;
int current_stack_size = g.BeginPopupStack.Size;
ImGuiPopupData popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
popup_ref.PopupId = id;
popup_ref.Window = NULL;
popup_ref.SourceWindow = g.NavWindow;
popup_ref.OpenFrameCount = g.FrameCount;
popup_ref.OpenParentId = parent_window->IDStack.back();
popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
//IMGUI_DEBUG_LOG("OpenPopupEx(0x%08X)\n", g.FrameCount, id);
if (g.OpenPopupStack.Size < current_stack_size + 1)
{
g.OpenPopupStack.push_back(popup_ref);
}
else
{
// Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui
// would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing
// situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand.
if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
{
g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
}
else
{
// Close child popups if any, then flag popup for open/reopen
g.OpenPopupStack.resize(current_stack_size + 1);
g.OpenPopupStack[current_stack_size] = popup_ref;
}
// When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
// This is equivalent to what ClosePopupToLevel() does.
//if (g.OpenPopupStack[current_stack_size].PopupId == id)
// FocusWindow(parent_window);
}
}
bool ImGui::OpenPopupOnItemClick(const char* str_id, int mouse_button)
{
ImGuiWindow* window = GImGui->CurrentWindow;
if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
{
ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
OpenPopupEx(id);
return true;
}
return false;
}
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
{
ImGuiContext& g = *GImGui;
if (g.OpenPopupStack.empty())
return;
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
// Don't close our own child popup windows.
int popup_count_to_keep = 0;
if (ref_window)
{
// Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
{
ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
if (!popup.Window)
continue;
IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
continue;
// Trim the stack when popups are not direct descendant of the reference window (the reference window is often the NavWindow)
bool popup_or_descendent_is_ref_window = false;
for (int m = popup_count_to_keep; m < g.OpenPopupStack.Size && !popup_or_descendent_is_ref_window; m++)
if (ImGuiWindow* popup_window = g.OpenPopupStack[m].Window)
if (popup_window->RootWindow == ref_window->RootWindow)
popup_or_descendent_is_ref_window = true;
if (!popup_or_descendent_is_ref_window)
break;
}
}
if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
{
//IMGUI_DEBUG_LOG("ClosePopupsOverWindow(%s) -> ClosePopupToLevel(%d)\n", ref_window->Name, popup_count_to_keep);
ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
}
}
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
ImGuiWindow* focus_window = g.OpenPopupStack[remaining].SourceWindow;
ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
g.OpenPopupStack.resize(remaining);
if (restore_focus_to_window_under_popup)
{
if (focus_window && !focus_window->WasActive && popup_window)
{
// Fallback
FocusTopMostWindowUnderOne(popup_window, NULL);
}
else
{
if (g.NavLayer == 0 && focus_window)
focus_window = NavRestoreLastChildNavWindow(focus_window);
FocusWindow(focus_window);
}
}
}
// Close the popup we have begin-ed into.
void ImGui::CloseCurrentPopup()
{
ImGuiContext& g = *GImGui;
int popup_idx = g.BeginPopupStack.Size - 1;
if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
return;
// Closing a menu closes its top-most parent popup (unless a modal)
while (popup_idx > 0)
{
ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
bool close_parent = false;
if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
if (parent_popup_window == NULL || !(parent_popup_window->Flags & ImGuiWindowFlags_Modal))
close_parent = true;
if (!close_parent)
break;
popup_idx--;
}
//IMGUI_DEBUG_LOG("CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
ClosePopupToLevel(popup_idx, true);
// A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
// To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
// Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
if (ImGuiWindow* window = g.NavWindow)
window->DC.NavHideHighlightOneFrame = true;
}
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags)
{
ImGuiContext& g = *GImGui;
if (!IsPopupOpen(id))
{
g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
return false;
}
char name[20];
if (extra_flags & ImGuiWindowFlags_ChildMenu)
ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginPopupStack.Size); // Recycle windows based on depth
else
ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
bool is_open = Begin(name, NULL, extra_flags | ImGuiWindowFlags_Popup);
if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
EndPopup();
return is_open;
}
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
{
g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
return false;
}
flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
return BeginPopupEx(g.CurrentWindow->GetID(str_id), flags);
}
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
// Note that popup visibility status is owned by imgui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here.
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImGuiID id = window->GetID(name);
if (!IsPopupOpen(id))
{
g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
return false;
}
// Center modal windows by default
// FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
if (g.NextWindowData.PosCond == 0)
SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings;
const bool is_open = Begin(name, p_open, flags);
if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
{
EndPopup();
if (is_open)
ClosePopupToLevel(g.BeginPopupStack.Size, true);
return false;
}
return is_open;
}
void ImGui::EndPopup()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.CurrentWindow->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
IM_ASSERT(g.BeginPopupStack.Size > 0);
// Make all menus and popups wrap around for now, may need to expose that policy.
NavMoveRequestTryWrapping(g.CurrentWindow, ImGuiNavMoveFlags_LoopY);
End();
}
// This is a helper to handle the simplest case of associating one named popup to one given widget.
// You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
// You can pass a NULL str_id to use the identifier of the last item.
bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button)
{
ImGuiWindow* window = GImGui->CurrentWindow;
ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
OpenPopupEx(id);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
bool ImGui::BeginPopupContextWindow(const char* str_id, int mouse_button, bool also_over_items)
{
if (!str_id)
str_id = "window_context";
ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
if (also_over_items || !IsAnyItemHovered())
OpenPopupEx(id);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button)
{
if (!str_id)
str_id = "void_context";
ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
OpenPopupEx(id);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
{
ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
//GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
//GetForegroundDrawList()->AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
// Combo Box policy (we want a connecting edge)
if (policy == ImGuiPopupPositionPolicy_ComboBox)
{
const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
{
const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
if (n != -1 && dir == *last_dir) // Already tried this direction?
continue;
ImVec2 pos;
if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default)
if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
if (!r_outer.Contains(ImRect(pos, pos + size)))
continue;
*last_dir = dir;
return pos;
}
}
// Default popup policy
const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
{
const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
if (n != -1 && dir == *last_dir) // Already tried this direction?
continue;
float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
if (avail_w < size.x || avail_h < size.y)
continue;
ImVec2 pos;
pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
*last_dir = dir;
return pos;
}
// Fallback, try to keep within display
*last_dir = ImGuiDir_None;
ImVec2 pos = ref_pos;
pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
return pos;
}
ImRect ImGui::GetWindowAllowedExtentRect(ImGuiWindow* window)
{
IM_UNUSED(window);
ImVec2 padding = GImGui->Style.DisplaySafeAreaPadding;
ImRect r_screen = GetViewportRect();
r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
return r_screen;
}
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
ImRect r_outer = GetWindowAllowedExtentRect(window);
if (window->Flags & ImGuiWindowFlags_ChildMenu)
{
// Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
// This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
IM_ASSERT(g.CurrentWindow == window);
ImGuiWindow* parent_window = g.CurrentWindowStack[g.CurrentWindowStack.Size - 2];
float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
ImRect r_avoid;
if (parent_window->DC.MenuBarAppending)
r_avoid = ImRect(-FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight(), FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight() + parent_window->MenuBarHeight());
else
r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
}
if (window->Flags & ImGuiWindowFlags_Popup)
{
ImRect r_avoid = ImRect(window->Pos.x - 1, window->Pos.y - 1, window->Pos.x + 1, window->Pos.y + 1);
return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
}
if (window->Flags & ImGuiWindowFlags_Tooltip)
{
// Position tooltip (always follows mouse)
float sc = g.Style.MouseCursorScale;
ImVec2 ref_pos = NavCalcPreferredRefPos();
ImRect r_avoid;
if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
else
r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
ImVec2 pos = FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
if (window->AutoPosLastDirection == ImGuiDir_None)
pos = ref_pos + ImVec2(2, 2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
return pos;
}
IM_ASSERT(0);
return window->Pos;
}
//-----------------------------------------------------------------------------
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
//-----------------------------------------------------------------------------
ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
{
if (ImFabs(dx) > ImFabs(dy))
return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
}
static float inline NavScoreItemDistInterval(float a0, float a1, float b0, float b1)
{
if (a1 < b0)
return a1 - b0;
if (b1 < a0)
return a0 - b1;
return 0.0f;
}
static void inline NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir, ImRect& r, const ImRect& clip_rect)
{
if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
{
r.Min.y = ImClamp(r.Min.y, clip_rect.Min.y, clip_rect.Max.y);
r.Max.y = ImClamp(r.Max.y, clip_rect.Min.y, clip_rect.Max.y);
}
else
{
r.Min.x = ImClamp(r.Min.x, clip_rect.Min.x, clip_rect.Max.x);
r.Max.x = ImClamp(r.Max.x, clip_rect.Min.x, clip_rect.Max.x);
}
}
// Scoring function for directional navigation. Based on https://gist.github.com/rygorous/6981057
static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavLayer != window->DC.NavLayerCurrent)
return false;
const ImRect& curr = g.NavScoringRectScreen; // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
g.NavScoringCount++;
// When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
if (window->ParentWindow == g.NavWindow)
{
IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
if (!window->ClipRect.Contains(cand))
return false;
cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
}
// We perform scoring on items bounding box clipped by the current clipping rectangle on the other axis (clipping on our movement axis would give us equal scores for all clipped items)
// For example, this ensure that items in one column are not reached when moving vertically from items in another column.
NavClampRectToVisibleAreaForMoveDir(g.NavMoveClipDir, cand, window->ClipRect);
// Compute distance between boxes
// FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
if (dby != 0.0f && dbx != 0.0f)
dbx = (dbx/1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
float dist_box = ImFabs(dbx) + ImFabs(dby);
// Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
// Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
ImGuiDir quadrant;
float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
if (dbx != 0.0f || dby != 0.0f)
{
// For non-overlapping boxes, use distance between boxes
dax = dbx;
day = dby;
dist_axial = dist_box;
quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
}
else if (dcx != 0.0f || dcy != 0.0f)
{
// For overlapping boxes with different centers, use distance between centers
dax = dcx;
day = dcy;
dist_axial = dist_center;
quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
}
else
{
// Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
quadrant = (window->DC.LastItemId < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
}
#if IMGUI_DEBUG_NAV_SCORING
char buf[128];
if (ImGui::IsMouseHoveringRect(cand.Min, cand.Max))
{
ImFormatString(buf, IM_ARRAYSIZE(buf), "dbox (%.2f,%.2f->%.4f)\ndcen (%.2f,%.2f->%.4f)\nd (%.2f,%.2f->%.4f)\nnav %c, quadrant %c", dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "WENS"[g.NavMoveDir], "WENS"[quadrant]);
ImDrawList* draw_list = ImGui::GetForegroundDrawList(window);
draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100));
draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200));
draw_list->AddRectFilled(cand.Max-ImVec2(4,4), cand.Max+ImGui::CalcTextSize(buf)+ImVec2(4,4), IM_COL32(40,0,0,150));
draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Max, ~0U, buf);
}
else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate.
{
if (ImGui::IsKeyPressedMap(ImGuiKey_C)) { g.NavMoveDirLast = (ImGuiDir)((g.NavMoveDirLast + 1) & 3); g.IO.KeysDownDuration[g.IO.KeyMap[ImGuiKey_C]] = 0.01f; }
if (quadrant == g.NavMoveDir)
{
ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
ImDrawList* draw_list = ImGui::GetForegroundDrawList(window);
draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200));
draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Min, IM_COL32(255, 255, 255, 255), buf);
}
}
#endif
// Is it in the quadrant we're interesting in moving to?
bool new_best = false;
if (quadrant == g.NavMoveDir)
{
// Does it beat the current best candidate?
if (dist_box < result->DistBox)
{
result->DistBox = dist_box;
result->DistCenter = dist_center;
return true;
}
if (dist_box == result->DistBox)
{
// Try using distance between center points to break ties
if (dist_center < result->DistCenter)
{
result->DistCenter = dist_center;
new_best = true;
}
else if (dist_center == result->DistCenter)
{
// Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
// (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
// this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
if (((g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
new_best = true;
}
}
}
// Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
// are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
// This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
// 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
// Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match
if (g.NavLayer == 1 && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
if ((g.NavMoveDir == ImGuiDir_Left && dax < 0.0f) || (g.NavMoveDir == ImGuiDir_Right && dax > 0.0f) || (g.NavMoveDir == ImGuiDir_Up && day < 0.0f) || (g.NavMoveDir == ImGuiDir_Down && day > 0.0f))
{
result->DistAxial = dist_axial;
new_best = true;
}
return new_best;
}
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id)
{
ImGuiContext& g = *GImGui;
//if (!g.IO.NavActive) // [2017/10/06] Removed this possibly redundant test but I am not sure of all the side-effects yet. Some of the feature here will need to work regardless of using a _NoNavInputs flag.
// return;
const ImGuiItemFlags item_flags = window->DC.ItemFlags;
const ImRect nav_bb_rel(nav_bb.Min - window->Pos, nav_bb.Max - window->Pos);
// Process Init Request
if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent)
{
// Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus) || g.NavInitResultId == 0)
{
g.NavInitResultId = id;
g.NavInitResultRectRel = nav_bb_rel;
}
if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus))
{
g.NavInitRequest = false; // Found a match, clear request
NavUpdateAnyRequestFlag();
}
}
// Process Move Request (scoring for navigation)
// FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRectScreen + scoring from a rect wrapped according to current wrapping policy)
if ((g.NavId != id || (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & (ImGuiItemFlags_Disabled|ImGuiItemFlags_NoNav)))
{
ImGuiNavMoveResult* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
#if IMGUI_DEBUG_NAV_SCORING
// [DEBUG] Score all items in NavWindow at all times
if (!g.NavMoveRequest)
g.NavMoveDir = g.NavMoveDirLast;
bool new_best = NavScoreItem(result, nav_bb) && g.NavMoveRequest;
#else
bool new_best = g.NavMoveRequest && NavScoreItem(result, nav_bb);
#endif
if (new_best)
{
result->ID = id;
result->SelectScopeId = g.MultiSelectScopeId;
result->Window = window;
result->RectRel = nav_bb_rel;
}
const float VISIBLE_RATIO = 0.70f;
if ((g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
if (NavScoreItem(&g.NavMoveResultLocalVisibleSet, nav_bb))
{
result = &g.NavMoveResultLocalVisibleSet;
result->ID = id;
result->SelectScopeId = g.MultiSelectScopeId;
result->Window = window;
result->RectRel = nav_bb_rel;
}
}
// Update window-relative bounding box of navigated item
if (g.NavId == id)
{
g.NavWindow = window; // Always refresh g.NavWindow, because some operations such as FocusItem() don't have a window.
g.NavLayer = window->DC.NavLayerCurrent;
g.NavIdIsAlive = true;
g.NavIdTabCounter = window->DC.FocusCounterTab;
window->NavRectRel[window->DC.NavLayerCurrent] = nav_bb_rel; // Store item bounding box (relative to window position)
}
}
bool ImGui::NavMoveRequestButNoResultYet()
{
ImGuiContext& g = *GImGui;
return g.NavMoveRequest && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
}
void ImGui::NavMoveRequestCancel()
{
ImGuiContext& g = *GImGui;
g.NavMoveRequest = false;
NavUpdateAnyRequestFlag();
}
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, const ImRect& bb_rel, ImGuiNavMoveFlags move_flags)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_None);
ImGui::NavMoveRequestCancel();
g.NavMoveDir = move_dir;
g.NavMoveClipDir = clip_dir;
g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued;
g.NavMoveRequestFlags = move_flags;
g.NavWindow->NavRectRel[g.NavLayer] = bb_rel;
}
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags)
{
ImGuiContext& g = *GImGui;
if (g.NavWindow != window || !NavMoveRequestButNoResultYet() || g.NavMoveRequestForward != ImGuiNavForward_None || g.NavLayer != 0)
return;
IM_ASSERT(move_flags != 0); // No points calling this with no wrapping
ImRect bb_rel = window->NavRectRel[0];
ImGuiDir clip_dir = g.NavMoveDir;
if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
{
bb_rel.Min.x = bb_rel.Max.x = ImMax(window->SizeFull.x, window->SizeContents.x) - window->Scroll.x;
if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(-bb_rel.GetHeight()); clip_dir = ImGuiDir_Up; }
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
{
bb_rel.Min.x = bb_rel.Max.x = -window->Scroll.x;
if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(+bb_rel.GetHeight()); clip_dir = ImGuiDir_Down; }
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
{
bb_rel.Min.y = bb_rel.Max.y = ImMax(window->SizeFull.y, window->SizeContents.y) - window->Scroll.y;
if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(-bb_rel.GetWidth()); clip_dir = ImGuiDir_Left; }
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
{
bb_rel.Min.y = bb_rel.Max.y = -window->Scroll.y;
if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(+bb_rel.GetWidth()); clip_dir = ImGuiDir_Right; }
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
}
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
// This way we could find the last focused window among our children. It would be much less confusing this way?
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
{
ImGuiWindow* parent_window = nav_window;
while (parent_window && (parent_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (parent_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
parent_window = parent_window->ParentWindow;
if (parent_window && parent_window != nav_window)
parent_window->NavLastChildNavWindow = nav_window;
}
// Restore the last focused child.
// Call when we are expected to land on the Main Layer (0) after FocusWindow()
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
{
return window->NavLastChildNavWindow ? window->NavLastChildNavWindow : window;
}
static void NavRestoreLayer(ImGuiNavLayer layer)
{
ImGuiContext& g = *GImGui;
g.NavLayer = layer;
if (layer == 0)
g.NavWindow = ImGui::NavRestoreLastChildNavWindow(g.NavWindow);
if (layer == 0 && g.NavWindow->NavLastIds[0] != 0)
ImGui::SetNavIDWithRectRel(g.NavWindow->NavLastIds[0], layer, g.NavWindow->NavRectRel[0]);
else
ImGui::NavInitWindow(g.NavWindow, true);
}
static inline void ImGui::NavUpdateAnyRequestFlag()
{
ImGuiContext& g = *GImGui;
g.NavAnyRequest = g.NavMoveRequest || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
if (g.NavAnyRequest)
IM_ASSERT(g.NavWindow != NULL);
}
// This needs to be called before we submit any widget (aka in or before Begin)
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(window == g.NavWindow);
bool init_for_nav = false;
if (!(window->Flags & ImGuiWindowFlags_NoNavInputs))
if (!(window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
init_for_nav = true;
if (init_for_nav)
{
SetNavID(0, g.NavLayer);
g.NavInitRequest = true;
g.NavInitRequestFromMove = false;
g.NavInitResultId = 0;
g.NavInitResultRectRel = ImRect();
NavUpdateAnyRequestFlag();
}
else
{
g.NavId = window->NavLastIds[0];
}
}
static ImVec2 ImGui::NavCalcPreferredRefPos()
{
ImGuiContext& g = *GImGui;
if (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow)
{
// Mouse (we need a fallback in case the mouse becomes invalid after being used)
if (IsMousePosValid(&g.IO.MousePos))
return g.IO.MousePos;
return g.LastValidMousePos;
}
else
{
// When navigation is active and mouse is disabled, decide on an arbitrary position around the bottom left of the currently navigated item.
const ImRect& rect_rel = g.NavWindow->NavRectRel[g.NavLayer];
ImVec2 pos = g.NavWindow->Pos + ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
ImRect visible_rect = GetViewportRect();
return ImFloor(ImClamp(pos, visible_rect.Min, visible_rect.Max)); // ImFloor() is important because non-integer mouse position application in back-end might be lossy and result in undesirable non-zero delta.
}
}
float ImGui::GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode)
{
ImGuiContext& g = *GImGui;
if (mode == ImGuiInputReadMode_Down)
return g.IO.NavInputs[n]; // Instant, read analog input (0.0f..1.0f, as provided by user)
const float t = g.IO.NavInputsDownDuration[n];
if (t < 0.0f && mode == ImGuiInputReadMode_Released) // Return 1.0f when just released, no repeat, ignore analog input.
return (g.IO.NavInputsDownDurationPrev[n] >= 0.0f ? 1.0f : 0.0f);
if (t < 0.0f)
return 0.0f;
if (mode == ImGuiInputReadMode_Pressed) // Return 1.0f when just pressed, no repeat, ignore analog input.
return (t == 0.0f) ? 1.0f : 0.0f;
if (mode == ImGuiInputReadMode_Repeat)
return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 0.80f, g.IO.KeyRepeatRate * 0.80f);
if (mode == ImGuiInputReadMode_RepeatSlow)
return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 1.00f, g.IO.KeyRepeatRate * 2.00f);
if (mode == ImGuiInputReadMode_RepeatFast)
return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 0.80f, g.IO.KeyRepeatRate * 0.30f);
return 0.0f;
}
ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor, float fast_factor)
{
ImVec2 delta(0.0f, 0.0f);
if (dir_sources & ImGuiNavDirSourceFlags_Keyboard)
delta += ImVec2(GetNavInputAmount(ImGuiNavInput_KeyRight_, mode) - GetNavInputAmount(ImGuiNavInput_KeyLeft_, mode), GetNavInputAmount(ImGuiNavInput_KeyDown_, mode) - GetNavInputAmount(ImGuiNavInput_KeyUp_, mode));
if (dir_sources & ImGuiNavDirSourceFlags_PadDPad)
delta += ImVec2(GetNavInputAmount(ImGuiNavInput_DpadRight, mode) - GetNavInputAmount(ImGuiNavInput_DpadLeft, mode), GetNavInputAmount(ImGuiNavInput_DpadDown, mode) - GetNavInputAmount(ImGuiNavInput_DpadUp, mode));
if (dir_sources & ImGuiNavDirSourceFlags_PadLStick)
delta += ImVec2(GetNavInputAmount(ImGuiNavInput_LStickRight, mode) - GetNavInputAmount(ImGuiNavInput_LStickLeft, mode), GetNavInputAmount(ImGuiNavInput_LStickDown, mode) - GetNavInputAmount(ImGuiNavInput_LStickUp, mode));
if (slow_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakSlow))
delta *= slow_factor;
if (fast_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakFast))
delta *= fast_factor;
return delta;
}
// Scroll to keep newly navigated item fully into view
// NB: We modify rect_rel by the amount we scrolled for, so it is immediately updated.
static void NavScrollToBringItemIntoView(ImGuiWindow* window, const ImRect& item_rect)
{
ImRect window_rect(window->InnerMainRect.Min - ImVec2(1, 1), window->InnerMainRect.Max + ImVec2(1, 1));
//GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG]
if (window_rect.Contains(item_rect))
return;
ImGuiContext& g = *GImGui;
if (window->ScrollbarX && item_rect.Min.x < window_rect.Min.x)
{
window->ScrollTarget.x = item_rect.Min.x - window->Pos.x + window->Scroll.x - g.Style.ItemSpacing.x;
window->ScrollTargetCenterRatio.x = 0.0f;
}
else if (window->ScrollbarX && item_rect.Max.x >= window_rect.Max.x)
{
window->ScrollTarget.x = item_rect.Max.x - window->Pos.x + window->Scroll.x + g.Style.ItemSpacing.x;
window->ScrollTargetCenterRatio.x = 1.0f;
}
if (item_rect.Min.y < window_rect.Min.y)
{
window->ScrollTarget.y = item_rect.Min.y - window->Pos.y + window->Scroll.y - g.Style.ItemSpacing.y;
window->ScrollTargetCenterRatio.y = 0.0f;
}
else if (item_rect.Max.y >= window_rect.Max.y)
{
window->ScrollTarget.y = item_rect.Max.y - window->Pos.y + window->Scroll.y + g.Style.ItemSpacing.y;
window->ScrollTargetCenterRatio.y = 1.0f;
}
}
static void ImGui::NavUpdate()
{
ImGuiContext& g = *GImGui;
g.IO.WantSetMousePos = false;
#if 0
if (g.NavScoringCount > 0) IMGUI_DEBUG_LOG("NavScoringCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.FrameCount, g.NavScoringCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
#endif
// Set input source as Gamepad when buttons are pressed before we map Keyboard (some features differs when used with Gamepad vs Keyboard)
bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
if (nav_gamepad_active)
if (g.IO.NavInputs[ImGuiNavInput_Activate] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Input] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Cancel] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Menu] > 0.0f)
g.NavInputSource = ImGuiInputSource_NavGamepad;
// Update Keyboard->Nav inputs mapping
if (nav_keyboard_active)
{
#define NAV_MAP_KEY(_KEY, _NAV_INPUT) if (IsKeyDown(g.IO.KeyMap[_KEY])) { g.IO.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_NavKeyboard; }
NAV_MAP_KEY(ImGuiKey_Space, ImGuiNavInput_Activate );
NAV_MAP_KEY(ImGuiKey_Enter, ImGuiNavInput_Input );
NAV_MAP_KEY(ImGuiKey_Escape, ImGuiNavInput_Cancel );
NAV_MAP_KEY(ImGuiKey_LeftArrow, ImGuiNavInput_KeyLeft_ );
NAV_MAP_KEY(ImGuiKey_RightArrow,ImGuiNavInput_KeyRight_);
NAV_MAP_KEY(ImGuiKey_UpArrow, ImGuiNavInput_KeyUp_ );
NAV_MAP_KEY(ImGuiKey_DownArrow, ImGuiNavInput_KeyDown_ );
NAV_MAP_KEY(ImGuiKey_Tab, ImGuiNavInput_KeyTab_ );
if (g.IO.KeyCtrl)
g.IO.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f;
if (g.IO.KeyShift)
g.IO.NavInputs[ImGuiNavInput_TweakFast] = 1.0f;
if (g.IO.KeyAlt && !g.IO.KeyCtrl) // AltGR is Alt+Ctrl, also even on keyboards without AltGR we don't want Alt+Ctrl to open menu.
g.IO.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f;
#undef NAV_MAP_KEY
}
memcpy(g.IO.NavInputsDownDurationPrev, g.IO.NavInputsDownDuration, sizeof(g.IO.NavInputsDownDuration));
for (int i = 0; i < IM_ARRAYSIZE(g.IO.NavInputs); i++)
g.IO.NavInputsDownDuration[i] = (g.IO.NavInputs[i] > 0.0f) ? (g.IO.NavInputsDownDuration[i] < 0.0f ? 0.0f : g.IO.NavInputsDownDuration[i] + g.IO.DeltaTime) : -1.0f;
// Process navigation init request (select first/default focus)
if (g.NavInitResultId != 0 && (!g.NavDisableHighlight || g.NavInitRequestFromMove))
{
// Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
IM_ASSERT(g.NavWindow);
if (g.NavInitRequestFromMove)
SetNavIDWithRectRel(g.NavInitResultId, g.NavLayer, g.NavInitResultRectRel);
else
SetNavID(g.NavInitResultId, g.NavLayer);
g.NavWindow->NavRectRel[g.NavLayer] = g.NavInitResultRectRel;
}
g.NavInitRequest = false;
g.NavInitRequestFromMove = false;
g.NavInitResultId = 0;
g.NavJustMovedToId = 0;
// Process navigation move request
if (g.NavMoveRequest)
NavUpdateMoveResult();
// When a forwarded move request failed, we restore the highlight that we disabled during the forward frame
if (g.NavMoveRequestForward == ImGuiNavForward_ForwardActive)
{
IM_ASSERT(g.NavMoveRequest);
if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0)
g.NavDisableHighlight = false;
g.NavMoveRequestForward = ImGuiNavForward_None;
}
// Apply application mouse position movement, after we had a chance to process move request result.
if (g.NavMousePosDirty && g.NavIdIsAlive)
{
// Set mouse position given our knowledge of the navigated item position from last frame
if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (g.IO.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
{
if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
{
g.IO.MousePos = g.IO.MousePosPrev = NavCalcPreferredRefPos();
g.IO.WantSetMousePos = true;
}
}
g.NavMousePosDirty = false;
}
g.NavIdIsAlive = false;
g.NavJustTabbedId = 0;
IM_ASSERT(g.NavLayer == 0 || g.NavLayer == 1);
// Store our return window (for returning from Layer 1 to Layer 0) and clear it as soon as we step back in our own Layer 0
if (g.NavWindow)
NavSaveLastChildNavWindowIntoParent(g.NavWindow);
if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == 0)
g.NavWindow->NavLastChildNavWindow = NULL;
// Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
NavUpdateWindowing();
// Set output flags for user application
g.IO.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
g.IO.NavVisible = (g.IO.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
// Process NavCancel input (to close a popup, get back to parent, clear focus)
if (IsNavInputPressed(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed))
{
if (g.ActiveId != 0)
{
if (!(g.ActiveIdBlockNavInputFlags & (1 << ImGuiNavInput_Cancel)))
ClearActiveID();
}
else if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow) && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
{
// Exit child window
ImGuiWindow* child_window = g.NavWindow;
ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
IM_ASSERT(child_window->ChildId != 0);
FocusWindow(parent_window);
SetNavID(child_window->ChildId, 0);
g.NavIdIsAlive = false;
if (g.NavDisableMouseHover)
g.NavMousePosDirty = true;
}
else if (g.OpenPopupStack.Size > 0)
{
// Close open popup/menu
if (!(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
}
else if (g.NavLayer != 0)
{
// Leave the "menu" layer
NavRestoreLayer(ImGuiNavLayer_Main);
}
else
{
// Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
g.NavWindow->NavLastIds[0] = 0;
g.NavId = 0;
}
}
// Process manual activation request
g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = 0;
if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
{
bool activate_down = IsNavInputDown(ImGuiNavInput_Activate);
bool activate_pressed = activate_down && IsNavInputPressed(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed);
if (g.ActiveId == 0 && activate_pressed)
g.NavActivateId = g.NavId;
if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down)
g.NavActivateDownId = g.NavId;
if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed)
g.NavActivatePressedId = g.NavId;
if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && IsNavInputPressed(ImGuiNavInput_Input, ImGuiInputReadMode_Pressed))
g.NavInputId = g.NavId;
}
if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
g.NavDisableHighlight = true;
if (g.NavActivateId != 0)
IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
g.NavMoveRequest = false;
// Process programmatic activation request
if (g.NavNextActivateId != 0)
g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = g.NavNextActivateId;
g.NavNextActivateId = 0;
// Initiate directional inputs request
const int allowed_dir_flags = (g.ActiveId == 0) ? ~0 : g.ActiveIdAllowNavDirFlags;
if (g.NavMoveRequestForward == ImGuiNavForward_None)
{
g.NavMoveDir = ImGuiDir_None;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_None;
if (g.NavWindow && !g.NavWindowingTarget && allowed_dir_flags && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
{
if ((allowed_dir_flags & (1<<ImGuiDir_Left)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadLeft, ImGuiNavInput_KeyLeft_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Left;
if ((allowed_dir_flags & (1<<ImGuiDir_Right)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadRight,ImGuiNavInput_KeyRight_,ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Right;
if ((allowed_dir_flags & (1<<ImGuiDir_Up)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadUp, ImGuiNavInput_KeyUp_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Up;
if ((allowed_dir_flags & (1<<ImGuiDir_Down)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadDown, ImGuiNavInput_KeyDown_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Down;
}
g.NavMoveClipDir = g.NavMoveDir;
}
else
{
// Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
// (Preserve g.NavMoveRequestFlags, g.NavMoveClipDir which were set by the NavMoveRequestForward() function)
IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_ForwardQueued);
g.NavMoveRequestForward = ImGuiNavForward_ForwardActive;
}
// Update PageUp/PageDown scroll
float nav_scoring_rect_offset_y = 0.0f;
if (nav_keyboard_active)
nav_scoring_rect_offset_y = NavUpdatePageUpPageDown(allowed_dir_flags);
// If we initiate a movement request and have no current NavId, we initiate a InitDefautRequest that will be used as a fallback if the direction fails to find a match
if (g.NavMoveDir != ImGuiDir_None)
{
g.NavMoveRequest = true;
g.NavMoveDirLast = g.NavMoveDir;
}
if (g.NavMoveRequest && g.NavId == 0)
{
g.NavInitRequest = g.NavInitRequestFromMove = true;
g.NavInitResultId = 0;
g.NavDisableHighlight = false;
}
NavUpdateAnyRequestFlag();
// Scrolling
if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
{
// *Fallback* manual-scroll with Nav directional keys when window has no navigable item
ImGuiWindow* window = g.NavWindow;
const float scroll_speed = ImFloor(window->CalcFontSize() * 100 * g.IO.DeltaTime + 0.5f); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll && g.NavMoveRequest)
{
if (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right)
SetWindowScrollX(window, ImFloor(window->Scroll.x + ((g.NavMoveDir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
if (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down)
SetWindowScrollY(window, ImFloor(window->Scroll.y + ((g.NavMoveDir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
}
// *Normal* Manual scroll with NavScrollXXX keys
// Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f/10.0f, 10.0f);
if (scroll_dir.x != 0.0f && window->ScrollbarX)
{
SetWindowScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed));
g.NavMoveFromClampedRefRect = true;
}
if (scroll_dir.y != 0.0f)
{
SetWindowScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed));
g.NavMoveFromClampedRefRect = true;
}
}
// Reset search results
g.NavMoveResultLocal.Clear();
g.NavMoveResultLocalVisibleSet.Clear();
g.NavMoveResultOther.Clear();
// When we have manually scrolled (without using navigation) and NavId becomes out of bounds, we project its bounding box to the visible area to restart navigation within visible items
if (g.NavMoveRequest && g.NavMoveFromClampedRefRect && g.NavLayer == 0)
{
ImGuiWindow* window = g.NavWindow;
ImRect window_rect_rel(window->InnerMainRect.Min - window->Pos - ImVec2(1,1), window->InnerMainRect.Max - window->Pos + ImVec2(1,1));
if (!window_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
{
float pad = window->CalcFontSize() * 0.5f;
window_rect_rel.Expand(ImVec2(-ImMin(window_rect_rel.GetWidth(), pad), -ImMin(window_rect_rel.GetHeight(), pad))); // Terrible approximation for the intent of starting navigation from first fully visible item
window->NavRectRel[g.NavLayer].ClipWith(window_rect_rel);
g.NavId = 0;
}
g.NavMoveFromClampedRefRect = false;
}
// For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
ImRect nav_rect_rel = (g.NavWindow && !g.NavWindow->NavRectRel[g.NavLayer].IsInverted()) ? g.NavWindow->NavRectRel[g.NavLayer] : ImRect(0,0,0,0);
g.NavScoringRectScreen = g.NavWindow ? ImRect(g.NavWindow->Pos + nav_rect_rel.Min, g.NavWindow->Pos + nav_rect_rel.Max) : GetViewportRect();
g.NavScoringRectScreen.TranslateY(nav_scoring_rect_offset_y);
g.NavScoringRectScreen.Min.x = ImMin(g.NavScoringRectScreen.Min.x + 1.0f, g.NavScoringRectScreen.Max.x);
g.NavScoringRectScreen.Max.x = g.NavScoringRectScreen.Min.x;
IM_ASSERT(!g.NavScoringRectScreen.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous ImFabs() calls in NavScoreItem().
//GetForegroundDrawList()->AddRect(g.NavScoringRectScreen.Min, g.NavScoringRectScreen.Max, IM_COL32(255,200,0,255)); // [DEBUG]
g.NavScoringCount = 0;
#if IMGUI_DEBUG_NAV_RECTS
if (g.NavWindow)
{
ImDrawList* draw_list = GetForegroundDrawList(g.NavWindow);
if (1) { for (int layer = 0; layer < 2; layer++) draw_list->AddRect(g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Min, g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Max, IM_COL32(255,200,0,255)); } // [DEBUG]
if (1) { ImU32 col = (!g.NavWindow->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
}
#endif
}
// Apply result from previous frame navigation directional move request
static void ImGui::NavUpdateMoveResult()
{
ImGuiContext& g = *GImGui;
if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0)
{
// In a situation when there is no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
if (g.NavId != 0)
{
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
}
return;
}
// Select which result to use
ImGuiNavMoveResult* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
// PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
if (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
if (g.NavMoveResultLocalVisibleSet.ID != 0 && g.NavMoveResultLocalVisibleSet.ID != g.NavId)
result = &g.NavMoveResultLocalVisibleSet;
// Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
result = &g.NavMoveResultOther;
IM_ASSERT(g.NavWindow && result->Window);
// Scroll to keep newly navigated item fully into view.
if (g.NavLayer == 0)
{
ImRect rect_abs = ImRect(result->RectRel.Min + result->Window->Pos, result->RectRel.Max + result->Window->Pos);
NavScrollToBringItemIntoView(result->Window, rect_abs);
// Estimate upcoming scroll so we can offset our result position so mouse position can be applied immediately after in NavUpdate()
ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(result->Window, false);
ImVec2 delta_scroll = result->Window->Scroll - next_scroll;
result->RectRel.Translate(delta_scroll);
// Also scroll parent window to keep us into view if necessary (we could/should technically recurse back the whole the parent hierarchy).
if (result->Window->Flags & ImGuiWindowFlags_ChildWindow)
NavScrollToBringItemIntoView(result->Window->ParentWindow, ImRect(rect_abs.Min + delta_scroll, rect_abs.Max + delta_scroll));
}
ClearActiveID();
g.NavWindow = result->Window;
if (g.NavId != result->ID)
{
// Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
g.NavJustMovedToId = result->ID;
g.NavJustMovedToMultiSelectScopeId = result->SelectScopeId;
}
SetNavIDWithRectRel(result->ID, g.NavLayer, result->RectRel);
g.NavMoveFromClampedRefRect = false;
}
static float ImGui::NavUpdatePageUpPageDown(int allowed_dir_flags)
{
ImGuiContext& g = *GImGui;
if (g.NavMoveDir == ImGuiDir_None && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget && g.NavLayer == 0)
{
ImGuiWindow* window = g.NavWindow;
bool page_up_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageUp]) && (allowed_dir_flags & (1 << ImGuiDir_Up));
bool page_down_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageDown]) && (allowed_dir_flags & (1 << ImGuiDir_Down));
if (page_up_held != page_down_held) // If either (not both) are pressed
{
if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll)
{
// Fallback manual-scroll when window has no navigable item
if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true))
SetWindowScrollY(window, window->Scroll.y - window->InnerMainRect.GetHeight());
else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true))
SetWindowScrollY(window, window->Scroll.y + window->InnerMainRect.GetHeight());
}
else
{
const ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
const float page_offset_y = ImMax(0.0f, window->InnerMainRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
float nav_scoring_rect_offset_y = 0.0f;
if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true))
{
nav_scoring_rect_offset_y = -page_offset_y;
g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset, we intentionally request the opposite direction (so we can always land on the last item)
g.NavMoveClipDir = ImGuiDir_Up;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
}
else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true))
{
nav_scoring_rect_offset_y = +page_offset_y;
g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset, we intentionally request the opposite direction (so we can always land on the last item)
g.NavMoveClipDir = ImGuiDir_Down;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
}
return nav_scoring_rect_offset_y;
}
}
}
return 0.0f;
}
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window) // FIXME-OPT O(N)
{
ImGuiContext& g = *GImGui;
for (int i = g.WindowsFocusOrder.Size-1; i >= 0; i--)
if (g.WindowsFocusOrder[i] == window)
return i;
return -1;
}
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
{
ImGuiContext& g = *GImGui;
for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
return g.WindowsFocusOrder[i];
return NULL;
}
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavWindowingTarget);
if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
return;
const int i_current = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
if (!window_target)
window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
if (window_target) // Don't reset windowing target if there's a single window in the list
g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
g.NavWindowingToggleLayer = false;
}
// Windowing management mode
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
// Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
static void ImGui::NavUpdateWindowing()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* apply_focus_window = NULL;
bool apply_toggle_layer = false;
ImGuiWindow* modal_window = GetFrontMostPopupModal();
if (modal_window != NULL)
{
g.NavWindowingTarget = NULL;
return;
}
// Fade out
if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
{
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - g.IO.DeltaTime * 10.0f, 0.0f);
if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
g.NavWindowingTargetAnim = NULL;
}
// Start CTRL-TAB or Square+L/R window selection
bool start_windowing_with_gamepad = !g.NavWindowingTarget && IsNavInputPressed(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed);
bool start_windowing_with_keyboard = !g.NavWindowingTarget && g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab) && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard);
if (start_windowing_with_gamepad || start_windowing_with_keyboard)
if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
{
g.NavWindowingTarget = g.NavWindowingTargetAnim = window;
g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
g.NavWindowingToggleLayer = start_windowing_with_keyboard ? false : true;
g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_NavKeyboard : ImGuiInputSource_NavGamepad;
}
// Gamepad update
g.NavWindowingTimer += g.IO.DeltaTime;
if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavGamepad)
{
// Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
// Select window to focus
const int focus_change_dir = (int)IsNavInputPressed(ImGuiNavInput_FocusPrev, ImGuiInputReadMode_RepeatSlow) - (int)IsNavInputPressed(ImGuiNavInput_FocusNext, ImGuiInputReadMode_RepeatSlow);
if (focus_change_dir != 0)
{
NavUpdateWindowingHighlightWindow(focus_change_dir);
g.NavWindowingHighlightAlpha = 1.0f;
}
// Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered front-most)
if (!IsNavInputDown(ImGuiNavInput_Menu))
{
g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
if (g.NavWindowingToggleLayer && g.NavWindow)
apply_toggle_layer = true;
else if (!g.NavWindowingToggleLayer)
apply_focus_window = g.NavWindowingTarget;
g.NavWindowingTarget = NULL;
}
}
// Keyboard: Focus
if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavKeyboard)
{
// Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
if (IsKeyPressedMap(ImGuiKey_Tab, true))
NavUpdateWindowingHighlightWindow(g.IO.KeyShift ? +1 : -1);
if (!g.IO.KeyCtrl)
apply_focus_window = g.NavWindowingTarget;
}
// Keyboard: Press and Release ALT to toggle menu layer
// FIXME: We lack an explicit IO variable for "is the imgui window focused", so compare mouse validity to detect the common case of back-end clearing releases all keys on ALT-TAB
if (IsNavInputPressed(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Pressed))
g.NavWindowingToggleLayer = true;
if ((g.ActiveId == 0 || g.ActiveIdAllowOverlap) && g.NavWindowingToggleLayer && IsNavInputPressed(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Released))
if (IsMousePosValid(&g.IO.MousePos) == IsMousePosValid(&g.IO.MousePosPrev))
apply_toggle_layer = true;
// Move window
if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
{
ImVec2 move_delta;
if (g.NavInputSource == ImGuiInputSource_NavKeyboard && !g.IO.KeyShift)
move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
if (g.NavInputSource == ImGuiInputSource_NavGamepad)
move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down);
if (move_delta.x != 0.0f || move_delta.y != 0.0f)
{
const float NAV_MOVE_SPEED = 800.0f;
const float move_speed = ImFloor(NAV_MOVE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); // FIXME: Doesn't code variable framerate very well
g.NavWindowingTarget->RootWindow->Pos += move_delta * move_speed;
g.NavDisableMouseHover = true;
MarkIniSettingsDirty(g.NavWindowingTarget);
}
}
// Apply final focus
if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
{
ClearActiveID();
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window);
ClosePopupsOverWindow(apply_focus_window, false);
FocusWindow(apply_focus_window);
if (apply_focus_window->NavLastIds[0] == 0)
NavInitWindow(apply_focus_window, false);
// If the window only has a menu layer, select it directly
if (apply_focus_window->DC.NavLayerActiveMask == (1 << ImGuiNavLayer_Menu))
g.NavLayer = ImGuiNavLayer_Menu;
}
if (apply_focus_window)
g.NavWindowingTarget = NULL;
// Apply menu/layer toggle
if (apply_toggle_layer && g.NavWindow)
{
// Move to parent menu if necessary
ImGuiWindow* new_nav_window = g.NavWindow;
while (new_nav_window->ParentWindow
&& (new_nav_window->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) == 0
&& (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
&& (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
new_nav_window = new_nav_window->ParentWindow;
if (new_nav_window != g.NavWindow)
{
ImGuiWindow* old_nav_window = g.NavWindow;
FocusWindow(new_nav_window);
new_nav_window->NavLastChildNavWindow = old_nav_window;
}
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
// When entering a regular menu bar with the Alt key, we always reinitialize the navigation ID.
const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
NavRestoreLayer(new_nav_layer);
}
}
// Window has already passed the IsWindowNavFocusable()
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
{
if (window->Flags & ImGuiWindowFlags_Popup)
return "(Popup)";
if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
return "(Main menu bar)";
return "(Untitled)";
}
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
void ImGui::NavUpdateWindowingList()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavWindowingTarget != NULL);
if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
return;
if (g.NavWindowingList == NULL)
g.NavWindowingList = FindWindowByName("###NavWindowingList");
SetNextWindowSizeConstraints(ImVec2(g.IO.DisplaySize.x * 0.20f, g.IO.DisplaySize.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Always, ImVec2(0.5f, 0.5f));
PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
{
ImGuiWindow* window = g.WindowsFocusOrder[n];
if (!IsWindowNavFocusable(window))
continue;
const char* label = window->Name;
if (label == FindRenderedTextEnd(label))
label = GetFallbackWindowNameForWindowingList(window);
Selectable(label, g.NavWindowingTarget == window);
}
End();
PopStyleVar();
}
//-----------------------------------------------------------------------------
// [SECTION] COLUMNS
// In the current version, Columns are very weak. Needs to be replaced with a more full-featured system.
//-----------------------------------------------------------------------------
void ImGui::NextColumn()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems || window->DC.CurrentColumns == NULL)
return;
ImGuiContext& g = *GImGui;
ImGuiColumns* columns = window->DC.CurrentColumns;
if (columns->Count == 1)
{
window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
IM_ASSERT(columns->Current == 0);
return;
}
PopItemWidth();
PopClipRect();
columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
if (++columns->Current < columns->Count)
{
// New column (columns 1+ cancels out IndentX)
window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + g.Style.ItemSpacing.x;
window->DrawList->ChannelsSetCurrent(columns->Current + 1);
}
else
{
// New row/line
window->DC.ColumnsOffset.x = 0.0f;
window->DrawList->ChannelsSetCurrent(1);
columns->Current = 0;
columns->LineMinY = columns->LineMaxY;
}
window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
window->DC.CursorPos.y = columns->LineMinY;
window->DC.CurrentLineSize = ImVec2(0.0f, 0.0f);
window->DC.CurrentLineTextBaseOffset = 0.0f;
PushColumnClipRect(columns->Current);
PushItemWidth(GetColumnWidth() * 0.65f); // FIXME-COLUMNS: Move on columns setup
}
int ImGui::GetColumnIndex()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CurrentColumns ? window->DC.CurrentColumns->Current : 0;
}
int ImGui::GetColumnsCount()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CurrentColumns ? window->DC.CurrentColumns->Count : 1;
}
static float OffsetNormToPixels(const ImGuiColumns* columns, float offset_norm)
{
return offset_norm * (columns->OffMaxX - columns->OffMinX);
}
static float PixelsToOffsetNorm(const ImGuiColumns* columns, float offset)
{
return offset / (columns->OffMaxX - columns->OffMinX);
}
static const float COLUMNS_HIT_RECT_HALF_WIDTH = 4.0f;
static float GetDraggedColumnOffset(ImGuiColumns* columns, int column_index)
{
// Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing
// window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning.
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(column_index > 0); // We are not supposed to drag column 0.
IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index));
float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + COLUMNS_HIT_RECT_HALF_WIDTH - window->Pos.x;
x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing);
if ((columns->Flags & ImGuiColumnsFlags_NoPreserveWidths))
x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing);
return x;
}
float ImGui::GetColumnOffset(int column_index)
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiColumns* columns = window->DC.CurrentColumns;
IM_ASSERT(columns != NULL);
if (column_index < 0)
column_index = columns->Current;
IM_ASSERT(column_index < columns->Columns.Size);
const float t = columns->Columns[column_index].OffsetNorm;
const float x_offset = ImLerp(columns->OffMinX, columns->OffMaxX, t);
return x_offset;
}
static float GetColumnWidthEx(ImGuiColumns* columns, int column_index, bool before_resize = false)
{
if (column_index < 0)
column_index = columns->Current;
float offset_norm;
if (before_resize)
offset_norm = columns->Columns[column_index + 1].OffsetNormBeforeResize - columns->Columns[column_index].OffsetNormBeforeResize;
else
offset_norm = columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm;
return OffsetNormToPixels(columns, offset_norm);
}
float ImGui::GetColumnWidth(int column_index)
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiColumns* columns = window->DC.CurrentColumns;
IM_ASSERT(columns != NULL);
if (column_index < 0)
column_index = columns->Current;
return OffsetNormToPixels(columns, columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm);
}
void ImGui::SetColumnOffset(int column_index, float offset)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiColumns* columns = window->DC.CurrentColumns;
IM_ASSERT(columns != NULL);
if (column_index < 0)
column_index = columns->Current;
IM_ASSERT(column_index < columns->Columns.Size);
const bool preserve_width = !(columns->Flags & ImGuiColumnsFlags_NoPreserveWidths) && (column_index < columns->Count-1);
const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f;
if (!(columns->Flags & ImGuiColumnsFlags_NoForceWithinWindow))
offset = ImMin(offset, columns->OffMaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index));
columns->Columns[column_index].OffsetNorm = PixelsToOffsetNorm(columns, offset - columns->OffMinX);
if (preserve_width)
SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width));
}
void ImGui::SetColumnWidth(int column_index, float width)
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiColumns* columns = window->DC.CurrentColumns;
IM_ASSERT(columns != NULL);
if (column_index < 0)
column_index = columns->Current;
SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width);
}
void ImGui::PushColumnClipRect(int column_index)
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiColumns* columns = window->DC.CurrentColumns;
if (column_index < 0)
column_index = columns->Current;
ImGuiColumnData* column = &columns->Columns[column_index];
PushClipRect(column->ClipRect.Min, column->ClipRect.Max, false);
}
// Get into the columns background draw command (which is generally the same draw command as before we called BeginColumns)
void ImGui::PushColumnsBackground()
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiColumns* columns = window->DC.CurrentColumns;
window->DrawList->ChannelsSetCurrent(0);
int cmd_size = window->DrawList->CmdBuffer.Size;
PushClipRect(columns->HostClipRect.Min, columns->HostClipRect.Max, false);
IM_ASSERT(cmd_size == window->DrawList->CmdBuffer.Size); // Being in channel 0 this should not have created an ImDrawCmd
}
void ImGui::PopColumnsBackground()
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiColumns* columns = window->DC.CurrentColumns;
window->DrawList->ChannelsSetCurrent(columns->Current + 1);
PopClipRect();
}
ImGuiColumns* ImGui::FindOrCreateColumns(ImGuiWindow* window, ImGuiID id)
{
// We have few columns per window so for now we don't need bother much with turning this into a faster lookup.
for (int n = 0; n < window->ColumnsStorage.Size; n++)
if (window->ColumnsStorage[n].ID == id)
return &window->ColumnsStorage[n];
window->ColumnsStorage.push_back(ImGuiColumns());
ImGuiColumns* columns = &window->ColumnsStorage.back();
columns->ID = id;
return columns;
}
ImGuiID ImGui::GetColumnsID(const char* str_id, int columns_count)
{
ImGuiWindow* window = GetCurrentWindow();
// Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget.
// In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer.
PushID(0x11223347 + (str_id ? 0 : columns_count));
ImGuiID id = window->GetID(str_id ? str_id : "columns");
PopID();
return id;
}
void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(columns_count >= 1);
IM_ASSERT(window->DC.CurrentColumns == NULL); // Nested columns are currently not supported
// Acquire storage for the columns set
ImGuiID id = GetColumnsID(str_id, columns_count);
ImGuiColumns* columns = FindOrCreateColumns(window, id);
IM_ASSERT(columns->ID == id);
columns->Current = 0;
columns->Count = columns_count;
columns->Flags = flags;
window->DC.CurrentColumns = columns;
// Set state for first column
const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? (window->SizeContentsExplicit.x) : (window->InnerClipRect.Max.x - window->Pos.x);
columns->OffMinX = window->DC.Indent.x - g.Style.ItemSpacing.x; // Lock our horizontal range
columns->OffMaxX = ImMax(content_region_width - window->Scroll.x, columns->OffMinX + 1.0f);
columns->HostCursorPosY = window->DC.CursorPos.y;
columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x;
columns->HostClipRect = window->ClipRect;
columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y;
window->DC.ColumnsOffset.x = 0.0f;
window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
// Clear data if columns count changed
if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1)
columns->Columns.resize(0);
// Initialize default widths
columns->IsFirstFrame = (columns->Columns.Size == 0);
if (columns->Columns.Size == 0)
{
columns->Columns.reserve(columns_count + 1);
for (int n = 0; n < columns_count + 1; n++)
{
ImGuiColumnData column;
column.OffsetNorm = n / (float)columns_count;
columns->Columns.push_back(column);
}
}
for (int n = 0; n < columns_count; n++)
{
// Compute clipping rectangle
ImGuiColumnData* column = &columns->Columns[n];
float clip_x1 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n));
float clip_x2 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n + 1) - 1.0f);
column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX);
column->ClipRect.ClipWith(window->ClipRect);
}
if (columns->Count > 1)
{
window->DrawList->ChannelsSplit(1 + columns->Count);
window->DrawList->ChannelsSetCurrent(1);
PushColumnClipRect(0);
}
PushItemWidth(GetColumnWidth() * 0.65f);
}
void ImGui::EndColumns()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
ImGuiColumns* columns = window->DC.CurrentColumns;
IM_ASSERT(columns != NULL);
PopItemWidth();
if (columns->Count > 1)
{
PopClipRect();
window->DrawList->ChannelsMerge();
}
const ImGuiColumnsFlags flags = columns->Flags;
columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
window->DC.CursorPos.y = columns->LineMaxY;
if (!(flags & ImGuiColumnsFlags_GrowParentContentsSize))
window->DC.CursorMaxPos.x = columns->HostCursorMaxPosX; // Restore cursor max pos, as columns don't grow parent
// Draw columns borders and handle resize
// The IsBeingResized flag ensure we preserve pre-resize columns width so back-and-forth are not lossy
bool is_being_resized = false;
if (!(flags & ImGuiColumnsFlags_NoBorder) && !window->SkipItems)
{
// We clip Y boundaries CPU side because very long triangles are mishandled by some GPU drivers.
const float y1 = ImMax(columns->HostCursorPosY, window->ClipRect.Min.y);
const float y2 = ImMin(window->DC.CursorPos.y, window->ClipRect.Max.y);
int dragging_column = -1;
for (int n = 1; n < columns->Count; n++)
{
ImGuiColumnData* column = &columns->Columns[n];
float x = window->Pos.x + GetColumnOffset(n);
const ImGuiID column_id = columns->ID + ImGuiID(n);
const float column_hit_hw = COLUMNS_HIT_RECT_HALF_WIDTH;
const ImRect column_hit_rect(ImVec2(x - column_hit_hw, y1), ImVec2(x + column_hit_hw, y2));
KeepAliveID(column_id);
if (IsClippedEx(column_hit_rect, column_id, false))
continue;
bool hovered = false, held = false;
if (!(flags & ImGuiColumnsFlags_NoResize))
{
ButtonBehavior(column_hit_rect, column_id, &hovered, &held);
if (hovered || held)
g.MouseCursor = ImGuiMouseCursor_ResizeEW;
if (held && !(column->Flags & ImGuiColumnsFlags_NoResize))
dragging_column = n;
}
// Draw column
const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
const float xi = (float)(int)x;
window->DrawList->AddLine(ImVec2(xi, y1 + 1.0f), ImVec2(xi, y2), col);
}
// Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame.
if (dragging_column != -1)
{
if (!columns->IsBeingResized)
for (int n = 0; n < columns->Count + 1; n++)
columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm;
columns->IsBeingResized = is_being_resized = true;
float x = GetDraggedColumnOffset(columns, dragging_column);
SetColumnOffset(dragging_column, x);
}
}
columns->IsBeingResized = is_being_resized;
window->DC.CurrentColumns = NULL;
window->DC.ColumnsOffset.x = 0.0f;
window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
}
// [2018-03: This is currently the only public API, while we are working on making BeginColumns/EndColumns user-facing]
void ImGui::Columns(int columns_count, const char* id, bool border)
{
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(columns_count >= 1);
ImGuiColumnsFlags flags = (border ? 0 : ImGuiColumnsFlags_NoBorder);
//flags |= ImGuiColumnsFlags_NoPreserveWidths; // NB: Legacy behavior
ImGuiColumns* columns = window->DC.CurrentColumns;
if (columns != NULL && columns->Count == columns_count && columns->Flags == flags)
return;
if (columns != NULL)
EndColumns();
if (columns_count != 1)
BeginColumns(id, columns_count, flags);
}
//-----------------------------------------------------------------------------
// [SECTION] DRAG AND DROP
//-----------------------------------------------------------------------------
void ImGui::ClearDragDrop()
{
ImGuiContext& g = *GImGui;
g.DragDropActive = false;
g.DragDropPayload.Clear();
g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
g.DragDropAcceptFrameCount = -1;
g.DragDropPayloadBufHeap.clear();
memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
}
// Call when current ID is active.
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
bool source_drag_active = false;
ImGuiID source_id = 0;
ImGuiID source_parent_id = 0;
int mouse_button = 0;
if (!(flags & ImGuiDragDropFlags_SourceExtern))
{
source_id = window->DC.LastItemId;
if (source_id != 0 && g.ActiveId != source_id) // Early out for most common case
return false;
if (g.IO.MouseDown[mouse_button] == false)
return false;
if (source_id == 0)
{
// If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
// A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag, C) Swallow your programmer pride.
if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
{
IM_ASSERT(0);
return false;
}
// Early out
if ((window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
return false;
// Magic fallback (=somehow reprehensible) to handle items with no assigned ID, e.g. Text(), Image()
// We build a throwaway ID based on current ID stack + relative AABB of items in window.
// THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
// We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
source_id = window->DC.LastItemId = window->GetIDFromRectangle(window->DC.LastItemRect);
bool is_hovered = ItemHoverable(window->DC.LastItemRect, source_id);
if (is_hovered && g.IO.MouseClicked[mouse_button])
{
SetActiveID(source_id, window);
FocusWindow(window);
}
if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
g.ActiveIdAllowOverlap = is_hovered;
}
else
{
g.ActiveIdAllowOverlap = false;
}
if (g.ActiveId != source_id)
return false;
source_parent_id = window->IDStack.back();
source_drag_active = IsMouseDragging(mouse_button);
}
else
{
window = NULL;
source_id = ImHashStr("#SourceExtern");
source_drag_active = true;
}
if (source_drag_active)
{
if (!g.DragDropActive)
{
IM_ASSERT(source_id != 0);
ClearDragDrop();
ImGuiPayload& payload = g.DragDropPayload;
payload.SourceId = source_id;
payload.SourceParentId = source_parent_id;
g.DragDropActive = true;
g.DragDropSourceFlags = flags;
g.DragDropMouseButton = mouse_button;
}
g.DragDropSourceFrameCount = g.FrameCount;
g.DragDropWithinSourceOrTarget = true;
if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
{
// Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
// We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
BeginTooltip();
if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
{
ImGuiWindow* tooltip_window = g.CurrentWindow;
tooltip_window->SkipItems = true;
tooltip_window->HiddenFramesCanSkipItems = 1;
}
}
if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
window->DC.LastItemStatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
return true;
}
return false;
}
void ImGui::EndDragDropSource()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.DragDropActive);
IM_ASSERT(g.DragDropWithinSourceOrTarget && "Not after a BeginDragDropSource()?");
if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
EndTooltip();
// Discard the drag if have not called SetDragDropPayload()
if (g.DragDropPayload.DataFrameCount == -1)
ClearDragDrop();
g.DragDropWithinSourceOrTarget = false;
}
// Use 'cond' to choose to submit payload on drag start or every frame
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
ImGuiPayload& payload = g.DragDropPayload;
if (cond == 0)
cond = ImGuiCond_Always;
IM_ASSERT(type != NULL);
IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
{
// Copy payload
ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
g.DragDropPayloadBufHeap.resize(0);
if (data_size > sizeof(g.DragDropPayloadBufLocal))
{
// Store in heap
g.DragDropPayloadBufHeap.resize((int)data_size);
payload.Data = g.DragDropPayloadBufHeap.Data;
memcpy(payload.Data, data, data_size);
}
else if (data_size > 0)
{
// Store locally
memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
payload.Data = g.DragDropPayloadBufLocal;
memcpy(payload.Data, data, data_size);
}
else
{
payload.Data = NULL;
}
payload.DataSize = (int)data_size;
}
payload.DataFrameCount = g.FrameCount;
return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
}
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
{
ImGuiContext& g = *GImGui;
if (!g.DragDropActive)
return false;
ImGuiWindow* window = g.CurrentWindow;
if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow)
return false;
IM_ASSERT(id != 0);
if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
return false;
if (window->SkipItems)
return false;
IM_ASSERT(g.DragDropWithinSourceOrTarget == false);
g.DragDropTargetRect = bb;
g.DragDropTargetId = id;
g.DragDropWithinSourceOrTarget = true;
return true;
}
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
// 1) we use LastItemRectHoveredRect which handles items that pushes a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
bool ImGui::BeginDragDropTarget()
{
ImGuiContext& g = *GImGui;
if (!g.DragDropActive)
return false;
ImGuiWindow* window = g.CurrentWindow;
if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
return false;
if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow)
return false;
const ImRect& display_rect = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? window->DC.LastItemDisplayRect : window->DC.LastItemRect;
ImGuiID id = window->DC.LastItemId;
if (id == 0)
id = window->GetIDFromRectangle(display_rect);
if (g.DragDropPayload.SourceId == id)
return false;
IM_ASSERT(g.DragDropWithinSourceOrTarget == false);
g.DragDropTargetRect = display_rect;
g.DragDropTargetId = id;
g.DragDropWithinSourceOrTarget = true;
return true;
}
bool ImGui::IsDragDropPayloadBeingAccepted()
{
ImGuiContext& g = *GImGui;
return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
}
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiPayload& payload = g.DragDropPayload;
IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ?
if (type != NULL && !payload.IsDataType(type))
return NULL;
// Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
// NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
ImRect r = g.DragDropTargetRect;
float r_surface = r.GetWidth() * r.GetHeight();
if (r_surface < g.DragDropAcceptIdCurrRectSurface)
{
g.DragDropAcceptFlags = flags;
g.DragDropAcceptIdCurr = g.DragDropTargetId;
g.DragDropAcceptIdCurrRectSurface = r_surface;
}
// Render default drop visuals
payload.Preview = was_accepted_previously;
flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that lives for 1 frame)
if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
{
// FIXME-DRAG: Settle on a proper default visuals for drop target.
r.Expand(3.5f);
bool push_clip_rect = !window->ClipRect.Contains(r);
if (push_clip_rect) window->DrawList->PushClipRect(r.Min-ImVec2(1,1), r.Max+ImVec2(1,1));
window->DrawList->AddRect(r.Min, r.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, ~0, 2.0f);
if (push_clip_rect) window->DrawList->PopClipRect();
}
g.DragDropAcceptFrameCount = g.FrameCount;
payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting os window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
return NULL;
return &payload;
}
const ImGuiPayload* ImGui::GetDragDropPayload()
{
ImGuiContext& g = *GImGui;
return g.DragDropActive ? &g.DragDropPayload : NULL;
}
// We don't really use/need this now, but added it for the sake of consistency and because we might need it later.
void ImGui::EndDragDropTarget()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.DragDropActive);
IM_ASSERT(g.DragDropWithinSourceOrTarget);
g.DragDropWithinSourceOrTarget = false;
}
//-----------------------------------------------------------------------------
// [SECTION] LOGGING/CAPTURING
//-----------------------------------------------------------------------------
// All text output from the interface can be captured into tty/file/clipboard.
// By default, tree nodes are automatically opened during logging.
//-----------------------------------------------------------------------------
// Pass text data straight to log (without being displayed)
void ImGui::LogText(const char* fmt, ...)
{
ImGuiContext& g = *GImGui;
if (!g.LogEnabled)
return;
va_list args;
va_start(args, fmt);
if (g.LogFile)
vfprintf(g.LogFile, fmt, args);
else
g.LogBuffer.appendfv(fmt, args);
va_end(args);
}
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
// We split text into individual lines to add current tree level padding
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!text_end)
text_end = FindRenderedTextEnd(text, text_end);
const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + 1);
if (ref_pos)
g.LogLinePosY = ref_pos->y;
if (log_new_line)
g.LogLineFirstItem = true;
const char* text_remaining = text;
if (g.LogDepthRef > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth
g.LogDepthRef = window->DC.TreeDepth;
const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
for (;;)
{
// Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry.
// We don't add a trailing \n to allow a subsequent item on the same line to be captured.
const char* line_start = text_remaining;
const char* line_end = ImStreolRange(line_start, text_end);
const bool is_first_line = (line_start == text);
const bool is_last_line = (line_end == text_end);
if (!is_last_line || (line_start != line_end))
{
const int char_count = (int)(line_end - line_start);
if (log_new_line || !is_first_line)
LogText(IM_NEWLINE "%*s%.*s", tree_depth * 4, "", char_count, line_start);
else if (g.LogLineFirstItem)
LogText("%*s%.*s", tree_depth * 4, "", char_count, line_start);
else
LogText(" %.*s", char_count, line_start);
g.LogLineFirstItem = false;
}
else if (log_new_line)
{
// An empty "" string at a different Y position should output a carriage return.
LogText(IM_NEWLINE);
break;
}
if (is_last_line)
break;
text_remaining = line_end + 1;
}
}
// Start logging/capturing text output
void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(g.LogEnabled == false);
IM_ASSERT(g.LogFile == NULL);
IM_ASSERT(g.LogBuffer.empty());
g.LogEnabled = true;
g.LogType = type;
g.LogDepthRef = window->DC.TreeDepth;
g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
g.LogLinePosY = FLT_MAX;
g.LogLineFirstItem = true;
}
void ImGui::LogToTTY(int auto_open_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
LogBegin(ImGuiLogType_TTY, auto_open_depth);
g.LogFile = stdout;
}
// Start logging/capturing text output to given file
void ImGui::LogToFile(int auto_open_depth, const char* filename)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
// FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
// be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
// By opening the file in binary mode "ab" we have consistent output everywhere.
if (!filename)
filename = g.IO.LogFilename;
if (!filename || !filename[0])
return;
FILE* f = ImFileOpen(filename, "ab");
if (f == NULL)
{
IM_ASSERT(0);
return;
}
LogBegin(ImGuiLogType_File, auto_open_depth);
g.LogFile = f;
}
// Start logging/capturing text output to clipboard
void ImGui::LogToClipboard(int auto_open_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
}
void ImGui::LogToBuffer(int auto_open_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
LogBegin(ImGuiLogType_Buffer, auto_open_depth);
}
void ImGui::LogFinish()
{
ImGuiContext& g = *GImGui;
if (!g.LogEnabled)
return;
LogText(IM_NEWLINE);
switch (g.LogType)
{
case ImGuiLogType_TTY:
fflush(g.LogFile);
break;
case ImGuiLogType_File:
fclose(g.LogFile);
break;
case ImGuiLogType_Buffer:
break;
case ImGuiLogType_Clipboard:
if (!g.LogBuffer.empty())
SetClipboardText(g.LogBuffer.begin());
break;
case ImGuiLogType_None:
IM_ASSERT(0);
break;
}
g.LogEnabled = false;
g.LogType = ImGuiLogType_None;
g.LogFile = NULL;
g.LogBuffer.clear();
}
// Helper to display logging buttons
// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
void ImGui::LogButtons()
{
ImGuiContext& g = *GImGui;
PushID("LogButtons");
const bool log_to_tty = Button("Log To TTY"); SameLine();
const bool log_to_file = Button("Log To File"); SameLine();
const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
PushAllowKeyboardFocus(false);
SetNextItemWidth(80.0f);
SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
PopAllowKeyboardFocus();
PopID();
// Start logging at the end of the function so that the buttons don't appear in the log
if (log_to_tty)
LogToTTY();
if (log_to_file)
LogToFile();
if (log_to_clipboard)
LogToClipboard();
}
//-----------------------------------------------------------------------------
// [SECTION] SETTINGS
//-----------------------------------------------------------------------------
void ImGui::MarkIniSettingsDirty()
{
ImGuiContext& g = *GImGui;
if (g.SettingsDirtyTimer <= 0.0f)
g.SettingsDirtyTimer = g.IO.IniSavingRate;
}
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
if (g.SettingsDirtyTimer <= 0.0f)
g.SettingsDirtyTimer = g.IO.IniSavingRate;
}
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
{
ImGuiContext& g = *GImGui;
g.SettingsWindows.push_back(ImGuiWindowSettings());
ImGuiWindowSettings* settings = &g.SettingsWindows.back();
settings->Name = ImStrdup(name);
settings->ID = ImHashStr(name);
return settings;
}
ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id)
{
ImGuiContext& g = *GImGui;
for (int i = 0; i != g.SettingsWindows.Size; i++)
if (g.SettingsWindows[i].ID == id)
return &g.SettingsWindows[i];
return NULL;
}
ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name)
{
if (ImGuiWindowSettings* settings = FindWindowSettings(ImHashStr(name)))
return settings;
return CreateNewWindowSettings(name);
}
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
{
size_t file_data_size = 0;
char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
if (!file_data)
return;
LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
IM_FREE(file_data);
}
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
{
ImGuiContext& g = *GImGui;
const ImGuiID type_hash = ImHashStr(type_name);
for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
return &g.SettingsHandlers[handler_n];
return NULL;
}
// Zero-tolerance, no error reporting, cheap .ini parsing
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized);
IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
// For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
// For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
if (ini_size == 0)
ini_size = strlen(ini_data);
char* buf = (char*)IM_ALLOC(ini_size + 1);
char* buf_end = buf + ini_size;
memcpy(buf, ini_data, ini_size);
buf[ini_size] = 0;
void* entry_data = NULL;
ImGuiSettingsHandler* entry_handler = NULL;
char* line_end = NULL;
for (char* line = buf; line < buf_end; line = line_end + 1)
{
// Skip new lines markers, then find end of the line
while (*line == '\n' || *line == '\r')
line++;
line_end = line;
while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
line_end++;
line_end[0] = 0;
if (line[0] == ';')
continue;
if (line[0] == '[' && line_end > line && line_end[-1] == ']')
{
// Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
line_end[-1] = 0;
const char* name_end = line_end - 1;
const char* type_start = line + 1;
char* type_end = (char*)(intptr_t)ImStrchrRange(type_start, name_end, ']');
const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
if (!type_end || !name_start)
{
name_start = type_start; // Import legacy entries that have no type
type_start = "Window";
}
else
{
*type_end = 0; // Overwrite first ']'
name_start++; // Skip second '['
}
entry_handler = FindSettingsHandler(type_start);
entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
}
else if (entry_handler != NULL && entry_data != NULL)
{
// Let type handler parse the line
entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
}
}
IM_FREE(buf);
g.SettingsLoaded = true;
}
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
{
ImGuiContext& g = *GImGui;
g.SettingsDirtyTimer = 0.0f;
if (!ini_filename)
return;
size_t ini_data_size = 0;
const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
FILE* f = ImFileOpen(ini_filename, "wt");
if (!f)
return;
fwrite(ini_data, sizeof(char), ini_data_size, f);
fclose(f);
}
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
{
ImGuiContext& g = *GImGui;
g.SettingsDirtyTimer = 0.0f;
g.SettingsIniData.Buf.resize(0);
g.SettingsIniData.Buf.push_back(0);
for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
{
ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
handler->WriteAllFn(&g, handler, &g.SettingsIniData);
}
if (out_size)
*out_size = (size_t)g.SettingsIniData.size();
return g.SettingsIniData.c_str();
}
static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
{
ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHashStr(name));
if (!settings)
settings = ImGui::CreateNewWindowSettings(name);
return (void*)settings;
}
static void SettingsHandlerWindow_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void* entry, const char* line)
{
ImGuiContext& g = *ctx;
ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
float x, y;
int i;
if (sscanf(line, "Pos=%f,%f", &x, &y) == 2) settings->Pos = ImVec2(x, y);
else if (sscanf(line, "Size=%f,%f", &x, &y) == 2) settings->Size = ImMax(ImVec2(x, y), g.Style.WindowMinSize);
else if (sscanf(line, "Collapsed=%d", &i) == 1) settings->Collapsed = (i != 0);
}
static void SettingsHandlerWindow_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
{
// Gather data from windows that were active during this session
// (if a window wasn't opened in this session we preserve its settings)
ImGuiContext& g = *ctx;
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
continue;
ImGuiWindowSettings* settings = (window->SettingsIdx != -1) ? &g.SettingsWindows[window->SettingsIdx] : ImGui::FindWindowSettings(window->ID);
if (!settings)
{
settings = ImGui::CreateNewWindowSettings(window->Name);
window->SettingsIdx = g.SettingsWindows.index_from_ptr(settings);
}
IM_ASSERT(settings->ID == window->ID);
settings->Pos = window->Pos;
settings->Size = window->SizeFull;
settings->Collapsed = window->Collapsed;
}
// Write to text buffer
buf->reserve(buf->size() + g.SettingsWindows.Size * 96); // ballpark reserve
for (int i = 0; i != g.SettingsWindows.Size; i++)
{
const ImGuiWindowSettings* settings = &g.SettingsWindows[i];
if (settings->Pos.x == FLT_MAX)
continue;
const char* name = settings->Name;
if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
name = p;
buf->appendf("[%s][%s]\n", handler->TypeName, name);
buf->appendf("Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y);
buf->appendf("Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y);
buf->appendf("Collapsed=%d\n", settings->Collapsed);
buf->appendf("\n");
}
}
//-----------------------------------------------------------------------------
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
//-----------------------------------------------------------------------------
// (this section is filled in the 'docking' branch)
//-----------------------------------------------------------------------------
// [SECTION] DOCKING
//-----------------------------------------------------------------------------
// (this section is filled in the 'docking' branch)
//-----------------------------------------------------------------------------
// [SECTION] PLATFORM DEPENDENT HELPERS
//-----------------------------------------------------------------------------
#if defined(_WIN32) && !defined(_WINDOWS_) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS))
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef __MINGW32__
#include <Windows.h>
#else
#include <windows.h>
#endif
#endif
// Win32 API clipboard implementation
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
#ifdef _MSC_VER
#pragma comment(lib, "user32")
#endif
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
static ImVector<char> buf_local;
buf_local.clear();
if (!::OpenClipboard(NULL))
return NULL;
HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
if (wbuf_handle == NULL)
{
::CloseClipboard();
return NULL;
}
if (ImWchar* wbuf_global = (ImWchar*)::GlobalLock(wbuf_handle))
{
int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1;
buf_local.resize(buf_len);
ImTextStrToUtf8(buf_local.Data, buf_len, wbuf_global, NULL);
}
::GlobalUnlock(wbuf_handle);
::CloseClipboard();
return buf_local.Data;
}
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
{
if (!::OpenClipboard(NULL))
return;
const int wbuf_length = ImTextCountCharsFromUtf8(text, NULL) + 1;
HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar));
if (wbuf_handle == NULL)
{
::CloseClipboard();
return;
}
ImWchar* wbuf_global = (ImWchar*)::GlobalLock(wbuf_handle);
ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL);
::GlobalUnlock(wbuf_handle);
::EmptyClipboard();
if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
::GlobalFree(wbuf_handle);
::CloseClipboard();
}
#else
// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
ImGuiContext& g = *GImGui;
return g.PrivateClipboard.empty() ? NULL : g.PrivateClipboard.begin();
}
// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
{
ImGuiContext& g = *GImGui;
g.PrivateClipboard.clear();
const char* text_end = text + strlen(text);
g.PrivateClipboard.resize((int)(text_end - text) + 1);
memcpy(&g.PrivateClipboard[0], text, (size_t)(text_end - text));
g.PrivateClipboard[(int)(text_end - text)] = 0;
}
#endif
// Win32 API IME support (for Asian languages, etc.)
#if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
#include <imm.h>
#ifdef _MSC_VER
#pragma comment(lib, "imm32")
#endif
static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y)
{
// Notify OS Input Method Editor of text input position
if (HWND hwnd = (HWND)GImGui->IO.ImeWindowHandle)
if (HIMC himc = ::ImmGetContext(hwnd))
{
COMPOSITIONFORM cf;
cf.ptCurrentPos.x = x;
cf.ptCurrentPos.y = y;
cf.dwStyle = CFS_FORCE_POSITION;
::ImmSetCompositionWindow(himc, &cf);
::ImmReleaseContext(hwnd, himc);
}
}
#else
static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {}
#endif
//-----------------------------------------------------------------------------
// [SECTION] METRICS/DEBUG WINDOW
//-----------------------------------------------------------------------------
void ImGui::ShowMetricsWindow(bool* p_open)
{
if (!ImGui::Begin("ImGui Metrics", p_open))
{
ImGui::End();
return;
}
enum { RT_OuterRect, RT_OuterRectClipped, RT_InnerMainRect, RT_InnerClipRect, RT_ContentsRegionRect, RT_ContentsFullRect };
static bool show_windows_begin_order = false;
static bool show_windows_rects = false;
static int show_windows_rect_type = RT_ContentsRegionRect;
static bool show_drawcmd_clip_rects = true;
ImGuiIO& io = ImGui::GetIO();
ImGui::Text("Dear ImGui %s", ImGui::GetVersion());
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
ImGui::Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
ImGui::Text("%d active windows (%d visible)", io.MetricsActiveWindows, io.MetricsRenderWindows);
ImGui::Text("%d active allocations", io.MetricsActiveAllocations);
ImGui::Separator();
struct Funcs
{
static void NodeDrawList(ImGuiWindow* window, ImDrawList* draw_list, const char* label)
{
bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size);
if (draw_list == ImGui::GetWindowDrawList())
{
ImGui::SameLine();
ImGui::TextColored(ImVec4(1.0f,0.4f,0.4f,1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
if (node_open) ImGui::TreePop();
return;
}
ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list
if (window && IsItemHovered())
fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
if (!node_open)
return;
int elem_offset = 0;
for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++)
{
if (pcmd->UserCallback == NULL && pcmd->ElemCount == 0)
continue;
if (pcmd->UserCallback)
{
ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
continue;
}
ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()),
"Draw %4d %s vtx, tex 0x%p, clip_rect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
pcmd->ElemCount, draw_list->IdxBuffer.Size > 0 ? "indexed" : "non-indexed", (void*)(intptr_t)pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
if (show_drawcmd_clip_rects && fg_draw_list && ImGui::IsItemHovered())
{
ImRect clip_rect = pcmd->ClipRect;
ImRect vtxs_rect;
for (int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++)
vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos);
clip_rect.Floor(); fg_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255,255,0,255));
vtxs_rect.Floor(); fg_draw_list->AddRect(vtxs_rect.Min, vtxs_rect.Max, IM_COL32(255,0,255,255));
}
if (!pcmd_node_open)
continue;
// Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
while (clipper.Step())
for (int prim = clipper.DisplayStart, idx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++)
{
char buf[300];
char *buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf);
ImVec2 triangles_pos[3];
for (int n = 0; n < 3; n++, idx_i++)
{
int vtx_i = idx_buffer ? idx_buffer[idx_i] : idx_i;
ImDrawVert& v = draw_list->VtxBuffer[vtx_i];
triangles_pos[n] = v.pos;
buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
(n == 0) ? "idx" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
}
ImGui::Selectable(buf, false);
if (fg_draw_list && ImGui::IsItemHovered())
{
ImDrawListFlags backup_flags = fg_draw_list->Flags;
fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines at is more readable for very large and thin triangles.
fg_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f);
fg_draw_list->Flags = backup_flags;
}
}
ImGui::TreePop();
}
ImGui::TreePop();
}
static void NodeColumns(const ImGuiColumns* columns)
{
if (!ImGui::TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
return;
ImGui::BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
ImGui::BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, OffsetNormToPixels(columns, columns->Columns[column_n].OffsetNorm));
ImGui::TreePop();
}
static void NodeWindows(ImVector<ImGuiWindow*>& windows, const char* label)
{
if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size))
return;
for (int i = 0; i < windows.Size; i++)
Funcs::NodeWindow(windows[i], "Window");
ImGui::TreePop();
}
static void NodeWindow(ImGuiWindow* window, const char* label)
{
if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window))
return;
ImGuiWindowFlags flags = window->Flags;
NodeDrawList(window, window->DrawList, "DrawList");
ImGui::BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), SizeContents (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->SizeContents.x, window->SizeContents.y);
ImGui::BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
(flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
(flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
(flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
ImGui::BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f)", window->Scroll.x, GetWindowScrollMaxX(window), window->Scroll.y, GetWindowScrollMaxY(window));
ImGui::BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
ImGui::BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
ImGui::BulletText("NavLastIds: 0x%08X,0x%08X, NavLayerActiveMask: %X", window->NavLastIds[0], window->NavLastIds[1], window->DC.NavLayerActiveMask);
ImGui::BulletText("NavLastChildNavWindow: %s", window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
if (!window->NavRectRel[0].IsInverted())
ImGui::BulletText("NavRectRel[0]: (%.1f,%.1f)(%.1f,%.1f)", window->NavRectRel[0].Min.x, window->NavRectRel[0].Min.y, window->NavRectRel[0].Max.x, window->NavRectRel[0].Max.y);
else
ImGui::BulletText("NavRectRel[0]: <None>");
if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow");
if (window->ParentWindow != NULL) NodeWindow(window->ParentWindow, "ParentWindow");
if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows");
if (window->ColumnsStorage.Size > 0 && ImGui::TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
{
for (int n = 0; n < window->ColumnsStorage.Size; n++)
NodeColumns(&window->ColumnsStorage[n]);
ImGui::TreePop();
}
ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.Size * (int)sizeof(ImGuiStorage::Pair));
ImGui::TreePop();
}
static void NodeTabBar(ImGuiTabBar* tab_bar)
{
// Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
char buf[256];
char* p = buf;
const char* buf_end = buf + IM_ARRAYSIZE(buf);
ImFormatString(p, buf_end - p, "TabBar (%d tabs)%s", tab_bar->Tabs.Size, (tab_bar->PrevFrameVisible < ImGui::GetFrameCount() - 2) ? " *Inactive*" : "");
if (ImGui::TreeNode(tab_bar, "%s", buf))
{
for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
{
const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
ImGui::PushID(tab);
if (ImGui::SmallButton("<")) { TabBarQueueChangeTabOrder(tab_bar, tab, -1); } ImGui::SameLine(0, 2);
if (ImGui::SmallButton(">")) { TabBarQueueChangeTabOrder(tab_bar, tab, +1); } ImGui::SameLine();
ImGui::Text("%02d%c Tab 0x%08X", tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID);
ImGui::PopID();
}
ImGui::TreePop();
}
}
};
// Access private state, we are going to display the draw lists from last frame
ImGuiContext& g = *GImGui;
Funcs::NodeWindows(g.Windows, "Windows");
if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.DrawDataBuilder.Layers[0].Size))
{
for (int i = 0; i < g.DrawDataBuilder.Layers[0].Size; i++)
Funcs::NodeDrawList(NULL, g.DrawDataBuilder.Layers[0][i], "DrawList");
ImGui::TreePop();
}
if (ImGui::TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
{
for (int i = 0; i < g.OpenPopupStack.Size; i++)
{
ImGuiWindow* window = g.OpenPopupStack[i].Window;
ImGui::BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : "");
}
ImGui::TreePop();
}
if (ImGui::TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.Data.Size))
{
for (int n = 0; n < g.TabBars.Data.Size; n++)
Funcs::NodeTabBar(g.TabBars.GetByIndex(n));
ImGui::TreePop();
}
if (ImGui::TreeNode("Internal state"))
{
const char* input_source_names[] = { "None", "Mouse", "Nav", "NavKeyboard", "NavGamepad" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT);
ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL");
ImGui::Text("HoveredId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not
ImGui::Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, input_source_names[g.ActiveIdSource]);
ImGui::Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
ImGui::Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
ImGui::Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
ImGui::Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
ImGui::Text("NavInputSource: %s", input_source_names[g.NavInputSource]);
ImGui::Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
ImGui::Text("NavActivateId: 0x%08X, NavInputId: 0x%08X", g.NavActivateId, g.NavInputId);
ImGui::Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
ImGui::Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
ImGui::Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
ImGui::TreePop();
}
if (ImGui::TreeNode("Tools"))
{
ImGui::Checkbox("Show windows begin order", &show_windows_begin_order);
ImGui::Checkbox("Show windows rectangles", &show_windows_rects);
ImGui::SameLine();
ImGui::SetNextItemWidth(ImGui::GetFontSize() * 12);
show_windows_rects |= ImGui::Combo("##rects_type", &show_windows_rect_type, "OuterRect\0" "OuterRectClipped\0" "InnerMainRect\0" "InnerClipRect\0" "ContentsRegionRect\0");
ImGui::Checkbox("Show clipping rectangle when hovering ImDrawCmd node", &show_drawcmd_clip_rects);
ImGui::TreePop();
}
if (show_windows_rects || show_windows_begin_order)
{
for (int n = 0; n < g.Windows.Size; n++)
{
ImGuiWindow* window = g.Windows[n];
if (!window->WasActive)
continue;
ImDrawList* draw_list = GetForegroundDrawList(window);
if (show_windows_rects)
{
ImRect r;
if (show_windows_rect_type == RT_OuterRect) { r = window->Rect(); }
else if (show_windows_rect_type == RT_OuterRectClipped) { r = window->OuterRectClipped; }
else if (show_windows_rect_type == RT_InnerMainRect) { r = window->InnerMainRect; }
else if (show_windows_rect_type == RT_InnerClipRect) { r = window->InnerClipRect; }
else if (show_windows_rect_type == RT_ContentsRegionRect) { r = window->ContentsRegionRect; }
draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
}
if (show_windows_begin_order && !(window->Flags & ImGuiWindowFlags_ChildWindow))
{
char buf[32];
ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
float font_size = ImGui::GetFontSize();
draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
}
}
}
ImGui::End();
}
//-----------------------------------------------------------------------------
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
#include "imgui_user.inl"
#endif
//-----------------------------------------------------------------------------<|fim▁end|> | return false; |
<|file_name|>ladder-dialog.component.spec.ts<|end_file_name|><|fim▁begin|>import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {LadderDialogComponent} from './ladder-dialog.component';
describe('LadderDialogComponent', () => {
let component: LadderDialogComponent;<|fim▁hole|> let fixture: ComponentFixture<LadderDialogComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [LadderDialogComponent]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LadderDialogComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});<|fim▁end|> | |
<|file_name|>package-info.java<|end_file_name|><|fim▁begin|>/**
* Tests of our statistical diagram computing attributes.
*/
<|fim▁hole|><|fim▁end|> | package test.junit.org.optimizationBenchmarking.evaluator.attributes.functions.aggregation2D; |
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate lib;
use std::task;
static mut statik: int = 0;
struct A;
impl Drop for A {
fn drop(&mut self) {
unsafe { statik = 1; }
}
}
fn main() {
task::try(proc() {
let _a = A;
lib::callback(|| fail!());
1i
});
unsafe {
assert!(lib::statik == 1);<|fim▁hole|><|fim▁end|> | assert!(statik == 1);
}
} |
<|file_name|>test_ceilometer_alarm.py<|end_file_name|><|fim▁begin|># Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_log import log as logging
from heat_integrationtests.common import test
LOG = logging.getLogger(__name__)
class CeilometerAlarmTest(test.HeatIntegrationTest):
"""Class is responsible for testing of ceilometer usage."""
def setUp(self):
super(CeilometerAlarmTest, self).setUp()
self.client = self.orchestration_client
self.template = self._load_template(__file__,
'test_ceilometer_alarm.yaml',
'templates')<|fim▁hole|> actual = self._stack_output(stack, 'asg_size')
if actual != expected:
LOG.warn('check_instance_count exp:%d, act:%s' % (expected,
actual))
return actual == expected
def test_alarm(self):
"""Confirm we can create an alarm and trigger it."""
# 1. create the stack
stack_identifier = self.stack_create(template=self.template)
# 2. send ceilometer a metric (should cause the alarm to fire)
sample = {}
sample['counter_type'] = 'gauge'
sample['counter_name'] = 'test_meter'
sample['counter_volume'] = 1
sample['counter_unit'] = 'count'
sample['resource_metadata'] = {'metering.stack_id':
stack_identifier.split('/')[-1]}
sample['resource_id'] = 'shouldnt_matter'
self.metering_client.samples.create(**sample)
# 3. confirm we get a scaleup.
# Note: there is little point waiting more than 60s+time to scale up.
self.assertTrue(test.call_until_true(
120, 2, self.check_instance_count, stack_identifier, 2))<|fim▁end|> |
def check_instance_count(self, stack_identifier, expected):
stack = self.client.stacks.get(stack_identifier) |
<|file_name|>svmClassifier.cpp<|end_file_name|><|fim▁begin|><|fim▁hole|>#include "svmClassifier.hpp"<|fim▁end|> | |
<|file_name|>api_test.go<|end_file_name|><|fim▁begin|>// Copyright 2016 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum 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 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum 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 the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package api
import (
"fmt"
"io"
"io/ioutil"
"os"
"testing"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/swarm/storage"
)
func testApi(t *testing.T, f func(*Api)) {
datadir, err := ioutil.TempDir("", "bzz-test")
if err != nil {
t.Fatalf("unable to create temp dir: %v", err)
}
os.RemoveAll(datadir)
defer os.RemoveAll(datadir)
dpa, err := storage.NewLocalDPA(datadir)
if err != nil {
return
}
api := NewApi(dpa, nil)
dpa.Start()
f(api)
dpa.Stop()
}
type testResponse struct {
reader storage.LazySectionReader
*Response
}
func checkResponse(t *testing.T, resp *testResponse, exp *Response) {
if resp.MimeType != exp.MimeType {
t.Errorf("incorrect mimeType. expected '%s', got '%s'", exp.MimeType, resp.MimeType)
}
if resp.Status != exp.Status {
t.Errorf("incorrect status. expected '%d', got '%d'", exp.Status, resp.Status)
}
if resp.Size != exp.Size {
t.Errorf("incorrect size. expected '%d', got '%d'", exp.Size, resp.Size)
}
if resp.reader != nil {
content := make([]byte, resp.Size)
read, _ := resp.reader.Read(content)
if int64(read) != exp.Size {
t.Errorf("incorrect content length. expected '%d...', got '%d...'", read, exp.Size)<|fim▁hole|> }
resp.Content = string(content)
}
if resp.Content != exp.Content {
// if !bytes.Equal(resp.Content, exp.Content)
t.Errorf("incorrect content. expected '%s...', got '%s...'", string(exp.Content), string(resp.Content))
}
}
// func expResponse(content []byte, mimeType string, status int) *Response {
func expResponse(content string, mimeType string, status int) *Response {
log.Trace(fmt.Sprintf("expected content (%v): %v ", len(content), content))
return &Response{mimeType, status, int64(len(content)), content}
}
// func testGet(t *testing.T, api *Api, bzzhash string) *testResponse {
func testGet(t *testing.T, api *Api, bzzhash string) *testResponse {
reader, mimeType, status, err := api.Get(bzzhash, true)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
quitC := make(chan bool)
size, err := reader.Size(quitC)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
log.Trace(fmt.Sprintf("reader size: %v ", size))
s := make([]byte, size)
_, err = reader.Read(s)
if err != io.EOF {
t.Fatalf("unexpected error: %v", err)
}
reader.Seek(0, 0)
return &testResponse{reader, &Response{mimeType, status, size, string(s)}}
// return &testResponse{reader, &Response{mimeType, status, reader.Size(), nil}}
}
func TestApiPut(t *testing.T) {
testApi(t, func(api *Api) {
content := "hello"
exp := expResponse(content, "text/plain", 0)
// exp := expResponse([]byte(content), "text/plain", 0)
bzzhash, err := api.Put(content, exp.MimeType)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
resp := testGet(t, api, bzzhash)
checkResponse(t, resp, exp)
})
}<|fim▁end|> | |
<|file_name|>maintree.py<|end_file_name|><|fim▁begin|>from flask import request, jsonify
from sql_classes import UrlList, Acl, UserGroup, User, Role
def _node_base_and_rest(path):
"""
Returns a tuple: (the substring of a path after the last nodeSeparator, the preceding path before it)
If 'base' includes its own baseSeparator - return only a string after it
So if a path is 'OU=Group,OU=Dept,OU=Company', the tuple result would be ('OU=Group,OU=Dept', 'Company')
"""
node_separator = ','
base_separator = '='
node_base = path[path.rfind(node_separator) + 1:]
if path.find(node_separator) != -1:
node_preceding = path[:len(path) - len(node_base) - 1]
else:
node_preceding = ''
return (node_preceding, node_base[node_base.find(base_separator) + 1:])
def _place_user_onto_tree(user, usertree, user_groups):
"""
Places a 'user' object on a 'usertree' object according to user's pathField string key
"""
curr_node = usertree
# Decompose 'OU=Group,OU=Dept,OU=Company' into ('OU=Group,OU=Dept', 'Company')
preceding, base = _node_base_and_rest(user['distinguishedName'])
full_node_path = ''
# Place all path groups onto a tree starting from the outermost
while base != '':
node_found = False
full_node_path = 'OU=' + base + (',' if full_node_path != '' else '') + full_node_path
# Search for corresponding base element on current hierarchy level
for obj in curr_node:
if obj.get('text') == None:
continue
if obj['text'] == base:
node_found = True
curr_node = obj['children']
break
# Create a new group node
if not node_found:
curr_node.append({
'id': 'usergroup_' + str(user_groups[full_node_path]),
'text': base,
'objectType': 'UserGroup',
'children': []
})
curr_node = curr_node[len(curr_node) - 1]['children']
preceding, base = _node_base_and_rest(preceding)
curr_node.append({
'id': 'user_' + str(user['id']),
'text': user['cn'],
'leaf': True,
'iconCls': 'x-fa fa-user' if user['status'] == 1 else 'x-fa fa-user-times',
'objectType': 'User'
})
def _sort_tree(subtree, sort_field):
"""
Sorts a subtree node by a sortField key of each element
"""
# Sort eval function, first by group property, then by text
subtree['children'] = sorted(
subtree['children'],
key=lambda obj: (1 if obj.get('children') == None else 0, obj[sort_field]))
for tree_elem in subtree['children']:
if tree_elem.get('children') != None:
_sort_tree(tree_elem, sort_field)
def _collapse_terminal_nodes(subtree):
"""
Collapses tree nodes which doesn't contain subgroups, just tree leaves
"""
subtree_has_group_nodes = False
for tree_elem in subtree['children']:
if tree_elem.get('children') != None:
subtree_has_group_nodes = True
_collapse_terminal_nodes(tree_elem)
subtree['expanded'] = subtree_has_group_nodes
def _expand_all_nodes(subtree):
"""
Expand all level nodes
"""
for tree_elem in subtree['children']:
if tree_elem.get('children') != None:
_expand_all_nodes(tree_elem)
subtree['expanded'] = True
def _get_user_tree(current_user_properties, Session):
"""
Build user tree
"""
current_user_permissions = current_user_properties['user_permissions']
session = Session()
# Get all groups
query_result = session.query(UserGroup.id, UserGroup.distinguishedName).all()
user_groups = {}
for query_result_row in query_result:
user_groups[query_result_row.distinguishedName] = query_result_row.id
# Get all users if ViewUsers permission present
if next((item for item in current_user_permissions if item['permissionName'] == 'ViewUsers'), None) != None:
query_result = session.query(
User.id.label('user_id'), User.cn, User.status, UserGroup.id.label('usergroup_id'),
UserGroup.distinguishedName).join(UserGroup).filter(User.hidden == 0).all()
# Get just the requester otherwise
else:
query_result = session.query(
User.id.label('user_id'), User.cn, User.status, UserGroup.id.label('usergroup_id'),
UserGroup.distinguishedName).join(UserGroup).\
filter(User.id == current_user_properties['user_object']['id'], User.hidden == 0).all()
Session.remove()
# Future tree
user_tree = []
# Place each user on a tree
for query_result_row in query_result:
user_object = {
'id': query_result_row.user_id,
'distinguishedName': query_result_row.distinguishedName,
'status': query_result_row.status,
'cn': query_result_row.cn
}
_place_user_onto_tree(user_object, user_tree, user_groups)
user_tree = {
'id': 'usergroup_0',
'objectType': 'UserGroup',
'text': 'Пользователи',
'children': user_tree
}
# Sort tree elements
_sort_tree(user_tree, 'text')
# Collapse/expand tree nodes
if next((item for item in current_user_permissions if item['permissionName'] == 'ViewUsers'), None) != None:
_collapse_terminal_nodes(user_tree)
else:
_expand_all_nodes(user_tree)
return user_tree
def _get_url_lists(Session):
"""
Get URL lists
"""
session = Session()
# Get all urllists from DB
query_result = session.query(UrlList.id, UrlList.name, UrlList.whitelist).all()
Session.remove()
urllist_list = []
# Making a list of them
for query_result_row in query_result:
url_list_object = {
'id': 'urllist_' + str(query_result_row.id),
'text': query_result_row.name,
'leaf': True,
'iconCls': 'x-fa fa-unlock' if query_result_row.whitelist else 'x-fa fa-lock',
'objectType': 'UrlList'
}
urllist_list.append(url_list_object)
url_lists = {
'id': 'urllists',
'objectType': 'UrlLists',
'text': 'Списки URL',
'iconCls': 'x-fa fa-cog',
'children': urllist_list
}
# Sort tree elements
_sort_tree(url_lists, 'text')
return url_lists
def _get_acls(Session):
"""
Get ACLs
"""
session = Session()
# Get all access control lists from DB
query_result = session.query(Acl.id, Acl.name).all()
Session.remove()
acl_list = []
# Making a list of them
for query_result_row in query_result:
acl_object = {
'id': 'acl_' + str(query_result_row.id),
'text': query_result_row.name,
'leaf': True,
'iconCls': 'x-fa fa-filter',
'objectType': 'AclContents'
}
acl_list.append(acl_object)
acls = {
'id': 'acls',
'objectType': 'Acls',
'text': 'Списки доступа',
'iconCls': 'x-fa fa-cog',
'children': acl_list
}
# Sort tree elements
_sort_tree(acls, 'text')
return acls
def _get_roles(Session):
"""
Get user roles
"""
session = Session()
# Get all roles from DB
query_result = session.query(Role.id, Role.name).all()
Session.remove()
roles_list = []
# Making a list of them
for query_result_row in query_result:
role_object = {
'id': 'role_' + str(query_result_row.id),
'text': query_result_row.name,
'leaf': True,
'iconCls': 'x-fa fa-key',
'objectType': 'Role'
}
roles_list.append(role_object)
roles = {
'id': 'roles',
'objectType': 'Roles',
'text': 'Роли',
'iconCls': 'x-fa fa-cog',
'children': roles_list
}
# Sorting tree elements
_sort_tree(roles, 'text')
return roles
def select_tree(current_user_properties, node_name, Session):
url_lists_node = None
acls_node = None
roles_node = None
users_node = None
current_user_permissions = current_user_properties['user_permissions']
if next((item for item in current_user_permissions if item['permissionName'] == 'ViewSettings'), None) != None:
if node_name in ['root', 'urllists']:
url_lists_node = _get_url_lists(Session)
if node_name in ['root', 'acls']:
acls_node = _get_acls(Session)
if next((item for item in current_user_permissions if item['permissionName'] == 'ViewPermissions'), None) != None:
if node_name in ['root', 'roles']:
roles_node = _get_roles(Session)
if node_name in ['root']:
users_node = _get_user_tree(current_user_properties, Session)
if node_name == 'root':
children_list = []
if url_lists_node is not None:
children_list.append(url_lists_node)
if acls_node is not None:
children_list.append(acls_node)
if roles_node is not None:
children_list.append(roles_node)
if users_node is not None:
children_list.append(users_node)
result = {
'success': True,
'children': children_list
}
elif node_name == 'urllists':
if next((item for item in current_user_permissions if item['permissionName'] == 'ViewSettings'), None) != None:
result = {
'success': True,
'children': url_lists_node['children']
}
else:
return Response('Forbidden', 403)
elif node_name == 'acls':
if next((item for item in current_user_permissions if item['permissionName'] == 'ViewSettings'), None) != None:
result = {
'success': True,
'children': acls_node['children']
}
else:
return Response('Forbidden', 403)
elif node_name == 'roles':
if next((item for item in current_user_permissions if item['permissionName'] == 'ViewPermissions'), None) != None:
result = {
'success': True,
'children': roles_node['children']
}
else:
return Response('Forbidden', 403)
<|fim▁hole|> return jsonify(result)<|fim▁end|> | |
<|file_name|>queuelib.py<|end_file_name|><|fim▁begin|>import os
import sqlite3
from time import sleep
from threading import get_ident
class FifoMemoryQueue(object):
def __init__(self):
self._db = []
def push(self, item):
if not isinstance(item, bytes):
raise TypeError('Unsupported type: {}'.format(type(item).__name__))
self._db.append(item)
def pop(self):
self._db.pop()
def pull(self, batch_size=10):
return self._db[:batch_size]
def close(self):
self._db = []
def __len__(self):
return len(self._db)
class FifoDiskQueue(object):
_create = (
'CREATE TABLE IF NOT EXISTS fifoqueue '
'('
' id INTEGER PRIMARY KEY AUTOINCREMENT,'
' item BLOB'
')'
)
_size = 'SELECT COUNT(*) FROM fifoqueue'
_iterate = 'SELECT id, item FROM queue'
_push = 'INSERT INTO fifoqueue (item) VALUES (?)'
_write_lock = 'BEGIN IMMEDIATE'
_pull = 'SELECT id, item FROM fifoqueue ORDER BY id LIMIT 1'
_del = 'DELETE FROM fifoqueue WHERE id = ?'
_peek = (
'SELECT item FROM queue '
'ORDER BY id LIMIT 1'
)<|fim▁hole|> self.path = os.path.abspath(path)
self._connection_cache = {}
with self._get_conn() as conn:
conn.execute(self._create)
def __len__(self):
with self._get_conn() as conn:
l = next(conn.execute(self._size))[0]
return l
def __iter__(self):
with self._get_conn() as conn:
for id, obj_buffer in conn.execute(self._iterate):
yield loads(str(obj_buffer))
def _get_conn(self):
id = get_ident()
if id not in self._connection_cache:
self._connection_cache[id] = sqlite3.Connection(self.path,
timeout=60)
self._connection_cache[id].text_factory = bytes
return self._connection_cache[id]
def push(self, obj):
if not isinstance(obj, bytes):
obj_buffer = bytes(obj, 'ascii')
else:
obj_buffer = obj
with self._get_conn() as conn:
conn.execute(self._push, (obj_buffer,))
def pull(self, sleep_wait=True):
keep_pooling = True
wait = 0.1
max_wait = 2
tries = 0
with self._get_conn() as conn:
while keep_pooling:
conn.execute(self._write_lock)
cursor = conn.execute(self._pull)
try:
id, obj_buffer = next(cursor)
yield obj_buffer
conn.execute(self._del, (id,))
keep_pooling = False
except StopIteration:
conn.commit() # unlock the database
if not sleep_wait:
keep_pooling = False
continue
tries += 1
sleep(wait)
wait = min(max_wait, tries/10 + wait)
def peek(self):
with self._get_conn() as conn:
cursor = conn.execute(self._peek)
try:
return loads(str(cursor.next()[0]))
except StopIteration:
return None
def close(self):
for k in self._connection_cache.keys():
self._connection_cache[k].close()
self._connection_cache = {}
class LifoDiskQueue(FifoDiskQueue):
_create = (
'CREATE TABLE IF NOT EXISTS lifoqueue '
'(id INTEGER PRIMARY KEY AUTOINCREMENT, item BLOB)'
)
_pop = 'SELECT id, item FROM lifoqueue ORDER BY id DESC LIMIT 1'
_size = 'SELECT COUNT(*) FROM lifoqueue'
_push = 'INSERT INTO lifoqueue (item) VALUES (?)'
_del = 'DELETE FROM lifoqueue WHERE id = ?'<|fim▁end|> |
def __init__(self, path): |
<|file_name|>normalize_projection_ty.rs<|end_file_name|><|fim▁begin|>use rustc_infer::infer::canonical::{Canonical, QueryResponse};
use rustc_infer::infer::TyCtxtInferExt;
use rustc_infer::traits::TraitEngineExt as _;
use rustc_middle::ty::query::Providers;
use rustc_middle::ty::{ParamEnvAnd, TyCtxt};
use rustc_trait_selection::infer::InferCtxtBuilderExt;
use rustc_trait_selection::traits::query::{
normalize::NormalizationResult, CanonicalProjectionGoal, NoSolution,
};
use rustc_trait_selection::traits::{self, ObligationCause, SelectionContext};
use std::sync::atomic::Ordering;
crate fn provide(p: &mut Providers) {
*p = Providers { normalize_projection_ty, ..*p };<|fim▁hole|>}
fn normalize_projection_ty<'tcx>(
tcx: TyCtxt<'tcx>,
goal: CanonicalProjectionGoal<'tcx>,
) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, NormalizationResult<'tcx>>>, NoSolution> {
debug!("normalize_provider(goal={:#?})", goal);
tcx.sess.perf_stats.normalize_projection_ty.fetch_add(1, Ordering::Relaxed);
tcx.infer_ctxt().enter_canonical_trait_query(
&goal,
|infcx, fulfill_cx, ParamEnvAnd { param_env, value: goal }| {
let selcx = &mut SelectionContext::new(infcx);
let cause = ObligationCause::dummy();
let mut obligations = vec![];
let answer = traits::normalize_projection_type(
selcx,
param_env,
goal,
cause,
0,
&mut obligations,
);
fulfill_cx.register_predicate_obligations(infcx, obligations);
Ok(NormalizationResult { normalized_ty: answer })
},
)
}<|fim▁end|> | |
<|file_name|>run.test.js<|end_file_name|><|fim▁begin|><|fim▁hole|>test('bolt workspaces run');<|fim▁end|> | // @flow
import { workspacesRun, toWorkspacesRunOptions } from '../run';
|
<|file_name|>main.tsx<|end_file_name|><|fim▁begin|><|fim▁hole|>import * as ReactDOM from 'react-dom';
import App from './components/App';
ReactDOM.render(<App name="James" />, document.getElementById('content'));<|fim▁end|> | import * as React from 'react'; |
<|file_name|>test_feature_calculations.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# This file as well as the whole tsfresh package are licenced under the MIT licence (see the LICENCE.txt)
# Maximilian Christ (maximilianchrist.com), Blue Yonder Gmbh, 2016
import math
import warnings
from random import shuffle
from unittest import TestCase
from matrixprofile.exceptions import NoSolutionPossible
from tsfresh.examples.driftbif_simulation import velocity
from tsfresh.feature_extraction.feature_calculators import *
from tsfresh.feature_extraction.feature_calculators import (
_aggregate_on_chunks,
_estimate_friedrich_coefficients,
_get_length_sequences_where,
_into_subchunks,
_roll,
)
class FeatureCalculationTestCase(TestCase):
def setUp(self):
# There will be a lot of warnings in the feature calculators.
# Just ignore all of them in these tests
warnings.simplefilter("ignore")
def tearDown(self):
warnings.resetwarnings()
def assertIsNaN(self, result):
self.assertTrue(np.isnan(result), msg="{} is not np.NaN")
def assertEqualOnAllArrayTypes(self, f, input_to_f, result, *args, **kwargs):
expected_result = f(input_to_f, *args, **kwargs)
self.assertEqual(
expected_result,
result,
msg="Not equal for lists: {} != {}".format(expected_result, result),
)
expected_result = f(np.array(input_to_f), *args, **kwargs)
self.assertEqual(
expected_result,
result,
msg="Not equal for numpy.arrays: {} != {}".format(expected_result, result),
)
expected_result = f(pd.Series(input_to_f, dtype="float64"), *args, **kwargs)
self.assertEqual(
expected_result,
result,
msg="Not equal for pandas.Series: {} != {}".format(expected_result, result),
)
def assertTrueOnAllArrayTypes(self, f, input_to_f, *args, **kwargs):
self.assertTrue(f(input_to_f, *args, **kwargs), msg="Not true for lists")
self.assertTrue(
f(np.array(input_to_f), *args, **kwargs), msg="Not true for numpy.arrays"
)
self.assertTrue(
f(pd.Series(input_to_f), *args, **kwargs), msg="Not true for pandas.Series"
)
def assertAllTrueOnAllArrayTypes(self, f, input_to_f, *args, **kwargs):
self.assertTrue(
all(dict(f(input_to_f, *args, **kwargs)).values()), msg="Not true for lists"
)
self.assertTrue(
all(dict(f(np.array(input_to_f), *args, **kwargs)).values()),
msg="Not true for numpy.arrays",
)
self.assertTrue(
all(dict(f(pd.Series(input_to_f), *args, **kwargs)).values()),
msg="Not true for pandas.Series",
)
def assertFalseOnAllArrayTypes(self, f, input_to_f, *args, **kwargs):
self.assertFalse(f(input_to_f, *args, **kwargs), msg="Not false for lists")
self.assertFalse(
f(np.array(input_to_f), *args, **kwargs), msg="Not false for numpy.arrays"
)
self.assertFalse(
f(pd.Series(input_to_f), *args, **kwargs), msg="Not false for pandas.Series"
)
def assertAllFalseOnAllArrayTypes(self, f, input_to_f, *args, **kwargs):
self.assertFalse(
any(dict(f(input_to_f, *args, **kwargs)).values()),
msg="Not false for lists",
)
self.assertFalse(
any(dict(f(np.array(input_to_f), *args, **kwargs)).values()),
msg="Not false for numpy.arrays",
)
self.assertFalse(
any(dict(f(pd.Series(input_to_f), *args, **kwargs)).values()),
msg="Not false for pandas.Series",
)
def assertAlmostEqualOnAllArrayTypes(self, f, input_to_f, result, *args, **kwargs):
expected_result = f(input_to_f, *args, **kwargs)
self.assertAlmostEqual(
expected_result,
result,
msg="Not almost equal for lists: {} != {}".format(expected_result, result),
)
expected_result = f(np.array(input_to_f), *args, **kwargs)
self.assertAlmostEqual(
expected_result,
result,
msg="Not almost equal for numpy.arrays: {} != {}".format(
expected_result, result
),
)
expected_result = f(pd.Series(input_to_f, dtype="float64"), *args, **kwargs)
self.assertAlmostEqual(
expected_result,
result,
msg="Not almost equal for pandas.Series: {} != {}".format(
expected_result, result
),
)
def assertIsNanOnAllArrayTypes(self, f, input_to_f, *args, **kwargs):
self.assertTrue(
np.isnan(f(input_to_f, *args, **kwargs)), msg="Not NaN for lists"
)
self.assertTrue(
np.isnan(f(np.array(input_to_f), *args, **kwargs)),
msg="Not NaN for numpy.arrays",
)
self.assertTrue(
np.isnan(f(pd.Series(input_to_f, dtype="float64"), *args, **kwargs)),
msg="Not NaN for pandas.Series",
)
def assertEqualPandasSeriesWrapper(self, f, input_to_f, result, *args, **kwargs):
self.assertEqual(
f(pd.Series(input_to_f), *args, **kwargs),
result,
msg="Not equal for pandas.Series: {} != {}".format(
f(pd.Series(input_to_f), *args, **kwargs), result
),
)
def test__roll(self):
x = np.random.normal(size=30)
for shift in [0, 1, 10, 11, 30, 31, 50, 51, 150, 151]:
np.testing.assert_array_equal(_roll(x, shift), np.roll(x, shift))
np.testing.assert_array_equal(_roll(x, -shift), np.roll(x, -shift))
def test___get_length_sequences_where(self):
self.assertEqualOnAllArrayTypes(
_get_length_sequences_where,
[0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1],
[1, 3, 1, 2],
)
self.assertEqualOnAllArrayTypes(
_get_length_sequences_where,
[0, True, 0, 0, True, True, True, 0, 0, True, 0, True, True],
[1, 3, 1, 2],
)
self.assertEqualOnAllArrayTypes(
_get_length_sequences_where,
[0, True, 0, 0, 1, True, 1, 0, 0, True, 0, 1, True],
[1, 3, 1, 2],
)
self.assertEqualOnAllArrayTypes(_get_length_sequences_where, [0] * 10, [0])
self.assertEqualOnAllArrayTypes(_get_length_sequences_where, [], [0])
def test__into_subchunks(self):
np.testing.assert_array_equal(
_into_subchunks(range(7), 3, 2), np.array([[0, 1, 2], [2, 3, 4], [4, 5, 6]])
)
np.testing.assert_array_equal(
_into_subchunks(range(5), 3), np.array([[0, 1, 2], [1, 2, 3], [2, 3, 4]])
)
def test_variance_larger_than_standard_deviation(self):
self.assertFalseOnAllArrayTypes(
variance_larger_than_standard_deviation, [-1, -1, 1, 1, 1]
)
self.assertTrueOnAllArrayTypes(
variance_larger_than_standard_deviation, [-1, -1, 1, 1, 2]
)
def test_large_standard_deviation(self):
self.assertFalseOnAllArrayTypes(large_standard_deviation, [1, 1, 1, 1], r=0)
self.assertFalseOnAllArrayTypes(large_standard_deviation, [1, 1, 1, 1], r=0)
self.assertTrueOnAllArrayTypes(large_standard_deviation, [-1, -1, 1, 1], r=0)
self.assertTrueOnAllArrayTypes(large_standard_deviation, [-1, -1, 1, 1], r=0.25)
self.assertTrueOnAllArrayTypes(large_standard_deviation, [-1, -1, 1, 1], r=0.3)
self.assertFalseOnAllArrayTypes(large_standard_deviation, [-1, -1, 1, 1], r=0.5)
def test_symmetry_looking(self):
self.assertAllTrueOnAllArrayTypes(
symmetry_looking, [-1, -1, 1, 1], [dict(r=0.05), dict(r=0.75)]
)
self.assertAllFalseOnAllArrayTypes(
symmetry_looking, [-1, -1, 1, 1], [dict(r=0)]
)
self.assertAllFalseOnAllArrayTypes(
symmetry_looking, [-1, -1, -1, -1, 1], [dict(r=0.05)]
)
self.assertAllTrueOnAllArrayTypes(
symmetry_looking, [-2, -2, -2, -1, -1, -1], [dict(r=0.05)]
)
self.assertAllTrueOnAllArrayTypes(
symmetry_looking, [-0.9, -0.900001], [dict(r=0.05)]
)
def test_has_duplicate_max(self):
self.assertTrueOnAllArrayTypes(has_duplicate_max, [2.1, 0, 0, 2.1, 1.1])
self.assertFalseOnAllArrayTypes(
has_duplicate_max, np.array([2.1, 0, 0, 2, 1.1])
)
self.assertTrueOnAllArrayTypes(has_duplicate_max, [1, 1, 1, 1])
self.assertFalseOnAllArrayTypes(has_duplicate_max, np.array([0]))
self.assertTrueOnAllArrayTypes(has_duplicate_max, np.array([1, 1]))
def test_has_duplicate_min(self):
self.assertTrueOnAllArrayTypes(has_duplicate_min, [-2.1, 0, 0, -2.1, 1.1])
self.assertFalseOnAllArrayTypes(has_duplicate_min, [2.1, 0, -1, 2, 1.1])
self.assertTrueOnAllArrayTypes(has_duplicate_min, np.array([1, 1, 1, 1]))
self.assertFalseOnAllArrayTypes(has_duplicate_min, np.array([0]))
self.assertTrueOnAllArrayTypes(has_duplicate_min, np.array([1, 1]))
def test_has_duplicate(self):
self.assertTrueOnAllArrayTypes(has_duplicate, np.array([-2.1, 0, 0, -2.1]))
self.assertTrueOnAllArrayTypes(has_duplicate, [-2.1, 2.1, 2.1, 2.1])
self.assertFalseOnAllArrayTypes(has_duplicate, [1.1, 1.2, 1.3, 1.4])
self.assertFalseOnAllArrayTypes(has_duplicate, [1])
self.assertFalseOnAllArrayTypes(has_duplicate, [])
def test_sum(self):
self.assertEqualOnAllArrayTypes(sum_values, [1, 2, 3, 4.1], 10.1)
self.assertEqualOnAllArrayTypes(sum_values, [-1.2, -2, -3, -4], -10.2)
self.assertEqualOnAllArrayTypes(sum_values, [], 0)
def test_agg_autocorrelation_returns_correct_values(self):
param = [{"f_agg": "mean", "maxlag": 10}]
x = [1, 1, 1, 1, 1, 1, 1]
expected_res = 0
res = dict(agg_autocorrelation(x, param=param))['f_agg_"mean"__maxlag_10']
self.assertAlmostEqual(res, expected_res, places=4)
x = [1, 2, -3]
expected_res = 1 / np.var(x) * (((1 * 2 + 2 * (-3)) / 2 + (1 * -3)) / 2)
res = dict(agg_autocorrelation(x, param=param))['f_agg_"mean"__maxlag_10']
self.assertAlmostEqual(res, expected_res, places=4)
np.random.seed(42)
x = np.random.normal(size=3000)
expected_res = 0
res = dict(agg_autocorrelation(x, param=param))['f_agg_"mean"__maxlag_10']
self.assertAlmostEqual(res, expected_res, places=2)
param = [{"f_agg": "median", "maxlag": 10}]
x = [1, 1, 1, 1, 1, 1, 1]
expected_res = 0
res = dict(agg_autocorrelation(x, param=param))['f_agg_"median"__maxlag_10']
self.assertAlmostEqual(res, expected_res, places=4)
x = [1, 2, -3]
expected_res = 1 / np.var(x) * (((1 * 2 + 2 * (-3)) / 2 + (1 * -3)) / 2)
res = dict(agg_autocorrelation(x, param=param))['f_agg_"median"__maxlag_10']
self.assertAlmostEqual(res, expected_res, places=4)
def test_agg_autocorrelation_returns_max_lag_does_not_affect_other_results(self):
param = [{"f_agg": "mean", "maxlag": 1}, {"f_agg": "mean", "maxlag": 10}]
x = range(10)
res1 = dict(agg_autocorrelation(x, param=param))['f_agg_"mean"__maxlag_1']
res10 = dict(agg_autocorrelation(x, param=param))['f_agg_"mean"__maxlag_10']
self.assertAlmostEqual(res1, 0.77777777, places=4)
self.assertAlmostEqual(res10, -0.64983164983165, places=4)
param = [{"f_agg": "mean", "maxlag": 1}]
x = range(10)
res1 = dict(agg_autocorrelation(x, param=param))['f_agg_"mean"__maxlag_1']
self.assertAlmostEqual(res1, 0.77777777, places=4)
def test_partial_autocorrelation(self):
# Test for altering time series
# len(x) < max_lag
param = [{"lag": lag} for lag in range(10)]
x = [1, 2, 1, 2, 1, 2]
expected_res = [("lag_0", 1.0), ("lag_1", -1.0), ("lag_2", np.nan)]
res = partial_autocorrelation(x, param=param)
self.assertAlmostEqual(res[0][1], expected_res[0][1], places=4)
self.assertAlmostEqual(res[1][1], expected_res[1][1], places=4)
self.assertIsNaN(res[2][1])
# Linear signal
param = [{"lag": lag} for lag in range(10)]
x = np.linspace(0, 1, 3000)
expected_res = [("lag_0", 1.0), ("lag_1", 1.0), ("lag_2", 0)]
res = partial_autocorrelation(x, param=param)
self.assertAlmostEqual(res[0][1], expected_res[0][1], places=2)
self.assertAlmostEqual(res[1][1], expected_res[1][1], places=2)
self.assertAlmostEqual(res[2][1], expected_res[2][1], places=2)
# Random noise
np.random.seed(42)
x = np.random.normal(size=3000)
param = [{"lag": lag} for lag in range(10)]
expected_res = [("lag_0", 1.0), ("lag_1", 0), ("lag_2", 0)]
res = partial_autocorrelation(x, param=param)
self.assertAlmostEqual(res[0][1], expected_res[0][1], places=1)
self.assertAlmostEqual(res[1][1], expected_res[1][1], places=1)
self.assertAlmostEqual(res[2][1], expected_res[2][1], places=1)
# On a simulated AR process
np.random.seed(42)
param = [{"lag": lag} for lag in range(10)]
# Simulate AR process
T = 3000
epsilon = np.random.randn(T)
x = np.repeat(1.0, T)
for t in range(T - 1):
x[t + 1] = 0.5 * x[t] + 2 + epsilon[t]
expected_res = [("lag_0", 1.0), ("lag_1", 0.5), ("lag_2", 0)]
res = partial_autocorrelation(x, param=param)
self.assertAlmostEqual(res[0][1], expected_res[0][1], places=1)
self.assertAlmostEqual(res[1][1], expected_res[1][1], places=1)
self.assertAlmostEqual(res[2][1], expected_res[2][1], places=1)
# Some pathological cases
param = [{"lag": lag} for lag in range(10)]
# List of length 1
res = partial_autocorrelation([1], param=param)
for lag_no, lag_val in res:
self.assertIsNaN(lag_val)
# Empty list
res = partial_autocorrelation([], param=param)
for lag_no, lag_val in res:
self.assertIsNaN(lag_val)
# List contains only zeros
res = partial_autocorrelation(np.zeros(100), param=param)
for lag_no, lag_val in res:
if lag_no == "lag_0":
self.assertEqual(lag_val, 1.0)
else:
self.assertIsNaN(lag_val)
def test_augmented_dickey_fuller(self):
# todo: add unit test for the values of the test statistic
# the adf hypothesis test checks for unit roots,
# so H_0 = {random drift} vs H_1 = {AR(1) model}
# H0 is true
np.random.seed(seed=42)
x = np.cumsum(np.random.uniform(size=100))
param = [
{"autolag": "BIC", "attr": "teststat"},
{"autolag": "BIC", "attr": "pvalue"},
{"autolag": "BIC", "attr": "usedlag"},
]
expected_index = [
'attr_"teststat"__autolag_"BIC"',
'attr_"pvalue"__autolag_"BIC"',
'attr_"usedlag"__autolag_"BIC"',
]
res = augmented_dickey_fuller(x=x, param=param)
res = pd.Series(dict(res))
self.assertCountEqual(list(res.index), expected_index)
self.assertGreater(res['attr_"pvalue"__autolag_"BIC"'], 0.10)
self.assertEqual(res['attr_"usedlag"__autolag_"BIC"'], 0)
# H0 should be rejected for AR(1) model with x_{t} = 1/2 x_{t-1} + e_{t}
np.random.seed(seed=42)
e = np.random.normal(0.1, 0.1, size=100)
m = 50
x = [0] * m
x[0] = 100
for i in range(1, m):
x[i] = x[i - 1] * 0.5 + e[i]
param = [
{"autolag": "AIC", "attr": "teststat"},
{"autolag": "AIC", "attr": "pvalue"},
{"autolag": "AIC", "attr": "usedlag"},
]
expected_index = [
'attr_"teststat"__autolag_"AIC"',
'attr_"pvalue"__autolag_"AIC"',
'attr_"usedlag"__autolag_"AIC"',
]
res = augmented_dickey_fuller(x=x, param=param)
res = pd.Series(dict(res))
self.assertCountEqual(list(res.index), expected_index)
self.assertLessEqual(res['attr_"pvalue"__autolag_"AIC"'], 0.05)
self.assertEqual(res['attr_"usedlag"__autolag_"AIC"'], 0)
# Check if LinAlgError and ValueError are catched
res_linalg_error = augmented_dickey_fuller(
x=np.repeat(np.nan, 100), param=param
)
res_value_error = augmented_dickey_fuller(x=[], param=param)
for index, val in res_linalg_error:
self.assertIsNaN(val)
for index, val in res_value_error:
self.assertIsNaN(val)
# Should return NaN if "attr" is unknown
res_attr_error = augmented_dickey_fuller(
x=x, param=[{"autolag": "AIC", "attr": ""}]
)
for index, val in res_attr_error:
self.assertIsNaN(val)
def test_abs_energy(self):
self.assertEqualOnAllArrayTypes(abs_energy, [1, 1, 1], 3)
self.assertEqualOnAllArrayTypes(abs_energy, [1, 2, 3], 14)
self.assertEqualOnAllArrayTypes(abs_energy, [-1, 2, -3], 14)
self.assertAlmostEqualOnAllArrayTypes(abs_energy, [-1, 1.3], 2.69)
self.assertEqualOnAllArrayTypes(abs_energy, [1], 1)
def test_cid_ce(self):
self.assertEqualOnAllArrayTypes(cid_ce, [1, 1, 1], 0, normalize=True)
self.assertEqualOnAllArrayTypes(cid_ce, [0, 4], 2, normalize=True)
self.assertEqualOnAllArrayTypes(cid_ce, [100, 104], 2, normalize=True)
self.assertEqualOnAllArrayTypes(cid_ce, [1, 1, 1], 0, normalize=False)
self.assertEqualOnAllArrayTypes(cid_ce, [0.5, 3.5, 7.5], 5, normalize=False)
self.assertEqualOnAllArrayTypes(
cid_ce, [-4.33, -1.33, 2.67], 5, normalize=False
)
def test_lempel_ziv_complexity(self):
self.assertAlmostEqualOnAllArrayTypes(
lempel_ziv_complexity, [1, 1, 1], 2.0 / 3, bins=2
)
self.assertAlmostEqualOnAllArrayTypes(
lempel_ziv_complexity, [1, 1, 1], 2.0 / 3, bins=5
)
self.assertAlmostEqualOnAllArrayTypes(
lempel_ziv_complexity, [1, 1, 1, 1, 1, 1, 1], 0.4285714285, bins=2
)
self.assertAlmostEqualOnAllArrayTypes(
lempel_ziv_complexity, [1, 1, 1, 2, 1, 1, 1], 0.5714285714, bins=2
)
self.assertAlmostEqualOnAllArrayTypes(
lempel_ziv_complexity, [-1, 4.3, 5, 1, -4.5, 1, 5, 7, -3.4, 6], 0.8, bins=10
)
self.assertAlmostEqualOnAllArrayTypes(
lempel_ziv_complexity,
[-1, np.nan, 5, 1, -4.5, 1, 5, 7, -3.4, 6],
0.4,
bins=10,
)
self.assertAlmostEqualOnAllArrayTypes(
lempel_ziv_complexity, np.linspace(0, 1, 10), 0.6, bins=3
)
self.assertAlmostEqualOnAllArrayTypes(
lempel_ziv_complexity, [1, 1, 2, 3, 4, 5, 6, 0, 7, 8], 0.6, bins=3
)
def test_fourier_entropy(self):
self.assertAlmostEqualOnAllArrayTypes(
fourier_entropy, [1, 2, 1], 0.693147180, bins=2
)
self.assertAlmostEqualOnAllArrayTypes(
fourier_entropy, [1, 2, 1], 0.693147180, bins=5
)
self.assertAlmostEqualOnAllArrayTypes(
fourier_entropy, [1, 1, 2, 1, 1, 1, 1], 0.5623351446188083, bins=5
)
self.assertAlmostEqualOnAllArrayTypes(
fourier_entropy, [1, 1, 1, 1, 2, 1, 1], 1.0397207708399179, bins=5
)
self.assertAlmostEqualOnAllArrayTypes(
fourier_entropy,
[-1, 4.3, 5, 1, -4.5, 1, 5, 7, -3.4, 6],
1.5607104090414063,
bins=10,
)
self.assertIsNanOnAllArrayTypes(
fourier_entropy, [-1, np.nan, 5, 1, -4.5, 1, 5, 7, -3.4, 6], bins=10
)
def test_permutation_entropy(self):
self.assertAlmostEqualOnAllArrayTypes(
permutation_entropy,
[4, 7, 9, 10, 6, 11, 3],
1.054920167,
dimension=3,
tau=1,
)
# should grow
self.assertAlmostEqualOnAllArrayTypes(
permutation_entropy,
[1, -1, 1, -1, 1, -1, 1, -1],
0.6931471805599453,
dimension=3,
tau=1,
)
self.assertAlmostEqualOnAllArrayTypes(
permutation_entropy,
[1, -1, 1, -1, 1, 1, 1, -1],
1.3296613488547582,
dimension=3,
tau=1,
)
self.assertAlmostEqualOnAllArrayTypes(
permutation_entropy,
[-1, 4.3, 5, 1, -4.5, 1, 5, 7, -3.4, 6],
1.0397207708399179,
dimension=3,
tau=2,
)
# nan is treated like any other number
self.assertAlmostEqualOnAllArrayTypes(
permutation_entropy,
[-1, 4.3, 5, 1, -4.5, 1, 5, np.nan, -3.4, 6],
1.0397207708399179,
dimension=3,
tau=2,
)
# if too short, return nan
self.assertIsNanOnAllArrayTypes(
permutation_entropy, [1, -1], dimension=3, tau=1
)
def test_ratio_beyond_r_sigma(self):
x = [0, 1] * 10 + [10, 20, -30] # std of x is 7.21, mean 3.04
self.assertEqualOnAllArrayTypes(ratio_beyond_r_sigma, x, 3.0 / len(x), r=1)
self.assertEqualOnAllArrayTypes(ratio_beyond_r_sigma, x, 2.0 / len(x), r=2)
self.assertEqualOnAllArrayTypes(ratio_beyond_r_sigma, x, 1.0 / len(x), r=3)
self.assertEqualOnAllArrayTypes(ratio_beyond_r_sigma, x, 0, r=20)
def test_mean_abs_change(self):
self.assertEqualOnAllArrayTypes(mean_abs_change, [-2, 2, 5], 3.5)
self.assertEqualOnAllArrayTypes(mean_abs_change, [1, 2, -1], 2)
def test_mean_change(self):
self.assertEqualOnAllArrayTypes(mean_change, [-2, 2, 5], 3.5)
self.assertEqualOnAllArrayTypes(mean_change, [1, 2, -1], -1)
self.assertEqualOnAllArrayTypes(mean_change, [10, 20], 10)
self.assertIsNanOnAllArrayTypes(mean_change, [1])
self.assertIsNanOnAllArrayTypes(mean_change, [])
def test_mean_second_derivate_central(self):
self.assertEqualOnAllArrayTypes(
mean_second_derivative_central, list(range(10)), 0
)
self.assertEqualOnAllArrayTypes(mean_second_derivative_central, [1, 3, 5], 0)
self.assertEqualOnAllArrayTypes(
mean_second_derivative_central, [1, 3, 7, -3], -3
)
def test_median(self):
self.assertEqualOnAllArrayTypes(median, [1, 1, 2, 2], 1.5)
self.assertEqualOnAllArrayTypes(median, [0.5, 0.5, 2, 3.5, 10], 2)
self.assertEqualOnAllArrayTypes(median, [0.5], 0.5)
self.assertIsNanOnAllArrayTypes(median, [])
def test_mean(self):
self.assertEqualOnAllArrayTypes(mean, [1, 1, 2, 2], 1.5)
self.assertEqualOnAllArrayTypes(mean, [0.5, 0.5, 2, 3.5, 10], 3.3)
self.assertEqualOnAllArrayTypes(mean, [0.5], 0.5)
self.assertIsNanOnAllArrayTypes(mean, [])
def test_length(self):
self.assertEqualOnAllArrayTypes(length, [1, 2, 3, 4], 4)
self.assertEqualOnAllArrayTypes(length, [1, 2, 3], 3)
self.assertEqualOnAllArrayTypes(length, [1, 2], 2)
self.assertEqualOnAllArrayTypes(length, [1, 2, 3, np.NaN], 4)
self.assertEqualOnAllArrayTypes(length, [], 0)
def test_standard_deviation(self):
self.assertAlmostEqualOnAllArrayTypes(standard_deviation, [1, 1, -1, -1], 1)
self.assertAlmostEqualOnAllArrayTypes(
standard_deviation, [1, 2, -2, -1], 1.58113883008
)
self.assertIsNanOnAllArrayTypes(standard_deviation, [])
def test_variation_coefficient(self):
self.assertIsNanOnAllArrayTypes(
variation_coefficient, [1, 1, -1, -1],
)
self.assertAlmostEqualOnAllArrayTypes(
variation_coefficient, [1, 2, -3, -1], -7.681145747868608
)
self.assertAlmostEqualOnAllArrayTypes(
variation_coefficient, [1, 2, 4, -1], 1.2018504251546631
)
self.assertIsNanOnAllArrayTypes(variation_coefficient, [])
def test_variance(self):
self.assertAlmostEqualOnAllArrayTypes(variance, [1, 1, -1, -1], 1)
self.assertAlmostEqualOnAllArrayTypes(variance, [1, 2, -2, -1], 2.5)
self.assertIsNanOnAllArrayTypes(variance, [])
def test_skewness(self):
self.assertEqualOnAllArrayTypes(skewness, [1, 1, 1, 2, 2, 2], 0)
self.assertAlmostEqualOnAllArrayTypes(
skewness, [1, 1, 1, 2, 2], 0.6085806194501855
)
self.assertEqualOnAllArrayTypes(skewness, [1, 1, 1], 0)
self.assertIsNanOnAllArrayTypes(skewness, [1, 1])
def test_kurtosis(self):
self.assertAlmostEqualOnAllArrayTypes(
kurtosis, [1, 1, 1, 2, 2], -3.333333333333333
)
self.assertAlmostEqualOnAllArrayTypes(kurtosis, [1, 1, 1, 1], 0)
self.assertIsNanOnAllArrayTypes(kurtosis, [1, 1, 1])
def test_root_mean_square(self):
self.assertAlmostEqualOnAllArrayTypes(
root_mean_square, [1, 1, 1, 2, 2], 1.4832396974191
)
self.assertAlmostEqualOnAllArrayTypes(root_mean_square, [0], 0)
self.assertIsNanOnAllArrayTypes(root_mean_square, [])
self.assertAlmostEqualOnAllArrayTypes(root_mean_square, [1], 1)
self.assertAlmostEqualOnAllArrayTypes(root_mean_square, [-1], 1)
def test_mean_n_absolute_max(self):
self.assertIsNanOnAllArrayTypes(mean_n_absolute_max, [], number_of_maxima=1)
self.assertIsNanOnAllArrayTypes(
mean_n_absolute_max, [12, 3], number_of_maxima=10
)
self.assertRaises(
AssertionError, mean_n_absolute_max, [12, 3], number_of_maxima=0
)
self.assertRaises(
AssertionError, mean_n_absolute_max, [12, 3], number_of_maxima=-1
)
self.assertAlmostEqualOnAllArrayTypes(
mean_n_absolute_max, [-1, -5, 4, 10], 6.33333333333, number_of_maxima=3
)
self.assertAlmostEqualOnAllArrayTypes(
mean_n_absolute_max, [0, -5, -9], 7.000000, number_of_maxima=2
)
self.assertAlmostEqualOnAllArrayTypes(
mean_n_absolute_max, [0, 0, 0], 0, number_of_maxima=1
)
def test_absolute_sum_of_changes(self):
self.assertEqualOnAllArrayTypes(absolute_sum_of_changes, [1, 1, 1, 1, 2, 1], 2)
self.assertEqualOnAllArrayTypes(absolute_sum_of_changes, [1, -1, 1, -1], 6)
self.assertEqualOnAllArrayTypes(absolute_sum_of_changes, [1], 0)
self.assertEqualOnAllArrayTypes(absolute_sum_of_changes, [], 0)
def test_longest_strike_below_mean(self):
self.assertEqualOnAllArrayTypes(
longest_strike_below_mean, [1, 2, 1, 1, 1, 2, 2, 2], 3
)
self.assertEqualOnAllArrayTypes(
longest_strike_below_mean, [1, 2, 3, 4, 5, 6], 3
)
self.assertEqualOnAllArrayTypes(longest_strike_below_mean, [1, 2, 3, 4, 5], 2)
self.assertEqualOnAllArrayTypes(longest_strike_below_mean, [1, 2, 1], 1)
self.assertEqualOnAllArrayTypes(longest_strike_below_mean, [], 0)
def test_longest_strike_above_mean(self):
self.assertEqualOnAllArrayTypes(
longest_strike_above_mean, [1, 2, 1, 2, 1, 2, 2, 1], 2
)
self.assertEqualOnAllArrayTypes(
longest_strike_above_mean, [1, 2, 3, 4, 5, 6], 3
)
self.assertEqualOnAllArrayTypes(longest_strike_above_mean, [1, 2, 3, 4, 5], 2)
self.assertEqualOnAllArrayTypes(longest_strike_above_mean, [1, 2, 1], 1)
self.assertEqualOnAllArrayTypes(longest_strike_above_mean, [], 0)
def test_count_above_mean(self):
self.assertEqualOnAllArrayTypes(count_above_mean, [1, 2, 1, 2, 1, 2], 3)
self.assertEqualOnAllArrayTypes(count_above_mean, [1, 1, 1, 1, 1, 2], 1)
self.assertEqualOnAllArrayTypes(count_above_mean, [1, 1, 1, 1, 1], 0)
self.assertEqualOnAllArrayTypes(count_above_mean, [], 0)
def test_count_below_mean(self):
self.assertEqualOnAllArrayTypes(count_below_mean, [1, 2, 1, 2, 1, 2], 3)
self.assertEqualOnAllArrayTypes(count_below_mean, [1, 1, 1, 1, 1, 2], 5)
self.assertEqualOnAllArrayTypes(count_below_mean, [1, 1, 1, 1, 1], 0)
self.assertEqualOnAllArrayTypes(count_below_mean, [], 0)
def test_last_location_maximum(self):
self.assertAlmostEqualOnAllArrayTypes(
last_location_of_maximum, [1, 2, 1, 2, 1], 0.8
)
self.assertAlmostEqualOnAllArrayTypes(
last_location_of_maximum, [1, 2, 1, 1, 2], 1.0
)
self.assertAlmostEqualOnAllArrayTypes(
last_location_of_maximum, [2, 1, 1, 1, 1], 0.2
)
self.assertAlmostEqualOnAllArrayTypes(
last_location_of_maximum, [1, 1, 1, 1, 1], 1.0
)
self.assertAlmostEqualOnAllArrayTypes(last_location_of_maximum, [1], 1.0)
self.assertIsNanOnAllArrayTypes(last_location_of_maximum, [])
def test_first_location_of_maximum(self):
self.assertAlmostEqualOnAllArrayTypes(
first_location_of_maximum, [1, 2, 1, 2, 1], 0.2
)
self.assertAlmostEqualOnAllArrayTypes(
first_location_of_maximum, [1, 2, 1, 1, 2], 0.2
)
self.assertAlmostEqualOnAllArrayTypes(
first_location_of_maximum, [2, 1, 1, 1, 1], 0.0
)
self.assertAlmostEqualOnAllArrayTypes(
first_location_of_maximum, [1, 1, 1, 1, 1], 0.0
)
self.assertAlmostEqualOnAllArrayTypes(first_location_of_maximum, [1], 0.0)
self.assertIsNanOnAllArrayTypes(first_location_of_maximum, [])
def test_last_location_of_minimum(self):
self.assertAlmostEqualOnAllArrayTypes(
last_location_of_minimum, [1, 2, 1, 2, 1], 1.0
)
self.assertAlmostEqualOnAllArrayTypes(
last_location_of_minimum, [1, 2, 1, 2, 2], 0.6
)
self.assertAlmostEqualOnAllArrayTypes(
last_location_of_minimum, [2, 1, 1, 1, 2], 0.8
)
self.assertAlmostEqualOnAllArrayTypes(
last_location_of_minimum, [1, 1, 1, 1, 1], 1.0
)
self.assertAlmostEqualOnAllArrayTypes(last_location_of_minimum, [1], 1.0)
self.assertIsNanOnAllArrayTypes(last_location_of_minimum, [])
def test_first_location_of_minimum(self):
self.assertAlmostEqualOnAllArrayTypes(
first_location_of_minimum, [1, 2, 1, 2, 1], 0.0
)
self.assertAlmostEqualOnAllArrayTypes(
first_location_of_minimum, [2, 2, 1, 2, 2], 0.4
)
self.assertAlmostEqualOnAllArrayTypes(
first_location_of_minimum, [2, 1, 1, 1, 2], 0.2
)
self.assertAlmostEqualOnAllArrayTypes(
first_location_of_minimum, [1, 1, 1, 1, 1], 0.0
)
self.assertAlmostEqualOnAllArrayTypes(first_location_of_minimum, [1], 0.0)
self.assertIsNanOnAllArrayTypes(first_location_of_minimum, [])
def test_percentage_of_doubled_datapoints(self):
self.assertAlmostEqualOnAllArrayTypes(
percentage_of_reoccurring_datapoints_to_all_datapoints, [1, 1, 2, 3, 4], 0.4
)
self.assertAlmostEqualOnAllArrayTypes(
percentage_of_reoccurring_datapoints_to_all_datapoints, [1, 1.5, 2, 3], 0
)
self.assertAlmostEqualOnAllArrayTypes(
percentage_of_reoccurring_datapoints_to_all_datapoints, [1], 0
)
self.assertAlmostEqualOnAllArrayTypes(
percentage_of_reoccurring_datapoints_to_all_datapoints,
[1.111, -2.45, 1.111, 2.45],
0.5,
)
self.assertIsNanOnAllArrayTypes(
percentage_of_reoccurring_datapoints_to_all_datapoints, []
)
def test_ratio_of_doubled_values(self):
self.assertAlmostEqualOnAllArrayTypes(
percentage_of_reoccurring_values_to_all_values, [1, 1, 2, 3, 4], 0.25
)
self.assertAlmostEqualOnAllArrayTypes(
percentage_of_reoccurring_values_to_all_values, [1, 1.5, 2, 3], 0
)
self.assertAlmostEqualOnAllArrayTypes(
percentage_of_reoccurring_values_to_all_values, [1], 0
)
self.assertAlmostEqualOnAllArrayTypes(
percentage_of_reoccurring_values_to_all_values,
[1.111, -2.45, 1.111, 2.45],
1.0 / 3.0,
)
self.assertIsNanOnAllArrayTypes(
percentage_of_reoccurring_values_to_all_values, []
)
def test_sum_of_reoccurring_values(self):
self.assertAlmostEqualOnAllArrayTypes(
sum_of_reoccurring_values, [1, 1, 2, 3, 4, 4], 5
)
self.assertAlmostEqualOnAllArrayTypes(
sum_of_reoccurring_values, [1, 1.5, 2, 3], 0
)
self.assertAlmostEqualOnAllArrayTypes(sum_of_reoccurring_values, [1], 0)
self.assertAlmostEqualOnAllArrayTypes(
sum_of_reoccurring_values, [1.111, -2.45, 1.111, 2.45], 1.111
)
self.assertAlmostEqualOnAllArrayTypes(sum_of_reoccurring_values, [], 0)
def test_sum_of_reoccurring_data_points(self):
self.assertAlmostEqualOnAllArrayTypes(
sum_of_reoccurring_data_points, [1, 1, 2, 3, 4, 4], 10
)
self.assertAlmostEqualOnAllArrayTypes(
sum_of_reoccurring_data_points, [1, 1.5, 2, 3], 0
)
self.assertAlmostEqualOnAllArrayTypes(sum_of_reoccurring_data_points, [1], 0)
self.assertAlmostEqualOnAllArrayTypes(
sum_of_reoccurring_data_points, [1.111, -2.45, 1.111, 2.45], 2.222
)
self.assertAlmostEqualOnAllArrayTypes(sum_of_reoccurring_data_points, [], 0)
def test_uniqueness_factor(self):
self.assertAlmostEqualOnAllArrayTypes(
ratio_value_number_to_time_series_length, [1, 1, 2, 3, 4], 0.8
)
self.assertAlmostEqualOnAllArrayTypes(
ratio_value_number_to_time_series_length, [1, 1.5, 2, 3], 1
)
self.assertAlmostEqualOnAllArrayTypes(
ratio_value_number_to_time_series_length, [1], 1
)
self.assertAlmostEqualOnAllArrayTypes(
ratio_value_number_to_time_series_length, [1.111, -2.45, 1.111, 2.45], 0.75
)
self.assertIsNanOnAllArrayTypes(ratio_value_number_to_time_series_length, [])
def test_fft_coefficient(self):
x = range(10)
param = [
{"coeff": 0, "attr": "real"},
{"coeff": 1, "attr": "real"},
{"coeff": 2, "attr": "real"},
{"coeff": 0, "attr": "imag"},
{"coeff": 1, "attr": "imag"},
{"coeff": 2, "attr": "imag"},
{"coeff": 0, "attr": "angle"},
{"coeff": 1, "attr": "angle"},
{"coeff": 2, "attr": "angle"},
{"coeff": 0, "attr": "abs"},
{"coeff": 1, "attr": "abs"},
{"coeff": 2, "attr": "abs"},
]
expected_index = [
'attr_"real"__coeff_0',
'attr_"real"__coeff_1',
'attr_"real"__coeff_2',
'attr_"imag"__coeff_0',
'attr_"imag"__coeff_1',
'attr_"imag"__coeff_2',
'attr_"angle"__coeff_0',
'attr_"angle"__coeff_1',
'attr_"angle"__coeff_2',
'attr_"abs"__coeff_0',
'attr_"abs"__coeff_1',
'attr_"abs"__coeff_2',
]
res = pd.Series(dict(fft_coefficient(x, param)))
self.assertCountEqual(list(res.index), expected_index)
self.assertAlmostEqual(res['attr_"imag"__coeff_0'], 0, places=6)
self.assertAlmostEqual(res['attr_"real"__coeff_0'], sum(x), places=6)
self.assertAlmostEqual(res['attr_"angle"__coeff_0'], 0, places=6)
self.assertAlmostEqual(res['attr_"abs"__coeff_0'], sum(x), places=6)
x = [0, 1, 0, 0]
res = pd.Series(dict(fft_coefficient(x, param)))
# see documentation of fft in numpy
# should return array([1. + 0.j, 0. - 1.j, -1. + 0.j])
self.assertAlmostEqual(res['attr_"imag"__coeff_0'], 0, places=6)
self.assertAlmostEqual(res['attr_"real"__coeff_0'], 1, places=6)
self.assertAlmostEqual(res['attr_"imag"__coeff_1'], -1, places=6)
self.assertAlmostEqual(res['attr_"angle"__coeff_1'], -90, places=6)
self.assertAlmostEqual(res['attr_"real"__coeff_1'], 0, places=6)
self.assertAlmostEqual(res['attr_"imag"__coeff_2'], 0, places=6)
self.assertAlmostEqual(res['attr_"real"__coeff_2'], -1, places=6)
# test what happens if coeff is biger than time series lenght
x = range(5)
param = [{"coeff": 10, "attr": "real"}]
expected_index = ['attr_"real"__coeff_10']
res = pd.Series(dict(fft_coefficient(x, param)))
self.assertCountEqual(list(res.index), expected_index)
self.assertIsNaN(res['attr_"real"__coeff_10'])
def test_fft_aggregated(self):
param = [
{"aggtype": "centroid"},
{"aggtype": "variance"},
{"aggtype": "skew"},
{"aggtype": "kurtosis"},
]
expected_index = [
'aggtype_"centroid"',
'aggtype_"variance"',
'aggtype_"skew"',
'aggtype_"kurtosis"',
]
x = np.arange(10)
res = pd.Series(dict(fft_aggregated(x, param)))
self.assertCountEqual(list(res.index), expected_index)
self.assertAlmostEqual(res['aggtype_"centroid"'], 1.135, places=3)
self.assertAlmostEqual(res['aggtype_"variance"'], 2.368, places=3)
self.assertAlmostEqual(res['aggtype_"skew"'], 1.249, places=3)
self.assertAlmostEqual(res['aggtype_"kurtosis"'], 3.643, places=3)
# Scalar multiplying the distribution should not change the results:
x = 10 * x
res = pd.Series(dict(fft_aggregated(x, param)))
self.assertCountEqual(list(res.index), expected_index)
self.assertAlmostEqual(res['aggtype_"centroid"'], 1.135, places=3)
self.assertAlmostEqual(res['aggtype_"variance"'], 2.368, places=3)
self.assertAlmostEqual(res['aggtype_"skew"'], 1.249, places=3)
self.assertAlmostEqual(res['aggtype_"kurtosis"'], 3.643, places=3)
# The fft of a sign wave is a dirac delta, variance and skew should be near zero, kurtosis should be near 3:
# However, in the discrete limit, skew and kurtosis blow up in a manner that is noise dependent and are
# therefore bad features, therefore an nan should be returned for these values
x = np.sin(2 * np.pi / 10 * np.arange(30))
res = pd.Series(dict(fft_aggregated(x, param)))
self.assertCountEqual(list(res.index), expected_index)
self.assertAlmostEqual(res['aggtype_"centroid"'], 3.0, places=5)
self.assertAlmostEqual(res['aggtype_"variance"'], 0.0, places=5)
self.assertIsNaN(res['aggtype_"skew"'])
self.assertIsNaN(res['aggtype_"kurtosis"'])
# Gaussian test:
def normal(y, mean_, sigma_):
return (
1
/ (2 * np.pi * sigma_ ** 2)
* np.exp(-((y - mean_) ** 2) / (2 * sigma_ ** 2))
)
mean_ = 500.0
sigma_ = 1.0
range_ = int(2 * mean_)
x = list(map(lambda x: normal(x, mean_, sigma_), range(range_)))
# The fourier transform of a Normal dist in the positive halfspace is a half normal,
# Hand calculated values of centroid and variance based for the half-normal dist:
# (Ref: https://en.wikipedia.org/wiki/Half-normal_distribution)
expected_fft_centroid = (range_ / (2 * np.pi * sigma_)) * np.sqrt(2 / np.pi)
expected_fft_var = (range_ / (2 * np.pi * sigma_)) ** 2 * (1 - 2 / np.pi)
# Calculate values for unit test:
res = pd.Series(dict(fft_aggregated(x, param)))
self.assertCountEqual(list(res.index), expected_index)
# Compare against hand calculated values:
rel_diff_allowed = 0.02
self.assertAlmostEqual(
res['aggtype_"centroid"'],
expected_fft_centroid,
delta=rel_diff_allowed * expected_fft_centroid,
)
self.assertAlmostEqual(
res['aggtype_"variance"'],
expected_fft_var,
delta=rel_diff_allowed * expected_fft_var,
)
def test_number_peaks(self):
x = np.array([0, 1, 2, 1, 0, 1, 2, 3, 4, 5, 4, 3, 2, 1])
self.assertEqualOnAllArrayTypes(number_peaks, x, 2, 1)
self.assertEqualOnAllArrayTypes(number_peaks, x, 2, 2)
self.assertEqualOnAllArrayTypes(number_peaks, x, 1, 3)
self.assertEqualOnAllArrayTypes(number_peaks, x, 1, 4)
self.assertEqualOnAllArrayTypes(number_peaks, x, 0, 5)
self.assertEqualOnAllArrayTypes(number_peaks, x, 0, 6)
def test_mass_quantile(self):
x = [1] * 101
param = [{"q": 0.5}]
expected_index = ["q_0.5"]
res = index_mass_quantile(x, param)
res = pd.Series(dict(res))
self.assertCountEqual(list(res.index), expected_index)
self.assertAlmostEqual(res["q_0.5"], 0.5, places=1)
# Test for parts of pandas series
x = pd.Series([0] * 55 + [1] * 101)
param = [{"q": 0.5}]
expected_index = ["q_0.5"]
res = index_mass_quantile(x[x > 0], param)
res = pd.Series(dict(res))
self.assertCountEqual(list(res.index), expected_index)
self.assertAlmostEqual(res["q_0.5"], 0.5, places=1)
x = [0] * 1000 + [1]
param = [{"q": 0.5}, {"q": 0.99}]
expected_index = ["q_0.5", "q_0.99"]
res = index_mass_quantile(x, param)
res = pd.Series(dict(res))
self.assertCountEqual(list(res.index), expected_index)
self.assertAlmostEqual(res["q_0.5"], 1, places=1)
self.assertAlmostEqual(res["q_0.99"], 1, places=1)
x = [0, 1, 1, 0, 0, 1, 0, 0]
param = [{"q": 0.30}, {"q": 0.60}, {"q": 0.90}]
expected_index = ["q_0.3", "q_0.6", "q_0.9"]
res = index_mass_quantile(x, param)
res = pd.Series(dict(res))
self.assertCountEqual(list(res.index), expected_index)
self.assertAlmostEqual(res["q_0.3"], 0.25, places=1)
self.assertAlmostEqual(res["q_0.6"], 0.375, places=1)
self.assertAlmostEqual(res["q_0.9"], 0.75, places=1)
x = [0, 0, 0]
param = [{"q": 0.5}]
expected_index = ["q_0.5"]
res = index_mass_quantile(x, param)
res = pd.Series(dict(res))
self.assertCountEqual(list(res.index), expected_index)
self.assertTrue(np.isnan(res["q_0.5"]))
x = []
param = [{"q": 0.5}]
expected_index = ["q_0.5"]
res = index_mass_quantile(x, param)
res = pd.Series(dict(res))
self.assertCountEqual(list(res.index), expected_index)
self.assertTrue(np.isnan(res["q_0.5"]))
def test_number_cwt_peaks(self):
x = [1, 1, 1, 1, 1, 1, 1, 5, 1, 1, 1, 1, 1, 1, 5, 1, 1, 1, 1, 1, 1]
self.assertEqualOnAllArrayTypes(number_cwt_peaks, x, 2, 2)
def test_spkt_welch_density(self):
# todo: improve tests
x = range(10)
param = [{"coeff": 1}, {"coeff": 10}]
expected_index = ["coeff_1", "coeff_10"]
res = pd.Series(dict(spkt_welch_density(x, param)))
self.assertCountEqual(list(res.index), expected_index)
self.assertIsNaN(res["coeff_10"])
def test_cwt_coefficients(self):
x = [0.1, 0.2, 0.3]
param = [
{"widths": (1, 2, 3), "coeff": 2, "w": 1},
{"widths": (1, 3), "coeff": 2, "w": 3},
{"widths": (1, 3), "coeff": 5, "w": 3},
]
shuffle(param)
expected_index = [
"coeff_2__w_1__widths_(1, 2, 3)",
"coeff_2__w_3__widths_(1, 3)",
"coeff_5__w_3__widths_(1, 3)",
]
res = cwt_coefficients(x, param)
res = pd.Series(dict(res))
# todo: add unit test for the values
self.assertCountEqual(list(res.index), expected_index)
self.assertTrue(math.isnan(res["coeff_5__w_3__widths_(1, 3)"]))
def test_ar_coefficient(self):
# Test for X_i = 2.5 * X_{i-1} + 1
param = [{"k": 1, "coeff": 0}, {"k": 1, "coeff": 1}]
shuffle(param)
x = [1] + 9 * [0]
for i in range(1, len(x)):
x[i] = 2.5 * x[i - 1] + 1
res = ar_coefficient(x, param)
expected_index = ["coeff_0__k_1", "coeff_1__k_1"]
res = pd.Series(dict(res))
self.assertCountEqual(list(res.index), expected_index)
self.assertAlmostEqual(res["coeff_0__k_1"], 1, places=2)
self.assertAlmostEqual(res["coeff_1__k_1"], 2.5, places=2)
# Test for X_i = 1.4 * X_{i-1} - 1 X_{i-2} + 1
param = [
{"k": 1, "coeff": 0},
{"k": 1, "coeff": 1},
{"k": 2, "coeff": 0},
{"k": 2, "coeff": 1},
{"k": 2, "coeff": 2},<|fim▁hole|> shuffle(param)
x = [1, 1] + 5 * [0]
for i in range(2, len(x)):
x[i] = (-2) * x[i - 2] + 3.5 * x[i - 1] + 1
res = ar_coefficient(x, param)
expected_index = [
"coeff_0__k_1",
"coeff_1__k_1",
"coeff_0__k_2",
"coeff_1__k_2",
"coeff_2__k_2",
"coeff_3__k_2",
]
res = pd.Series(dict(res))
self.assertIsInstance(res, pd.Series)
self.assertCountEqual(list(res.index), expected_index)
self.assertAlmostEqual(res["coeff_0__k_2"], 1, places=2)
self.assertAlmostEqual(res["coeff_1__k_2"], 3.5, places=2)
self.assertAlmostEqual(res["coeff_2__k_2"], -2, places=2)
self.assertTrue(np.isnan(res["coeff_3__k_2"]))
def test_time_reversal_asymmetry_statistic(self):
x = [1] * 10
self.assertAlmostEqualOnAllArrayTypes(
time_reversal_asymmetry_statistic, x, 0, 0
)
self.assertAlmostEqualOnAllArrayTypes(
time_reversal_asymmetry_statistic, x, 0, 1
)
self.assertAlmostEqualOnAllArrayTypes(
time_reversal_asymmetry_statistic, x, 0, 2
)
self.assertAlmostEqualOnAllArrayTypes(
time_reversal_asymmetry_statistic, x, 0, 3
)
x = [1, 2, -3, 4]
# 1/2 * ( (4^2 * -3 + 3 * 2^2) + (3^2*2)-(2*1^1)) = 1/2 * (-48+12+18-2) = 20/2
self.assertAlmostEqualOnAllArrayTypes(
time_reversal_asymmetry_statistic, x, -10, 1
)
self.assertAlmostEqualOnAllArrayTypes(
time_reversal_asymmetry_statistic, x, 0, 2
)
self.assertAlmostEqualOnAllArrayTypes(
time_reversal_asymmetry_statistic, x, 0, 3
)
def test_number_crossing_m(self):
x = [10, -10, 10, -10]
self.assertEqualOnAllArrayTypes(number_crossing_m, x, 3, 0)
self.assertEqualOnAllArrayTypes(number_crossing_m, x, 0, 10)
x = [10, 20, 20, 30]
self.assertEqualOnAllArrayTypes(number_crossing_m, x, 0, 0)
self.assertEqualOnAllArrayTypes(number_crossing_m, x, 1, 15)
def test_c3(self):
x = [1] * 10
self.assertAlmostEqualOnAllArrayTypes(c3, x, 1, 0)
self.assertAlmostEqualOnAllArrayTypes(c3, x, 1, 1)
self.assertAlmostEqualOnAllArrayTypes(c3, x, 1, 2)
self.assertAlmostEqualOnAllArrayTypes(c3, x, 1, 3)
x = [1, 2, -3, 4]
# 1/2 *(1*2*(-3)+2*(-3)*4) = 1/2 *(-6-24) = -30/2
self.assertAlmostEqualOnAllArrayTypes(c3, x, -15, 1)
self.assertAlmostEqualOnAllArrayTypes(c3, x, 0, 2)
self.assertAlmostEqualOnAllArrayTypes(c3, x, 0, 3)
def test_binned_entropy(self):
self.assertAlmostEqualOnAllArrayTypes(binned_entropy, [10] * 100, 0, 10)
self.assertAlmostEqualOnAllArrayTypes(
binned_entropy,
[10] * 10 + [1],
-(10 / 11 * np.math.log(10 / 11) + 1 / 11 * np.math.log(1 / 11)),
10,
)
self.assertAlmostEqualOnAllArrayTypes(
binned_entropy,
[10] * 10 + [1],
-(10 / 11 * np.math.log(10 / 11) + 1 / 11 * np.math.log(1 / 11)),
10,
)
self.assertAlmostEqualOnAllArrayTypes(
binned_entropy,
[10] * 10 + [1],
-(10 / 11 * np.math.log(10 / 11) + 1 / 11 * np.math.log(1 / 11)),
100,
)
self.assertAlmostEqualOnAllArrayTypes(
binned_entropy, list(range(10)), -np.math.log(1 / 10), 100
)
self.assertAlmostEqualOnAllArrayTypes(
binned_entropy, list(range(100)), -np.math.log(1 / 2), 2
)
def test_sample_entropy(self):
# "random" list -> large entropy
ts = [
1,
4,
5,
1,
7,
3,
1,
2,
5,
8,
9,
7,
3,
7,
9,
5,
4,
3,
9,
1,
2,
3,
4,
2,
9,
6,
7,
4,
9,
2,
9,
9,
6,
5,
1,
3,
8,
1,
5,
3,
8,
4,
1,
2,
2,
1,
6,
5,
3,
6,
5,
4,
8,
9,
6,
7,
5,
3,
2,
5,
4,
2,
5,
1,
6,
5,
3,
5,
6,
7,
8,
5,
2,
8,
6,
3,
8,
2,
7,
1,
7,
3,
5,
6,
2,
1,
3,
7,
3,
5,
3,
7,
6,
7,
7,
2,
3,
1,
7,
8,
]
self.assertAlmostEqualOnAllArrayTypes(sample_entropy, ts, 2.38262780)
# This is not very complex, so it gives a small value
ts = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
self.assertAlmostEqualOnAllArrayTypes(sample_entropy, ts, 0.25131442)
# however adding a 2 increases complexity
ts = [1, 1, 2, 1, 1, 1, 1, 1, 1, 1]
self.assertAlmostEqualOnAllArrayTypes(sample_entropy, ts, 0.74193734)
# and it does not matter where
ts = [1, 1, 1, 2, 1, 1, 1, 1, 1, 1]
self.assertAlmostEqualOnAllArrayTypes(sample_entropy, ts, 0.74193734)
# negative numbers also work
ts = [1, -1, 1, -1, 1, -1]
self.assertAlmostEqualOnAllArrayTypes(sample_entropy, ts, 0.69314718)
# nan gives nan
ts = [1, -1, 1, np.nan, 1, -1]
self.assertIsNanOnAllArrayTypes(sample_entropy, ts)
# this is not a very "random" list, so it should give a small entropy
ts = list(range(1000))
self.assertAlmostEqualOnAllArrayTypes(sample_entropy, ts, 0.0010314596066622707)
def test_autocorrelation(self):
self.assertAlmostEqualOnAllArrayTypes(
autocorrelation, [1, 2, 1, 2, 1, 2], -1, 1
)
self.assertAlmostEqualOnAllArrayTypes(autocorrelation, [1, 2, 1, 2, 1, 2], 1, 2)
self.assertAlmostEqualOnAllArrayTypes(
autocorrelation, [1, 2, 1, 2, 1, 2], -1, 3
)
self.assertAlmostEqualOnAllArrayTypes(autocorrelation, [1, 2, 1, 2, 1, 2], 1, 4)
self.assertAlmostEqualOnAllArrayTypes(
autocorrelation, pd.Series([0, 1, 2, 0, 1, 2]), -0.75, 2
)
# Autocorrelation lag is larger than length of the time series
self.assertIsNanOnAllArrayTypes(autocorrelation, [1, 2, 1, 2, 1, 2], 200)
self.assertIsNanOnAllArrayTypes(autocorrelation, [np.nan], 0)
self.assertIsNanOnAllArrayTypes(autocorrelation, [], 0)
# time series with length 1 has no variance, therefore no result for autocorrelation at lag 0
self.assertIsNanOnAllArrayTypes(autocorrelation, [1], 0)
def test_quantile(self):
self.assertAlmostEqualOnAllArrayTypes(
quantile, [1, 1, 1, 3, 4, 7, 9, 11, 13, 13], 1.0, 0.2
)
self.assertAlmostEqualOnAllArrayTypes(
quantile, [1, 1, 1, 3, 4, 7, 9, 11, 13, 13], 13, 0.9
)
self.assertAlmostEqualOnAllArrayTypes(
quantile, [1, 1, 1, 3, 4, 7, 9, 11, 13, 13], 13, 1.0
)
self.assertAlmostEqualOnAllArrayTypes(quantile, [1], 1, 0.5)
self.assertIsNanOnAllArrayTypes(quantile, [], 0.5)
def test_mean_abs_change_quantiles(self):
self.assertAlmostEqualOnAllArrayTypes(
change_quantiles,
list(range(10)),
1,
ql=0.1,
qh=0.9,
isabs=True,
f_agg="mean",
)
self.assertAlmostEqualOnAllArrayTypes(
change_quantiles,
list(range(10)),
0,
ql=0.15,
qh=0.18,
isabs=True,
f_agg="mean",
)
self.assertAlmostEqualOnAllArrayTypes(
change_quantiles, [0, 1, 0, 0, 0], 0.5, ql=0, qh=1, isabs=True, f_agg="mean"
)
self.assertAlmostEqualOnAllArrayTypes(
change_quantiles,
[0, 1, 0, 0, 0],
0.5,
ql=0.1,
qh=1,
isabs=True,
f_agg="mean",
)
self.assertAlmostEqualOnAllArrayTypes(
change_quantiles,
[0, 1, 0, 0, 0],
0,
ql=0.1,
qh=0.6,
isabs=True,
f_agg="mean",
)
self.assertAlmostEqualOnAllArrayTypes(
change_quantiles, [0, 1, -9, 0, 0], 5, ql=0, qh=1, isabs=True, f_agg="mean"
)
self.assertAlmostEqualOnAllArrayTypes(
change_quantiles,
[0, 1, -9, 0, 0],
0.5,
ql=0.1,
qh=1,
isabs=True,
f_agg="mean",
)
self.assertAlmostEqualOnAllArrayTypes(
change_quantiles,
[0, 1, -9, 0, 0, 1, 0],
0.75,
ql=0.1,
qh=1,
isabs=True,
f_agg="mean",
)
self.assertAlmostEqualOnAllArrayTypes(
change_quantiles,
list(range(10)),
1,
ql=0.1,
qh=0.9,
isabs=False,
f_agg="mean",
)
self.assertAlmostEqualOnAllArrayTypes(
change_quantiles,
list(range(10)),
0,
ql=0.15,
qh=0.18,
isabs=False,
f_agg="mean",
)
self.assertAlmostEqualOnAllArrayTypes(
change_quantiles, [0, 1, 0, 0, 0], 0, ql=0, qh=1, isabs=False, f_agg="mean"
)
self.assertAlmostEqualOnAllArrayTypes(
change_quantiles,
[0, 1, 0, 0, 0],
0,
ql=0.1,
qh=1,
isabs=False,
f_agg="mean",
)
self.assertAlmostEqualOnAllArrayTypes(
change_quantiles,
[0, 1, 0, 0, 0],
0,
ql=0.1,
qh=0.6,
isabs=False,
f_agg="mean",
)
self.assertAlmostEqualOnAllArrayTypes(
change_quantiles, [0, 1, -9, 0, 0], 0, ql=0, qh=1, isabs=False, f_agg="mean"
)
self.assertAlmostEqualOnAllArrayTypes(
change_quantiles,
[0, 1, -9, 0, 0],
0.5,
ql=0.1,
qh=1,
isabs=False,
f_agg="mean",
)
self.assertAlmostEqualOnAllArrayTypes(
change_quantiles,
[0, 1, -9, 0, 0, 1, 0],
0.25,
ql=0.1,
qh=1,
isabs=False,
f_agg="mean",
)
self.assertAlmostEqualOnAllArrayTypes(
change_quantiles,
list(range(10)),
0,
ql=0.1,
qh=0.9,
isabs=True,
f_agg="std",
)
self.assertAlmostEqualOnAllArrayTypes(
change_quantiles, [0, 1, 0, 0, 0], 0.5, ql=0, qh=1, isabs=True, f_agg="std"
)
self.assertAlmostEqualOnAllArrayTypes(
change_quantiles,
list(range(10)),
0,
ql=0.1,
qh=0.9,
isabs=False,
f_agg="std",
)
self.assertAlmostEqualOnAllArrayTypes(
change_quantiles, [0, 1, 0, 1, 0], 1, ql=0, qh=1, isabs=False, f_agg="std"
)
def test_value_count(self):
self.assertEqualPandasSeriesWrapper(value_count, [1] * 10, 10, value=1)
self.assertEqualPandasSeriesWrapper(value_count, list(range(10)), 1, value=0)
self.assertEqualPandasSeriesWrapper(value_count, [1] * 10, 0, value=0)
self.assertEqualPandasSeriesWrapper(value_count, [np.NaN, 0, 1] * 3, 3, value=0)
self.assertEqualPandasSeriesWrapper(
value_count, [np.NINF, 0, 1] * 3, 3, value=0
)
self.assertEqualPandasSeriesWrapper(
value_count, [np.PINF, 0, 1] * 3, 3, value=0
)
self.assertEqualPandasSeriesWrapper(
value_count, [0.1, 0.2, 0.3] * 3, 3, value=0.2
)
self.assertEqualPandasSeriesWrapper(
value_count, [np.NaN, 0, 1] * 3, 3, value=np.NaN
)
self.assertEqualPandasSeriesWrapper(
value_count, [np.NINF, 0, 1] * 3, 3, value=np.NINF
)
self.assertEqualPandasSeriesWrapper(
value_count, [np.PINF, 0, 1] * 3, 3, value=np.PINF
)
def test_range_count(self):
self.assertEqualPandasSeriesWrapper(range_count, [1] * 10, 0, min=1, max=1)
self.assertEqualPandasSeriesWrapper(range_count, [1] * 10, 0, min=0.9, max=1)
self.assertEqualPandasSeriesWrapper(range_count, [1] * 10, 10, min=1, max=1.1)
self.assertEqualPandasSeriesWrapper(
range_count, list(range(10)), 9, min=0, max=9
)
self.assertEqualPandasSeriesWrapper(
range_count, list(range(10)), 10, min=0, max=10
)
self.assertEqualPandasSeriesWrapper(
range_count, list(range(0, -10, -1)), 9, min=-10, max=0
)
self.assertEqualPandasSeriesWrapper(
range_count, [np.NaN, np.PINF, np.NINF] + list(range(10)), 10, min=0, max=10
)
def test_approximate_entropy(self):
self.assertEqualOnAllArrayTypes(approximate_entropy, [1], 0, m=2, r=0.5)
self.assertEqualOnAllArrayTypes(approximate_entropy, [1, 2], 0, m=2, r=0.5)
self.assertEqualOnAllArrayTypes(approximate_entropy, [1, 2, 3], 0, m=2, r=0.5)
self.assertEqualOnAllArrayTypes(approximate_entropy, [1, 2, 3], 0, m=2, r=0.5)
self.assertAlmostEqualOnAllArrayTypes(
approximate_entropy, [12, 13, 15, 16, 17] * 10, 0.282456191, m=2, r=0.9
)
self.assertRaises(
ValueError, approximate_entropy, x=[12, 13, 15, 16, 17] * 10, m=2, r=-0.5
)
def test_absolute_maximum(self):
self.assertEqualOnAllArrayTypes(absolute_maximum, [-5, 0, 1], 5)
self.assertEqualOnAllArrayTypes(absolute_maximum, [0], 0)
self.assertIsNanOnAllArrayTypes(absolute_maximum, [])
def test_max_langevin_fixed_point(self):
"""
Estimating the intrinsic velocity of a dissipative soliton
"""
default_params = {"m": 3, "r": 30}
# active Brownian motion
ds = velocity(tau=3.8, delta_t=0.05, R=3e-4, seed=0)
v = ds.simulate(100000, v0=np.zeros(1))
v0 = max_langevin_fixed_point(v[:, 0], **default_params)
self.assertLess(abs(ds.deterministic - v0), 0.001)
# Brownian motion
ds = velocity(tau=2.0 / 0.3 - 3.8, delta_t=0.05, R=3e-4, seed=0)
v = ds.simulate(10000, v0=np.zeros(1))
v0 = max_langevin_fixed_point(v[:, 0], **default_params)
self.assertLess(v0, 0.001)
def test_linear_trend(self):
# check linear up trend
x = range(10)
param = [
{"attr": "pvalue"},
{"attr": "rvalue"},
{"attr": "intercept"},
{"attr": "slope"},
{"attr": "stderr"},
]
res = linear_trend(x, param)
res = pd.Series(dict(res))
expected_index = [
'attr_"pvalue"',
'attr_"intercept"',
'attr_"rvalue"',
'attr_"slope"',
'attr_"stderr"',
]
self.assertEqual(len(res), 5)
self.assertCountEqual(list(res.index), expected_index)
self.assertAlmostEqual(res['attr_"pvalue"'], 0)
self.assertAlmostEqual(res['attr_"stderr"'], 0)
self.assertAlmostEqual(res['attr_"intercept"'], 0)
self.assertAlmostEqual(res['attr_"slope"'], 1.0)
# check p value for random trend
np.random.seed(42)
x = np.random.uniform(size=100)
param = [{"attr": "rvalue"}]
res = linear_trend(x, param)
res = pd.Series(dict(res))
self.assertLess(abs(res['attr_"rvalue"']), 0.1)
# check slope and intercept decreasing trend with intercept
x = [42 - 2 * x for x in range(10)]
param = [{"attr": "intercept"}, {"attr": "slope"}]
res = linear_trend(x, param)
res = pd.Series(dict(res))
self.assertAlmostEqual(res['attr_"intercept"'], 42)
self.assertAlmostEqual(res['attr_"slope"'], -2)
def test__aggregate_on_chunks(self):
self.assertListEqual(
_aggregate_on_chunks(x=pd.Series([0, 1, 2, 3]), f_agg="max", chunk_len=2),
[1, 3],
)
self.assertListEqual(
_aggregate_on_chunks(x=pd.Series([1, 1, 3, 3]), f_agg="max", chunk_len=2),
[1, 3],
)
self.assertListEqual(
_aggregate_on_chunks(x=pd.Series([0, 1, 2, 3]), f_agg="min", chunk_len=2),
[0, 2],
)
self.assertListEqual(
_aggregate_on_chunks(
x=pd.Series([0, 1, 2, 3, 5]), f_agg="min", chunk_len=2
),
[0, 2, 5],
)
self.assertListEqual(
_aggregate_on_chunks(x=pd.Series([0, 1, 2, 3]), f_agg="mean", chunk_len=2),
[0.5, 2.5],
)
self.assertListEqual(
_aggregate_on_chunks(
x=pd.Series([0, 1, 0, 4, 5]), f_agg="mean", chunk_len=2
),
[0.5, 2, 5],
)
self.assertListEqual(
_aggregate_on_chunks(
x=pd.Series([0, 1, 0, 4, 5]), f_agg="mean", chunk_len=3
),
[1 / 3, 4.5],
)
self.assertListEqual(
_aggregate_on_chunks(
x=pd.Series([0, 1, 2, 3, 5, -2]), f_agg="median", chunk_len=2
),
[0.5, 2.5, 1.5],
)
self.assertListEqual(
_aggregate_on_chunks(
x=pd.Series([-10, 5, 3, -3, 4, -6]), f_agg="median", chunk_len=3
),
[3, -3],
)
self.assertListEqual(
_aggregate_on_chunks(
x=pd.Series([0, 1, 2, np.NaN, 5]), f_agg="median", chunk_len=2
),
[0.5, 2, 5],
)
def test_agg_linear_trend(self):
x = pd.Series(range(9), index=range(9))
param = [
{"attr": "intercept", "chunk_len": 3, "f_agg": "max"},
{"attr": "slope", "chunk_len": 3, "f_agg": "max"},
{"attr": "intercept", "chunk_len": 3, "f_agg": "min"},
{"attr": "slope", "chunk_len": 3, "f_agg": "min"},
{"attr": "intercept", "chunk_len": 3, "f_agg": "mean"},
{"attr": "slope", "chunk_len": 3, "f_agg": "mean"},
{"attr": "intercept", "chunk_len": 3, "f_agg": "median"},
{"attr": "slope", "chunk_len": 3, "f_agg": "median"},
]
expected_index = [
'attr_"intercept"__chunk_len_3__f_agg_"max"',
'attr_"slope"__chunk_len_3__f_agg_"max"',
'attr_"intercept"__chunk_len_3__f_agg_"min"',
'attr_"slope"__chunk_len_3__f_agg_"min"',
'attr_"intercept"__chunk_len_3__f_agg_"mean"',
'attr_"slope"__chunk_len_3__f_agg_"mean"',
'attr_"intercept"__chunk_len_3__f_agg_"median"',
'attr_"slope"__chunk_len_3__f_agg_"median"',
]
res = agg_linear_trend(x=x, param=param)
res = pd.Series(dict(res))
self.assertEqual(len(res), 8)
self.maxDiff = 2000
self.assertCountEqual(list(res.index), expected_index)
self.assertAlmostEqual(res['attr_"intercept"__chunk_len_3__f_agg_"max"'], 2)
self.assertAlmostEqual(res['attr_"slope"__chunk_len_3__f_agg_"max"'], 3)
self.assertAlmostEqual(res['attr_"intercept"__chunk_len_3__f_agg_"min"'], 0)
self.assertAlmostEqual(res['attr_"slope"__chunk_len_3__f_agg_"min"'], 3)
self.assertAlmostEqual(res['attr_"intercept"__chunk_len_3__f_agg_"mean"'], 1)
self.assertAlmostEqual(res['attr_"slope"__chunk_len_3__f_agg_"mean"'], 3)
self.assertAlmostEqual(res['attr_"intercept"__chunk_len_3__f_agg_"median"'], 1)
self.assertAlmostEqual(res['attr_"slope"__chunk_len_3__f_agg_"median"'], 3)
x = pd.Series([np.NaN, np.NaN, np.NaN, -3, -3, -3])
res = agg_linear_trend(x=x, param=param)
res = pd.Series(dict(res))
self.assertIsNaN(res['attr_"intercept"__chunk_len_3__f_agg_"max"'])
self.assertIsNaN(res['attr_"slope"__chunk_len_3__f_agg_"max"'])
self.assertIsNaN(res['attr_"intercept"__chunk_len_3__f_agg_"min"'])
self.assertIsNaN(res['attr_"slope"__chunk_len_3__f_agg_"min"'])
self.assertIsNaN(res['attr_"intercept"__chunk_len_3__f_agg_"mean"'])
self.assertIsNaN(res['attr_"slope"__chunk_len_3__f_agg_"mean"'])
self.assertIsNaN(res['attr_"intercept"__chunk_len_3__f_agg_"median"'])
self.assertIsNaN(res['attr_"slope"__chunk_len_3__f_agg_"median"'])
x = pd.Series([np.NaN, np.NaN, -3, -3, -3, -3])
res = agg_linear_trend(x=x, param=param)
res = pd.Series(dict(res))
self.assertAlmostEqual(res['attr_"intercept"__chunk_len_3__f_agg_"max"'], -3)
self.assertAlmostEqual(res['attr_"slope"__chunk_len_3__f_agg_"max"'], 0)
self.assertAlmostEqual(res['attr_"intercept"__chunk_len_3__f_agg_"min"'], -3)
self.assertAlmostEqual(res['attr_"slope"__chunk_len_3__f_agg_"min"'], 0)
self.assertAlmostEqual(res['attr_"intercept"__chunk_len_3__f_agg_"mean"'], -3)
self.assertAlmostEqual(res['attr_"slope"__chunk_len_3__f_agg_"mean"'], 0)
self.assertAlmostEqual(res['attr_"intercept"__chunk_len_3__f_agg_"median"'], -3)
self.assertAlmostEqual(res['attr_"slope"__chunk_len_3__f_agg_"median"'], 0)
def test_energy_ratio_by_chunks(self):
x = pd.Series(range(90), index=range(90))
param = [{"num_segments": 6, "segment_focus": i} for i in range(6)]
output = energy_ratio_by_chunks(x=x, param=param)
self.assertAlmostEqual(output[0][1], 0.0043, places=3)
self.assertAlmostEqual(output[1][1], 0.0316, places=3)
self.assertAlmostEqual(output[2][1], 0.0871, places=3)
self.assertAlmostEqual(output[3][1], 0.1709, places=3)
self.assertAlmostEqual(output[4][1], 0.2829, places=3)
self.assertAlmostEqual(output[5][1], 0.4232, places=3)
# Sum of the ratios should be 1.0
sum = 0.0
for name, dat in output:
sum = sum + dat
self.assertAlmostEqual(sum, 1.0)
x = pd.Series(1, index=range(10))
param = [{"num_segments": 3, "segment_focus": i} for i in range(3)]
output = energy_ratio_by_chunks(x=x, param=param)
self.assertAlmostEqual(output[0][1], 0.4, places=3)
self.assertAlmostEqual(output[1][1], 0.3, places=3)
self.assertAlmostEqual(output[2][1], 0.3, places=3)
# Sum of the ratios should be 1.0
sum = 0.0
for name, dat in output:
sum = sum + dat
self.assertAlmostEqual(sum, 1.0)
x = pd.Series(0, index=range(10))
param = [{"num_segments": 3, "segment_focus": i} for i in range(3)]
output = energy_ratio_by_chunks(x=x, param=param)
self.assertIsNaN(output[0][1])
self.assertIsNaN(output[1][1])
self.assertIsNaN(output[2][1])
def test_linear_trend_timewise_hours(self):
"""Test linear_trend_timewise function with hour intervals."""
x = pd.Series(
[0, 1, 3, 6],
index=pd.DatetimeIndex(
[
"2018-01-01 04:00:00",
"2018-01-01 05:00:00",
"2018-01-01 07:00:00",
"2018-01-01 10:00:00",
]
),
)
param = [
{"attr": "pvalue"},
{"attr": "rvalue"},
{"attr": "intercept"},
{"attr": "slope"},
{"attr": "stderr"},
]
res = linear_trend_timewise(x, param)
res = pd.Series(dict(res))
expected_index = [
'attr_"pvalue"',
'attr_"intercept"',
'attr_"rvalue"',
'attr_"slope"',
'attr_"stderr"',
]
self.assertEqual(len(res), 5)
self.assertCountEqual(list(res.index), expected_index)
self.assertAlmostEqual(res['attr_"pvalue"'], 0, places=3)
self.assertAlmostEqual(res['attr_"stderr"'], 0, places=3)
self.assertAlmostEqual(res['attr_"intercept"'], 0, places=3)
self.assertAlmostEqual(res['attr_"slope"'], 1.0, places=3)
def test_linear_trend_timewise_days(self):
"""Test linear_trend_timewise function with day intervals."""
# Try with different days
x = pd.Series(
[0, 24, 48, 72],
index=pd.DatetimeIndex(
[
"2018-01-01 04:00:00",
"2018-01-02 04:00:00",
"2018-01-03 04:00:00",
"2018-01-04 04:00:00",
]
),
)
param = [
{"attr": "pvalue"},
{"attr": "rvalue"},
{"attr": "intercept"},
{"attr": "slope"},
{"attr": "stderr"},
]
res = linear_trend_timewise(x, param)
res = pd.Series(dict(res))
self.assertAlmostEqual(res['attr_"pvalue"'], 0, places=3)
self.assertAlmostEqual(res['attr_"stderr"'], 0, places=3)
self.assertAlmostEqual(res['attr_"intercept"'], 0, places=3)
self.assertAlmostEqual(res['attr_"slope"'], 1.0, places=3)
def test_linear_trend_timewise_seconds(self):
"""Test linear_trend_timewise function with second intervals."""
# Try with different days
x = pd.Series(
[0, 1 / float(3600), 2 / float(3600), 3 / float(3600)],
index=pd.DatetimeIndex(
[
"2018-01-01 04:00:01",
"2018-01-01 04:00:02",
"2018-01-01 04:00:03",
"2018-01-01 04:00:04",
]
),
)
param = [
{"attr": "pvalue"},
{"attr": "rvalue"},
{"attr": "intercept"},
{"attr": "slope"},
{"attr": "stderr"},
]
res = linear_trend_timewise(x, param)
res = pd.Series(dict(res))
self.assertAlmostEqual(res['attr_"pvalue"'], 0, places=3)
self.assertAlmostEqual(res['attr_"stderr"'], 0, places=3)
self.assertAlmostEqual(res['attr_"intercept"'], 0, places=3)
self.assertAlmostEqual(res['attr_"slope"'], 1.0, places=3)
def test_linear_trend_timewise_years(self):
"""Test linear_trend_timewise function with year intervals."""
# Try with different days
x = pd.Series(
[
0,
365 * 24,
365 * 48,
365 * 72 + 24,
], # Add 24 to the last one since it's a leap year
index=pd.DatetimeIndex(
[
"2018-01-01 04:00:00",
"2019-01-01 04:00:00",
"2020-01-01 04:00:00",
"2021-01-01 04:00:00",
]
),
)
param = [
{"attr": "pvalue"},
{"attr": "rvalue"},
{"attr": "intercept"},
{"attr": "slope"},
{"attr": "stderr"},
]
res = linear_trend_timewise(x, param)
res = pd.Series(dict(res))
self.assertAlmostEqual(res['attr_"pvalue"'], 0, places=3)
self.assertAlmostEqual(res['attr_"stderr"'], 0, places=3)
self.assertAlmostEqual(res['attr_"intercept"'], 0, places=3)
self.assertAlmostEqual(res['attr_"slope"'], 1.0, places=3)
def test_change_quantiles(self):
"""Test change_quantiles function when changing from `sum` to `np.sum`."""
np.random.seed(0)
res = change_quantiles(np.random.rand(10000) * 1000, 0.1, 0.2, False, "mean")
self.assertAlmostEqual(res, -0.9443846621365727)
def test_count_above(self):
self.assertEqualPandasSeriesWrapper(count_above, [1] * 10, 1, t=1)
self.assertEqualPandasSeriesWrapper(count_above, list(range(10)), 1, t=0)
self.assertEqualPandasSeriesWrapper(count_above, list(range(10)), 0.5, t=5)
self.assertEqualPandasSeriesWrapper(
count_above, [0.1, 0.2, 0.3] * 3, 2 / 3, t=0.2
)
self.assertEqualPandasSeriesWrapper(count_above, [np.NaN, 0, 1] * 3, 2 / 3, t=0)
self.assertEqualPandasSeriesWrapper(
count_above, [np.NINF, 0, 1] * 3, 2 / 3, t=0
)
self.assertEqualPandasSeriesWrapper(count_above, [np.PINF, 0, 1] * 3, 1, t=0)
self.assertEqualPandasSeriesWrapper(
count_above, [np.NaN, 0, 1] * 3, 0, t=np.NaN
)
self.assertEqualPandasSeriesWrapper(
count_above, [np.NINF, 0, np.PINF] * 3, 1, t=np.NINF
)
self.assertEqualPandasSeriesWrapper(
count_above, [np.PINF, 0, 1] * 3, 1 / 3, t=np.PINF
)
def test_count_below(self):
self.assertEqualPandasSeriesWrapper(count_below, [1] * 10, 1, t=1)
self.assertEqualPandasSeriesWrapper(count_below, list(range(10)), 1 / 10, t=0)
self.assertEqualPandasSeriesWrapper(count_below, list(range(10)), 6 / 10, t=5)
self.assertEqualPandasSeriesWrapper(
count_below, [0.1, 0.2, 0.3] * 3, 2 / 3, t=0.2
)
self.assertEqualPandasSeriesWrapper(count_below, [np.NaN, 0, 1] * 3, 1 / 3, t=0)
self.assertEqualPandasSeriesWrapper(
count_below, [np.NINF, 0, 1] * 3, 2 / 3, t=0
)
self.assertEqualPandasSeriesWrapper(
count_below, [np.PINF, 0, 1] * 3, 1 / 3, t=0
)
self.assertEqualPandasSeriesWrapper(
count_below, [np.NaN, 0, 1] * 3, 0, t=np.NaN
)
self.assertEqualPandasSeriesWrapper(
count_below, [np.NINF, 0, np.PINF] * 3, 1 / 3, t=np.NINF
)
self.assertEqualPandasSeriesWrapper(
count_below, [np.PINF, 0, 1] * 3, 1, t=np.PINF
)
def test_benford_correlation(self):
# A test with list of random values
np.random.seed(42)
random_list = np.random.uniform(size=100)
# Fibonacci series is known to match the Newcomb-Benford's Distribution
fibonacci_list = [0, 1]
for i in range(2, 200):
fibonacci_list.append(fibonacci_list[i - 1] + fibonacci_list[i - 2])
# A list of equally distributed digits (returns NaN)
equal_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# A list containing NaN
list_with_nan = [
1.354,
0.058,
0.055,
0.99,
3.15,
np.nan,
0.3,
2.3,
0,
0.59,
0.74,
]
self.assertAlmostEqual(benford_correlation(random_list), 0.39458056)
self.assertAlmostEqual(benford_correlation(fibonacci_list), 0.998003988)
self.assertAlmostEqual(benford_correlation(list_with_nan), 0.10357511)
self.assertIsNaN(benford_correlation(equal_list))
def test_query_similarity_count(self):
np.random.seed(42)
query = np.random.uniform(size=10)
threshold = 3.0
x = np.random.uniform(size=100)
# z-normalized Euclidean distances
param = [{"query": query}]
self.assertAlmostEqual(query_similarity_count(x, param=param)[0][1], 0.0)
param = [{"query": query, "threshold": threshold}]
self.assertAlmostEqual(query_similarity_count(x, param=param)[0][1], 6.0)
# non-normalized Euclidean distances
param = [{"query": query, "normalize": False}]
self.assertAlmostEqual(query_similarity_count(x, param=param)[0][1], 0.0)
param = [{"query": query, "threshold": threshold, "normalize": False}]
self.assertAlmostEqual(query_similarity_count(x, param=param)[0][1], 91.0)
def test_matrix_profile_window(self):
# Test matrix profile output with specified window
np.random.seed(9999)
ts = np.random.uniform(size=2 ** 10)
w = 2 ** 5
subq = ts[0:w]
ts[0:w] = subq
ts[w + 100 : w + 100 + w] = subq
param = [
{"threshold": 0.98, "windows": 36, "feature": "min"},
{"threshold": 0.98, "windows": 36, "feature": "max"},
{"threshold": 0.98, "windows": 36, "feature": "mean"},
{"threshold": 0.98, "windows": 36, "feature": "median"},
{"threshold": 0.98, "windows": 36, "feature": "25"},
{"threshold": 0.98, "windows": 36, "feature": "75"},
]
self.assertAlmostEqual(matrix_profile(ts, param=param)[0][1], 2.825786727580335)
def test_matrix_profile_no_window(self):
# Test matrix profile output with no window specified
np.random.seed(9999)
ts = np.random.uniform(size=2 ** 10)
w = 2 ** 5
subq = ts[0:w]
ts[0:w] = subq
ts[w + 100 : w + 100 + w] = subq
param = [
{"threshold": 0.98, "feature": "min"},
{"threshold": 0.98, "feature": "max"},
{"threshold": 0.98, "feature": "mean"},
{"threshold": 0.98, "feature": "median"},
{"threshold": 0.98, "feature": "25"},
{"threshold": 0.98, "feature": "75"},
]
# Test matrix profile output with no window specified
self.assertAlmostEqual(matrix_profile(ts, param=param)[0][1], 2.825786727580335)
def test_matrix_profile_nan(self):
# Test matrix profile of NaNs (NaN output)
ts = np.random.uniform(size=2 ** 6)
ts[:] = np.nan
param = [
{"threshold": 0.98, "windows": None, "feature": "min"},
{"threshold": 0.98, "windows": None, "feature": "max"},
{"threshold": 0.98, "windows": None, "feature": "mean"},
{"threshold": 0.98, "windows": None, "feature": "median"},
{"threshold": 0.98, "windows": None, "feature": "25"},
{"threshold": 0.98, "windows": None, "feature": "75"},
]
self.assertTrue(np.isnan(matrix_profile(ts, param=param)[0][1]))
class FriedrichTestCase(TestCase):
def test_estimate_friedrich_coefficients(self):
"""
Estimate friedrich coefficients
"""
default_params = {"m": 3, "r": 30}
# active Brownian motion
ds = velocity(tau=3.8, delta_t=0.05, R=3e-4, seed=0)
v = ds.simulate(10000, v0=np.zeros(1))
coeff = _estimate_friedrich_coefficients(v[:, 0], **default_params)
self.assertLess(abs(coeff[-1]), 0.0001)
# Brownian motion
ds = velocity(tau=2.0 / 0.3 - 3.8, delta_t=0.05, R=3e-4, seed=0)
v = ds.simulate(10000, v0=np.zeros(1))
coeff = _estimate_friedrich_coefficients(v[:, 0], **default_params)
self.assertLess(abs(coeff[-1]), 0.0001)
def test_friedrich_coefficients(self):
# Test binning error returns vector of NaNs
param = [{"coeff": coeff, "m": 2, "r": 30} for coeff in range(4)]
x = np.zeros(100)
res = pd.Series(dict(friedrich_coefficients(x, param)))
expected_index = [
"coeff_0__m_2__r_30",
"coeff_1__m_2__r_30",
"coeff_2__m_2__r_30",
"coeff_3__m_2__r_30",
]
self.assertCountEqual(list(res.index), expected_index)
self.assertTrue(np.sum(np.isnan(res)), 3)
def test_friedrich_number_of_returned_features_is_equal_to_number_of_parameters(
self,
):
"""unit test for issue 501"""
param = [
{"m": 3, "r": 5, "coeff": 2},
{"m": 3, "r": 5, "coeff": 3},
{"m": 3, "r": 2, "coeff": 3},
]
x = np.zeros(100)
res = pd.Series(dict(friedrich_coefficients(x, param)))
expected_index = ["coeff_2__m_3__r_5", "coeff_3__m_3__r_5", "coeff_3__m_3__r_2"]
self.assertCountEqual(list(res.index), expected_index)
self.assertTrue(np.sum(np.isnan(res)), 3)
def test_friedrich_equal_to_snapshot(self):
param = [{"coeff": coeff, "m": 2, "r": 30} for coeff in range(4)]
x = np.array(
[
-0.53,
-0.61,
-1.26,
-0.88,
-0.34,
0.58,
2.86,
-0.47,
0.78,
-0.45,
-0.27,
0.43,
1.72,
0.26,
1.02,
-0.09,
0.65,
1.49,
-0.95,
-1.02,
-0.64,
-1.63,
-0.71,
-0.43,
-1.69,
0.05,
1.58,
1.1,
0.55,
-1.02,
]
)
res = pd.Series(dict(friedrich_coefficients(x, param)))
self.assertAlmostEqual(res["coeff_0__m_2__r_30"], -0.24536975738843042)
self.assertAlmostEqual(res["coeff_1__m_2__r_30"], -0.533309548662685)
self.assertAlmostEqual(res["coeff_2__m_2__r_30"], 0.2759399238199404)<|fim▁end|> | {"k": 2, "coeff": 3},
] |
<|file_name|>processVideo.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Created on Fri Oct 14 15:30:11 2016
@author: worm_rig
"""
import json
import os
import tables
from tierpsy.analysis.compress.compressVideo import compressVideo, initMasksGroups
from tierpsy.analysis.compress.selectVideoReader import selectVideoReader
from tierpsy.helper.misc import TimeCounter, print_flush
#default parameters if wormencoder.ini does not exist
DFLT_SAVE_FULL_INTERVAL = 5000
DFLT_BUFFER_SIZE = 5
DFLT_MASK_PARAMS = {'min_area' : 50,
'max_area' : 500000000,
'thresh_C' : 15,
'thresh_block_size' : 61,
'dilation_size' : 7
}
def _getWormEnconderParams(fname):
def numOrStr(x):
x = x.strip()
try:
return int(x)
except:
return x
if os.path.exists(fname):
with open(fname, 'r') as fid:
dd = fid.read().split('\n')
plugin_params = {a.strip() : numOrStr(b) for a,b in
[x.split('=') for x in dd if x and x[0].isalpha()]}
else:
plugin_params = {}
return plugin_params
def _getReformatParams(plugin_params):
if plugin_params:
save_full_interval = plugin_params['UNMASKEDFRAMES']
buffer_size = plugin_params['MASK_RECALC_RATE']
mask_params = {'min_area' : plugin_params['MINBLOBSIZE'],
'max_area' : plugin_params['MAXBLOBSIZE'],
'thresh_C' : plugin_params['THRESHOLD_C'],
'thresh_block_size' : plugin_params['THRESHOLD_BLOCK_SIZE'],
'dilation_size' : plugin_params['DILATION_KERNEL_SIZE']}
else:
#if an empty dictionary was given return default values
save_full_interval = DFLT_SAVE_FULL_INTERVAL
buffer_size = DFLT_BUFFER_SIZE
mask_params = DFLT_MASK_PARAMS
return save_full_interval, buffer_size, mask_params
def _isValidSource(original_file):
try:
with tables.File(original_file, 'r') as fid:
fid.get_node('/mask')
return True
except tables.exceptions.HDF5ExtError:
return False
def reformatRigMaskedVideo(original_file, new_file, plugin_param_file, expected_fps, microns_per_pixel):
plugin_params = _getWormEnconderParams(plugin_param_file)
base_name = original_file.rpartition('.')[0].rpartition(os.sep)[-1]
if not _isValidSource(original_file):
print_flush(new_file + ' ERROR. File might be corrupt. ' + original_file)
return
save_full_interval, buffer_size, mask_params = _getReformatParams(plugin_params)
with tables.File(original_file, 'r') as fid_old, \
tables.File(new_file, 'w') as fid_new:
mask_old = fid_old.get_node('/mask')
tot_frames, im_height, im_width = mask_old.shape
progress_timer = TimeCounter('Reformating Gecko plugin hdf5 video.', tot_frames)
attr_params = dict(
expected_fps = expected_fps,
microns_per_pixel = microns_per_pixel,<|fim▁hole|> )
mask_new, full_new, _ = initMasksGroups(fid_new, tot_frames, im_height, im_width,
attr_params, save_full_interval, is_expandable=False)
mask_new.attrs['plugin_params'] = json.dumps(plugin_params)
img_buff_ini = mask_old[:buffer_size]
full_new[0] = img_buff_ini[0]
mask_new[:buffer_size] = img_buff_ini*(mask_old[buffer_size] != 0)
for frame in range(buffer_size, tot_frames):
if frame % save_full_interval != 0:
mask_new[frame] = mask_old[frame]
else:
full_frame_n = frame //save_full_interval
img = mask_old[frame]
full_new[full_frame_n] = img
mask_new[frame] = img*(mask_old[frame-1] != 0)
if frame % 500 == 0:
# calculate the progress and put it in a string
progress_str = progress_timer.get_str(frame)
print_flush(base_name + ' ' + progress_str)
print_flush(
base_name +
' Compressed video done. Total time:' +
progress_timer.get_time_str())
def isGoodVideo(video_file):
try:
vid = selectVideoReader(video_file)
# i have problems with corrupt videos that can create infinite loops...
#it is better to test it before start a large taks
vid.release()
return True
except OSError:
# corrupt file, cannot read the size
return False
def processVideo(video_file, masked_image_file, compress_vid_param):
if video_file.endswith('hdf5'):
plugin_param_file = os.path.join(os.path.dirname(video_file), 'wormencoder.ini')
expected_fps = compress_vid_param['expected_fps']
microns_per_pixel = compress_vid_param['microns_per_pixel']
reformatRigMaskedVideo(video_file, masked_image_file, plugin_param_file, expected_fps=expected_fps, microns_per_pixel=microns_per_pixel)
else:
compressVideo(video_file, masked_image_file, **compress_vid_param)
if __name__ == '__main__':
import argparse
fname_wenconder = os.path.join(os.path.dirname(__file__), 'wormencoder.ini')
parser = argparse.ArgumentParser(description='Reformat the files produced by the Gecko plugin in to the format of tierpsy.')
parser.add_argument('original_file', help='path of the original file produced by the plugin')
parser.add_argument('new_file', help='new file name')
parser.add_argument(
'--plugin_param_file',
default = fname_wenconder,
help='wormencoder file used by the Gecko plugin.')
parser.add_argument(
'--expected_fps',
default=25,
help='Expected recording rate in frame per seconds.')
args = parser.parse_args()
reformatRigMaskedVideo(**vars(args))<|fim▁end|> | is_light_background = True |
<|file_name|>graph2.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from collections import defaultdict
from functools import partial
from itertools import count
import json
import networkx as nx
from networkx.algorithms import weakly_connected_component_subgraphs
from numpy import subtract
from numpy.linalg import norm
from typing import Any, DefaultDict, Dict, List, Optional, Tuple, Union
from django.db import connection
from django.http import JsonResponse
from rest_framework.decorators import api_view
from catmaid.models import UserRole
from catmaid.control.authentication import requires_user_role
from catmaid.control.common import (get_relation_to_id_map, get_request_bool,
get_request_list)
from catmaid.control.link import KNOWN_LINK_PAIRS, UNDIRECTED_LINK_TYPES
from catmaid.control.tree_util import simplify
from catmaid.control.synapseclustering import tree_max_density
def make_new_synapse_count_array() -> List[int]:
return [0, 0, 0, 0, 0]
def basic_graph(project_id, skeleton_ids, relations=None,
source_link:str="presynaptic_to", target_link:str="postsynaptic_to",
allowed_connector_ids=None) -> Dict[str, Tuple]:
if not skeleton_ids:
raise ValueError("No skeleton IDs provided")
cursor = connection.cursor()
if not relations:
relations = get_relation_to_id_map(project_id, (source_link, target_link), cursor)
source_rel_id, target_rel_id = relations[source_link], relations[target_link]
undirected_links = source_link in UNDIRECTED_LINK_TYPES and \
target_link in UNDIRECTED_LINK_TYPES
# Find all links in the passed in set of skeletons. If a relation is
# reciprocal, we need to avoid getting two result rows back for each
# treenode-connector-treenode connection. To keep things simple, we will add
# a "skeleton ID 1" < "skeleton ID 2" test for reciprocal links.
cursor.execute(f"""
SELECT t1.skeleton_id, t2.skeleton_id, LEAST(t1.confidence, t2.confidence)
FROM treenode_connector t1,
treenode_connector t2
WHERE t1.skeleton_id = ANY(%(skeleton_ids)s::bigint[])
AND t1.relation_id = %(source_rel)s
AND t1.connector_id = t2.connector_id
AND t2.skeleton_id = ANY(%(skeleton_ids)s::bigint[])
AND t2.relation_id = %(target_rel)s
AND t1.id <> t2.id
{'AND t1.skeleton_id < t2.skeleton_id' if undirected_links else ''}
{'AND t1.connector_id = ANY(%(allowed_c_ids)s::bigint[])' if allowed_connector_ids else ''}
""", {
'skeleton_ids': list(skeleton_ids),
'source_rel': source_rel_id,
'target_rel': target_rel_id,
'allowed_c_ids': allowed_connector_ids,
})
edges:DefaultDict = defaultdict(partial(defaultdict, make_new_synapse_count_array))
for row in cursor.fetchall():
edges[row[0]][row[1]][row[2] - 1] += 1
return {
'edges': tuple((s, t, count)
for s, edge in edges.items()
for t, count in edge.items())
}
def confidence_split_graph(project_id, skeleton_ids, confidence_threshold,
relations=None, source_rel:str="presynaptic_to",
target_rel:str="postsynaptic_to", allowed_connector_ids=None) -> Dict[str, Any]:
""" Assumes 0 < confidence_threshold <= 5. """
if not skeleton_ids:
raise ValueError("No skeleton IDs provided")
# We need skeleton IDs as a list
skeleton_ids = list(skeleton_ids)
cursor = connection.cursor()
if not relations:
relations = get_relation_to_id_map(project_id, (source_rel, target_rel), cursor)
source_rel_id, target_rel_id = relations[source_rel], relations[target_rel]
# Fetch (valid) synapses of all skeletons
cursor.execute(f'''
SELECT skeleton_id, treenode_id, connector_id, relation_id, confidence
FROM treenode_connector
WHERE project_id = %(project_id)s
AND skeleton_id = ANY(%(skids)s::bigint[])
AND relation_id IN (%(source_rel_id)s, %(target_rel_id)s)
{'AND connector_id = ANY(%(allowed_c_ids)s::bigint[])' if allowed_connector_ids else ''}
''', {
'project_id': int(project_id),
'skids': skeleton_ids,
'source_rel_id': source_rel_id,
'target_rel_id': target_rel_id,
'allowed_c_ids': allowed_connector_ids,
})
stc:DefaultDict[Any, List] = defaultdict(list)
for row in cursor.fetchall():
stc[row[0]].append(row[1:]) # skeleton_id vs (treenode_id, connector_id, relation_id, confidence)
# Fetch all treenodes of all skeletons
cursor.execute('''
SELECT skeleton_id, id, parent_id, confidence
FROM treenode
WHERE project_id = %(project_id)s
AND skeleton_id = ANY(%(skeleton_ids)s::bigint[])
ORDER BY skeleton_id
''', {
'project_id': project_id,
'skeleton_ids': skeleton_ids,
})
# Dictionary of connector_id vs relation_id vs list of sub-skeleton ID
connectors:DefaultDict = defaultdict(partial(defaultdict, list))
# All nodes of the graph
nodeIDs:List = []
# Read out into memory only one skeleton at a time
current_skid = None
tree:Optional[nx.DiGraph] = None
for row in cursor.fetchall():
if row[0] == current_skid:
# Build the tree, breaking it at the low-confidence edges
if row[2] and row[3] >= confidence_threshold:
# mypy cannot prove this will be a DiGraph by here
tree.add_edge(row[2], row[1]) # type: ignore
continue
if tree:
nodeIDs.extend(split_by_confidence(current_skid, tree, stc[current_skid], connectors))
# Start the next tree
current_skid = row[0]
tree = nx.DiGraph()
if row[2] and row[3] > confidence_threshold:
tree.add_edge(row[2], row[1])
if tree:
nodeIDs.extend(split_by_confidence(current_skid, tree, stc[current_skid], connectors))
# Create the edges of the graph from the connectors, which was populated as a side effect of 'split_by_confidence'
edges:DefaultDict = defaultdict(partial(defaultdict, make_new_synapse_count_array)) # pre vs post vs count
for c in connectors.values():
for pre in c[source_rel_id]:
for post in c[target_rel_id]:
edges[pre[0]][post[0]][min(pre[1], post[1]) - 1] += 1
return {
'nodes': nodeIDs,
'edges': [(s, t, count)
for s, edge in edges.items()
for t, count in edge.items()]
}
def dual_split_graph(project_id, skeleton_ids, confidence_threshold, bandwidth,
expand, relations=None, source_link="presynaptic_to",
target_link="postsynaptic_to", allowed_connector_ids=None) -> Dict[str, Any]:
""" Assumes bandwidth > 0 and some skeleton_id in expand. """
cursor = connection.cursor()
skeleton_ids = set(skeleton_ids)
expand = set(expand)
if not skeleton_ids:
raise ValueError("No skeleton IDs provided")
if not relations:
relations = get_relation_to_id_map(project_id, (source_link, target_link), cursor)
source_rel_id, target_rel_id = relations[source_link], relations[target_link]
# Fetch synapses of all skeletons
cursor.execute(f'''
SELECT skeleton_id, treenode_id, connector_id, relation_id, confidence
FROM treenode_connector
WHERE project_id = %(project_id)s
AND skeleton_id = ANY(%(skids)s::bigint[])
AND relation_id IN (%(source_rel_id)s, %(target_rel_id)s)
{'AND connector_id = ANY(%(allowed_c_ids)s::bigint[])' if allowed_connector_ids else ''}
''', {
'project_id': int(project_id),
'skids': list(skeleton_ids),
'source_rel_id': source_rel_id,
'target_rel_id': target_rel_id,
'allowed_c_ids': allowed_connector_ids,
})
stc:DefaultDict[Any, List] = defaultdict(list)
for row in cursor.fetchall():
stc[row[0]].append(row[1:]) # skeleton_id vs (treenode_id, connector_id, relation_id)
# Dictionary of connector_id vs relation_id vs list of sub-skeleton ID
connectors:DefaultDict = defaultdict(partial(defaultdict, list))
# All nodes of the graph (with or without edges. Includes those representing synapse domains)
nodeIDs:List = []
not_to_expand = skeleton_ids - expand
if confidence_threshold > 0 and not_to_expand:
# Now fetch all treenodes of only skeletons in skeleton_ids (the ones not to expand)
cursor.execute('''
SELECT skeleton_id, id, parent_id, confidence
FROM treenode
WHERE project_id = %(project_id)s
AND skeleton_id = ANY(%(skids)s::bigint[])
ORDER BY skeleton_id
''', {
'project_id': project_id,
'skids': list(not_to_expand),
})
# Read out into memory only one skeleton at a time
current_skid = None
tree:Optional[nx.DiGraph] = None
for row in cursor.fetchall():
if row[0] == current_skid:
# Build the tree, breaking it at the low-confidence edges
if row[2] and row[3] >= confidence_threshold:
# mypy cannot prove this will be a nx.DiGraph by here
tree.add_edge(row[2], row[1]) # type: ignore
continue
if tree:
nodeIDs.extend(split_by_confidence(current_skid, tree, stc[current_skid], connectors))
# Start the next tree
current_skid = row[0]
tree = nx.DiGraph()<|fim▁hole|>
if tree:
nodeIDs.extend(split_by_confidence(current_skid, tree, stc[current_skid], connectors))
else:
# No need to split.
# Populate connectors from the connections among them
for skid in not_to_expand:
nodeIDs.append(skid)
for c in stc[skid]:
connectors[c[1]][c[2]].append((skid, c[3]))
# Now fetch all treenodes of all skeletons to expand
cursor.execute('''
SELECT skeleton_id, id, parent_id, confidence, location_x, location_y, location_z
FROM treenode
WHERE project_id = %(project_id)s
AND skeleton_id = ANY(%(skids)s::bigint[])
ORDER BY skeleton_id
''', {
'project_id': project_id,
'skids': list(expand),
})
# list of edges among synapse domains
intraedges:List = []
# list of branch nodes, merely structural
branch_nodeIDs:List = []
# reset
current_skid = None
tree = None
locations:Optional[Dict] = None
for row in cursor.fetchall():
if row[0] == current_skid:
# Build the tree, breaking it at the low-confidence edges
# mypy cannot prove this will have a value by here
locations[row[1]] = row[4:] # type: ignore
if row[2] and row[3] >= confidence_threshold:
# mypy cannot prove this will have a value by here
tree.add_edge(row[2], row[1]) # type: ignore
continue
if tree:
ns, bs = split_by_both(current_skid, tree, locations, bandwidth, stc[current_skid], connectors, intraedges)
nodeIDs.extend(ns)
branch_nodeIDs.extend(bs)
# Start the next tree
current_skid = row[0]
tree = nx.DiGraph()
locations = {}
locations[row[1]] = row[4:]
if row[2] and row[3] > confidence_threshold:
tree.add_edge(row[2], row[1])
if tree:
ns, bs = split_by_both(current_skid, tree, locations, bandwidth, stc[current_skid], connectors, intraedges)
nodeIDs.extend(ns)
branch_nodeIDs.extend(bs)
# Create the edges of the graph
edges:DefaultDict = defaultdict(partial(defaultdict, make_new_synapse_count_array)) # pre vs post vs count
for c in connectors.values():
for pre in c[source_rel_id]:
for post in c[target_rel_id]:
edges[pre[0]][post[0]][min(pre[1], post[1]) - 1] += 1
return {
'nodes': nodeIDs,
'edges': [(s, t, count)
for s, edge in edges.items()
for t, count in edge.items()],
'branch_nodes': branch_nodeIDs,
'intraedges': intraedges
}
def populate_connectors(chunkIDs, chunks, cs, connectors) -> None:
# Build up edges via the connectors
for c in cs:
# c is (treenode_id, connector_id, relation_id, confidence)
for chunkID, chunk in zip(chunkIDs, chunks):
if c[0] in chunk:
connectors[c[1]][c[2]].append((chunkID, c[3]))
break
def subgraphs(digraph, skeleton_id) -> Tuple[List, Tuple]:
chunks = list(weakly_connected_component_subgraphs(digraph))
if 1 == len(chunks):
chunkIDs:Tuple = (str(skeleton_id),) # Note: Here we're loosening the implicit type
else:
chunkIDs = tuple('%s_%s' % (skeleton_id, (i+1)) for i in range(len(chunks)))
return chunks, chunkIDs
def split_by_confidence(skeleton_id, digraph, cs, connectors) -> Tuple:
""" Split by confidence threshold. Populates connectors (side effect). """
chunks, chunkIDs = subgraphs(digraph, skeleton_id)
populate_connectors(chunkIDs, chunks, cs, connectors)
return chunkIDs
def split_by_both(skeleton_id, digraph, locations, bandwidth, cs, connectors, intraedges) -> Tuple[List, List]:
""" Split by confidence and synapse domain. Populates connectors and intraedges (side effects). """
nodes = []
branch_nodes = []
chunks, chunkIDs = subgraphs(digraph, skeleton_id)
for i, chunkID, chunk in zip(count(start=1), chunkIDs, chunks):
# Populate edge properties with the weight
for parent, child in chunk.edges_iter():
chunk[parent][child]['weight'] = norm(subtract(locations[child], locations[parent]))
# Check if need to expand at all
blob = tuple(c for c in cs if c[0] in chunk)
if 0 == len(blob): # type: ignore
nodes.append(chunkID)
continue
treenode_ids, connector_ids, relation_ids, confidences = list(zip(*blob)) # type: ignore
if 0 == len(connector_ids):
nodes.append(chunkID)
continue
# Invoke Casey's magic: split by synapse domain
max_density = tree_max_density(chunk.to_undirected(), treenode_ids,
connector_ids, relation_ids, [bandwidth])
# Get first element of max_density
domains = next(iter(max_density.values()))
# domains is a dictionary of index vs SynapseGroup instance
if 1 == len(domains):
for connector_id, relation_id, confidence in zip(connector_ids, relation_ids, confidences):
connectors[connector_id][relation_id].append((chunkID, confidence))
nodes.append(chunkID)
continue
# Create edges between domains
# Pick one treenode from each domain to act as anchor
anchors = {d.node_ids[0]: (i+k, d) for k, d in domains.items()}
# Create new Graph where the edges are the edges among synapse domains
mini = simplify(chunk, anchors.keys())
# Many side effects:
# * add internal edges to intraedges
# * add each domain to nodes
# * custom-apply populate_connectors with the known synapses of each domain
# (rather than having to sift through all in cs)
mini_nodes = {}
for node in mini.nodes_iter():
nblob = anchors.get(node)
if nblob:
index, domain = nblob
domainID = '%s_%s' % (chunkID, index)
nodes.append(domainID)
for connector_id, relation_id in zip(domain.connector_ids, domain.relations):
confidence = confidences[connector_ids.index(connector_id)]
connectors[connector_id][relation_id].append((domainID, confidence))
else:
domainID = '%s_%s' % (chunkID, node)
branch_nodes.append(domainID)
mini_nodes[node] = domainID
for a1, a2 in mini.edges_iter():
intraedges.append((mini_nodes[a1], mini_nodes[a2]))
return nodes, branch_nodes
def _skeleton_graph(project_id, skeleton_ids, confidence_threshold, bandwidth,
expand, compute_risk, cable_spread, path_confluence,
with_overall_counts=False, relation_map=None, link_types=None,
allowed_connector_ids=None) -> Optional[Dict]:
by_link_type = bool(link_types)
if not by_link_type:
link_types = ['synaptic-connector']
if not expand:
# Prevent expensive operations that will do nothing
bandwidth = 0
cursor = connection.cursor()
relation_map = get_relation_to_id_map(project_id, cursor=cursor)
result:Optional[Dict] = None
for link_type in link_types:
pair = KNOWN_LINK_PAIRS.get(link_type)
if not pair:
raise ValueError(f"Unknown link type: {link_type}")
source_rel = pair['source']
target_rel = pair['target']
if 0 == bandwidth:
if 0 == confidence_threshold:
graph:Dict[str, Any] = basic_graph(project_id, skeleton_ids, relation_map,
source_rel, target_rel,
allowed_connector_ids)
else:
graph = confidence_split_graph(project_id, skeleton_ids,
confidence_threshold, relation_map, source_rel,
target_rel, allowed_connector_ids)
else:
graph = dual_split_graph(project_id, skeleton_ids, confidence_threshold,
bandwidth, expand, relation_map)
if with_overall_counts:
source_rel_id = relation_map[source_rel]
target_rel_id = relation_map[target_rel]
cursor.execute(f'''
SELECT tc1.skeleton_id, tc2.skeleton_id,
tc1.relation_id, tc2.relation_id,
LEAST(tc1.confidence, tc2.confidence)
FROM treenode_connector tc1
JOIN UNNEST(%(skeleton_id)s::bigint[]) skeleton(id)
ON tc1.skeleton_id = skeleton.id
JOIN treenode_connector tc2
ON tc1.connector_id = tc2.connector_id
WHERE tc1.id != tc2.id
AND tc1.relation_id IN (%(source_rel_id)s, %(target_rel_id)s)
AND tc2.relation_id IN (%(source_rel_id)s, %(target_rel_id)s)
''', {
'skeleton_ids': skeleton_ids,
'source_rel_id': source_rel_id,
'target_rel_id': target_rel_id,
})
query_skeleton_ids = set(skeleton_ids)
overall_counts:DefaultDict = defaultdict(partial(defaultdict, make_new_synapse_count_array))
# Iterate through each pre/post connection
for skid1, skid2, rel1, rel2, conf in cursor.fetchall():
# Increment number of links to/from skid1 with relation rel1.
overall_counts[skid1][rel1][conf - 1] += 1
# Attach counts and a map of relation names to their IDs.
graph['overall_counts'] = overall_counts
graph['relation_map'] = {
source_rel: source_rel_id,
target_rel: target_rel_id
}
if by_link_type:
if not result:
result = {}
result[link_type] = graph
else:
result = graph
return result
@api_view(['POST'])
@requires_user_role([UserRole.Annotate, UserRole.Browse])
def skeleton_graph(request, project_id=None):
"""Get a synaptic graph between skeletons compartmentalized by confidence.
Given a set of skeletons, retrieve presynaptic-to-postsynaptic edges
between them, annotated with count. If a confidence threshold is
supplied, compartmentalize the skeletons at edges in the arbor
below that threshold and report connectivity based on these
compartments.
When skeletons are split into compartments, nodes in the graph take an
string ID like ``{skeleton_id}_{compartment #}``.
---
parameters:
- name: skeleton_ids[]
description: IDs of the skeletons to graph
required: true
type: array
items:
type: integer
paramType: form
- name: confidence_threshold
description: Confidence value below which to segregate compartments
type: integer
paramType: form
- name: bandwidth
description: Bandwidth in nanometers
type: number
- name: cable_spread
description: Cable spread in nanometers
type: number
- name: expand[]
description: IDs of the skeletons to expand
type: array
items:
type: integer
- name: link_types[]
description: IDs of link types to respect
type: array
items:
type: string
- name: allowed_connector_ids[]
description: (Optional) IDs of allowed conectors. All other connectors will be ignored.
required: false
type: array
items:
type: integer
models:
skeleton_graph_edge:
id: skeleton_graph_edge
properties:
- description: ID of the presynaptic skeleton or compartment
type: integer|string
required: true
- description: ID of the postsynaptic skeleton or compartment
type: integer|string
required: true
- description: number of synapses constituting this edge
$ref: skeleton_graph_edge_count
required: true
skeleton_graph_edge_count:
id: skeleton_graph_edge_count
properties:
- description: Number of synapses with confidence 1
type: integer
required: true
- description: Number of synapses with confidence 2
type: integer
required: true
- description: Number of synapses with confidence 3
type: integer
required: true
- description: Number of synapses with confidence 4
type: integer
required: true
- description: Number of synapses with confidence 5
type: integer
required: true
skeleton_graph_intraedge:
id: skeleton_graph_intraedge
properties:
- description: ID of the presynaptic skeleton or compartment
type: integer|string
required: true
- description: ID of the postsynaptic skeleton or compartment
type: integer|string
required: true
type:
edges:
type: array
items:
$ref: skeleton_graph_edge
required: true
nodes:
type: array
items:
type: integer|string
required: false
intraedges:
type: array
items:
$ref: skeleton_graph_intraedge
required: false
branch_nodes:
type: array
items:
type: integer|string
required: false
"""
compute_risk = 1 == int(request.POST.get('risk', 0))
if compute_risk:
# TODO port the last bit: computing the synapse risk
from graph import skeleton_graph as slow_graph
return slow_graph(request, project_id)
project_id = int(project_id)
skeleton_ids = set(int(v) for k,v in request.POST.items() if k.startswith('skeleton_ids['))
confidence_threshold = min(int(request.POST.get('confidence_threshold', 0)), 5)
bandwidth = float(request.POST.get('bandwidth', 0)) # in nanometers
cable_spread = float(request.POST.get('cable_spread', 2500)) # in nanometers
path_confluence = int(request.POST.get('path_confluence', 10)) # a count
expand = set(int(v) for k,v in request.POST.items() if k.startswith('expand['))
with_overall_counts = get_request_bool(request.POST, 'with_overall_counts', False)
expand = set(int(v) for k,v in request.POST.items() if k.startswith('expand['))
link_types = get_request_list(request.POST, 'link_types', None)
allowed_connector_ids = get_request_list(request.POST, 'allowed_connector_ids', None)
graph = _skeleton_graph(project_id, skeleton_ids,
confidence_threshold, bandwidth, expand, compute_risk, cable_spread,
path_confluence, with_overall_counts, link_types=link_types,
allowed_connector_ids=allowed_connector_ids)
if not graph:
raise ValueError("Could not compute graph")
return JsonResponse(graph)<|fim▁end|> | if row[2] and row[3] > confidence_threshold:
tree.add_edge(row[2], row[1]) |
<|file_name|>edt_stats.py<|end_file_name|><|fim▁begin|># -*-coding:Utf-8 -*
# Copyright (c) 2010 LE GOFF Vincent
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE<|fim▁hole|>"""Fichier contenant le contexte éditeur EdtStats"""
from primaires.interpreteur.editeur import Editeur
from primaires.format.fonctions import contient
class EdtStats(Editeur):
"""Classe définissant le contexte éditeur 'stats'.
Ce contexte permet d'éditer les stats d'une race.
"""
def __init__(self, pere, objet=None, attribut=None):
"""Constructeur de l'éditeur"""
Editeur.__init__(self, pere, objet, attribut)
def accueil(self):
"""Message d'accueil"""
msg = \
"Entrez le |ent|nom|ff| de la stat, un signe |ent|/|ff| " \
"et la valeur pour modifier une stat.\nExemple : |cmd|force / " \
"45|ff|\n\nEntrez |ent|/|ff| pour revenir à la fenêtre parente\n\n"
stats = self.objet
msg += "+-" + "-" * 20 + "-+-" + "-" * 6 + "-+\n"
msg += "| " + "Nom".ljust(20) + " | " + "Valeur".ljust(6) + " |\n"
msg += "| " + " ".ljust(20) + " | " + " ".ljust(6) + " |"
for stat in stats:
if not stat.max:
msg += "\n| |ent|" + stat.nom.ljust(20) + "|ff| | "
msg += str(stat.defaut).rjust(6) + " |"
return msg
def interpreter(self, msg):
"""Interprétation du message"""
try:
nom_stat, valeur = msg.split(" / ")
except ValueError:
self.pere << "|err|Syntaxe invalide.|ff|"
else:
# On cherche la stat
stat = None
for t_stat in self.objet:
if not t_stat.max and contient(t_stat.nom, nom_stat):
stat = t_stat
break
if not stat:
self.pere << "|err|Cette stat est introuvable.|ff|"
else:
# Convertion
try:
valeur = int(valeur)
assert valeur > 0
assert valeur >= stat.marge_min
assert valeur <= stat.marge_max
except (ValueError, AssertionError):
self.pere << "|err|Valeur invalide.|ff|"
else:
stat.defaut = valeur
stat.courante = valeur
self.actualiser()<|fim▁end|> | # POSSIBILITY OF SUCH DAMAGE.
|
<|file_name|>GGIDrawableFactory.hh<|end_file_name|><|fim▁begin|>/*$Id$
*
* This source file is a part of the Fresco Project.
* Copyright (C) 2000 Stefan Seefeld <[email protected]>
* http://www.fresco.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#ifndef _Berlin_Console_GGIDrawableFactory_hh
#define _Berlin_Console_GGIDrawableFactory_hh
#include <Berlin/config.hh>
#include <Berlin/Console.hh>
#include <string>
extern "C"
{<|fim▁hole|>
namespace Berlin
{
namespace Console_Extension
{
class GGIDrawable : public virtual Berlin::Console::Drawable
{
public:
virtual const std::string &name() const = 0;
virtual ggi_mode mode() const = 0;
virtual ggi_visual_t visual() const = 0;
};
class GGIDrawableFactory : virtual public Berlin::Console::Extension
{
public:
//. Creates a new Drawable of the given size (x, y) and depth.
//. It is accessable under the given shm-id.
virtual GGIDrawable *create_drawable(int shmid,
Fresco::PixelCoord,
Fresco::PixelCoord,
Fresco::PixelCoord) = 0;
};
} // namespace
} // namespace
#endif<|fim▁end|> | #include <ggi/ggi-unix.h>
} |
<|file_name|>JapaneseVillagePrefabs.cpp<|end_file_name|><|fim▁begin|>// JapaneseVillagePrefabs.cpp
// Defines the prefabs in the group JapaneseVillage
// NOTE: This file has been generated automatically by GalExport!
// Any manual changes will be overwritten by the next automatic export!
#include "Globals.h"
#include "JapaneseVillagePrefabs.h"
const cPrefab::sDef g_JapaneseVillagePrefabs[] =
{
////////////////////////////////////////////////////////////////////////////////
// Arch:
// The data has been exported from the gallery Plains, area index 144, ID 488, created by Aloe_vera
{
// Size:
11, 7, 5, // SizeX = 11, SizeY = 7, SizeZ = 5
// Hitbox (relative to bounding box):
-1, 0, 0, // MinX, MinY, MinZ
11, 6, 4, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 2: 0\n" /* grass */
"b: 13: 0\n" /* gravel */
"c:113: 0\n" /* netherbrickfence */
"d: 50: 5\n" /* torch */
"e: 44: 8\n" /* step */
"f: 44: 0\n" /* step */
"g: 43: 0\n" /* doubleslab */
"m: 19: 0\n" /* sponge */,
// Block data:
// Level 0
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "aaaabbbaaaa"
/* 1 */ "aaaabbbaaaa"
/* 2 */ "aaaabbbaaaa"
/* 3 */ "aaaabbbaaaa"
/* 4 */ "aaaabbbaaaa"
// Level 1
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..c.....c.."
/* 1 */ "..c.....c.."
/* 2 */ "..c.....c.."
/* 3 */ "..c.....c.."
/* 4 */ "..c.....c.."
// Level 2
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..c.....c.."
/* 1 */ "..........."
/* 2 */ "..c.....c.."
/* 3 */ "..........."
/* 4 */ "..c.....c.."
// Level 3
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..d.....d.."
/* 1 */ "..........."
/* 2 */ "..c.....c.."
/* 3 */ "..........."
/* 4 */ "..d.....d.."
// Level 4
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "...eeeee..."
/* 1 */ "..........."
/* 2 */ "..c.....c.."
/* 3 */ "..........."
/* 4 */ "...eeeee..."
// Level 5
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..f.....f.."
/* 1 */ ".egfffffge."
/* 2 */ ".egeeeeege."
/* 3 */ ".egfffffge."
/* 4 */ "..f.....f.."
// Level 6
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..........."
/* 2 */ "gf.......fg"
/* 3 */ "..........."
/* 4 */ "...........",
// Connectors:
"2: 5, 1, 4: 3\n" /* Type 2, direction Z+ */
"2: 5, 1, 0: 2\n" /* Type 2, direction Z- */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // Arch
////////////////////////////////////////////////////////////////////////////////
// Farm:
// The data has been exported from the gallery Plains, area index 166, ID 554, created by Aloe_vera
{
// Size:
11, 8, 13, // SizeX = 11, SizeY = 8, SizeZ = 13
// Hitbox (relative to bounding box):
0, 0, 0, // MinX, MinY, MinZ
10, 7, 12, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 3: 0\n" /* dirt */
"b: 60: 7\n" /* tilleddirt */
"c: 8: 0\n" /* water */
"d: 43: 0\n" /* doubleslab */
"e: 44: 0\n" /* step */
"f: 59: 7\n" /* crops */
"g: 83: 0\n" /* reedblock */
"h:113: 0\n" /* netherbrickfence */
"i: 50: 5\n" /* torch */
"m: 19: 0\n" /* sponge */,
// Block data:
// Level 0
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "mmmmmmmmmmm"
/* 1 */ "maaaaaaaaam"
/* 2 */ "maaaaaaaaam"
/* 3 */ "maaaaaaaaam"
/* 4 */ "maaaaaaaaam"
/* 5 */ "maaaaaaaaam"
/* 6 */ "maaaaaaaaam"
/* 7 */ "maaaaaaaaam"
/* 8 */ "maaaaaaaaam"
/* 9 */ "maaaaaaaaam"
/* 10 */ "maaaaaaaaam"
/* 11 */ "maaaaaaaaam"
/* 12 */ "mmmmmmmmmmm"
// Level 1
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "mmmmmmmmmmm"
/* 1 */ "maaaaaaaaam"
/* 2 */ "mabbbbbbbam"
/* 3 */ "mabbbbbbbam"
/* 4 */ "mabbbbbbbam"
/* 5 */ "mabbbbbbbam"
/* 6 */ "mabcccccaam"
/* 7 */ "mabbbbbbbam"
/* 8 */ "mabbbbbbbam"
/* 9 */ "mabbbbbbbam"
/* 10 */ "mabbbbbbbam"
/* 11 */ "maaaaaaaaam"
/* 12 */ "mmmmmmmmmmm"
// Level 2
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ ".deeeeeeed."
/* 2 */ ".efffffffe."
/* 3 */ ".efffffffe."
/* 4 */ ".efffffffe."
/* 5 */ ".efgggggfe."
/* 6 */ ".eg.....ge."
/* 7 */ ".efgggggfe."
/* 8 */ ".efffffffe."
/* 9 */ ".efffffffe."
/* 10 */ ".efffffffe."
/* 11 */ ".deeeeeeed."
/* 12 */ "..........."
// Level 3
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ ".h.......h."
/* 2 */ "..........."
/* 3 */ "..........."
/* 4 */ "..........."
/* 5 */ "...ggggg..."
/* 6 */ "..g.....g.."
/* 7 */ "...ggggg..."
/* 8 */ "..........."
/* 9 */ "..........."
/* 10 */ "..........."
/* 11 */ ".h.......h."
/* 12 */ "..........."
// Level 4
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ ".h.......h."
/* 2 */ "..........."
/* 3 */ "..........."
/* 4 */ "..........."
/* 5 */ "...ggggg..."
/* 6 */ "..g.....g.."
/* 7 */ "...ggggg..."
/* 8 */ "..........."
/* 9 */ "..........."
/* 10 */ "..........."
/* 11 */ ".h.......h."
/* 12 */ "..........."
// Level 5
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ ".h.......h."
/* 2 */ "..........."
/* 3 */ "..........."
/* 4 */ "..........."
/* 5 */ "..........."
/* 6 */ "..........."
/* 7 */ "..........."
/* 8 */ "..........."
/* 9 */ "..........."
/* 10 */ "..........."
/* 11 */ ".h.......h."
/* 12 */ "..........."
// Level 6
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ ".h.......h."
/* 1 */ "hhh.....hhh"
/* 2 */ ".h.......h."
/* 3 */ "..........."
/* 4 */ "..........."
/* 5 */ "..........."
/* 6 */ "..........."
/* 7 */ "..........."
/* 8 */ "..........."
/* 9 */ "..........."
/* 10 */ ".h.......h."
/* 11 */ "hhh.....hhh"
/* 12 */ ".h.......h."
// Level 7
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ ".i.......i."
/* 1 */ "i.i.....i.i"
/* 2 */ ".i.......i."
/* 3 */ "..........."
/* 4 */ "..........."
/* 5 */ "..........."
/* 6 */ "..........."
/* 7 */ "..........."
/* 8 */ "..........."
/* 9 */ "..........."
/* 10 */ ".i.......i."
/* 11 */ "i.i.....i.i"
/* 12 */ ".i.......i.",
// Connectors:
"-1: 10, 2, 6: 5\n" /* Type -1, direction X+ */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // Farm
////////////////////////////////////////////////////////////////////////////////
// Forge:
// The data has been exported from the gallery Plains, area index 79, ID 145, created by Aloe_vera
{
// Size:
16, 11, 14, // SizeX = 16, SizeY = 11, SizeZ = 14
// Hitbox (relative to bounding box):
0, 0, -1, // MinX, MinY, MinZ
16, 10, 14, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 4: 0\n" /* cobblestone */
"b: 17: 1\n" /* tree */
"c: 67: 0\n" /* stairs */
"d: 5: 2\n" /* wood */
"e: 67: 2\n" /* stairs */
"f:113: 0\n" /* netherbrickfence */
"g:118: 2\n" /* cauldronblock */
"h: 67: 6\n" /* stairs */
"i: 67: 4\n" /* stairs */
"j: 87: 0\n" /* netherstone */
"k: 67: 7\n" /* stairs */
"l: 54: 5\n" /* chest */
"m: 19: 0\n" /* sponge */
"n: 61: 2\n" /* furnace */
"o:101: 0\n" /* ironbars */
"p: 51: 0\n" /* fire */
"q: 50: 4\n" /* torch */
"r: 50: 2\n" /* torch */
"s: 35: 0\n" /* wool */
"t: 67: 3\n" /* stairs */
"u: 50: 3\n" /* torch */
"v: 44: 8\n" /* step */
"w: 43: 0\n" /* doubleslab */
"x: 44: 0\n" /* step */
"y: 17: 5\n" /* tree */
"z: 17: 9\n" /* tree */,
// Block data:
// Level 0
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "mmmmmmmmmmmmmmmm"
/* 1 */ "mmmmmmmmmmmmmmmm"
/* 2 */ "mmaaaaaaaaaaaamm"
/* 3 */ "mmaaaaaaaaaaaamm"
/* 4 */ "mmaaaaaaaaaaaamm"
/* 5 */ "mmaaaaaaaaaaaamm"
/* 6 */ "mmaaaaaaaaaaaamm"
/* 7 */ "mmaaaaaaaaaaaamm"
/* 8 */ "mmaaaaaaaaaaaamm"
/* 9 */ "mmaaaaaaaaaaaamm"
/* 10 */ "mmaaaaaaaaaaaamm"
/* 11 */ "mmaaaaaaaaaaaamm"
/* 12 */ "mmmmmmmmmmmmmmmm"
/* 13 */ "mmmmmmmmmmmmmmmm"
// Level 1
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "................"
/* 2 */ ".....bbbbbbbbb.."
/* 3 */ ".....cdddddddb.."
/* 4 */ ".....cddaaaadb.."
/* 5 */ "..beeedaaaaadb.."
/* 6 */ "..bddddaaaaadb.."
/* 7 */ "..bddddaaaaadb.."
/* 8 */ "..bddddaaaaadb.."
/* 9 */ "..bddddaaaaadb.."
/* 10 */ "..bddddddddddb.."
/* 11 */ "..bbbbbbbbbbbb.."
/* 12 */ "................"
/* 13 */ "................"
// Level 2
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "................"
/* 2 */ ".....bfffbfffb.."
/* 3 */ ".............a.."
/* 4 */ ".............a.."
/* 5 */ "..b.....ghh..a.."
/* 6 */ "..f.....haa..b.."
/* 7 */ "..f.....ija..b.."
/* 8 */ "..f.....kaa..a.."
/* 9 */ "..f..........a.."
/* 10 */ "..fl.........a.."
/* 11 */ "..bffffbbffffb.."
/* 12 */ "................"
/* 13 */ "................"
// Level 3
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "................"
/* 2 */ ".....bfffbfffb.."
/* 3 */ ".............a.."
/* 4 */ ".............a.."
/* 5 */ "..b......nn..a.."
/* 6 */ "..f.....oaa..b.."
/* 7 */ "..f.....opa..b.."
/* 8 */ "..f.....oaa..a.."
/* 9 */ "..f..........a.."
/* 10 */ "..f..........a.."
/* 11 */ "..bffffbbffffb.."
/* 12 */ "................"
/* 13 */ "................"
// Level 4
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ ".........q...q.."
/* 2 */ "....rbsssbsssb.."
/* 3 */ ".............a.."
/* 4 */ "..q..........a.."
/* 5 */ "..b......ce..a.."
/* 6 */ "..s......ea..b.."
/* 7 */ "..s......aa..b.."
/* 8 */ "..s......ta..a.."
/* 9 */ "..s..........a.."
/* 10 */ "..s..........a.."
/* 11 */ ".rbssssbbssssb.."
/* 12 */ "..u....uu....u.."
/* 13 */ "................"
// Level 5
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ ".vwxxxxxxxxxxwv."
/* 1 */ "vvvvvvvvvvvvvvvv"
/* 2 */ "wvbyybyyybbyybvw"
/* 3 */ "xvz..........zvx"
/* 4 */ "xvz..........zvx"
/* 5 */ "xvb..........zvx"
/* 6 */ "xvz.......a..bvx"
/* 7 */ "xvz......ca..bvx"
/* 8 */ "xvz.......a..zvx"
/* 9 */ "xvz..........zvx"
/* 10 */ "xvz..........zvx"
/* 11 */ "wvbyyyyyyyyyybvw"
/* 12 */ "vvvvvvvvvvvvvvvv"
/* 13 */ ".vwxxxxxxxxxxwv."
// Level 6
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "wx............xw"
/* 1 */ "x..............x"
/* 2 */ "..xxxxxxxxxxxx.."
/* 3 */ "..xwwwwwwwwwwx.."
/* 4 */ "..xwvvvvvvvvvx.."
/* 5 */ "..xwv.......vx.."
/* 6 */ "..xwv.....a.vx.."
/* 7 */ "..xwv.....a.vx.."
/* 8 */ "..xwv.....a.vx.."
/* 9 */ "..xwvvvvvvvvvx.."
/* 10 */ "..xwwwwwwwwwwx.."
/* 11 */ "..xxxxxxxxxxxx.."
/* 12 */ "x..............x"
/* 13 */ "wx............xw"
// Level 7
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "................"
/* 2 */ "................"
/* 3 */ "................"
/* 4 */ "....xxxxxxxx...."
/* 5 */ "....xxxxxxxx...."
/* 6 */ "....xwwwwwax...."
/* 7 */ "....xwvvvvax...."
/* 8 */ "....xwwwwwax...."
/* 9 */ "....xxxxxxxx...."
/* 10 */ "................"
/* 11 */ "................"
/* 12 */ "................"
/* 13 */ "................"
// Level 8
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "................"
/* 2 */ "................"
/* 3 */ "................"
/* 4 */ "................"
/* 5 */ "................"
/* 6 */ "..........a....."
/* 7 */ ".......xx.a....."
/* 8 */ "..........a....."
/* 9 */ "................"
/* 10 */ "................"
/* 11 */ "................"
/* 12 */ "................"
/* 13 */ "................"
// Level 9
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "................"
/* 2 */ "................"
/* 3 */ "................"
/* 4 */ "................"
/* 5 */ "................"
/* 6 */ "..........a....."
/* 7 */ "..........a....."
/* 8 */ "..........a....."
/* 9 */ "................"
/* 10 */ "................"
/* 11 */ "................"
/* 12 */ "................"
/* 13 */ "................"
// Level 10
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "................"
/* 2 */ "................"
/* 3 */ "................"
/* 4 */ "................"
/* 5 */ "................"
/* 6 */ "..........a....."
/* 7 */ "..........a....."
/* 8 */ "..........a....."
/* 9 */ "................"
/* 10 */ "................"
/* 11 */ "................"
/* 12 */ "................"
/* 13 */ "................",
// Connectors:
"-1: 0, 1, 3: 4\n" /* Type -1, direction X- */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // Forge
////////////////////////////////////////////////////////////////////////////////
// Garden2:
// The data has been exported from the gallery Plains, area index 147, ID 491, created by Aloe_vera
{
// Size:
16, 5, 16, // SizeX = 16, SizeY = 5, SizeZ = 16
// Hitbox (relative to bounding box):
0, 0, 0, // MinX, MinY, MinZ
15, 4, 15, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 3: 0\n" /* dirt */
"b: 8: 0\n" /* water */
"c: 2: 0\n" /* grass */
"d: 17: 1\n" /* tree */
"e: 13: 0\n" /* gravel */
"f: 31: 2\n" /* tallgrass */
"g: 18: 5\n" /* leaves */
"h: 38: 7\n" /* rose */
"i: 17: 9\n" /* tree */
"m: 19: 0\n" /* sponge */,
// Block data:
// Level 0
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "aaaaaaaaaaaaaaaa"
/* 1 */ "aaaaaaaaaaaaaaaa"
/* 2 */ "aaaaaaaaaaaaaaaa"
/* 3 */ "aaaaaaaaaaaaaaaa"
/* 4 */ "aaaaaaaaaaaaaaaa"
/* 5 */ "aaaaaaaaaaaaaaaa"
/* 6 */ "aaaaaaaaaaaaaaaa"
/* 7 */ "aaaaaaaaaaaaaaaa"
/* 8 */ "aaaaaaaaaaaaaaaa"
/* 9 */ "aaaaaaaaaaaaaaaa"
/* 10 */ "aaaaaaaaaaaaaaaa"
/* 11 */ "aaaaaaaaaaaaaaaa"
/* 12 */ "aaaaaaaaaaaaaaaa"
/* 13 */ "aaaaaaaaaaaaaaaa"
/* 14 */ "aaaaaaaaaaaaaaaa"
/* 15 */ "aaaaaaaaaaaaaaaa"
// Level 1
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "aaaaaaaaaaaaaaaa"
/* 1 */ "aaaaaaaaaaaaaaaa"
/* 2 */ "aaaaaaaaaaaaaaaa"
/* 3 */ "aaaaaaaaaaaaaaaa"
/* 4 */ "aaaaaaaaaaaaaaaa"
/* 5 */ "aaaaaaaaaaaaaaaa"
/* 6 */ "aaaabbaaaaaaaaaa"
/* 7 */ "aaabbbaaaaaaaaaa"
/* 8 */ "aaabbaaaaaaaaaaa"
/* 9 */ "aaaabaaaaaaaaaaa"
/* 10 */ "aaaaaaaaaaaaaaaa"
/* 11 */ "aaaaaaaaaaaaaaaa"
/* 12 */ "aaaaaaaaaaaaaaaa"
/* 13 */ "aaaaaaaaaaaaaaaa"
/* 14 */ "aaaaaaaaaaaaaaaa"
/* 15 */ "aaaaaaaaaaaaaaaa"
// Level 2
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "cccccccccccccccc"
/* 1 */ "ccdccccccccdcccc"
/* 2 */ "cccccceecccccdcc"
/* 3 */ "ccccccceeccccccc"
/* 4 */ "cccccccceccccccc"
/* 5 */ "cccbbbbceccccccc"
/* 6 */ "cccbbbbceecccccc"
/* 7 */ "ccbbbbbcceeeeccc"
/* 8 */ "ccbbbbbccccceecc"
/* 9 */ "ccbbbbcccccccecc"
/* 10 */ "ccccbcccccccceec"
/* 11 */ "ccccccccccccccec"
/* 12 */ "ccccccccaaacccec"
/* 13 */ "cccccccccaccccec"
/* 14 */ "ccccccccccccceec"
/* 15 */ "cccccccccccceecc"
// Level 3
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "......f...gg.g.."
/* 1 */ "..gg.....gggggg."
/* 2 */ "ffgg......ghgggg"
/* 3 */ ".............gg."
/* 4 */ "...........f...."
/* 5 */ "...........h.ff."
/* 6 */ ".............fh."
/* 7 */ "...............f"
/* 8 */ "................"
/* 9 */ ".......ff.f....."
/* 10 */ ".f.....ffggf...."
/* 11 */ ".......gggg.f..."
/* 12 */ ".f......iddg...."
/* 13 */ ".....f..gdgg...."
/* 14 */ "....ff...gg....."
/* 15 */ "................"
// Level 4
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "...........g.g.."
/* 2 */ ".............gg."
/* 3 */ "................"
/* 4 */ "................"
/* 5 */ "................"
/* 6 */ "................"
/* 7 */ "................"
/* 8 */ "................"
/* 9 */ "................"
/* 10 */ ".........g......"
/* 11 */ "........ggg....."
/* 12 */ "........ggg....."
/* 13 */ ".........g......"
/* 14 */ "................"
/* 15 */ "................",
// Connectors:
"-1: 12, 3, 15: 3\n" /* Type -1, direction Z+ */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // Garden2
////////////////////////////////////////////////////////////////////////////////
// HouseMid:
// The data has been exported from the gallery Plains, area index 62, ID 119, created by Aloe_vera
{
// Size:
10, 9, 9, // SizeX = 10, SizeY = 9, SizeZ = 9
// Hitbox (relative to bounding box):
0, 0, -1, // MinX, MinY, MinZ
10, 8, 9, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 5: 2\n" /* wood */
"b:135: 2\n" /* 135 */
"c:135: 0\n" /* 135 */
"d: 17: 9\n" /* tree */
"e:135: 3\n" /* 135 */
"f: 85: 0\n" /* fence */
"g: 17: 1\n" /* tree */
"h:171: 0\n" /* carpet */
"i: 50: 5\n" /* torch */
"j: 35: 0\n" /* wool */
"k: 17: 5\n" /* tree */
"l:124: 0\n" /* redstonelampon */
"m: 19: 0\n" /* sponge */
"n: 69: 9\n" /* lever */
"o: 44: 8\n" /* step */
"p: 43: 0\n" /* doubleslab */
"q: 44: 0\n" /* step */,
// Block data:
// Level 0
/* z\x* */
/* * 0123456789 */
/* 0 */ "maaaaaaaaa"
/* 1 */ "maaaaaaaaa"
/* 2 */ "aaaaaaaaaa"
/* 3 */ "aaaaaaaaaa"
/* 4 */ "aaaaaaaaaa"
/* 5 */ "aaaaaaaaaa"
/* 6 */ "aaaaaaaaaa"
/* 7 */ "maaaaaaaaa"
/* 8 */ "maaaaaaaaa"
// Level 1
/* z\x* */
/* * 0123456789 */
/* 0 */ ".aaaaaaaaa"
/* 1 */ ".aaaaaaaaa"
/* 2 */ "baaaaaaaaa"
/* 3 */ "caaaaaaaaa"
/* 4 */ "caadaaaaaa"
/* 5 */ "caaaaaaaaa"
/* 6 */ "eaaaaaaaaa"
/* 7 */ ".aaaaaaaaa"
/* 8 */ ".aaaaaaaaa"
// Level 2
/* z\x* */
/* * 0123456789 */
/* 0 */ ".fffffffff"
/* 1 */ ".f.......f"
/* 2 */ ".f.ggggg.f"
/* 3 */ "...ghhhg.f"
/* 4 */ "....hhhg.f"
/* 5 */ "...ghhhg.f"
/* 6 */ ".f.ggggg.f"
/* 7 */ ".f.......f"
/* 8 */ ".fffffffff"
// Level 3
/* z\x* */
/* * 0123456789 */
/* 0 */ ".....i...i"
/* 1 */ ".........."
/* 2 */ ".i.jjgjj.."
/* 3 */ "...g...j.."
/* 4 */ ".......g.i"
/* 5 */ "...g...j.."
/* 6 */ ".i.jjgjj.."
/* 7 */ ".........."
/* 8 */ ".....i...i"
// Level 4
/* z\x* */
/* * 0123456789 */
/* 0 */ ".........."
/* 1 */ ".........."
/* 2 */ "...jjgjj.."
/* 3 */ "...g...j.."
/* 4 */ "...j...g.."
/* 5 */ "...g...j.."
/* 6 */ "...jjgjj.."
/* 7 */ ".........."
/* 8 */ ".........."
// Level 5
/* z\x* */
/* * 0123456789 */
/* 0 */ ".........."
/* 1 */ "...f...f.."
/* 2 */ "..fgkgkgf."
/* 3 */ "..fd...d.."
/* 4 */ "...d.lng.."
/* 5 */ "..fd...d.."
/* 6 */ "..fgkgkgf."
/* 7 */ "...f...f.."
/* 8 */ ".........."
// Level 6
/* z\x* */
/* * 0123456789 */
/* 0 */ "...ooooo.."
/* 1 */ "..opppppo."
/* 2 */ ".opgjjjgpo"
/* 3 */ ".opjgggjpo"
/* 4 */ ".opjgggjpo"
/* 5 */ ".opjgggjpo"
/* 6 */ ".opgjjjgpo"
/* 7 */ "..opppppo."
/* 8 */ "...ooooo.."
// Level 7
/* z\x* */
/* * 0123456789 */
/* 0 */ ".opq...qpo"
/* 1 */ ".pq.....qp"
/* 2 */ ".q.qqqqq.q"
/* 3 */ "...qpppq.."
/* 4 */ "...qpppq.."
/* 5 */ "...qpppq.."
/* 6 */ ".q.qqqqq.q"
/* 7 */ ".pq.....qp"
/* 8 */ ".opq...qpo"
// Level 8
/* z\x* */
/* * 0123456789 */
/* 0 */ ".q.......q"
/* 1 */ ".........."
/* 2 */ ".........."
/* 3 */ ".........."
/* 4 */ ".....q...."
/* 5 */ ".........."
/* 6 */ ".........."
/* 7 */ ".........."
/* 8 */ ".q.......q",
// Connectors:
"-1: 0, 1, 4: 4\n" /* Type -1, direction X- */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // HouseMid
////////////////////////////////////////////////////////////////////////////////
// HouseSmall:
// The data has been exported from the gallery Plains, area index 68, ID 131, created by Aloe_vera
{
// Size:
7, 6, 7, // SizeX = 7, SizeY = 6, SizeZ = 7
// Hitbox (relative to bounding box):
-1, 0, 0, // MinX, MinY, MinZ
7, 5, 7, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 5: 2\n" /* wood */
"b: 17: 1\n" /* tree */
"c: 35: 0\n" /* wool */
"d: 50: 4\n" /* torch */
"e: 85: 0\n" /* fence */
"f: 44: 8\n" /* step */
"g: 43: 0\n" /* doubleslab */
"h: 44: 0\n" /* step */
"m: 19: 0\n" /* sponge */,
// Block data:
// Level 0
/* z\x* 0123456 */
/* 0 */ "mmmmmmm"
/* 1 */ "maaaaam"
/* 2 */ "maaaaam"
/* 3 */ "maaaaam"
/* 4 */ "maaaaam"
/* 5 */ "maaaaam"
/* 6 */ "mmmmmmm"
// Level 1
/* z\x* 0123456 */
/* 0 */ "......."
/* 1 */ ".bcc.b."
/* 2 */ ".c...c."
/* 3 */ ".c...c."
/* 4 */ ".c...c."
/* 5 */ ".bcccb."
/* 6 */ "......."
// Level 2
/* z\x* 0123456 */
/* 0 */ ".....d."
/* 1 */ ".bee.b."
/* 2 */ ".c...c."
/* 3 */ ".e...e."
/* 4 */ ".c...c."
/* 5 */ ".beeeb."
/* 6 */ "......."
// Level 3
/* z\x* 0123456 */
/* 0 */ ".fffff."
/* 1 */ "fbcccbf"
/* 2 */ "fc...cf"
/* 3 */ "fc...cf"
/* 4 */ "fc...cf"
/* 5 */ "fbcccbf"
/* 6 */ ".fffff."
// Level 4
/* z\x* 0123456 */
/* 0 */ "gh...hg"
/* 1 */ "hhhhhhh"
/* 2 */ ".hgggh."
/* 3 */ ".hgggh."
/* 4 */ ".hgggh."
/* 5 */ "hhhhhhh"
/* 6 */ "gh...hg"
// Level 5
/* z\x* 0123456 */
/* 0 */ "......."
/* 1 */ "......."
/* 2 */ "......."
/* 3 */ "...h..."
/* 4 */ "......."
/* 5 */ "......."
/* 6 */ ".......",
// Connectors:
"-1: 4, 1, 0: 2\n" /* Type -1, direction Z- */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // HouseSmall
////////////////////////////////////////////////////////////////////////////////
// HouseSmallDblWithDoor:
// The data has been exported from the gallery Plains, area index 113, ID 265, created by Aloe_vera
{
// Size:
11, 6, 7, // SizeX = 11, SizeY = 6, SizeZ = 7
// Hitbox (relative to bounding box):
-1, 0, 0, // MinX, MinY, MinZ
11, 5, 7, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 5: 2\n" /* wood */
"b: 17: 9\n" /* tree */
"c: 17: 1\n" /* tree */
"d: 35: 0\n" /* wool */
"e: 64: 7\n" /* wooddoorblock */
"f:171:12\n" /* carpet */
"g:135: 1\n" /* 135 */
"h:126: 2\n" /* woodenslab */
"i:135: 2\n" /* 135 */
"j: 50: 4\n" /* torch */
"k: 64:12\n" /* wooddoorblock */
"l: 85: 0\n" /* fence */
"m: 19: 0\n" /* sponge */
"n: 44: 8\n" /* step */
"o: 43: 0\n" /* doubleslab */
"p: 44: 0\n" /* step */,
// Block data:
// Level 0
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "mmmmmmmmmmm"
/* 1 */ "maaaaaaaaam"
/* 2 */ "maaaabaaaam"
/* 3 */ "maaaabaaaam"
/* 4 */ "maaaabaaaam"
/* 5 */ "maaaaaaaaam"
/* 6 */ "mmmmmmmmmmm"
// Level 1
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ ".cdedcdddc."
/* 2 */ ".dfff.fffd."
/* 3 */ ".dgffdfhfd."
/* 4 */ ".diifdfffd."
/* 5 */ ".cdddcdddc."
/* 6 */ "..........."
// Level 2
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ ".j...j...j."
/* 1 */ ".cdkdclllc."
/* 2 */ ".d.......l."
/* 3 */ ".l...l...l."
/* 4 */ ".d...l...l."
/* 5 */ ".clllclllc."
/* 6 */ "..........."
// Level 3
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ ".nnnnnnnnn."
/* 1 */ "ncdddcdddcn"
/* 2 */ "nd...d...dn"
/* 3 */ "nd...d...dn"
/* 4 */ "nd...d...dn"
/* 5 */ "ncdddcdddcn"
/* 6 */ ".nnnnnnnnn."
// Level 4
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "op.......po"
/* 1 */ "ppppppppppp"
/* 2 */ ".pooooooop."
/* 3 */ ".ponndnnop."
/* 4 */ ".pooooooop."
/* 5 */ "ppppppppppp"
/* 6 */ "op.......po"
// Level 5
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..........."
/* 2 */ "..........."
/* 3 */ "...ppppp..."
/* 4 */ "..........."
/* 5 */ "..........."
/* 6 */ "...........",
// Connectors:
"-1: 3, 1, -1: 2\n" /* Type -1, direction Z- */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // HouseSmallDblWithDoor
////////////////////////////////////////////////////////////////////////////////
// HouseSmallDouble:
// The data has been exported from the gallery Plains, area index 72, ID 135, created by Aloe_vera
{
// Size:
11, 6, 7, // SizeX = 11, SizeY = 6, SizeZ = 7
// Hitbox (relative to bounding box):
-1, 0, 0, // MinX, MinY, MinZ
11, 5, 7, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 5: 2\n" /* wood */
"b: 17: 1\n" /* tree */
"c: 35: 0\n" /* wool */
"d:171:12\n" /* carpet */
"e:135: 1\n" /* 135 */
"f:126: 2\n" /* woodenslab */
"g:135: 2\n" /* 135 */
"h: 50: 4\n" /* torch */
"i: 85: 0\n" /* fence */
"j: 44: 8\n" /* step */
"k: 43: 0\n" /* doubleslab */
"l: 44: 0\n" /* step */
"m: 19: 0\n" /* sponge */,
// Block data:
// Level 0
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "mmmmmmmmmmm"
/* 1 */ "maaaaaaaaam"
/* 2 */ "maaaaaaaaam"
/* 3 */ "maaaaaaaaam"
/* 4 */ "maaaaaaaaam"
/* 5 */ "maaaaaaaaam"
/* 6 */ "mmmmmmmmmmm"
// Level 1
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ ".bcc.bcccb."
/* 2 */ ".cddd.dddc."
/* 3 */ ".ceddcdfdc."
/* 4 */ ".cggdcdddc."
/* 5 */ ".bcccbcccb."
/* 6 */ "..........."
// Level 2
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ ".h...h...h."
/* 1 */ ".bii.biiib."
/* 2 */ ".c.......c."
/* 3 */ ".i...i...i."
/* 4 */ ".c...i...c."
/* 5 */ ".biiibiiib."
/* 6 */ "..........."
// Level 3
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ ".jjjjjjjjj."
/* 1 */ "jbiiibiiibj"
/* 2 */ "jc.......cj"
/* 3 */ "jc...c...cj"
/* 4 */ "jc...c...cj"
/* 5 */ "jbcccbcccbj"
/* 6 */ ".jjjjjjjjj."
// Level 4
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "kl...l...lk"
/* 1 */ "lllllllllll"
/* 2 */ ".lkkklkkkl."
/* 3 */ ".lkjklkkkl."
/* 4 */ ".lkkklkkkl."
/* 5 */ "lllllllllll"
/* 6 */ "kl...l...lk"
// Level 5
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..........."
/* 2 */ "..........."
/* 3 */ "...l...l..."
/* 4 */ "..........."
/* 5 */ "..........."
/* 6 */ "...........",
// Connectors:
"-1: 4, 1, 0: 2\n" /* Type -1, direction Z- */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // HouseSmallDouble
////////////////////////////////////////////////////////////////////////////////
// HouseSmallWithDoor:
// The data has been exported from the gallery Plains, area index 112, ID 264, created by Aloe_vera
{
// Size:
7, 6, 7, // SizeX = 7, SizeY = 6, SizeZ = 7
// Hitbox (relative to bounding box):
-1, 0, 0, // MinX, MinY, MinZ
7, 5, 7, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 5: 2\n" /* wood */
"b: 17: 1\n" /* tree */
"c: 35: 0\n" /* wool */
"d: 64: 7\n" /* wooddoorblock */
"e: 50: 4\n" /* torch */
"f: 64:12\n" /* wooddoorblock */
"g: 85: 0\n" /* fence */
"h: 44: 8\n" /* step */
"i: 43: 0\n" /* doubleslab */
"j: 44: 0\n" /* step */
"m: 19: 0\n" /* sponge */,
// Block data:
// Level 0
/* z\x* 0123456 */
/* 0 */ "mmmmmmm"
/* 1 */ "maaaaam"
/* 2 */ "maaaaam"
/* 3 */ "maaaaam"
/* 4 */ "maaaaam"
/* 5 */ "maaaaam"
/* 6 */ "mmmmmmm"
// Level 1
/* z\x* 0123456 */
/* 0 */ "......."
/* 1 */ ".bcdcb."
/* 2 */ ".c...c."
/* 3 */ ".c...c."
/* 4 */ ".c...c."
/* 5 */ ".bcccb."
/* 6 */ "......."
// Level 2
/* z\x* 0123456 */
/* 0 */ ".....e."
/* 1 */ ".bcfcb."
/* 2 */ ".g...g."
/* 3 */ ".g...g."
/* 4 */ ".g...g."
/* 5 */ ".bgggb."
/* 6 */ "......."
// Level 3
/* z\x* 0123456 */
/* 0 */ ".hhhhh."
/* 1 */ "hbcccbh"
/* 2 */ "hc...ch"
/* 3 */ "hc...ch"
/* 4 */ "hc...ch"
/* 5 */ "hbcccbh"
/* 6 */ ".hhhhh."
// Level 4
/* z\x* 0123456 */
/* 0 */ "ij...ji"
/* 1 */ "jjjjjjj"
/* 2 */ ".jiiij."
/* 3 */ ".jiiij."
/* 4 */ ".jiiij."
/* 5 */ "jjjjjjj"
/* 6 */ "ij...ji"
// Level 5
/* z\x* 0123456 */
/* 0 */ "......."
/* 1 */ "......."
/* 2 */ "......."
/* 3 */ "...j..."
/* 4 */ "......."
/* 5 */ "......."
/* 6 */ ".......",
// Connectors:
"-1: 3, 1, 0: 2\n" /* Type -1, direction Z- */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // HouseSmallWithDoor
////////////////////////////////////////////////////////////////////////////////
// HouseWide:
// The data has been exported from the gallery Plains, area index 64, ID 121, created by STR_Warrior
{
// Size:
11, 6, 11, // SizeX = 11, SizeY = 6, SizeZ = 11
// Hitbox (relative to bounding box):
-1, 0, -1, // MinX, MinY, MinZ
11, 5, 10, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 5: 2\n" /* wood */
"b: 17: 1\n" /* tree */
"c: 35: 0\n" /* wool */
"d:171: 0\n" /* carpet */
"e:126: 1\n" /* woodenslab */
"f: 64: 5\n" /* wooddoorblock */
"g: 85: 0\n" /* fence */
"h: 50: 1\n" /* torch */
"i: 50: 2\n" /* torch */
"j: 64:12\n" /* wooddoorblock */
"k:126:11\n" /* woodenslab */
"l: 17: 5\n" /* tree */
"m: 19: 0\n" /* sponge */
"n:126: 3\n" /* woodenslab */
"o:125: 3\n" /* woodendoubleslab */
"p: 5: 3\n" /* wood */,
// Block data:
// Level 0
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "mmmmmmmmmmm"
/* 1 */ "mmaaaaaaamm"
/* 2 */ "maaaaaaaaam"
/* 3 */ "maaaaaaaaam"
/* 4 */ "maaaaaaaaam"
/* 5 */ "maaaaaaaaam"
/* 6 */ "maaaaaaaaam"
/* 7 */ "maaaaaaaaam"
/* 8 */ "maaaaaaaaam"
/* 9 */ "mmaaaaaaamm"
/* 10 */ "mmmmmmmmmmm"
// Level 1
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..bcbcbcb.."
/* 2 */ ".b.d.....b."
/* 3 */ ".cded....c."
/* 4 */ ".bded....b."
/* 5 */ ".c.d.....c."
/* 6 */ ".b.......b."
/* 7 */ ".c.......c."
/* 8 */ ".b.......b."
/* 9 */ "..bcbfbcb.."
/* 10 */ "..........."
// Level 2
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..bgbgbgb.."
/* 2 */ ".b.......b."
/* 3 */ ".g.......g."
/* 4 */ ".bh.....ib."
/* 5 */ ".g.......g."
/* 6 */ ".b.......b."
/* 7 */ ".g.......g."
/* 8 */ ".b.......b."
/* 9 */ "..bgbjbgb.."
/* 10 */ "..........."
// Level 3
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "...kkkkk..."
/* 1 */ "..bcbcbcb.."
/* 2 */ ".b.......b."
/* 3 */ "kc.......ck"
/* 4 */ "kb.......bk"
/* 5 */ "kc.......ck"
/* 6 */ "kb.......bk"
/* 7 */ "kc.......ck"
/* 8 */ ".b.......b."
/* 9 */ "..bcblbcb.."
/* 10 */ "...kkkkk..."
// Level 4
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ ".kn.....nk."
/* 1 */ "konnnnnnnok"
/* 2 */ "nnnnnnnnnnn"
/* 3 */ ".nnpppppnn."
/* 4 */ ".nnpkkkpnn."
/* 5 */ ".nnpkkkpnn."
/* 6 */ ".nnpkkkpnn."
/* 7 */ ".nnpppppnn."
/* 8 */ "nnnnnnnnnnn"
/* 9 */ "kknnnnnnnok"
/* 10 */ ".kn.....nk."
// Level 5
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "n.........n"
/* 1 */ "..........."
/* 2 */ "..........."
/* 3 */ "..........."
/* 4 */ "....nnn...."
/* 5 */ "....non...."
/* 6 */ "....nnn...."
/* 7 */ "..........."
/* 8 */ "..........."
/* 9 */ "..........."
/* 10 */ "n.........n",
// Connectors:
"-1: 5, 1, 10: 3\n" /* Type -1, direction Z+ */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // HouseWide
////////////////////////////////////////////////////////////////////////////////
// HouseWithGarden:
// The data has been exported from the gallery Plains, area index 67, ID 130, created by Aloe_vera
{
// Size:
16, 9, 16, // SizeX = 16, SizeY = 9, SizeZ = 16
// Hitbox (relative to bounding box):
-1, 0, 0, // MinX, MinY, MinZ
16, 8, 16, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 3: 0\n" /* dirt */
"b: 5: 2\n" /* wood */
"c: 2: 0\n" /* grass */
"d:113: 0\n" /* netherbrickfence */
"e: 17: 1\n" /* tree */
"f: 35: 0\n" /* wool */
"g:126: 2\n" /* woodenslab */
"h: 31: 2\n" /* tallgrass */
"i:125: 2\n" /* woodendoubleslab */
"j: 38: 3\n" /* rose */
"k: 38: 2\n" /* rose */
"l: 38: 1\n" /* rose */
"m: 19: 0\n" /* sponge */
"n: 17: 2\n" /* tree */
"o: 50: 4\n" /* torch */
"p: 85: 0\n" /* fence */
"q:140: 0\n" /* flowerpotblock */
"r: 50: 3\n" /* torch */
"s: 44: 8\n" /* step */
"t: 50: 1\n" /* torch */
"u: 50: 2\n" /* torch */
"v: 43: 0\n" /* doubleslab */
"w: 44: 0\n" /* step */
"x: 18:10\n" /* leaves */,
// Block data:
// Level 0
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "mmmmmmmmmaammmmm"
/* 1 */ "aabbbbbbbbbbaaam"
/* 2 */ "aabbbbbbbbbbaaam"
/* 3 */ "aabbbbbbbbbbaaam"
/* 4 */ "aabbbbbbbbbbaaam"
/* 5 */ "aabbbbbbbbbbaaam"
/* 6 */ "aabbbbbbbbbbaaam"
/* 7 */ "aabbbbbbbbbbaaam"
/* 8 */ "aabbbbbbbbbbaaam"
/* 9 */ "aabbbbbbbbbbaaam"
/* 10 */ "aaaaaaaaaaaaaaam"
/* 11 */ "aaaaaaaaaaaaaaam"
/* 12 */ "aaaaaaaaaaaaaaam"
/* 13 */ "aaaaaaaaaaaaaaam"
/* 14 */ "aaaaaaaaaaaaaaam"
/* 15 */ "mmmmmmmmmmmmmmmm"
// Level 1
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "mmmmmmmmmccmmmmm"
/* 1 */ "ccbbbbbbbbbbcccm"
/* 2 */ "ccbbbbbbbbbbcccm"
/* 3 */ "ccbbbbbbbbbbcccm"
/* 4 */ "ccbbbbbbbbbbcccm"
/* 5 */ "ccbbbbbbbbbbcccm"
/* 6 */ "ccbbbbbbbbbbcccm"
/* 7 */ "ccbbbbbbbbbbcccm"
/* 8 */ "ccbbbbbbbbbbcccm"
/* 9 */ "ccbbbbbbbbbbcccm"
/* 10 */ "cccccccccccccccm"
/* 11 */ "cccccccccccccccm"
/* 12 */ "cccccccccccccccm"
/* 13 */ "cccccccccccccacm"
/* 14 */ "cccccccccccccccm"
/* 15 */ "mmmmmmmmmmmmmmmm"
// Level 2
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "ddeffeffe..eddd."
/* 2 */ "d.fbbgggg..f..d."
/* 3 */ "d.fbgggggggf.hd."
/* 4 */ "d.fbgggggggf..d."
/* 5 */ "d.eggggggggehhd."
/* 6 */ "d.fgiiggiigf.hd."
/* 7 */ "d.fgiiggiigf..d."
/* 8 */ "d.fggggggggf..d."
/* 9 */ "d.efffeefffe.hd."
/* 10 */ "d.............d."
/* 11 */ "djhhk.jhh..hh.d."
/* 12 */ "d.jlk.hj.h....d."
/* 13 */ "d..jh.hh..h..nd."
/* 14 */ "ddddddddddddddd."
/* 15 */ "................"
// Level 3
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "........o..o...."
/* 1 */ "..eppeffe..e...."
/* 2 */ "..pqq......p...."
/* 3 */ "..pq.......p...."
/* 4 */ "..pq.......p...."
/* 5 */ "..e........e...."
/* 6 */ "..p........p...."
/* 7 */ "..p........p...."
/* 8 */ "..p........p...."
/* 9 */ "..epppeepppe...."
/* 10 */ "......rr........"
/* 11 */ "................"
/* 12 */ "................"
/* 13 */ ".............n.."
/* 14 */ "................"
/* 15 */ "................"
// Level 4
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "..ssssssssss...."
/* 1 */ ".seffeffeffes..."
/* 2 */ ".sf..r.....fs..."
/* 3 */ ".sf........fs..."
/* 4 */ ".sf........fs..."
/* 5 */ ".set......ues..."
/* 6 */ ".sf........fs..."
/* 7 */ ".sf........fs..."
/* 8 */ ".sf........fs..."
/* 9 */ ".sefffeefffes..."
/* 10 */ "..ssssssssss...."
/* 11 */ "................"
/* 12 */ "................"
/* 13 */ ".............n.."
/* 14 */ "................"
/* 15 */ "................"
// Level 5
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ ".vw........wv..."
/* 1 */ ".wwwwwwwwwwww..."
/* 2 */ "..wvvvvvvvvw...."
/* 3 */ "..wvvvvvvvvw...."
/* 4 */ "..wvvvvvvvvw...."
/* 5 */ "..wvvvvvvvvw...."
/* 6 */ "..wvvvvvvvvw...."
/* 7 */ "..wvvvvvvvvw...."
/* 8 */ "..wvvvvvvvvw...."
/* 9 */ ".wwwwwwwwwwww..."
/* 10 */ ".vw........wv..."
/* 11 */ "............xxx."
/* 12 */ "...........xxxxx"
/* 13 */ "...........xxnxx"
/* 14 */ "...........xxxxx"
/* 15 */ "............xxx."
// Level 6
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "................"
/* 2 */ "................"
/* 3 */ "....wwwwww......"
/* 4 */ "....wvvvvw......"
/* 5 */ "....wvvvvw......"
/* 6 */ "....wvvvvw......"
/* 7 */ "....wwwwww......"
/* 8 */ "................"
/* 9 */ "................"
/* 10 */ "................"
/* 11 */ "............xxx."
/* 12 */ "...........xxxxx"
/* 13 */ "...........xxnxx"
/* 14 */ "...........xxxxx"
/* 15 */ "............xxx."
// Level 7
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "................"
/* 2 */ "................"
/* 3 */ "................"
/* 4 */ "................"
/* 5 */ "......ww........"
/* 6 */ "................"
/* 7 */ "................"
/* 8 */ "................"
/* 9 */ "................"
/* 10 */ "................"
/* 11 */ "................"
/* 12 */ "............xxx."
/* 13 */ "............xnx."
/* 14 */ "............xx.."
/* 15 */ "................"
// Level 8
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "................"
/* 2 */ "................"
/* 3 */ "................"
/* 4 */ "................"
/* 5 */ "................"
/* 6 */ "................"
/* 7 */ "................"
/* 8 */ "................"
/* 9 */ "................"
/* 10 */ "................"
/* 11 */ "................"
/* 12 */ ".............x.."
/* 13 */ "............xxx."
/* 14 */ ".............x.."
/* 15 */ "................",
// Connectors:
"-1: 9, 2, 0: 2\n" /* Type -1, direction Z- */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // HouseWithGarden
////////////////////////////////////////////////////////////////////////////////
// HouseWithSakura1:
// The data has been exported from the gallery Plains, area index 75, ID 141, created by Aloe_vera
{
// Size:
13, 7, 15, // SizeX = 13, SizeY = 7, SizeZ = 15
// Hitbox (relative to bounding box):
-1, 0, 0, // MinX, MinY, MinZ
13, 6, 15, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 3: 0\n" /* dirt */
"b: 2: 0\n" /* grass */
"c: 17: 5\n" /* tree */
"d: 5: 2\n" /* wood */
"e: 17: 9\n" /* tree */
"f:113: 0\n" /* netherbrickfence */
"g: 17: 1\n" /* tree */
"h: 35: 0\n" /* wool */
"i: 31: 2\n" /* tallgrass */
"j: 54: 2\n" /* chest */
"k: 38: 6\n" /* rose */
"l: 38: 2\n" /* rose */
"m: 19: 0\n" /* sponge */
"n: 50: 4\n" /* torch */
"o: 85: 0\n" /* fence */
"p: 44: 8\n" /* step */
"q: 35: 6\n" /* wool */
"r: 43: 0\n" /* doubleslab */
"s: 44: 0\n" /* step */,
// Block data:
// Level 0
/* z\x* 111 */
/* * 0123456789012 */
/* 0 */ "aaaaaaaaaaaaa"
/* 1 */ "aaaaaaaaaaaaa"
/* 2 */ "aaaaaaaaaaaaa"
/* 3 */ "aaaaaaaaaaaaa"
/* 4 */ "aaaaaaaaaaaaa"
/* 5 */ "aaaaaaaaaaaaa"
/* 6 */ "aaaaaaaaaaaaa"
/* 7 */ "aaaaaaaaaaaaa"
/* 8 */ "aaaaaaaaaaaaa"
/* 9 */ "aaaaaaaaaaaaa"
/* 10 */ "aaaaaaaaaaaaa"
/* 11 */ "aaaaaaaaaaaaa"
/* 12 */ "aaaaaaaaaaaaa"
/* 13 */ "aaaaaaaaaaaaa"
/* 14 */ "aaaaaaaaaaaaa"
// Level 1
/* z\x* 111 */
/* * 0123456789012 */
/* 0 */ "bbbbbbbbbbbbb"
/* 1 */ "bbbbbbbbbbbbb"
/* 2 */ "bbbaccdabbbbb"
/* 3 */ "bbbedddebbbbb"
/* 4 */ "bbbedddebbbbb"
/* 5 */ "bbbedddebbbbb"
/* 6 */ "bbbacccabbbbb"
/* 7 */ "bbbbbbbbbbbbb"
/* 8 */ "bbbbbbbbbbbbb"
/* 9 */ "bbbbbbbbbbbbb"
/* 10 */ "bbbbbbbbbbabb"
/* 11 */ "bbbbbbbbbbbbb"
/* 12 */ "bbbbbbbbbbbbb"
/* 13 */ "bbbbbbbbbbbbb"
/* 14 */ "bbbbbbbbbbbbb"
// Level 2
/* z\x* 111 */
/* * 0123456789012 */
/* 0 */ "ffff...ffffff"
/* 1 */ "f...........f"
/* 2 */ "f..ghh.g..i.f"
/* 3 */ "f..h...h..i.f"
/* 4 */ "f..h...h....f"
/* 5 */ "fi.h..jh..i.f"
/* 6 */ "f..ghhhg....f"
/* 7 */ "f.........i.f"
/* 8 */ "fii.........f"
/* 9 */ "f.k..k.i....f"
/* 10 */ "fl.i..i...g.f"
/* 11 */ "f.i..i.k....f"
/* 12 */ "f.l.k.......f"
/* 13 */ "f.....l.....f"
/* 14 */ "fffffffffffff"
// Level 3
/* z\x* 111 */
/* * 0123456789012 */
/* 0 */ "............."
/* 1 */ ".......n....."
/* 2 */ "...goo.g....."
/* 3 */ "...h...h....."
/* 4 */ "...o...o....."
/* 5 */ "...h...h....."
/* 6 */ "...gooog....."
/* 7 */ "............."
/* 8 */ "............."
/* 9 */ "............."
/* 10 */ "..........g.."
/* 11 */ "............."
/* 12 */ "............."
/* 13 */ "............."
/* 14 */ "............."
// Level 4
/* z\x* 111 */
/* * 0123456789012 */
/* 0 */ "............."
/* 1 */ "...ppppp....."
/* 2 */ "..pghhhgp...."
/* 3 */ "..ph...hp...."
/* 4 */ "..ph...hp...."
/* 5 */ "..ph...hp...."
/* 6 */ "..pghhhgp...."
/* 7 */ "...ppppp....."
/* 8 */ "............."
/* 9 */ "..........q.."
/* 10 */ ".........qgq."
/* 11 */ "..........q.."
/* 12 */ "............."
/* 13 */ "............."
/* 14 */ "............."
// Level 5
/* z\x* 111 */
/* * 0123456789012 */
/* 0 */ "............."
/* 1 */ "..rs...sr...."
/* 2 */ "..sssssss...."
/* 3 */ "...srrrs....."
/* 4 */ "...srrrs....."
/* 5 */ "...srrrs....."
/* 6 */ "..sssssss...."
/* 7 */ "..rs...sr...."
/* 8 */ "............."
/* 9 */ ".........qqq."
/* 10 */ ".........qqq."
/* 11 */ ".........qqq."
/* 12 */ "............."
/* 13 */ "............."
/* 14 */ "............."
// Level 6
/* z\x* 111 */
/* * 0123456789012 */
/* 0 */ "............."
/* 1 */ "............."
/* 2 */ "............."
/* 3 */ "............."
/* 4 */ ".....s......."
/* 5 */ "............."
/* 6 */ "............."
/* 7 */ "............."
/* 8 */ "............."
/* 9 */ "............."
/* 10 */ "..........q.."
/* 11 */ "............."
/* 12 */ "............."
/* 13 */ "............."
/* 14 */ ".............",
// Connectors:
"-1: 5, 2, 0: 2\n" /* Type -1, direction Z- */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // HouseWithSakura1
////////////////////////////////////////////////////////////////////////////////
// HouseWithSpa:
// The data has been exported from the gallery Plains, area index 73, ID 139, created by Aloe_vera
{
// Size:
16, 8, 14, // SizeX = 16, SizeY = 8, SizeZ = 14
// Hitbox (relative to bounding box):
0, 0, 0, // MinX, MinY, MinZ
15, 7, 13, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 5: 2\n" /* wood */
"b: 3: 0\n" /* dirt */
"c: 2: 0\n" /* grass */
"d: 8: 0\n" /* water */
"e:135: 3\n" /* 135 */
"f:135: 1\n" /* 135 */
"g:113: 0\n" /* netherbrickfence */
"h: 17: 1\n" /* tree */
"i: 35: 0\n" /* wool */
"j:171:12\n" /* carpet */
"k: 64: 6\n" /* wooddoorblock */
"l:126: 2\n" /* woodenslab */
"m: 19: 0\n" /* sponge */
"n:135: 2\n" /* 135 */
"o: 64: 7\n" /* wooddoorblock */
"p: 50: 4\n" /* torch */
"q: 85: 0\n" /* fence */
"r: 64:12\n" /* wooddoorblock */
"s: 50: 3\n" /* torch */
"t: 44: 8\n" /* step */
"u: 43: 0\n" /* doubleslab */
"v: 44: 0\n" /* step */,
// Block data:
// Level 0
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ ".aaaaaaaaaaaaaa."
/* 2 */ ".aaaaaaaaaaaaaa."
/* 3 */ ".aaaaaaaaaaaaaa."
/* 4 */ ".aaaaaaaaaaaaaa."
/* 5 */ ".aaaaaaaaaaaaaa."
/* 6 */ ".aaaaaaaaaaaaaa."
/* 7 */ ".aaaaaabbbbbbbbb"
/* 8 */ ".aaaaaabbbbbbbbb"
/* 9 */ ".aaaaaabbbbbbbbb"
/* 10 */ ".aaaaaabbbbbbbbb"
/* 11 */ ".aaaaaabbbbbbbbb"
/* 12 */ ".aaaaaabbbbbbbbb"
/* 13 */ ".......bbbbbbbbb"
// Level 1
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "mmmmmmmmmmmmmmmm"
/* 1 */ "maaaaaaaaaaaaaam"
/* 2 */ "maaaaaaaaaaaaaam"
/* 3 */ "maaaaaaaaaaaaaam"
/* 4 */ "maaaaaaaaaaaaaam"
/* 5 */ "maaaaaaaaaaaaaam"
/* 6 */ "maaaaaaaaaaaaaam"
/* 7 */ "maaaaaaaaaaccccc"
/* 8 */ "maaaaaaacccccccc"
/* 9 */ "maaaaaaacccccccc"
/* 10 */ "maaaaaaacccccccc"
/* 11 */ "maaaaaaccccccccc"
/* 12 */ "maaaaaaccccccccc"
/* 13 */ "mmmmmmmccccccccc"
// Level 2
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ ".aaaaaaaaaaaaaa."
/* 2 */ ".aaaaaaaaaaaaaa."
/* 3 */ ".aaaaaaaaaaaaaa."
/* 4 */ ".aaaaaaaaaaaaaa."
/* 5 */ ".aaaaaaaaaaaaaa."
/* 6 */ ".aaddaaaaaaaaaa."
/* 7 */ ".aaddaaeeef....."
/* 8 */ ".aaddaaf........"
/* 9 */ ".aaddaaf........"
/* 10 */ ".aaddaae........"
/* 11 */ ".aaddaa........."
/* 12 */ ".aaaaaa........."
/* 13 */ "................"
// Level 3
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ ".ggggghiiihiiih."
/* 2 */ ".geee.ijjjjjjji."
/* 3 */ ".gf...kjjjijlji."
/* 4 */ ".gf...innjijjji."
/* 5 */ ".g....hiiohiiih."
/* 6 */ ".g....g........."
/* 7 */ ".g.............."
/* 8 */ ".g.............."
/* 9 */ ".g.............."
/* 10 */ ".g....g........."
/* 11 */ ".g....g........."
/* 12 */ ".gggggg........."
/* 13 */ "................"
// Level 4
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "......p...p...p."
/* 1 */ ".g....hqqqhqqqh."
/* 2 */ "......i.......i."
/* 3 */ "......r...q...q."
/* 4 */ "......i...q...i."
/* 5 */ "......hqqrhqqqh."
/* 6 */ "......g...s....."
/* 7 */ "................"
/* 8 */ "................"
/* 9 */ "................"
/* 10 */ "................"
/* 11 */ "................"
/* 12 */ ".g....g........."
/* 13 */ "................"
// Level 5
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ ".tttttttttttttt."
/* 1 */ "tggggghqqqhqqqht"
/* 2 */ "tg....i.......it"
/* 3 */ "tg....i...i...it"
/* 4 */ "tg....i...i...it"
/* 5 */ "tg....hiiihiiiht"
/* 6 */ "tg....gtttttttt."
/* 7 */ "tg....gt........"
/* 8 */ "tg....gt........"
/* 9 */ "tg....gt........"
/* 10 */ "tg....gt........"
/* 11 */ "tg....gt........"
/* 12 */ "tggggggt........"
/* 13 */ ".tttttt........."
// Level 6
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "uv............vu"
/* 1 */ "vvvvvvvvvvvvvvvv"
/* 2 */ ".vuuuuuuuuuuuuv."
/* 3 */ ".vuuuuuutuuuuuv."
/* 4 */ ".vuuuuuuuuuuuuv."
/* 5 */ ".vuuuuvvvvvvvvvv"
/* 6 */ ".vuuuuv.......vu"
/* 7 */ ".vuuuuv........."
/* 8 */ ".vuuuuv........."
/* 9 */ ".vuuuuv........."
/* 10 */ ".vuuuuv........."
/* 11 */ ".vuuuuv........."
/* 12 */ "vvvvvvvv........"
/* 13 */ "uv....vu........"
// Level 7
/* z\x* 111111 */
/* * 0123456789012345 */
/* 0 */ "................"
/* 1 */ "................"
/* 2 */ "................"
/* 3 */ "...vvvvvvvvvv..."
/* 4 */ "...vv..........."
/* 5 */ "...vv..........."
/* 6 */ "...vv..........."
/* 7 */ "...vv..........."
/* 8 */ "...vv..........."
/* 9 */ "...vv..........."
/* 10 */ "...vv..........."
/* 11 */ "................"
/* 12 */ "................"
/* 13 */ "................",
// Connectors:
"",
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // HouseWithSpa
////////////////////////////////////////////////////////////////////////////////
// MediumSakuraTree:
// The data has been exported from the gallery Plains, area index 146, ID 490, created by STR_Warrior
{
// Size:
7, 10, 7, // SizeX = 7, SizeY = 10, SizeZ = 7
// Hitbox (relative to bounding box):
0, 0, 0, // MinX, MinY, MinZ
6, 9, 6, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 3: 0\n" /* dirt */
"b: 2: 0\n" /* grass */
"c: 31: 1\n" /* tallgrass */
"d: 38: 7\n" /* rose */
"e: 17: 1\n" /* tree */
"f: 38: 0\n" /* rose */
"g: 38: 8\n" /* rose */
"h: 38: 5\n" /* rose */
"i: 35: 6\n" /* wool */
"m: 19: 0\n" /* sponge */,
// Block data:
// Level 0
/* z\x* 0123456 */
/* 0 */ "aaaaaaa"
/* 1 */ "aaaaaaa"
/* 2 */ "aaaaaaa"
/* 3 */ "aaaaaaa"
/* 4 */ "aaaaaaa"
/* 5 */ "aaaaaaa"
/* 6 */ "aaaaaaa"
// Level 1
/* z\x* 0123456 */
/* 0 */ "bbbbbbb"
/* 1 */ "bbbbbbb"
/* 2 */ "bbbbbbb"
/* 3 */ "bbbabbb"
/* 4 */ "bbbbbbb"
/* 5 */ "bbbbbbb"
/* 6 */ "bbbbbbb"
// Level 2
/* z\x* 0123456 */
/* 0 */ "mm...mm"
/* 1 */ "m.c...m"
/* 2 */ ".dccdc."
/* 3 */ "..cefc."
/* 4 */ ".ccfgh."
/* 5 */ "m.ccc.m"
/* 6 */ "mm...mm"
// Level 3
/* z\x* 0123456 */
/* 0 */ "m.....m"
/* 1 */ "......."
/* 2 */ "......."
/* 3 */ "...e..."
/* 4 */ "......."
/* 5 */ "......."
/* 6 */ "m.....m"
// Level 4
/* z\x* 0123456 */
/* 0 */ "......."
/* 1 */ "..i...."
/* 2 */ "......."
/* 3 */ "...e.i."
/* 4 */ ".i....."
/* 5 */ "......."
/* 6 */ "......."
// Level 5
/* z\x* 0123456 */
/* 0 */ "......."
/* 1 */ "..i...."
/* 2 */ "...i..."
/* 3 */ "..ieii."
/* 4 */ ".i.ii.."
/* 5 */ "...i..."
/* 6 */ "......."
// Level 6
/* z\x* 0123456 */
/* 0 */ "......."
/* 1 */ "..ii..."
/* 2 */ "..iii.."
/* 3 */ ".iieii."
/* 4 */ ".iiii.."
/* 5 */ "..iii.."
/* 6 */ "......."
// Level 7
/* z\x* 0123456 */
/* 0 */ "......."
/* 1 */ "..iii.."
/* 2 */ ".iiiii."
/* 3 */ ".iieii."
/* 4 */ ".iiiii."
/* 5 */ "..iii.."
/* 6 */ "......."
// Level 8
/* z\x* 0123456 */
/* 0 */ "......."
/* 1 */ "...i..."
/* 2 */ "..iiii."
/* 3 */ ".iiiii."
/* 4 */ "..iii.."
/* 5 */ "...i..."
/* 6 */ "......."
// Level 9
/* z\x* 0123456 */
/* 0 */ "......."
/* 1 */ "......."
/* 2 */ "...i..."
/* 3 */ "..iii.."
/* 4 */ "...i..."
/* 5 */ "......."
/* 6 */ ".......",
// Connectors:
"-1: 3, 2, 0: 2\n" /* Type -1, direction Z- */
"3: 6, 2, 3: 5\n" /* Type 3, direction X+ */
"-3: 0, 2, 3: 4\n" /* Type -3, direction X- */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // MediumSakuraTree
////////////////////////////////////////////////////////////////////////////////
// Restaurant:
// The data has been exported from the gallery Plains, area index 61, ID 117, created by Aloe_vera
{
// Size:
15, 10, 15, // SizeX = 15, SizeY = 10, SizeZ = 15
// Hitbox (relative to bounding box):
-1, 0, -1, // MinX, MinY, MinZ
14, 9, 15, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 5: 2\n" /* wood */
"b:135: 0\n" /* 135 */
"c:135: 2\n" /* 135 */
"d:135: 1\n" /* 135 */
"e: 17: 9\n" /* tree */
"f:135: 3\n" /* 135 */
"g: 85: 0\n" /* fence */
"h: 17: 1\n" /* tree */
"i:171: 0\n" /* carpet */
"j:171:12\n" /* carpet */
"k:126: 1\n" /* woodenslab */
"l: 50: 5\n" /* torch */
"m: 19: 0\n" /* sponge */
"n: 35: 0\n" /* wool */
"o: 50: 3\n" /* torch */
"p: 50: 1\n" /* torch */
"q: 50: 4\n" /* torch */
"r: 35:14\n" /* wool */
"s: 44: 8\n" /* step */
"t: 43: 0\n" /* doubleslab */
"u: 44: 0\n" /* step */
"v: 17: 5\n" /* tree */,
// Block data:
// Level 0
/* z\x* 11111 */
/* * 012345678901234 */
/* 0 */ "mmmmaaaaaaammmm"
/* 1 */ "maaaaaaaaaaaaam"
/* 2 */ "maaaaaaaaaaaaam"
/* 3 */ "maaaaaaaaaaaaam"
/* 4 */ "aaaaaaaaaaaaaaa"
/* 5 */ "aaaaaaaaaaaaaaa"
/* 6 */ "aaaaaaaaaaaaaaa"
/* 7 */ "aaaaaaaaaaaaaaa"
/* 8 */ "aaaaaaaaaaaaaaa"
/* 9 */ "aaaaaaaaaaaaaaa"
/* 10 */ "aaaaaaaaaaaaaaa"
/* 11 */ "maaaaaaaaaaaaam"
/* 12 */ "maaaaaaaaaaaaam"
/* 13 */ "maaaaaaaaaaaaam"
/* 14 */ "mmmmaaaaaaammmm"
// Level 1
/* z\x* 11111 */
/* * 012345678901234 */
/* 0 */ "....bcccccd...."
/* 1 */ ".aaaaaaaaaaaaa."
/* 2 */ ".aaaaaaaaaaaaa."
/* 3 */ ".aaaaaaaaaaaaa."
/* 4 */ "caaaaaaaaaaaaac"
/* 5 */ "baaaaaaaaaaaaad"
/* 6 */ "baaaaaaaaaaaaad"
/* 7 */ "baaaaaaaaaaeaad"
/* 8 */ "baaaaaaaaaaaaad"
/* 9 */ "baaaaaaaaaaaaad"
/* 10 */ "faaaaaaaaaaaaaf"
/* 11 */ ".aaaaaaaaaaaaa."
/* 12 */ ".aaaaaaaaaaaaa."
/* 13 */ ".aaaaaaaaaaaaa."
/* 14 */ "....bfffffd...."
// Level 2
/* z\x* 11111 */
/* * 012345678901234 */
/* 0 */ "..............."
/* 1 */ ".gggg.....gggg."
/* 2 */ ".g...........g."
/* 3 */ ".g.hhhhhhhhh.g."
/* 4 */ ".g.hiiijiiih.g."
/* 5 */ "...hikijikih..."
/* 6 */ "...hiiijiiihg.."
/* 7 */ "...hjjjjjjj...."
/* 8 */ "...hiiijiiihg.."
/* 9 */ "...hikijikih..."
/* 10 */ ".g.hiiijiiih.g."
/* 11 */ ".g.hhhhhhhhh.g."
/* 12 */ ".g...........g."
/* 13 */ ".gggg.....gggg."
/* 14 */ "..............."
// Level 3
/* z\x* 11111 */
/* * 012345678901234 */
/* 0 */ "..............."
/* 1 */ ".l..g.....g..l."
/* 2 */ "..............."
/* 3 */ "...hnnnhnnnh..."
/* 4 */ ".g.n.......n.g."
/* 5 */ "...n.......n..."
/* 6 */ "...n.......hl.."
/* 7 */ "...h..........."
/* 8 */ "...n.......hl.."
/* 9 */ "...n.......n..."
/* 10 */ ".g.n.......n.g."
/* 11 */ "...hnnnhnnnh..."
/* 12 */ "..............."
/* 13 */ ".l..g.....g..l."
/* 14 */ "..............."
// Level 4
/* z\x* 11111 */
/* * 012345678901234 */
/* 0 */ "..............."
/* 1 */ "....g.....g...."
/* 2 */ "..............."
/* 3 */ "...hn.nhn.nh..."
/* 4 */ ".g.n...o...n.g."
/* 5 */ "...n.......n..."
/* 6 */ "...n.......h..."
/* 7 */ "...hp......e..."
/* 8 */ "...n.......h..."
/* 9 */ "...n.......n..."
/* 10 */ ".g.n...q...n.g."
/* 11 */ "...hn.nhn.nh..."
/* 12 */ "..............."
/* 13 */ "....g.....g...."
/* 14 */ "..............."
// Level 5
/* z\x* 11111 */
/* * 012345678901234 */
/* 0 */ "..............."
/* 1 */ "....g.....g...."
/* 2 */ "....ggggggg...."
/* 3 */ "...hnnnhnnnh..."
/* 4 */ ".ggn.......ngg."
/* 5 */ "..gn.......ng.."
/* 6 */ "..gn.......hg.."
/* 7 */ "..gh..r.r..ng.."
/* 8 */ "..gn.......hg.."
/* 9 */ "..gn.......ng.."
/* 10 */ ".ggn.......ngg."
/* 11 */ "...hnnnhnnnh..."
/* 12 */ "....ggggggg...."
/* 13 */ "....g.....g...."
/* 14 */ "..............."
// Level 6
/* z\x* 11111 */
/* * 012345678901234 */
/* 0 */ "..............."
/* 1 */ "...stuuuuuts..."
/* 2 */ "..sttttttttts.."
/* 3 */ ".sthvvvhvvvhts."
/* 4 */ ".tte.......ett."
/* 5 */ ".ute.......etu."
/* 6 */ ".ute.......htu."
/* 7 */ ".uth..g.g..etu."
/* 8 */ ".ute.......htu."
/* 9 */ ".ute.......etu."
/* 10 */ ".tte.......ett."
/* 11 */ ".sthvvvhvvvhts."
/* 12 */ "..sttttttttts.."
/* 13 */ "...stuuuuuts..."
/* 14 */ "..............."
// Level 7
/* z\x* 11111 */
/* * 012345678901234 */
/* 0 */ "..............."
/* 1 */ ".stu.......uts."
/* 2 */ ".tu.........ut."
/* 3 */ ".u.uuuuuuuuu.u."
/* 4 */ "...utttttttu..."
/* 5 */ "...utttttttu..."
/* 6 */ "...utttttttu..."
/* 7 */ "...utttttttu..."
/* 8 */ "...utttttttu..."
/* 9 */ "...utttttttu..."
/* 10 */ "...utttttttu..."
/* 11 */ ".u.uuuuuuuuu.u."
/* 12 */ ".tu.........ut."
/* 13 */ ".stu.......uts."
/* 14 */ "..............."
// Level 8
/* z\x* 11111 */
/* * 012345678901234 */
/* 0 */ "..............."
/* 1 */ ".u...........u."
/* 2 */ "..............."
/* 3 */ "..............."
/* 4 */ "..............."
/* 5 */ ".....uuuuu....."
/* 6 */ ".....utttu....."
/* 7 */ ".....utttu....."
/* 8 */ ".....utttu....."
/* 9 */ ".....uuuuu....."
/* 10 */ "..............."
/* 11 */ "..............."
/* 12 */ "..............."
/* 13 */ ".u...........u."
/* 14 */ "..............."
// Level 9
/* z\x* 11111 */
/* * 012345678901234 */
/* 0 */ "..............."
/* 1 */ "..............."
/* 2 */ "..............."
/* 3 */ "..............."
/* 4 */ "..............."
/* 5 */ "..............."
/* 6 */ "..............."
/* 7 */ ".......u......."
/* 8 */ "..............."
/* 9 */ "..............."
/* 10 */ "..............."
/* 11 */ "..............."
/* 12 */ "..............."
/* 13 */ "..............."
/* 14 */ "...............",
// Connectors:
"-1: 14, 1, 7: 5\n" /* Type -1, direction X+ */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // Restaurant
////////////////////////////////////////////////////////////////////////////////
// SakuraDouble:
// The data has been exported from the gallery Plains, area index 76, ID 142, created by Aloe_vera
{
// Size:
12, 8, 6, // SizeX = 12, SizeY = 8, SizeZ = 6
// Hitbox (relative to bounding box):
-1, 0, -1, // MinX, MinY, MinZ
12, 7, 6, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 3: 0\n" /* dirt */
"b: 2: 0\n" /* grass */
"c: 17: 1\n" /* tree */
"d: 35: 6\n" /* wool */
"m: 19: 0\n" /* sponge */,
// Block data:
// Level 0
/* z\x* 11 */
/* * 012345678901 */
/* 0 */ "aaaaaaaaaaaa"
/* 1 */ "aaaaaaaaaaaa"
/* 2 */ "aaaaaaaaaaaa"
/* 3 */ "aaaaaaaaaaaa"
/* 4 */ "aaaaaaaaaaaa"
/* 5 */ "aaaaaaaaaaaa"
// Level 1
/* z\x* 11 */
/* * 012345678901 */
/* 0 */ "bbbbbbbbbbbb"
/* 1 */ "bbbbbbbbbbbb"
/* 2 */ "bbabbbbbbbbb"
/* 3 */ "bbbbbbbbbabb"
/* 4 */ "bbbbbbbbbbbb"
/* 5 */ "bbbbbbbbbbbb"
// Level 2
/* z\x* 11 */
/* * 012345678901 */
/* 0 */ "............"
/* 1 */ "............"
/* 2 */ "..c........."
/* 3 */ ".........c.."
/* 4 */ "............"
/* 5 */ "............"
// Level 3
/* z\x* 11 */
/* * 012345678901 */
/* 0 */ "............"
/* 1 */ "............"
/* 2 */ "..c........."
/* 3 */ ".........c.."
/* 4 */ "............"
/* 5 */ "............"
// Level 4
/* z\x* 11 */
/* * 012345678901 */
/* 0 */ "..d........."
/* 1 */ "ddddd......."
/* 2 */ "ddcdd...ddd."
/* 3 */ "ddddd...dcd."
/* 4 */ "..d.....ddd."
/* 5 */ "............"
// Level 5
/* z\x* 11 */
/* * 012345678901 */
/* 0 */ ".ddd........"
/* 1 */ ".ddd....ddd."
/* 2 */ "ddddd..ddddd"
/* 3 */ ".ddd...ddcdd"
/* 4 */ ".ddd...ddddd"
/* 5 */ "........ddd."
// Level 6
/* z\x* 11 */
/* * 012345678901 */
/* 0 */ "............"
/* 1 */ "..d......d.."
/* 2 */ ".ddd....ddd."
/* 3 */ "..d....ddddd"
/* 4 */ "........ddd."
/* 5 */ ".........d.."
// Level 7
/* z\x* 11 */
/* * 012345678901 */
/* 0 */ "............"
/* 1 */ "............"
/* 2 */ "............"
/* 3 */ ".........d.."
/* 4 */ "............"
/* 5 */ "............",
// Connectors:
"-1: -1, 2, 2: 4\n" /* Type -1, direction X- */
"3: 5, 2, 6: 3\n" /* Type 3, direction Z+ */
"-3: 6, 2, -1: 2\n" /* Type -3, direction Z- */
"-3: 12, 2, 2: 5\n" /* Type -3, direction X+ */
"3: 12, 2, 2: 5\n" /* Type 3, direction X+ */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // SakuraDouble
////////////////////////////////////////////////////////////////////////////////
// SakuraSmall:
// The data has been exported from the gallery Plains, area index 145, ID 489, created by Aloe_vera
{
// Size:
5, 7, 5, // SizeX = 5, SizeY = 7, SizeZ = 5
// Hitbox (relative to bounding box):
-1, 0, -1, // MinX, MinY, MinZ
5, 6, 5, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 3: 0\n" /* dirt */
"b: 2: 0\n" /* grass */
"c: 17: 1\n" /* tree */
"d: 35: 6\n" /* wool */
"m: 19: 0\n" /* sponge */,
// Block data:
// Level 0
/* z\x* 01234 */
/* 0 */ "aaaaa"
/* 1 */ "aaaaa"
/* 2 */ "aaaaa"
/* 3 */ "aaaaa"
/* 4 */ "aaaaa"
// Level 1
/* z\x* 01234 */
/* 0 */ "bbbbb"
/* 1 */ "bbbbb"
/* 2 */ "bbabb"
/* 3 */ "bbbbb"
/* 4 */ "bbbbb"
// Level 2
/* z\x* 01234 */
/* 0 */ "....."
/* 1 */ "....."
/* 2 */ "..c.."
/* 3 */ "....."
/* 4 */ "....."
// Level 3
/* z\x* 01234 */
/* 0 */ "....."
/* 1 */ "....."
/* 2 */ "..c.."
/* 3 */ "....."
/* 4 */ "....."
// Level 4
/* z\x* 01234 */
/* 0 */ "..d.."
/* 1 */ "ddddd"
/* 2 */ "ddcdd"
/* 3 */ "ddddd"
/* 4 */ "..d.."
// Level 5
/* z\x* 01234 */
/* 0 */ ".ddd."
/* 1 */ ".ddd."
/* 2 */ "ddddd"
/* 3 */ ".ddd."
/* 4 */ ".ddd."
// Level 6
/* z\x* 01234 */
/* 0 */ "....."
/* 1 */ "..d.."
/* 2 */ ".ddd."
/* 3 */ "..d.."
/* 4 */ ".....",
// Connectors:
"-1: 2, 2, -1: 2\n" /* Type -1, direction Z- */
"3: 5, 2, 2: 5\n" /* Type 3, direction X+ */
"-3: -1, 2, 2: 4\n" /* Type -3, direction X- */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // SakuraSmall
}; // g_JapaneseVillagePrefabs
const cPrefab::sDef g_JapaneseVillageStartingPrefabs[] =
{
////////////////////////////////////////////////////////////////////////////////
// HighTemple:
// The data has been exported from the gallery Plains, area index 70, ID 133, created by Aloe_vera
{
// Size:
11, 19, 11, // SizeX = 11, SizeY = 19, SizeZ = 11
// Hitbox (relative to bounding box):
0, 0, 0, // MinX, MinY, MinZ
10, 18, 10, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 5: 2\n" /* wood */
"b:135: 0\n" /* 135 */
"c:135: 2\n" /* 135 */
"d:135: 1\n" /* 135 */
"e: 17: 9\n" /* tree */
"f:135: 3\n" /* 135 */
"g: 85: 0\n" /* fence */
"h: 17: 1\n" /* tree */
"i:171: 0\n" /* carpet */
"j: 50: 5\n" /* torch */
"k: 35: 0\n" /* wool */
"l: 17: 5\n" /* tree */
"m: 19: 0\n" /* sponge */
"n:124: 0\n" /* redstonelampon */
"o: 69: 9\n" /* lever */
"p: 44: 8\n" /* step */
"q: 43: 0\n" /* doubleslab */
"r: 44: 0\n" /* step */
"s: 50: 4\n" /* torch */
"t: 50: 1\n" /* torch */
"u: 50: 3\n" /* torch */,
// Block data:
// Level 0
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "mmmaaaaammm"
/* 1 */ "maaaaaaaaam"
/* 2 */ "maaaaaaaaam"
/* 3 */ "aaaaaaaaaaa"
/* 4 */ "aaaaaaaaaaa"
/* 5 */ "aaaaaaaaaaa"
/* 6 */ "aaaaaaaaaaa"
/* 7 */ "aaaaaaaaaaa"
/* 8 */ "maaaaaaaaam"
/* 9 */ "maaaaaaaaam"
/* 10 */ "mmmaaaaammm"
// Level 1
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "...bcccd..."
/* 1 */ ".aaaaaaaaa."
/* 2 */ ".aaaaaaaaa."
/* 3 */ "caaaaaaaaac"
/* 4 */ "baaaaaaaaad"
/* 5 */ "baaeaaaaaad"
/* 6 */ "baaaaaaaaad"
/* 7 */ "faaaaaaaaaf"
/* 8 */ ".aaaaaaaaa."
/* 9 */ ".aaaaaaaaa."
/* 10 */ "...bfffd..."
// Level 2
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ ".ggg...ggg."
/* 2 */ ".g.......g."
/* 3 */ ".g.hhhhh.g."
/* 4 */ "...hiiih..."
/* 5 */ "....iiih..."
/* 6 */ "...hiiih..."
/* 7 */ ".g.hhhhh.g."
/* 8 */ ".g.......g."
/* 9 */ ".ggg...ggg."
/* 10 */ "..........."
// Level 3
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ ".j.g...g.j."
/* 2 */ "..........."
/* 3 */ ".g.kkhkk.g."
/* 4 */ "...h...k..."
/* 5 */ ".......h..."
/* 6 */ "...h...k..."
/* 7 */ ".g.kkhkk.g."
/* 8 */ "..........."
/* 9 */ ".j.g...g.j."
/* 10 */ "..........."
// Level 4
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "...g...g..."
/* 2 */ "..........."
/* 3 */ ".g.kkhkk.g."
/* 4 */ "...h...k..."
/* 5 */ "...k...h..."
/* 6 */ "...h...k..."
/* 7 */ ".g.kkhkk.g."
/* 8 */ "..........."
/* 9 */ "...g...g..."
/* 10 */ "..........."
// Level 5
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "...g...g..."
/* 2 */ "...ggggg..."
/* 3 */ ".gghlhlhgg."
/* 4 */ "..ge...eg.."
/* 5 */ "..ge.nohg.."
/* 6 */ "..ge...eg.."
/* 7 */ ".gghlhlhgg."
/* 8 */ "...ggggg..."
/* 9 */ "...g...g..."
/* 10 */ "..........."
// Level 6
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..pqrrrqp.."
/* 2 */ ".pqqqqqqqp."
/* 3 */ ".qqhkkkhqq."
/* 4 */ ".rqkhhhkqr."
/* 5 */ ".rqkhhhkqr."
/* 6 */ ".rqkhhhkqr."
/* 7 */ ".qqhkkkhqq."
/* 8 */ ".pqqqqqqqp."
/* 9 */ "..pqrrrqp.."
/* 10 */ "..........."
// Level 7
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ ".qr.....rq."
/* 2 */ ".........r."
/* 3 */ "...hhhhh..."
/* 4 */ "...hiiih..."
/* 5 */ "....iiih..."
/* 6 */ "...hiiih..."
/* 7 */ "...hhhhh..."
/* 8 */ ".r.......r."
/* 9 */ ".qr.....rq."
/* 10 */ "..........."
// Level 8
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..........."
/* 2 */ "..........."
/* 3 */ "...kkhkk..."
/* 4 */ "...h...k..."
/* 5 */ ".......h..."
/* 6 */ "...h...k..."
/* 7 */ "...kkhkk..."
/* 8 */ "..........."
/* 9 */ "..........."
/* 10 */ "..........."
// Level 9
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..........."
/* 2 */ ".....s....."
/* 3 */ "...kkhkk..."
/* 4 */ "...h...k..."
/* 5 */ "...k...ht.."
/* 6 */ "...h...k..."
/* 7 */ "...kkhkk..."
/* 8 */ ".....u....."
/* 9 */ "..........."
/* 10 */ "..........."
// Level 10
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..........."
/* 2 */ "...ggggg..."
/* 3 */ "..ghlhlhg.."
/* 4 */ "..ge...eg.."
/* 5 */ "..ge.nohg.."
/* 6 */ "..ge...eg.."
/* 7 */ "..ghlhlhg.."
/* 8 */ "...ggggg..."
/* 9 */ "..........."
/* 10 */ "..........."
// Level 11
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..prrrrrp.."
/* 2 */ ".pqqqqqqqp."
/* 3 */ ".qqhkkkhqq."
/* 4 */ ".rqkhhhkqr."
/* 5 */ ".rqkhhhkqr."
/* 6 */ ".rqkhhhkqr."
/* 7 */ ".qqhkkkhqr."
/* 8 */ ".pqqqqqqqp."
/* 9 */ "..pqrrrqp.."
/* 10 */ "..........."
// Level 12
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ ".qr.....rq."
/* 2 */ ".r.......r."
/* 3 */ "...hhhhh..."
/* 4 */ "...hiiih..."
/* 5 */ "....iiih..."
/* 6 */ "...hiiih..."
/* 7 */ "...hhhhh..."
/* 8 */ ".r.......r."
/* 9 */ ".qr.....rq."
/* 10 */ "..........."
// Level 13
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..........."
/* 2 */ "..........."
/* 3 */ "...kkhkk..."
/* 4 */ "...h...k..."
/* 5 */ ".......h..."
/* 6 */ "...h...k..."
/* 7 */ "...kkhkk..."
/* 8 */ "..........."
/* 9 */ "..........."
/* 10 */ "..........."
// Level 14
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..........."
/* 2 */ ".....s....."
/* 3 */ "...kkhkk..."
/* 4 */ "...h...k..."
/* 5 */ "...k...ht.."
/* 6 */ "...h...k..."
/* 7 */ "...kkhkk..."
/* 8 */ ".....u....."
/* 9 */ "..........."
/* 10 */ "..........."
// Level 15
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..........."
/* 2 */ "...ggggg..."
/* 3 */ "..ghlhlhg.."
/* 4 */ "..ge...eg.."
/* 5 */ "..ge.nohg.."
/* 6 */ "..ge...eg.."
/* 7 */ "..ghlhlhg.."
/* 8 */ "...ggggg..."
/* 9 */ "..........."
/* 10 */ "..........."
// Level 16
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..pqrrrqp.."
/* 2 */ ".pqqqqqqqp."
/* 3 */ ".qqrrrrrqq."
/* 4 */ ".rqrrrrrqr."
/* 5 */ ".rqrrrrrqr."
/* 6 */ ".rqrrrrrqr."
/* 7 */ ".qqrrrrrqq."
/* 8 */ ".pqqqqqqqp."
/* 9 */ "..pqrrrqp.."
/* 10 */ "..........."
// Level 17
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ ".qr.....rq."
/* 2 */ ".rr.....rr."
/* 3 */ "...rrrrr..."
/* 4 */ "...rqqqr..."
/* 5 */ "...rqqqr..."
/* 6 */ "...rqqqr..."
/* 7 */ "...rrrrr..."
/* 8 */ ".rr.....rr."
/* 9 */ ".qr.....rq."
/* 10 */ "..........."
// Level 18
/* z\x* 1 */
/* * 01234567890 */
/* 0 */ "..........."
/* 1 */ "..........."
/* 2 */ "..........."
/* 3 */ "..........."
/* 4 */ "..........."
/* 5 */ ".....r....."
/* 6 */ "..........."
/* 7 */ "..........."
/* 8 */ "..........."
/* 9 */ "..........."
/* 10 */ "...........",
// Connectors:
"2: 0, 1, 5: 4\n" /* Type 2, direction X- */
"2: 5, 1, 0: 2\n" /* Type 2, direction Z- */
"2: 10, 1, 5: 5\n" /* Type 2, direction X+ */
"2: 5, 1, 10: 3\n" /* Type 2, direction Z+ */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:
cBlockArea::msSpongePrint,
// ShouldExtendFloor:
true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // HighTemple
////////////////////////////////////////////////////////////////////////////////
// Well:
// The data has been exported from the gallery Plains, area index 143, ID 487, created by STR_Warrior
{
// Size:
7, 14, 7, // SizeX = 7, SizeY = 14, SizeZ = 7
// Hitbox (relative to bounding box):
0, 0, 0, // MinX, MinY, MinZ
6, 13, 6, // MaxX, MaxY, MaxZ
// Block definitions:
".: 0: 0\n" /* air */
"a: 1: 0\n" /* stone */
"b: 4: 0\n" /* cobblestone */
"c: 8: 0\n" /* water */
"d: 13: 0\n" /* gravel */
"e: 67: 1\n" /* stairs */
"f: 67: 2\n" /* stairs */
"g: 67: 0\n" /* stairs */
"h: 67: 3\n" /* stairs */
"i: 85: 0\n" /* fence */
"j: 44: 8\n" /* step */
"k: 44: 0\n" /* step */
"l: 43: 0\n" /* doubleslab */
"m: 19: 0\n" /* sponge */,
// Block data:
// Level 0
/* z\x* 0123456 */
/* 0 */ "mmmmmmm"
/* 1 */ "maaaaam"
/* 2 */ "maaaaam"
/* 3 */ "maaaaam"
/* 4 */ "maaaaam"
/* 5 */ "maaaaam"
/* 6 */ "mmmmmmm"
// Level 1
/* z\x* 0123456 */
/* 0 */ "mmmmmmm"
/* 1 */ "mbbbbbm"
/* 2 */ "mbcc.bm"
/* 3 */ "mbcccbm"
/* 4 */ "mbcccbm"
/* 5 */ "mbbbbbm"
/* 6 */ "mmmmmmm"
// Level 2
/* z\x* 0123456 */
/* 0 */ "mmmmmmm"
/* 1 */ "mbbbbbm"
/* 2 */ "mbcccbm"
/* 3 */ "mbcccbm"
/* 4 */ "mbcccbm"
/* 5 */ "mbbbbbm"
/* 6 */ "mmmmmmm"
// Level 3
/* z\x* 0123456 */
/* 0 */ "mmmmmmm"
/* 1 */ "mbbbbbm"
/* 2 */ "mbcccbm"
/* 3 */ "mbcccbm"
/* 4 */ "mbcccbm"
/* 5 */ "mbbbbbm"
/* 6 */ "mmmmmmm"
// Level 4
/* z\x* 0123456 */
/* 0 */ "mmmmmmm"
/* 1 */ "mbbbbbm"
/* 2 */ "mbcccbm"
/* 3 */ "mbcccbm"
/* 4 */ "mbcccbm"
/* 5 */ "mbbbbbm"
/* 6 */ "mmmmmmm"
// Level 5
/* z\x* 0123456 */
/* 0 */ "mmmmmmm"
/* 1 */ "mbbbbbm"
/* 2 */ "mbcccbm"
/* 3 */ "mbcccbm"
/* 4 */ "mbcccbm"
/* 5 */ "mbbbbbm"
/* 6 */ "mmmmmmm"
// Level 6
/* z\x* 0123456 */
/* 0 */ "mmmmmmm"
/* 1 */ "mbbbbbm"
/* 2 */ "mbcccbm"
/* 3 */ "mbcccbm"
/* 4 */ "mbcccbm"
/* 5 */ "mbbbbbm"
/* 6 */ "mmmmmmm"
// Level 7
/* z\x* 0123456 */
/* 0 */ "mmbbbmm"
/* 1 */ "mbbbbbm"
/* 2 */ "bbcccbb"
/* 3 */ "bbcccbb"
/* 4 */ "bbcccbb"
/* 5 */ "mbbbbbm"
/* 6 */ "mmbbbmm"
// Level 8
/* z\x* 0123456 */
/* 0 */ "mmdddmm"
/* 1 */ "mbbbbbm"
/* 2 */ "dbcccbd"
/* 3 */ "dbcccbd"
/* 4 */ "dbcccbd"
/* 5 */ "mbbbbbm"
/* 6 */ "mmdddmm"
// Level 9
/* z\x* 0123456 */
/* 0 */ "mm...mm"
/* 1 */ "mbefgbm"
/* 2 */ ".h...h."
/* 3 */ ".g...e."
/* 4 */ ".f...f."
/* 5 */ "mbehgbm"
/* 6 */ "mm...mm"
// Level 10
/* z\x* 0123456 */
/* 0 */ "mm...mm"
/* 1 */ "mi...im"
/* 2 */ "......."
/* 3 */ "......."
/* 4 */ "......."
/* 5 */ "mi...im"
/* 6 */ "mm...mm"
// Level 11
/* z\x* 0123456 */
/* 0 */ "mm...mm"
/* 1 */ "mi...im"
/* 2 */ "......."
/* 3 */ "......."
/* 4 */ "......."
/* 5 */ "mi...im"
/* 6 */ "mm...mm"
// Level 12
/* z\x* 0123456 */
/* 0 */ "mjkkkjm"
/* 1 */ "jlllllj"
/* 2 */ "klllllk"
/* 3 */ "klllllk"
/* 4 */ "klllllk"
/* 5 */ "jlllllj"
/* 6 */ "mjkkkjm"
// Level 13
/* z\x* 0123456 */
/* 0 */ "k.....k"
/* 1 */ "......."
/* 2 */ "..kkk.."
/* 3 */ "..klk.."
/* 4 */ "..kkk.."
/* 5 */ "......."
/* 6 */ "k.....k",
// Connectors:
"2: 0, 9, 3: 4\n" /* Type 2, direction X- */
"2: 3, 9, 0: 2\n" /* Type 2, direction Z- */
"2: 6, 9, 3: 5\n" /* Type 2, direction X+ */
"2: 3, 9, 6: 3\n" /* Type 2, direction Z+ */,
// AllowedRotations:
7, /* 1, 2, 3 CCW rotation allowed */
// Merge strategy:<|fim▁hole|> true,
// DefaultWeight:
100,
// DepthWeight:
"",
// AddWeightIfSame:
0,
// MoveToGround:
true,
}, // Well
};
// The prefab counts:
const size_t g_JapaneseVillagePrefabsCount = ARRAYCOUNT(g_JapaneseVillagePrefabs);
const size_t g_JapaneseVillageStartingPrefabsCount = ARRAYCOUNT(g_JapaneseVillageStartingPrefabs);<|fim▁end|> | cBlockArea::msSpongePrint,
// ShouldExtendFloor: |
<|file_name|>test_ramda_v0.27.x_misc.js<|end_file_name|><|fim▁begin|>/* @flow */
/*eslint-disable no-undef, no-unused-vars, no-console*/
import _, {
compose,
pipe,
curry,
filter,
find,
isNil,
repeat,
replace,
zipWith
} from "ramda";
import { describe, it } from 'flow-typed-test';
const ns: Array<number> = [1, 2, 3, 4, 5];
const ss: Array<string> = ["one", "two", "three", "four"];
const obj: { [k: string]: number } = { a: 1, c: 2 };
const objMixed: { [k: string]: mixed } = { a: 1, c: "d" };
const os: Array<{ [k: string]: * }> = [{ a: 1, c: "d" }, { b: 2 }];
const str: string = "hello world";
// Math
{
const partDiv: (a: number) => number = _.divide(6);
const div: number = _.divide(6, 2);
//$FlowExpectedError
const div2: number = _.divide(6, true);<|fim▁hole|> const ss: Array<string | void> = _.match(/h/, "b");
describe('replace', () => {
it('should supports replace by string', () => {
const r1: string = replace(",", "|", "b,d,d");
const r2: string = replace(",")("|", "b,d,d");
const r3: string = replace(",")("|")("b,d,d");
const r4: string = replace(",", "|")("b,d,d");
});
it('should supports replace by RegExp', () => {
const r1: string = replace(/[,]/, "|", "b,d,d");
const r2: string = replace(/[,]/)("|", "b,d,d");
const r3: string = replace(/[,]/)("|")("b,d,d");
const r4: string = replace(/[,]/, "|")("b,d,d");
});
it('should supports replace by RegExp with replacement fn', () => {
const fn = (match: string, g1: string): string => g1;
const r1: string = replace(/([,])d/, fn, "b,d,d");
const r2: string = replace(/([,])d/)(fn, "b,d,d");
const r3: string = replace(/([,])d/)(fn)("b,d,d");
const r4: string = replace(/([,])d/, fn)("b,d,d");
});
});
const ss2: Array<string> = _.split(",", "b,d,d");
const ss1: boolean = _.test(/h/, "b");
const s: string = _.trim("s");
const x: string = _.head("one");
const sss: string = _.concat("H", "E");
const sss1: string = _.concat("H")("E");
const ssss: string = _.drop(1, "EF");
const ssss1: string = _.drop(1)("E");
const ssss2: string = _.dropLast(1, "EF");
const ys: string = _.nth(2, "curry");
const ys1: string = _.nth(2)("curry");
}
//Type
{
const x: boolean = _.is(Number, 1);
const x1: boolean = isNil(1);
// should refine type
const x1a: ?{ a: number } = { a: 1 };
//$FlowExpectedError
x1a.a;
if (!isNil(x1a)) {
x1a.a;
}
const x2: boolean = _.propIs(1, "num", { num: 1 });
}<|fim▁end|> | }
// String
{ |
<|file_name|>blog-archive.component.ts<|end_file_name|><|fim▁begin|>import { Component, OnInit } from '@angular/core';
// import { TreeModule, TreeNode } from "primeng/primeng";
import { BlogPostService } from '../shared/blog-post.service';
import { BlogPostDetails } from '../shared/blog-post.model';
@Component({
selector: 'ejc-blog-archive',
templateUrl: './blog-archive.component.html',
styleUrls: ['./blog-archive.component.scss']
})
export class BlogArchiveComponent implements OnInit {
constructor(
// private postService: BlogPostService
) { }<|fim▁hole|> }
// // it would be best if the data in the blog post details file was already organized into tree nodes
// private buildTreeNodes(): TreeNode[] {}
}<|fim▁end|> |
ngOnInit() { |
<|file_name|>main.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
lit - LLVM Integrated Tester.
See lit.pod for more information.
"""
from __future__ import absolute_import
import math, os, platform, random, re, sys, time
import lit.ProgressBar
import lit.LitConfig
import lit.Test
import lit.run
import lit.util
import lit.discovery
class TestingProgressDisplay(object):
def __init__(self, opts, numTests, progressBar=None):
self.opts = opts
self.numTests = numTests
self.current = None
self.progressBar = progressBar
self.completed = 0
def finish(self):
if self.progressBar:
self.progressBar.clear()
elif self.opts.quiet:
pass
elif self.opts.succinct:
sys.stdout.write('\n')
def update(self, test):
self.completed += 1
if self.opts.incremental:
update_incremental_cache(test)
if self.progressBar:
self.progressBar.update(float(self.completed)/self.numTests,
test.getFullName())
shouldShow = test.result.code.isFailure or \
self.opts.showAllOutput or \
(not self.opts.quiet and not self.opts.succinct)
if not shouldShow:
return
if self.progressBar:
self.progressBar.clear()
# Show the test result line.
test_name = test.getFullName()
print('%s: %s (%d of %d)' % (test.result.code.name, test_name,
self.completed, self.numTests))
# Show the test failure output, if requested.
if (test.result.code.isFailure and self.opts.showOutput) or \
self.opts.showAllOutput:
if test.result.code.isFailure:
print("%s TEST '%s' FAILED %s" % ('*'*20, test.getFullName(),
'*'*20))
print(test.result.output)
print("*" * 20)
# Report test metrics, if present.
if test.result.metrics:
print("%s TEST '%s' RESULTS %s" % ('*'*10, test.getFullName(),
'*'*10))
items = sorted(test.result.metrics.items())
for metric_name, value in items:
print('%s: %s ' % (metric_name, value.format()))
print("*" * 10)
# Ensure the output is flushed.
sys.stdout.flush()
def write_test_results(run, lit_config, testing_time, output_path):
try:
import json
except ImportError:
lit_config.fatal('test output unsupported with Python 2.5')
# Construct the data we will write.
data = {}
# Encode the current lit version as a schema version.
data['__version__'] = lit.__versioninfo__
data['elapsed'] = testing_time
# FIXME: Record some information on the lit configuration used?
# FIXME: Record information from the individual test suites?
# Encode the tests.
data['tests'] = tests_data = []
for test in run.tests:
test_data = {
'name' : test.getFullName(),
'code' : test.result.code.name,
'output' : test.result.output,
'elapsed' : test.result.elapsed }
# Add test metrics, if present.
if test.result.metrics:
test_data['metrics'] = metrics_data = {}
for key, value in test.result.metrics.items():
metrics_data[key] = value.todata()
tests_data.append(test_data)
# Write the output.
f = open(output_path, 'w')
try:
json.dump(data, f, indent=2, sort_keys=True)
f.write('\n')
finally:
f.close()
def update_incremental_cache(test):
if not test.result.code.isFailure:
return
fname = test.getFilePath()
os.utime(fname, None)
def sort_by_incremental_cache(run):
def sortIndex(test):
fname = test.getFilePath()
try:
return -os.path.getmtime(fname)
except:
return 0
run.tests.sort(key = lambda t: sortIndex(t))
def main(builtinParameters = {}):
# Use processes by default on Unix platforms.
isWindows = platform.system() == 'Windows'
useProcessesIsDefault = not isWindows
global options
from optparse import OptionParser, OptionGroup
parser = OptionParser("usage: %prog [options] {file-or-path}")
parser.add_option("", "--version", dest="show_version",
help="Show version and exit",
action="store_true", default=False)
parser.add_option("-j", "--threads", dest="numThreads", metavar="N",
help="Number of testing threads",
type=int, action="store", default=None)
parser.add_option("", "--config-prefix", dest="configPrefix",
metavar="NAME", help="Prefix for 'lit' config files",
action="store", default=None)
parser.add_option("-D", "--param", dest="userParameters",
metavar="NAME=VAL",
help="Add 'NAME' = 'VAL' to the user defined parameters",
type=str, action="append", default=[])
group = OptionGroup(parser, "Output Format")
# FIXME: I find these names very confusing, although I like the
# functionality.
group.add_option("-q", "--quiet", dest="quiet",
help="Suppress no error output",
action="store_true", default=False)
group.add_option("-s", "--succinct", dest="succinct",
help="Reduce amount of output",
action="store_true", default=False)
group.add_option("-v", "--verbose", dest="showOutput",
help="Show test output for failures",
action="store_true", default=False)
group.add_option("-a", "--show-all", dest="showAllOutput",
help="Display all commandlines and output",
action="store_true", default=False)
group.add_option("-o", "--output", dest="output_path",
help="Write test results to the provided path",
action="store", type=str, metavar="PATH")
group.add_option("", "--no-progress-bar", dest="useProgressBar",
help="Do not use curses based progress bar",
action="store_false", default=True)
group.add_option("", "--show-unsupported", dest="show_unsupported",
help="Show unsupported tests",
action="store_true", default=False)
group.add_option("", "--show-xfail", dest="show_xfail",
help="Show tests that were expected to fail",
action="store_true", default=False)
parser.add_option_group(group)
group = OptionGroup(parser, "Test Execution")
group.add_option("", "--path", dest="path",
help="Additional paths to add to testing environment",
action="append", type=str, default=[])
group.add_option("", "--vg", dest="useValgrind",
help="Run tests under valgrind",
action="store_true", default=False)
group.add_option("", "--vg-leak", dest="valgrindLeakCheck",
help="Check for memory leaks under valgrind",
action="store_true", default=False)
group.add_option("", "--vg-arg", dest="valgrindArgs", metavar="ARG",
help="Specify an extra argument for valgrind",
type=str, action="append", default=[])
group.add_option("", "--time-tests", dest="timeTests",
help="Track elapsed wall time for each test",
action="store_true", default=False)
group.add_option("", "--no-execute", dest="noExecute",
help="Don't execute any tests (assume PASS)",
action="store_true", default=False)
group.add_option("", "--xunit-xml-output", dest="xunit_output_file",
help=("Write XUnit-compatible XML test reports to the"
" specified file"), default=None)
group.add_option("", "--timeout", dest="maxIndividualTestTime",
help="Maximum time to spend running a single test (in seconds)."
"0 means no time limit. [Default: 0]",
type=int, default=None)
parser.add_option_group(group)
group = OptionGroup(parser, "Test Selection")
group.add_option("", "--max-tests", dest="maxTests", metavar="N",
help="Maximum number of tests to run",
action="store", type=int, default=None)
group.add_option("", "--max-time", dest="maxTime", metavar="N",
help="Maximum time to spend testing (in seconds)",
action="store", type=float, default=None)
group.add_option("", "--shuffle", dest="shuffle",
help="Run tests in random order",
action="store_true", default=False)
group.add_option("-i", "--incremental", dest="incremental",
help="Run modified and failing tests first (updates "
"mtimes)",
action="store_true", default=False)
group.add_option("", "--filter", dest="filter", metavar="REGEX",
help=("Only run tests with paths matching the given "
"regular expression"),
action="store", default=None)
parser.add_option_group(group)
group = OptionGroup(parser, "Debug and Experimental Options")
group.add_option("", "--debug", dest="debug",
help="Enable debugging (for 'lit' development)",
action="store_true", default=False)
group.add_option("", "--show-suites", dest="showSuites",<|fim▁hole|> action="store_true", default=False)
group.add_option("", "--use-processes", dest="useProcesses",
help="Run tests in parallel with processes (not threads)",
action="store_true", default=useProcessesIsDefault)
group.add_option("", "--use-threads", dest="useProcesses",
help="Run tests in parallel with threads (not processes)",
action="store_false", default=useProcessesIsDefault)
parser.add_option_group(group)
(opts, args) = parser.parse_args()
if opts.show_version:
print("lit %s" % (lit.__version__,))
return
if not args:
parser.error('No inputs specified')
if opts.numThreads is None:
# Python <2.5 has a race condition causing lit to always fail with numThreads>1
# http://bugs.python.org/issue1731717
# I haven't seen this bug occur with 2.5.2 and later, so only enable multiple
# threads by default there.
if sys.hexversion >= 0x2050200:
opts.numThreads = lit.util.detectCPUs()
else:
opts.numThreads = 1
inputs = args
# Create the user defined parameters.
userParams = dict(builtinParameters)
for entry in opts.userParameters:
if '=' not in entry:
name,opc = entry,''
else:
name,opc = entry.split('=', 1)
userParams[name] = opc
# Decide what the requested maximum indvidual test time should be
if opts.maxIndividualTestTime != None:
maxIndividualTestTime = opts.maxIndividualTestTime
else:
# Default is zero
maxIndividualTestTime = 0
# Create the global config object.
litConfig = lit.LitConfig.LitConfig(
progname = os.path.basename(sys.argv[0]),
path = opts.path,
quiet = opts.quiet,
useValgrind = opts.useValgrind,
valgrindLeakCheck = opts.valgrindLeakCheck,
valgrindArgs = opts.valgrindArgs,
noExecute = opts.noExecute,
debug = opts.debug,
isWindows = isWindows,
params = userParams,
config_prefix = opts.configPrefix,
maxIndividualTestTime = maxIndividualTestTime)
# Perform test discovery.
run = lit.run.Run(litConfig,
lit.discovery.find_tests_for_inputs(litConfig, inputs))
# After test discovery the configuration might have changed
# the maxIndividualTestTime. If we explicitly set this on the
# command line then override what was set in the test configuration
if opts.maxIndividualTestTime != None:
if opts.maxIndividualTestTime != litConfig.maxIndividualTestTime:
litConfig.note(('The test suite configuration requested an individual'
' test timeout of {0} seconds but a timeout of {1} seconds was'
' requested on the command line. Forcing timeout to be {1}'
' seconds')
.format(litConfig.maxIndividualTestTime,
opts.maxIndividualTestTime))
litConfig.maxIndividualTestTime = opts.maxIndividualTestTime
if opts.showSuites or opts.showTests:
# Aggregate the tests by suite.
suitesAndTests = {}
for result_test in run.tests:
if result_test.suite not in suitesAndTests:
suitesAndTests[result_test.suite] = []
suitesAndTests[result_test.suite].append(result_test)
suitesAndTests = list(suitesAndTests.items())
suitesAndTests.sort(key = lambda item: item[0].name)
# Show the suites, if requested.
if opts.showSuites:
print('-- Test Suites --')
for ts,ts_tests in suitesAndTests:
print(' %s - %d tests' %(ts.name, len(ts_tests)))
print(' Source Root: %s' % ts.source_root)
print(' Exec Root : %s' % ts.exec_root)
if ts.config.available_features:
print(' Available Features : %s' % ' '.join(
sorted(ts.config.available_features)))
# Show the tests, if requested.
if opts.showTests:
print('-- Available Tests --')
for ts,ts_tests in suitesAndTests:
ts_tests.sort(key = lambda test: test.path_in_suite)
for test in ts_tests:
print(' %s' % (test.getFullName(),))
# Exit.
sys.exit(0)
# Select and order the tests.
numTotalTests = len(run.tests)
# First, select based on the filter expression if given.
if opts.filter:
try:
rex = re.compile(opts.filter)
except:
parser.error("invalid regular expression for --filter: %r" % (
opts.filter))
run.tests = [result_test for result_test in run.tests
if rex.search(result_test.getFullName())]
# Then select the order.
if opts.shuffle:
random.shuffle(run.tests)
elif opts.incremental:
sort_by_incremental_cache(run)
else:
run.tests.sort(key = lambda t: (not t.isEarlyTest(), t.getFullName()))
# Finally limit the number of tests, if desired.
if opts.maxTests is not None:
run.tests = run.tests[:opts.maxTests]
# Don't create more threads than tests.
opts.numThreads = min(len(run.tests), opts.numThreads)
# Because some tests use threads internally, and at least on Linux each
# of these threads counts toward the current process limit, try to
# raise the (soft) process limit so that tests don't fail due to
# resource exhaustion.
try:
cpus = lit.util.detectCPUs()
desired_limit = opts.numThreads * cpus * 2 # the 2 is a safety factor
# Import the resource module here inside this try block because it
# will likely fail on Windows.
import resource
max_procs_soft, max_procs_hard = resource.getrlimit(resource.RLIMIT_NPROC)
desired_limit = min(desired_limit, max_procs_hard)
if max_procs_soft < desired_limit:
resource.setrlimit(resource.RLIMIT_NPROC, (desired_limit, max_procs_hard))
litConfig.note('raised the process limit from %d to %d' % \
(max_procs_soft, desired_limit))
except:
pass
extra = ''
if len(run.tests) != numTotalTests:
extra = ' of %d' % numTotalTests
header = '-- Testing: %d%s tests, %d threads --'%(len(run.tests), extra,
opts.numThreads)
progressBar = None
if not opts.quiet:
if opts.succinct and opts.useProgressBar:
try:
tc = lit.ProgressBar.TerminalController()
progressBar = lit.ProgressBar.ProgressBar(tc, header)
except ValueError:
print(header)
progressBar = lit.ProgressBar.SimpleProgressBar('Testing: ')
else:
print(header)
startTime = time.time()
display = TestingProgressDisplay(opts, len(run.tests), progressBar)
try:
run.execute_tests(display, opts.numThreads, opts.maxTime,
opts.useProcesses)
except KeyboardInterrupt:
sys.exit(2)
display.finish()
testing_time = time.time() - startTime
if not opts.quiet:
print('Testing Time: %.2fs' % (testing_time,))
# Write out the test data, if requested.
if opts.output_path is not None:
write_test_results(run, litConfig, testing_time, opts.output_path)
# List test results organized by kind.
hasFailures = False
byCode = {}
for test in run.tests:
if test.result.code not in byCode:
byCode[test.result.code] = []
byCode[test.result.code].append(test)
if test.result.code.isFailure:
hasFailures = True
# Print each test in any of the failing groups.
for title,code in (('Unexpected Passing Tests', lit.Test.XPASS),
('Failing Tests', lit.Test.FAIL),
('Unresolved Tests', lit.Test.UNRESOLVED),
('Unsupported Tests', lit.Test.UNSUPPORTED),
('Expected Failing Tests', lit.Test.XFAIL),
('Timed Out Tests', lit.Test.TIMEOUT)):
if (lit.Test.XFAIL == code and not opts.show_xfail) or \
(lit.Test.UNSUPPORTED == code and not opts.show_unsupported):
continue
elts = byCode.get(code)
if not elts:
continue
print('*'*20)
print('%s (%d):' % (title, len(elts)))
for test in elts:
print(' %s' % test.getFullName())
sys.stdout.write('\n')
if opts.timeTests and run.tests:
# Order by time.
test_times = [(test.getFullName(), test.result.elapsed)
for test in run.tests]
lit.util.printHistogram(test_times, title='Tests')
for name,code in (('Expected Passes ', lit.Test.PASS),
('Passes With Retry ', lit.Test.FLAKYPASS),
('Expected Failures ', lit.Test.XFAIL),
('Unsupported Tests ', lit.Test.UNSUPPORTED),
('Unresolved Tests ', lit.Test.UNRESOLVED),
('Unexpected Passes ', lit.Test.XPASS),
('Unexpected Failures', lit.Test.FAIL),
('Individual Timeouts', lit.Test.TIMEOUT)):
if opts.quiet and not code.isFailure:
continue
N = len(byCode.get(code,[]))
if N:
print(' %s: %d' % (name,N))
if opts.xunit_output_file:
# Collect the tests, indexed by test suite
by_suite = {}
for result_test in run.tests:
suite = result_test.suite.config.name
if suite not in by_suite:
by_suite[suite] = {
'passes' : 0,
'failures' : 0,
'tests' : [] }
by_suite[suite]['tests'].append(result_test)
if result_test.result.code.isFailure:
by_suite[suite]['failures'] += 1
else:
by_suite[suite]['passes'] += 1
xunit_output_file = open(opts.xunit_output_file, "w")
xunit_output_file.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n")
xunit_output_file.write("<testsuites>\n")
for suite_name, suite in by_suite.items():
safe_suite_name = suite_name.replace(".", "-")
xunit_output_file.write("<testsuite name='" + safe_suite_name + "'")
xunit_output_file.write(" tests='" + str(suite['passes'] +
suite['failures']) + "'")
xunit_output_file.write(" failures='" + str(suite['failures']) +
"'>\n")
for result_test in suite['tests']:
xunit_output_file.write(result_test.getJUnitXML() + "\n")
xunit_output_file.write("</testsuite>\n")
xunit_output_file.write("</testsuites>")
xunit_output_file.close()
# If we encountered any additional errors, exit abnormally.
if litConfig.numErrors:
sys.stderr.write('\n%d error(s), exiting.\n' % litConfig.numErrors)
sys.exit(2)
# Warn about warnings.
if litConfig.numWarnings:
sys.stderr.write('\n%d warning(s) in tests.\n' % litConfig.numWarnings)
if hasFailures:
sys.exit(1)
sys.exit(0)
if __name__=='__main__':
main()<|fim▁end|> | help="Show discovered test suites",
action="store_true", default=False)
group.add_option("", "--show-tests", dest="showTests",
help="Show all discovered tests", |
<|file_name|>core__cm_func_8h.js<|end_file_name|><|fim▁begin|>var core__cm_func_8h =
[<|fim▁hole|> [ "__CORE_CMFUNC_H", "core__cm_func_8h.html#a50c339231579f3b052ed89428a8a2453", null ]
];<|fim▁end|> | |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>use gst::{glib, prelude::*};
pub(crate) mod bin;
glib::wrapper! {
pub struct RendererBin(ObjectSubclass<bin::RendererBin>) @extends gst::Bin, gst::Element, gst::Object;
}
impl RendererBin {
/// Asynchronoulsy call the provided function on the parent.
///
/// This is useful to set the state of the pipeline.
fn parent_call_async(&self, f: impl FnOnce(&RendererBin, &gst::Element) + Send + 'static) {
match self.parent() {
Some(parent) => parent.downcast_ref::<gst::Element>().unwrap().call_async(
glib::clone!(@weak self as bin => @default-panic, move |parent| f(&bin, parent)),
),
None => unreachable!("media-toc renderer bin has no parent"),
}
}
}
unsafe impl Send for RendererBin {}
unsafe impl Sync for RendererBin {}<|fim▁hole|>glib::wrapper! {
pub struct Renderer(ObjectSubclass<renderer::Renderer>) @extends gst::Element, gst::Object;
}
unsafe impl Send for Renderer {}
unsafe impl Sync for Renderer {}
pub(crate) mod renderer;
pub use renderer::{
SeekField, SegmentField, BUFFER_SIZE_PROP, CLOCK_REF_PROP, DBL_RENDERER_IMPL_PROP,
MUST_REFRESH_SIGNAL, NAME as RENDERER_NAME, SEGMENT_DONE_SIGNAL,
};
pub(crate) use renderer::GET_WINDOW_TIMESTAMPS_SIGNAL;
pub const PLAY_RANGE_DONE_SIGNAL: &str = "play-range-done";
gst::plugin_define!(
mediatocvisu,
env!("CARGO_PKG_DESCRIPTION"),
plugin_init,
concat!(env!("CARGO_PKG_VERSION"), "-", env!("COMMIT_ID")),
"MIT/X11",
env!("CARGO_PKG_NAME"),
env!("CARGO_PKG_NAME"),
env!("CARGO_PKG_REPOSITORY"),
env!("BUILD_REL_DATE")
);
pub fn init() {
use std::sync::Once;
static INIT: Once = Once::new();
INIT.call_once(|| {
gst::init().unwrap();
self::plugin_register_static().expect("media-toc rendering plugin init");
});
}
fn plugin_init(plugin: &gst::Plugin) -> Result<(), glib::BoolError> {
gst::Element::register(
Some(plugin),
bin::NAME,
gst::Rank::None,
RendererBin::static_type(),
)?;
gst::Element::register(
Some(plugin),
renderer::NAME,
gst::Rank::None,
Renderer::static_type(),
)?;
Ok(())
}<|fim▁end|> |
pub use bin::NAME as RENDERER_BIN_NAME;
|
<|file_name|>base.py<|end_file_name|><|fim▁begin|>import numpy as np
import pandas as pd
from lazy_property import LazyProperty
from . import _describe_template
from .plot import Plotter
from .. import bin_counts
from .. import numeric_datatypes, _pretty_print
from ..util import seaborn_required
class Column(object):
"""
In Pandas, a column of a DataFrame is represented as a Series.
Similarly, a column in a database table is represented by
an object from this class.
Note that the Series represented by these columns have the default index (ie non-negative, consecutive integers starting at zero). Thus, for the portion of the Pandas Series API mocked here, we need not worry about multilevel (hierarchical) indices.
"""
def __init__(self, name, parent_table):
"""
:param str name: The name of the column. Required.
:param pg_utils.table.Table parent_table: The table to which this column belongs. Required.
"""
self.parent_table = parent_table
self.name = name
self.is_numeric = parent_table._all_column_data_types[name] in numeric_datatypes
self.plot = Plotter(self)
def select_all_query(self):
"""
Provides the SQL used when selecting everything from this column.
:return: The SQL statement.
:rtype: str
"""
return "select {} from {}".format(self, self.parent_table)
def sort_values(self, ascending=True, limit=None, **sql_kwargs):
"""
Mimics the method `pandas.Series.sort_values <http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.sort_values.html#pandas.Series.sort_values>`_.
:param int|None limit: Either a positive integer for the number of rows to take or ``None`` to take all.
:param bool ascending: Sort ascending vs descending.
:param dict sql_kwargs: A dictionary of keyword arguments passed into `pandas.read_sql <http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql.html>`_.
:return: The resulting series.
:rtype: pandas.Series
"""
if limit is not None and (not isinstance(limit, int) or limit <= 0):
raise ValueError("limit must be a positive integer or None (got {})".format(limit))
sql = self.select_all_query() + " order by 1"
if not ascending:
sql += " desc"
if limit is not None:
sql += " limit {}".format(limit)
return pd.read_sql(sql, self.parent_table.conn, **sql_kwargs)[self.name]
def unique(self):
"""
Returns an array of unique values in this column. Includes ``null`` (represented as ``None``).
:return: The unique values.
:rtype: np.array
"""
cur = self.parent_table.conn.cursor()
cur.execute("select distinct {} from {}".format(self, self.parent_table))
return np.array([x[0] for x in cur.fetchall()])
def hist(self, **kwargs):
return self.plot.hist(**kwargs)
def head(self, num_rows=10):
"""
Fetches some values of this column.
:param int|str num_rows: Either a positive integer number of values or the string `"all"` to fetch all values
:return: A NumPy array of the values
:rtype: np.array
"""
if (isinstance(num_rows, int) and num_rows < 0) or \
num_rows != "all":
raise ValueError("num_rows must be a positive integer or the string 'all'")
query = self.select_all_query()
if num_rows != "all":
query += " limit {}".format(num_rows)
cur = self.parent_table.conn.cursor()
cur.execute(query)
return np.array([x[0] for x in cur.fetchall()])
@LazyProperty
def is_unique(self):
"""
Determines whether or not the values of this column are all unique (ie whether this column is a unique identifier for the table).
:return: Whether or not this column contains unique values.
:rtype: bool
"""
cur = self.parent_table.conn.cursor()
cur.execute("""select {}
from {}
group by 1 having count(1) > 1""".format(self, self.parent_table))
return cur.fetchone() is None
@LazyProperty
def dtype(self):
"""
The ``dtype`` of this column (represented as a string).
:return: The ``dtype``.
:rtype: str
"""
return self.parent_table._all_column_data_types[self.name]
def _get_describe_query(self, percentiles=None, type_="continuous"):
if type_.lower() not in ["continuous", "discrete"]:
raise ValueError("The 'type_' parameter must be 'continuous' or 'discrete'")
if not self.is_numeric:
return None
if percentiles is None:
percentiles = [0.25, 0.5, 0.75]
elif not bool(percentiles):
percentiles = []
if not isinstance(percentiles, (list, tuple)):
percentiles = [percentiles]
if any([x < 0 or x > 1 for x in percentiles]):
raise ValueError(
"The `percentiles` attribute must be None or consist of numbers between 0 and 1 (got {})".format(
percentiles))
percentiles = sorted([float("{0:.2f}".format(p)) for p in percentiles if p > 0])
suffix = "cont" if type_.lower() == "continuous" else "desc"
query = _describe_template.render(column=self, percentiles=percentiles,
suffix=suffix, table=self.parent_table)
if self.parent_table.debug:
_pretty_print(query)
return query
def describe(self, percentiles=None, type_="continuous"):
"""
This mocks the method `pandas.Series.describe`, and provides
a series with the same data (just calculated by the database).
:param None|list[float] percentiles: A list of percentiles to evaluate (with numbers between 0 and 1). If not specified, quartiles (0.25, 0.5, 0.75) are used.
:param str type_: Specifies whether the percentiles are to be taken as discrete or continuous. Must be one of `"discrete"` or `"continuous"`.
:return: A series returning the description of the column, in the same format as ``pandas.Series.describe``.
:rtype: pandas.Series
"""
if percentiles is None:
percentiles = [0.25, 0.5, 0.75]
cur = self.parent_table.conn.cursor()
cur.execute(self._get_describe_query(percentiles=percentiles, type_=type_))
index = ["count", "mean", "std_dev", "minimum"] + \
["{}%".format(int(100 * p)) for p in percentiles] + \
["maximum"]
return pd.Series(cur.fetchone()[1:], index=index)
@seaborn_required
def distplot(self, bins=None, **kwargs):
"""
Produces a ``distplot``. See `the seaborn docs <http://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.distplot.html>`_ on ``distplot`` for more information.
Note that this requires Seaborn in order to function.
:param int|None bins: The number of bins to use. If unspecified, the `Freedman-Diaconis rule <https://en.wikipedia.org/wiki/Freedman%E2%80%93Diaconis_rule>`_ will be used to determine the number of bins.
:param dict kwargs: A dictionary of options to pass on to `seaborn.distplot <http://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.distplot.html>`_.
"""
import seaborn
bc = bin_counts.counts(self, bins=bins)
n = sum([entry[2] for entry in bc])
left = np.zeros(n)
right = np.zeros(n)
overall_index = 0<|fim▁hole|> overall_index += 1
# We'll take our overall data points to be in the midpoint
# of each binning interval
# TODO: make this more configurable (left, right, etc)
return seaborn.distplot((left + right) / 2.0, **kwargs)
@LazyProperty
def values(self):
"""
Mocks the method `pandas.Series.values`, returning a simple NumPy array
consisting of the values of this column.
:return: The NumPy array containing the values.
:rtype: np.array
"""
cur = self.parent_table.conn.cursor()
cur.execute(self.select_all_query())
return np.array([x[0] for x in cur.fetchall()])
def _calculate_aggregate(self, aggregate):
query = "select {}({}) from (\n{}\n)a".format(
aggregate, self, self.select_all_query())
cur = self.parent_table.conn.cursor()
cur.execute(query)
return cur.fetchone()[0]
@LazyProperty
def mean(self):
"""
Mocks the ``pandas.Series.mean`` method to give the mean of the values in this column.
:return: The mean.
:rtype: float
"""
return self._calculate_aggregate("avg")
@LazyProperty
def max(self):
"""
Mocks the ``pandas.Series.max`` method to give the maximum of the values in this column.
:return: The maximum.
:rtype: float
"""
return self._calculate_aggregate("max")
@LazyProperty
def min(self):
"""
Mocks the ``pandas.Series.min`` method to give the maximum of the values in this column.
:return: The minimum.
:rtype: float
"""
return self._calculate_aggregate("min")
@LazyProperty
def size(self):
"""
Mocks the ``pandas.Series.size`` property to give a count of the values in this column.
:return: The count.
:rtype: int
"""
return self.parent_table.count
def __str__(self):
return self.name
def __repr__(self):
return "<{} '{}'>".format(self.__class__, self.name)
def __eq__(self, other):
if not isinstance(other, Column):
return False
return self.name == other.name and self.parent_table == other.parent_table
def __ne__(self, other):
return not self.__eq__(other)<|fim▁end|> | for entry in bc:
for i in range(entry[2]):
left[overall_index] = entry[0]
right[overall_index] = entry[1] |
<|file_name|>Northwind.RegionService.ts<|end_file_name|><|fim▁begin|>namespace Enterprise.Northwind {
export namespace RegionService {
export const baseUrl = 'Northwind/Region';
export declare function Create(request: Serenity.SaveRequest<RegionRow>, onSuccess?: (response: Serenity.SaveResponse) => void, opt?: Q.ServiceOptions<any>): JQueryXHR;
export declare function Update(request: Serenity.SaveRequest<RegionRow>, onSuccess?: (response: Serenity.SaveResponse) => void, opt?: Q.ServiceOptions<any>): JQueryXHR;
export declare function Delete(request: Serenity.DeleteRequest, onSuccess?: (response: Serenity.DeleteResponse) => void, opt?: Q.ServiceOptions<any>): JQueryXHR;
export declare function Retrieve(request: Serenity.RetrieveRequest, onSuccess?: (response: Serenity.RetrieveResponse<RegionRow>) => void, opt?: Q.ServiceOptions<any>): JQueryXHR;
export declare function List(request: Serenity.ListRequest, onSuccess?: (response: Serenity.ListResponse<RegionRow>) => void, opt?: Q.ServiceOptions<any>): JQueryXHR;
export namespace Methods {
export declare const Create: string;
export declare const Update: string;
export declare const Delete: string;
export declare const Retrieve: string;
export declare const List: string;
}
[
'Create',
'Update',
'Delete', <|fim▁hole|> ].forEach(x => {
(<any>RegionService)[x] = function (r, s, o) {
return Q.serviceRequest(baseUrl + '/' + x, r, s, o);
};
(<any>Methods)[x] = baseUrl + '/' + x;
});
}
}<|fim▁end|> | 'Retrieve',
'List' |
<|file_name|>conversationhandler.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2018
# Leandro Toledo de Souza <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains the ConversationHandler."""
import logging
from telegram import Update
from telegram.ext import (Handler, CallbackQueryHandler, InlineQueryHandler,
ChosenInlineResultHandler)
from telegram.utils.promise import Promise
from MongoDict import MongoDict
class ConversationHandler(Handler):
"""
A handler to hold a conversation with a single user by managing four collections of other
handlers. Note that neither posts in Telegram Channels, nor group interactions with multiple
users are managed by instances of this class.
The first collection, a ``list`` named :attr:`entry_points`, is used to initiate the
conversation, for example with a :class:`telegram.ext.CommandHandler` or
:class:`telegram.ext.RegexHandler`.
The second collection, a ``dict`` named :attr:`states`, contains the different conversation<|fim▁hole|> the conversation with them is currently in that state. You will probably use mostly
:class:`telegram.ext.MessageHandler` and :class:`telegram.ext.RegexHandler` here.
The third collection, a ``list`` named :attr:`fallbacks`, is used if the user is currently in a
conversation but the state has either no associated handler or the handler that is associated
to the state is inappropriate for the update, for example if the update contains a command, but
a regular text message is expected. You could use this for a ``/cancel`` command or to let the
user know their message was not recognized.
The fourth, optional collection of handlers, a ``list`` named :attr:`timed_out_behavior` is
used if the wait for ``run_async`` takes longer than defined in :attr:`run_async_timeout`.
For example, you can let the user know that they should wait for a bit before they can
continue.
To change the state of conversation, the callback function of a handler must return the new
state after responding to the user. If it does not return anything (returning ``None`` by
default), the state will not change. To end the conversation, the callback function must
return :attr:`END` or ``-1``.
Attributes:
entry_points (List[:class:`telegram.ext.Handler`]): A list of ``Handler`` objects that can
trigger the start of the conversation.
states (Dict[:obj:`object`, List[:class:`telegram.ext.Handler`]]): A :obj:`dict` that
defines the different states of conversation a user can be in and one or more
associated ``Handler`` objects that should be used in that state.
fallbacks (List[:class:`telegram.ext.Handler`]): A list of handlers that might be used if
the user is in a conversation, but every handler for their current state returned
``False`` on :attr:`check_update`.
allow_reentry (:obj:`bool`): Optional. Determines if a user can restart a conversation with
an entry point.
run_async_timeout (:obj:`float`): Optional. The time-out for ``run_async`` decorated
Handlers.
timed_out_behavior (List[:class:`telegram.ext.Handler`]): Optional. A list of handlers that
might be used if the wait for ``run_async`` timed out.
per_chat (:obj:`bool`): Optional. If the conversationkey should contain the Chat's ID.
per_user (:obj:`bool`): Optional. If the conversationkey should contain the User's ID.
per_message (:obj:`bool`): Optional. If the conversationkey should contain the Message's
ID.
conversation_timeout (:obj:`float`|:obj:`datetime.timedelta`): Optional. When this handler
is inactive more than this timeout (in seconds), it will be automatically ended. If
this value is 0 (default), there will be no timeout.
Args:
entry_points (List[:class:`telegram.ext.Handler`]): A list of ``Handler`` objects that can
trigger the start of the conversation. The first handler which :attr:`check_update`
method returns ``True`` will be used. If all return ``False``, the update is not
handled.
states (Dict[:obj:`object`, List[:class:`telegram.ext.Handler`]]): A :obj:`dict` that
defines the different states of conversation a user can be in and one or more
associated ``Handler`` objects that should be used in that state. The first handler
which :attr:`check_update` method returns ``True`` will be used.
fallbacks (List[:class:`telegram.ext.Handler`]): A list of handlers that might be used if
the user is in a conversation, but every handler for their current state returned
``False`` on :attr:`check_update`. The first handler which :attr:`check_update` method
returns ``True`` will be used. If all return ``False``, the update is not handled.
allow_reentry (:obj:`bool`, optional): If set to ``True``, a user that is currently in a
conversation can restart the conversation by triggering one of the entry points.
run_async_timeout (:obj:`float`, optional): If the previous handler for this user was
running asynchronously using the ``run_async`` decorator, it might not be finished when
the next message arrives. This timeout defines how long the conversation handler should
wait for the next state to be computed. The default is ``None`` which means it will
wait indefinitely.
timed_out_behavior (List[:class:`telegram.ext.Handler`], optional): A list of handlers that
might be used if the wait for ``run_async`` timed out. The first handler which
:attr:`check_update` method returns ``True`` will be used. If all return ``False``,
the update is not handled.
per_chat (:obj:`bool`, optional): If the conversationkey should contain the Chat's ID.
Default is ``True``.
per_user (:obj:`bool`, optional): If the conversationkey should contain the User's ID.
Default is ``True``.
per_message (:obj:`bool`, optional): If the conversationkey should contain the Message's
ID. Default is ``False``.
conversation_timeout (:obj:`float`|:obj:`datetime.timedelta`, optional): When this handler
is inactive more than this timeout (in seconds), it will be automatically ended. If
this value is 0 or None (default), there will be no timeout.
Raises:
ValueError
"""
END = -1
""":obj:`int`: Used as a constant to return when a conversation is ended."""
def __init__(self,
entry_points,
states,
fallbacks,
allow_reentry=False,
run_async_timeout=None,
timed_out_behavior=None,
per_chat=True,
per_user=True,
per_message=False,
conversation_timeout=None,
collection=None):
self.logger = logging.getLogger(__name__)
self.entry_points = entry_points
self.states = states
self.fallbacks = fallbacks
self.allow_reentry = allow_reentry
self.run_async_timeout = run_async_timeout
self.timed_out_behavior = timed_out_behavior
self.per_user = per_user
self.per_chat = per_chat
self.per_message = per_message
self.conversation_timeout = conversation_timeout
self.timeout_jobs = dict()
self.conversations = MongoDict(collection=collection, warm_cache=True)
self.logger.info("Conversations: %s", self.conversations.idb)
self.current_conversation = None
self.current_handler = None
if not any((self.per_user, self.per_chat, self.per_message)):
raise ValueError("'per_user', 'per_chat' and 'per_message' can't all be 'False'")
if self.per_message and not self.per_chat:
logging.warning("If 'per_message=True' is used, 'per_chat=True' should also be used, "
"since message IDs are not globally unique.")
all_handlers = list()
all_handlers.extend(entry_points)
all_handlers.extend(fallbacks)
for state_handlers in states.values():
all_handlers.extend(state_handlers)
if self.per_message:
for handler in all_handlers:
if not isinstance(handler, CallbackQueryHandler):
logging.warning("If 'per_message=True', all entry points and state handlers"
" must be 'CallbackQueryHandler', since no other handlers "
"have a message context.")
else:
for handler in all_handlers:
if isinstance(handler, CallbackQueryHandler):
logging.warning("If 'per_message=False', 'CallbackQueryHandler' will not be "
"tracked for every message.")
if self.per_chat:
for handler in all_handlers:
if isinstance(handler, (InlineQueryHandler, ChosenInlineResultHandler)):
logging.warning("If 'per_chat=True', 'InlineQueryHandler' can not be used, "
"since inline queries have no chat context.")
def _get_key(self, update):
chat = update.effective_chat
user = update.effective_user
key = list()
if self.per_chat:
key.append(chat.id)
if self.per_user and user is not None:
key.append(user.id)
if self.per_message:
key.append(update.callback_query.inline_message_id
or update.callback_query.message.message_id)
return tuple(key)
def check_update(self, update):
"""
Determines whether an update should be handled by this conversationhandler, and if so in
which state the conversation currently is.
Args:
update (:class:`telegram.Update`): Incoming telegram update.
Returns:
:obj:`bool`
"""
# Ignore messages in channels
if (not isinstance(update, Update) or
update.channel_post or
self.per_chat and not update.effective_chat or
self.per_message and not update.callback_query or
update.callback_query and self.per_chat and not update.callback_query.message):
return False
key = self._get_key(update)
state = self.conversations.get(key)
# Resolve promises
if isinstance(state, tuple) and len(state) is 2 and isinstance(state[1], Promise):
self.logger.debug('waiting for promise...')
old_state, new_state = state
error = False
try:
res = new_state.result(timeout=self.run_async_timeout)
except Exception as exc:
self.logger.exception("Promise function raised exception")
self.logger.exception("{}".format(exc))
error = True
if not error and new_state.done.is_set():
self.update_state(res, key)
state = self.conversations.get(key)
else:
for candidate in (self.timed_out_behavior or []):
if candidate.check_update(update):
# Save the current user and the selected handler for handle_update
self.current_conversation = key
self.current_handler = candidate
return True
else:
return False
self.logger.debug('selecting conversation %s with state %s' % (str(key), str(state)))
handler = None
# Search entry points for a match
if state is None or self.allow_reentry:
for entry_point in self.entry_points:
if entry_point.check_update(update):
handler = entry_point
break
else:
if state is None:
return False
# Get the handler list for current state, if we didn't find one yet and we're still here
if state is not None and not handler:
handlers = self.states.get(state)
for candidate in (handlers or []):
if candidate.check_update(update):
handler = candidate
break
# Find a fallback handler if all other handlers fail
else:
for fallback in self.fallbacks:
if fallback.check_update(update):
handler = fallback
break
else:
return False
# Save the current user and the selected handler for handle_update
self.current_conversation = key
self.current_handler = handler
return True
def handle_update(self, update, dispatcher):
"""Send the update to the callback for the current state and Handler
Args:
update (:class:`telegram.Update`): Incoming telegram update.
dispatcher (:class:`telegram.ext.Dispatcher`): Dispatcher that originated the Update.
"""
new_state = self.current_handler.handle_update(update, dispatcher)
timeout_job = self.timeout_jobs.pop(self.current_conversation, None)
if timeout_job is not None:
timeout_job.schedule_removal()
if self.conversation_timeout and new_state != self.END:
self.timeout_jobs[self.current_conversation] = dispatcher.job_queue.run_once(
self._trigger_timeout, self.conversation_timeout,
context=self.current_conversation
)
self.update_state(new_state, self.current_conversation)
def update_state(self, new_state, key):
if new_state == self.END:
if key in self.conversations:
del self.conversations[key]
else:
pass
elif isinstance(new_state, Promise):
self.conversations[key] = (self.conversations.get(key), new_state)
elif new_state is not None:
self.conversations[key] = new_state
def _trigger_timeout(self, bot, job):
del self.timeout_jobs[job.context]
self.update_state(self.END, job.context)<|fim▁end|> | steps and one or more associated handlers that should be used if the user sends a message when |
<|file_name|>inherited_text.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public<|fim▁hole|> * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::Parser;
use media_queries::CSSErrorReporterTest;
use style::parser::ParserContext;
use style::stylesheets::Origin;
#[test]
fn text_emphasis_style_longhand_should_parse_properly() {
use style::properties::longhands::text_emphasis_style;
use style::properties::longhands::text_emphasis_style::{ShapeKeyword, SpecifiedValue, KeywordValue};
let none = parse_longhand!(text_emphasis_style, "none");
assert_eq!(none, SpecifiedValue::None);
let fill = parse_longhand!(text_emphasis_style, "open");
let fill_struct = SpecifiedValue::Keyword(KeywordValue::Fill(false));
assert_eq!(fill, fill_struct);
let shape = parse_longhand!(text_emphasis_style, "triangle");
let shape_struct = SpecifiedValue::Keyword(KeywordValue::Shape(ShapeKeyword::Triangle));
assert_eq!(shape, shape_struct);
let fill_shape = parse_longhand!(text_emphasis_style, "filled dot");
let fill_shape_struct = SpecifiedValue::Keyword(KeywordValue::FillAndShape(true, ShapeKeyword::Dot));
assert_eq!(fill_shape, fill_shape_struct);
let shape_fill = parse_longhand!(text_emphasis_style, "dot filled");
let shape_fill_struct = SpecifiedValue::Keyword(KeywordValue::FillAndShape(true, ShapeKeyword::Dot));
assert_eq!(shape_fill, shape_fill_struct);
let a_string = parse_longhand!(text_emphasis_style, "\"a\"");
let a_string_struct = SpecifiedValue::String("a".to_string());
assert_eq!(a_string, a_string_struct);
let chinese_string = parse_longhand!(text_emphasis_style, "\"点\"");
let chinese_string_struct = SpecifiedValue::String("点".to_string());
assert_eq!(chinese_string, chinese_string_struct);
let unicode_string = parse_longhand!(text_emphasis_style, "\"\\25B2\"");
let unicode_string_struct = SpecifiedValue::String("▲".to_string());
assert_eq!(unicode_string, unicode_string_struct);
let devanagari_string = parse_longhand!(text_emphasis_style, "\"षि\"");
let devanagari_string_struct = SpecifiedValue::String("षि".to_string());
assert_eq!(devanagari_string, devanagari_string_struct);
}
#[test]
fn test_text_emphasis_position() {
use style::properties::longhands::text_emphasis_position;
use style::properties::longhands::text_emphasis_position::{HorizontalWritingModeValue, VerticalWritingModeValue };
use style::properties::longhands::text_emphasis_position::SpecifiedValue;
let over_right = parse_longhand!(text_emphasis_position, "over right");
assert_eq!(over_right, SpecifiedValue(HorizontalWritingModeValue::Over, VerticalWritingModeValue::Right));
let over_left = parse_longhand!(text_emphasis_position, "over left");
assert_eq!(over_left, SpecifiedValue(HorizontalWritingModeValue::Over, VerticalWritingModeValue::Left));
let under_right = parse_longhand!(text_emphasis_position, "under right");
assert_eq!(under_right, SpecifiedValue(HorizontalWritingModeValue::Under, VerticalWritingModeValue::Right));
let under_left = parse_longhand!(text_emphasis_position, "under left");
assert_eq!(under_left, SpecifiedValue(HorizontalWritingModeValue::Under, VerticalWritingModeValue::Left));
let right_over = parse_longhand!(text_emphasis_position, "right over");
assert_eq!(right_over, SpecifiedValue(HorizontalWritingModeValue::Over, VerticalWritingModeValue::Right));
let left_over = parse_longhand!(text_emphasis_position, "left over");
assert_eq!(left_over, SpecifiedValue(HorizontalWritingModeValue::Over, VerticalWritingModeValue::Left));
let right_under = parse_longhand!(text_emphasis_position, "right under");
assert_eq!(right_under, SpecifiedValue(HorizontalWritingModeValue::Under, VerticalWritingModeValue::Right));
let left_under = parse_longhand!(text_emphasis_position, "left under");
assert_eq!(left_under, SpecifiedValue(HorizontalWritingModeValue::Under, VerticalWritingModeValue::Left));
}
#[test]
fn webkit_text_stroke_shorthand_should_parse_properly() {
use media_queries::CSSErrorReporterTest;
use servo_url::ServoUrl;
use style::properties::longhands::_webkit_text_stroke_color;
use style::properties::longhands::_webkit_text_stroke_width;
use style::properties::shorthands::_webkit_text_stroke;
let url = ServoUrl::parse("http://localhost").unwrap();
let context = ParserContext::new(Origin::Author, &url, Box::new(CSSErrorReporterTest));
let mut parser = Parser::new("thin red");
let result = _webkit_text_stroke::parse_value(&context, &mut parser).unwrap();
assert_eq!(result._webkit_text_stroke_color.unwrap(), parse_longhand!(_webkit_text_stroke_color, "red"));
assert_eq!(result._webkit_text_stroke_width.unwrap(), parse_longhand!(_webkit_text_stroke_width, "thin"));
// ensure its no longer sensitive to order
let mut parser = Parser::new("red thin");
let result = _webkit_text_stroke::parse_value(&context, &mut parser).unwrap();
assert_eq!(result._webkit_text_stroke_color.unwrap(), parse_longhand!(_webkit_text_stroke_color, "red"));
assert_eq!(result._webkit_text_stroke_width.unwrap(), parse_longhand!(_webkit_text_stroke_width, "thin"));
}<|fim▁end|> | * License, v. 2.0. If a copy of the MPL was not distributed with this |
<|file_name|>_minexponent.py<|end_file_name|><|fim▁begin|>import _plotly_utils.basevalidators
class MinexponentValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(
self,
plotly_name="minexponent",
parent_name="histogram.marker.colorbar",
**kwargs
):
super(MinexponentValidator, self).__init__(<|fim▁hole|> min=kwargs.pop("min", 0),
**kwargs
)<|fim▁end|> | plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "colorbars"), |
<|file_name|>main.py<|end_file_name|><|fim▁begin|>"""
@created_at 2014-07-15
@author Exequiel Fuentes <[email protected]>
@author Brian Keith <[email protected]>
"""
# Se recomienda seguir los siguientes estandares:
# 1. Para codificacion: PEP 8 - Style Guide for Python Code (http://legacy.python.org/dev/peps/pep-0008/)
# 2. Para documentacion: PEP 257 - Docstring Conventions (http://legacy.python.org/dev/peps/pep-0257/)
import os
import traceback
import sys
from lib import *
def check_version():
"""Python v2.7 es requerida por el curso, entonces verificamos la version"""
if sys.version_info[:2] != (2, 7):
raise Exception("Parece que python v2.7 no esta instalado en el sistema")
def db_path():
"""Retorna el path de las base de datos"""
pathfile = os.path.dirname(os.path.abspath(__file__))
return os.path.join(pathfile, "db")
if __name__ == "__main__":
try:
# Verificar version de python
check_version()
# Cargar los datos
my_pca_lda = FKSkLearn(os.path.join(db_path(), "datos_diabetes.npz"))
# Preparar los datos para validacion
my_pca_lda.fk_train_test_split()
# Se entrena el clasificador PCA + LDA con la dimension optima.
my_pca_lda.fk_pca_lda()
# Contruye el clasificar Bayes usando la libreria sklearn
my_pca_lda.fk_bayes_classifier()
print("**************")
print("sklearn_Bayes:")
print("Number of mislabeled points : %d" % (my_pca_lda.fk_get_y_test() != my_pca_lda.fk_get_y_pred()).sum())
print("Accuracy: ", my_pca_lda.fk_score())
print("**************")
# Implementacion propia del clasificador.
fknb = FKNaiveBayesClassifier()
fknb.fit(my_pca_lda.fk_get_lda_train(), my_pca_lda.fk_get_y_train())
y_pred_FK = fknb.predict(my_pca_lda.fk_get_lda_test())
print("FK_Bayes")
print("Number of mislabeled points : %d" % (my_pca_lda.fk_get_y_test() != y_pred_FK).sum())
print("Accuracy: ", fknb.score(my_pca_lda.fk_get_lda_test(), my_pca_lda.fk_get_y_test()))
print("**************")
<|fim▁hole|> print("...probando igualdad...")
y_pred_SK = [int(i) for i in my_pca_lda.fk_get_y_pred()]
#print y_pred_SK
#print y_pred_FK
# Se verifica si la lista esta vacia.
if y_pred_SK == y_pred_FK:
print "Son iguales los dos metodos!"
else:
print "No son iguales. :("
# Se grafica la informacion.
graph = Graph(my_pca_lda.fk_get_lda_train(), my_pca_lda.fk_get_y_train())
graph.frequencies_histogram()
graph.probability_density_functions()
graph.conditional_probability(my_pca_lda.fk_get_lda_train(), my_pca_lda.fk_get_y_prob())
graph.show_graphs()
except Exception, err:
print traceback.format_exc()
finally:
sys.exit()<|fim▁end|> | # Esto es para verificar que las predicciones son iguales, deberia entregar una lista vacia. |
<|file_name|>test_client.py<|end_file_name|><|fim▁begin|>from buildpal_client import compile as buildpal_compile
import os
import subprocess
import asyncio
import sys
import struct
import threading
import pytest
from buildpal.common import MessageProtocol
class ProtocolTester(MessageProtocol):
@classmethod
def check_exit_code(cls, code):
if hasattr(cls, 'expected_exit_code'):
assert code == cls.expected_exit_code
def __init__(self, loop):
self.initial = True
self.loop = loop
super().__init__()
def process_msg(self, msg):
if self.initial:
assert len(msg) > 5
self.compiler_name = msg[0].decode()
assert self.compiler_name == 'msvc'
self.executable = msg[1].decode()
assert os.path.exists(self.executable)
assert os.path.isfile(self.executable)
assert os.path.basename(self.executable) == 'cl.exe'
self.sysinclude_dirs = msg[2].decode().rstrip(';').split(';')
for path in self.sysinclude_dirs:
assert os.path.exists(path)
assert os.path.isdir(path)
self.cwd = msg[3].decode()
assert os.path.exists(self.cwd)
assert os.path.isdir(self.cwd)
self.command = [x.decode() for x in msg[4:]]
self.send_request()
self.initial = False
else:
self.process_response(msg)
def send_request(self):
raise NotImplementedError()
def process_response(self, msg):
raise NotImplementedError()
def connection_lost(self, exc):
self.loop.stop()
class RunLocallyTester(ProtocolTester):
expected_exit_code = 0
def send_request(self):
self.send_msg([b'RUN_LOCALLY'])
class ExecuteAndExitTester(ProtocolTester):
@classmethod
def check_exit_code(cls, code):
assert code != 0
def send_request(self):
self.send_msg([b'EXECUTE_AND_EXIT', b'/nologo'])
class ExecuteGetOutputTester(ProtocolTester):
expected_exit_code = 6132
def send_request(self):
self.send_msg([b'EXECUTE_GET_OUTPUT', b'/nologo'])
def process_response(self, msg):
retcode, stdout, stderr = msg
retcode = int(retcode.memory())
assert retcode != 0
assert not stdout.memory()
assert b'missing source filename' in stderr.tobytes()
self.send_msg([b'EXIT', struct.pack('!I', self.expected_exit_code & 0xFFFFFFFF), b'',
b''])
class ExitTester(ProtocolTester):
expected_exit_code = 666
def send_request(self):
self.send_msg([b'EXIT', struct.pack('!I', self.expected_exit_code & 0xFFFFFFFF), b'',
b''])
class LocateFiles(ProtocolTester):
expected_exit_code = 3124
files = [b'cl.exe', b'c1xx.dll']
def send_request(self):
self.send_msg([b'LOCATE_FILES'] + self.files)
def process_response(self, msg):
assert len(msg) == len(self.files)
for file, full in zip(self.files, msg):
assert os.path.basename(full.tobytes()) == file
assert os.path.isfile(full.tobytes())
self.send_msg([b'EXIT', struct.pack('!I', self.expected_exit_code & 0xFFFFFFFF), b'',
b''])
@pytest.fixture(scope='function')
def buildpal_compile_args(tmpdir, vcenv_and_cl):
port = 'test_protocol_{}'.format(os.getpid())
file = os.path.join(str(tmpdir), 'aaa.cpp')
with open(file, 'wt'):
pass
args = ['compile', '/c', file]
env, cl = vcenv_and_cl
return ("msvc", cl, env, subprocess.list2cmdline(args), port)
@pytest.mark.parametrize("protocol_tester", [RunLocallyTester,
ExecuteGetOutputTester, ExecuteAndExitTester, ExitTester, LocateFiles])
def test_protocol(buildpal_compile_args, protocol_tester):
loop = asyncio.ProactorEventLoop()
[server] = loop.run_until_complete(loop.start_serving_pipe(
lambda : protocol_tester(loop), "\\\\.\\pipe\\BuildPal_{}".format(buildpal_compile_args[-1])))
class ExitCode:
pass
def run_thread():
ExitCode.exit_code = buildpal_compile(*buildpal_compile_args)
thread = threading.Thread(target=run_thread)
thread.start()
loop.run_forever()
<|fim▁hole|> @asyncio.coroutine
def close_server():
server.close()
loop.run_until_complete(close_server())
assert ExitCode.exit_code != None
protocol_tester.check_exit_code(ExitCode.exit_code)<|fim▁end|> | thread.join()
|
<|file_name|>flows_overview.ts<|end_file_name|><|fim▁begin|>import {ChangeDetectionStrategy, Component, EventEmitter, Input, Output} from '@angular/core';
import {BehaviorSubject, Observable} from 'rxjs';
import {map} from 'rxjs/operators';
import {FlowListItem, FlowsByCategory} from '../../components/flow_picker/flow_list_item';
import {compareAlphabeticallyBy} from '../../lib/type_utils';
interface FlowOverviewCategory {
readonly title: string;
readonly items: ReadonlyArray<FlowListItem>;
}
/**
* Component that displays available Flows.
*/
@Component({
selector: 'flows-overview',
templateUrl: './flows_overview.ng.html',
styleUrls: ['./flows_overview.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class FlowsOverview {
@Input()
set flowsByCategory(value: FlowsByCategory|null) {
this.flowsByCategory$.next(value);
}
get flowsByCategory(): FlowsByCategory|null {
return this.flowsByCategory$.value;
}
private readonly flowsByCategory$ =
new BehaviorSubject<FlowsByCategory|null>(null);
readonly categories$: Observable<ReadonlyArray<FlowOverviewCategory>> =
this.flowsByCategory$.pipe(
map(fbc => {
const result = Array.from(fbc?.entries() ?? [])
.map(([categoryTitle, items]) => {<|fim▁hole|> item => item.friendlyName));
return {
title: categoryTitle,
items: sortedItems,
};
});
result.sort(compareAlphabeticallyBy(cat => cat.title));
return result;
}),
);
/**
* Event that is triggered when a flow is selected.
*/
@Output() flowSelected = new EventEmitter<FlowListItem>();
trackByCategoryTitle(index: number, category: FlowOverviewCategory): string {
return category.title;
}
trackByFlowName(index: number, fli: FlowListItem): string {
return fli.name;
}
}<|fim▁end|> | const sortedItems = [...items];
sortedItems.sort(compareAlphabeticallyBy( |
<|file_name|>base.py<|end_file_name|><|fim▁begin|>from openerp.osv import osv, fields
class IrActionsActWindowMenu(osv.Model):
_name = 'ir.actions.act_window.menu'
_description = 'Menu on the actions'
_columns = {
'name': fields.char('Label', size=64, required=True, translate=True),
'active': fields.boolean(
'Active', help='if check, this object is always available'),
}
_defaults = {
'active': True,
}
class IrActionsActWindowButton(osv.Model):
_name = 'ir.actions.act_window.button'
_description = 'Button to display'
_order = 'name'
_columns = {
'action_from_id': fields.many2one('ir.actions.act_window', 'from Action',
required=True),
'action_to_open_id': fields.many2one('ir.actions.actions', 'to Action',
required=True),
'name': fields.char('Label', size=64, required=True, translate=True),
'menu_id': fields.many2one('ir.actions.act_window.menu', 'Menu'),
'active': fields.boolean(
'Active', help='if check, this object is always available'),
'visibility_model_name': fields.char(u"Modele",
help=u"Model where visible_button_method_name is"
u"define to manage the button visibility."),
'visible_button_method_name': fields.char('Visibility method name',
help=u"Method that tell if the button should be "
u"visible or not, return True if it must "
u"be visible False otherwise."
u"def Method(cr, uid, context=None)"),
}
_defaults = {
'active': True,
}
def format_buttons(self, cr, uid, ids, context=None):
res = {}
action = self.pool.get('ir.actions.actions')
def get_action(action_id):
model = self.pool.get(action.read(cr, uid, action_id, ['type'],
context=context)['type'])
return model.read(cr, uid, action_id, [], load="_classic_write",
context=context)
for this in self.browse(cr, uid, ids, context=context):
if not this.active:
continue
if this.menu_id:
if not this.menu_id.active:
continue
if this.visibility_model_name and this.visible_button_method_name:
model = self.pool.get(this.visibility_model_name)
if not getattr(model, this.visible_button_method_name)(
cr, uid, context=context):
continue
menu = this.menu_id.name if this.menu_id else False
if menu not in res.keys():
res[menu] = []
val = get_action(this.action_to_open_id.id)
val.update({'name': this.name})
res[menu].append(val)
return res
class IrActionsActWindow(osv.Model):
_inherit = 'ir.actions.act_window'
_columns = {
'buttons_ids': fields.one2many('ir.actions.act_window.button',
'action_from_id', 'Buttons'),
}
def get_menus_and_buttons(self, cr, uid, ids, context=None):<|fim▁hole|> cr, uid, [x.id for x in this.buttons_ids], context=context)
return res<|fim▁end|> | res = {}
button = self.pool.get('ir.actions.act_window.button')
for this in self.browse(cr, uid, ids, context=context):
res[this.id] = button.format_buttons( |
<|file_name|>window.rs<|end_file_name|><|fim▁begin|>// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use cairo;
use cairo_sys;
use gdk_pixbuf;
use gdk_sys;
#[cfg(any(feature = "v3_16", feature = "dox"))]
use glib;
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::connect_raw;
use glib::signal::SignalHandlerId;
use glib::translate::*;
use glib_sys;
use libc;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem;
use std::mem::transmute;
use std::ptr;
#[cfg(any(feature = "v3_24", feature = "dox"))]
use AnchorHints;
use Cursor;
use Device;
use Display;
use DragProtocol;
#[cfg(any(feature = "v3_22", feature = "dox"))]
use DrawingContext;
use Event;
use EventMask;
use FrameClock;
use FullscreenMode;
#[cfg(any(feature = "v3_16", feature = "dox"))]
use GLContext;
use Geometry;
#[cfg(any(feature = "v3_24", feature = "dox"))]
use Gravity;
use InputSource;
use ModifierType;
use Rectangle;
use Screen;
use Visual;
use WMDecoration;
use WMFunction;
use WindowEdge;
use WindowHints;
use WindowState;
use WindowType;
use WindowTypeHint;
use RGBA;
glib_wrapper! {
pub struct Window(Object<gdk_sys::GdkWindow, gdk_sys::GdkWindowClass, WindowClass>);
match fn {
get_type => || gdk_sys::gdk_window_get_type(),
}
}
impl Window {
pub fn constrain_size(
geometry: &mut Geometry,
flags: WindowHints,
width: i32,
height: i32,
) -> (i32, i32) {
assert_initialized_main_thread!();
unsafe {
let mut new_width = mem::MaybeUninit::uninit();
let mut new_height = mem::MaybeUninit::uninit();
gdk_sys::gdk_window_constrain_size(
geometry.to_glib_none_mut().0,
flags.to_glib(),
width,
height,
new_width.as_mut_ptr(),
new_height.as_mut_ptr(),
);
let new_width = new_width.assume_init();
let new_height = new_height.assume_init();
(new_width, new_height)
}
}
#[cfg_attr(feature = "v3_22", deprecated)]
pub fn process_all_updates() {
assert_initialized_main_thread!();
unsafe {
gdk_sys::gdk_window_process_all_updates();
}
}
#[cfg_attr(feature = "v3_22", deprecated)]
pub fn set_debug_updates(setting: bool) {
assert_initialized_main_thread!();
unsafe {
gdk_sys::gdk_window_set_debug_updates(setting.to_glib());
}
}
}
pub const NONE_WINDOW: Option<&Window> = None;
pub trait WindowExt: 'static {
//fn add_filter(&self, function: /*Unimplemented*/Fn(/*Unimplemented*/XEvent, &Event) -> /*Ignored*/FilterReturn, data: /*Unimplemented*/Option<Fundamental: Pointer>);
fn beep(&self);
#[cfg(any(feature = "v3_22", feature = "dox"))]
fn begin_draw_frame(&self, region: &cairo::Region) -> Option<DrawingContext>;
fn begin_move_drag(&self, button: i32, root_x: i32, root_y: i32, timestamp: u32);
fn begin_move_drag_for_device(
&self,
device: &Device,
button: i32,
root_x: i32,
root_y: i32,
timestamp: u32,
);
#[cfg_attr(feature = "v3_22", deprecated)]
fn begin_paint_rect(&self, rectangle: &Rectangle);
#[cfg_attr(feature = "v3_22", deprecated)]
fn begin_paint_region(&self, region: &cairo::Region);
fn begin_resize_drag(
&self,
edge: WindowEdge,
button: i32,
root_x: i32,
root_y: i32,
timestamp: u32,
);
fn begin_resize_drag_for_device(
&self,
edge: WindowEdge,
device: &Device,
button: i32,
root_x: i32,
root_y: i32,
timestamp: u32,
);
fn coords_from_parent(&self, parent_x: f64, parent_y: f64) -> (f64, f64);
fn coords_to_parent(&self, x: f64, y: f64) -> (f64, f64);
#[cfg(any(feature = "v3_16", feature = "dox"))]
fn create_gl_context(&self) -> Result<GLContext, glib::Error>;
fn create_similar_image_surface(
&self,
format: i32,
width: i32,
height: i32,
scale: i32,
) -> Option<cairo::Surface>;
fn deiconify(&self);
fn destroy(&self);
fn destroy_notify(&self);
#[cfg(any(feature = "v3_22", feature = "dox"))]
fn end_draw_frame(&self, context: &DrawingContext);
fn end_paint(&self);
fn ensure_native(&self) -> bool;
fn focus(&self, timestamp: u32);
#[cfg_attr(feature = "v3_16", deprecated)]
fn freeze_toplevel_updates_libgtk_only(&self);
fn freeze_updates(&self);
fn fullscreen(&self);
#[cfg(any(feature = "v3_18", feature = "dox"))]
fn fullscreen_on_monitor(&self, monitor: i32);
fn geometry_changed(&self);
fn get_accept_focus(&self) -> bool;
fn get_children(&self) -> Vec<Window>;
//fn get_children_with_user_data(&self, user_data: /*Unimplemented*/Option<Fundamental: Pointer>) -> Vec<Window>;
fn get_clip_region(&self) -> Option<cairo::Region>;
#[cfg_attr(feature = "v3_16", deprecated)]
fn get_composited(&self) -> bool;
fn get_cursor(&self) -> Option<Cursor>;
fn get_decorations(&self) -> Option<WMDecoration>;
fn get_device_cursor(&self, device: &Device) -> Option<Cursor>;
fn get_device_events(&self, device: &Device) -> EventMask;
fn get_device_position(&self, device: &Device) -> (Option<Window>, i32, i32, ModifierType);
fn get_device_position_double(
&self,
device: &Device,
) -> (Option<Window>, f64, f64, ModifierType);
fn get_display(&self) -> Display;
fn get_drag_protocol(&self) -> (DragProtocol, Window);
fn get_effective_parent(&self) -> Option<Window>;
fn get_effective_toplevel(&self) -> Window;
fn get_event_compression(&self) -> bool;
fn get_events(&self) -> EventMask;
fn get_focus_on_map(&self) -> bool;
fn get_frame_clock(&self) -> Option<FrameClock>;
fn get_frame_extents(&self) -> Rectangle;
fn get_fullscreen_mode(&self) -> FullscreenMode;
fn get_geometry(&self) -> (i32, i32, i32, i32);
fn get_group(&self) -> Option<Window>;
fn get_height(&self) -> i32;
fn get_modal_hint(&self) -> bool;
fn get_origin(&self) -> (i32, i32, i32);
fn get_parent(&self) -> Option<Window>;
#[cfg(any(feature = "v3_18", feature = "dox"))]
fn get_pass_through(&self) -> bool;
fn get_position(&self) -> (i32, i32);
fn get_root_coords(&self, x: i32, y: i32) -> (i32, i32);
fn get_root_origin(&self) -> (i32, i32);
fn get_scale_factor(&self) -> i32;
fn get_screen(&self) -> Screen;
fn get_source_events(&self, source: InputSource) -> EventMask;
fn get_state(&self) -> WindowState;
fn get_support_multidevice(&self) -> bool;
fn get_toplevel(&self) -> Window;
fn get_type_hint(&self) -> WindowTypeHint;
fn get_update_area(&self) -> Option<cairo::Region>;
fn get_visible_region(&self) -> Option<cairo::Region>;
fn get_visual(&self) -> Visual;
fn get_width(&self) -> i32;
fn get_window_type(&self) -> WindowType;
fn has_native(&self) -> bool;
fn hide(&self);
fn iconify(&self);
fn input_shape_combine_region(
&self,
shape_region: &cairo::Region,
offset_x: i32,
offset_y: i32,
);
fn invalidate_maybe_recurse(
&self,
region: &cairo::Region,
child_func: Option<&mut dyn (FnMut(&Window) -> bool)>,
);
fn invalidate_rect(&self, rect: Option<&Rectangle>, invalidate_children: bool);
fn invalidate_region(&self, region: &cairo::Region, invalidate_children: bool);
fn is_destroyed(&self) -> bool;
fn is_input_only(&self) -> bool;
fn is_shaped(&self) -> bool;
fn is_viewable(&self) -> bool;
fn is_visible(&self) -> bool;
fn lower(&self);
#[cfg(any(feature = "v3_16", feature = "dox"))]
fn mark_paint_from_clip(&self, cr: &cairo::Context);
fn maximize(&self);
fn merge_child_input_shapes(&self);
fn merge_child_shapes(&self);
fn move_(&self, x: i32, y: i32);
fn move_region(&self, region: &cairo::Region, dx: i32, dy: i32);
fn move_resize(&self, x: i32, y: i32, width: i32, height: i32);
#[cfg(any(feature = "v3_24", feature = "dox"))]
fn move_to_rect(
&self,
rect: &Rectangle,
rect_anchor: Gravity,
window_anchor: Gravity,
anchor_hints: AnchorHints,
rect_anchor_dx: i32,
rect_anchor_dy: i32,
);
fn peek_children(&self) -> Vec<Window>;
#[cfg_attr(feature = "v3_22", deprecated)]
fn process_updates(&self, update_children: bool);
fn raise(&self);
fn register_dnd(&self);
//fn remove_filter(&self, function: /*Unimplemented*/Fn(/*Unimplemented*/XEvent, &Event) -> /*Ignored*/FilterReturn, data: /*Unimplemented*/Option<Fundamental: Pointer>);
fn reparent<P: IsA<Window>>(&self, new_parent: &P, x: i32, y: i32);
fn resize(&self, width: i32, height: i32);
fn restack<P: IsA<Window>>(&self, sibling: Option<&P>, above: bool);
fn scroll(&self, dx: i32, dy: i32);
fn set_accept_focus(&self, accept_focus: bool);
#[cfg_attr(feature = "v3_22", deprecated)]
fn set_background_rgba(&self, rgba: &RGBA);
fn set_child_input_shapes(&self);
fn set_child_shapes(&self);
#[cfg_attr(feature = "v3_16", deprecated)]
fn set_composited(&self, composited: bool);
fn set_cursor(&self, cursor: Option<&Cursor>);
fn set_decorations(&self, decorations: WMDecoration);
fn set_device_cursor(&self, device: &Device, cursor: &Cursor);
fn set_device_events(&self, device: &Device, event_mask: EventMask);
fn set_event_compression(&self, event_compression: bool);
fn set_events(&self, event_mask: EventMask);
fn set_focus_on_map(&self, focus_on_map: bool);
fn set_fullscreen_mode(&self, mode: FullscreenMode);
fn set_functions(&self, functions: WMFunction);
fn set_geometry_hints(&self, geometry: &Geometry, geom_mask: WindowHints);
fn set_group<P: IsA<Window>>(&self, leader: Option<&P>);
fn set_icon_list(&self, pixbufs: &[gdk_pixbuf::Pixbuf]);
fn set_icon_name(&self, name: Option<&str>);
//fn set_invalidate_handler<P: Fn(&Window, &cairo::Region) + 'static>(&self, handler: P);
fn set_keep_above(&self, setting: bool);
fn set_keep_below(&self, setting: bool);
fn set_modal_hint(&self, modal: bool);
fn set_opacity(&self, opacity: f64);
fn set_opaque_region(&self, region: Option<&cairo::Region>);
fn set_override_redirect(&self, override_redirect: bool);
#[cfg(any(feature = "v3_18", feature = "dox"))]
fn set_pass_through(&self, pass_through: bool);
fn set_role(&self, role: &str);
fn set_shadow_width(&self, left: i32, right: i32, top: i32, bottom: i32);
fn set_skip_pager_hint(&self, skips_pager: bool);
fn set_skip_taskbar_hint(&self, skips_taskbar: bool);
fn set_source_events(&self, source: InputSource, event_mask: EventMask);
fn set_startup_id(&self, startup_id: &str);
#[cfg_attr(feature = "v3_16", deprecated)]
fn set_static_gravities(&self, use_static: bool) -> bool;
fn set_support_multidevice(&self, support_multidevice: bool);
fn set_title(&self, title: &str);
fn set_transient_for<P: IsA<Window>>(&self, parent: &P);
fn set_type_hint(&self, hint: WindowTypeHint);
fn set_urgency_hint(&self, urgent: bool);
fn shape_combine_region(
&self,
shape_region: Option<&cairo::Region>,
offset_x: i32,
offset_y: i32,
);
fn show(&self);
fn show_unraised(&self);
fn show_window_menu(&self, event: &mut Event) -> bool;
fn stick(&self);
#[cfg_attr(feature = "v3_16", deprecated)]
fn thaw_toplevel_updates_libgtk_only(&self);
fn thaw_updates(&self);
fn unfullscreen(&self);
fn unmaximize(&self);
fn unstick(&self);
fn withdraw(&self);
fn connect_create_surface<F: Fn(&Self, i32, i32) -> cairo::Surface + 'static>(
&self,
f: F,
) -> SignalHandlerId;
//fn connect_from_embedder<Unsupported or ignored types>(&self, f: F) -> SignalHandlerId;
//#[cfg(any(feature = "v3_22", feature = "dox"))]
//fn connect_moved_to_rect<Unsupported or ignored types>(&self, f: F) -> SignalHandlerId;
fn connect_pick_embedded_child<F: Fn(&Self, f64, f64) -> Option<Window> + 'static>(
&self,
f: F,
) -> SignalHandlerId;
//fn connect_to_embedder<Unsupported or ignored types>(&self, f: F) -> SignalHandlerId;
fn connect_property_cursor_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
}
impl<O: IsA<Window>> WindowExt for O {
//fn add_filter(&self, function: /*Unimplemented*/Fn(/*Unimplemented*/XEvent, &Event) -> /*Ignored*/FilterReturn, data: /*Unimplemented*/Option<Fundamental: Pointer>) {
// unsafe { TODO: call gdk_sys:gdk_window_add_filter() }
//}
fn beep(&self) {
unsafe {
gdk_sys::gdk_window_beep(self.as_ref().to_glib_none().0);
}
}
#[cfg(any(feature = "v3_22", feature = "dox"))]
fn begin_draw_frame(&self, region: &cairo::Region) -> Option<DrawingContext> {
unsafe {
from_glib_none(gdk_sys::gdk_window_begin_draw_frame(
self.as_ref().to_glib_none().0,
region.to_glib_none().0,
))
}
}
fn begin_move_drag(&self, button: i32, root_x: i32, root_y: i32, timestamp: u32) {
unsafe {
gdk_sys::gdk_window_begin_move_drag(
self.as_ref().to_glib_none().0,
button,
root_x,
root_y,
timestamp,
);
}
}
fn begin_move_drag_for_device(
&self,
device: &Device,
button: i32,
root_x: i32,
root_y: i32,
timestamp: u32,
) {
unsafe {
gdk_sys::gdk_window_begin_move_drag_for_device(
self.as_ref().to_glib_none().0,
device.to_glib_none().0,
button,
root_x,
root_y,
timestamp,
);
}
}
fn begin_paint_rect(&self, rectangle: &Rectangle) {
unsafe {
gdk_sys::gdk_window_begin_paint_rect(
self.as_ref().to_glib_none().0,
rectangle.to_glib_none().0,
);
}
}
fn begin_paint_region(&self, region: &cairo::Region) {
unsafe {
gdk_sys::gdk_window_begin_paint_region(
self.as_ref().to_glib_none().0,
region.to_glib_none().0,
);
}
}
fn begin_resize_drag(
&self,
edge: WindowEdge,
button: i32,
root_x: i32,
root_y: i32,
timestamp: u32,
) {
unsafe {
gdk_sys::gdk_window_begin_resize_drag(
self.as_ref().to_glib_none().0,
edge.to_glib(),
button,
root_x,
root_y,
timestamp,
);
}
}
fn begin_resize_drag_for_device(
&self,
edge: WindowEdge,
device: &Device,
button: i32,
root_x: i32,
root_y: i32,
timestamp: u32,
) {
unsafe {
gdk_sys::gdk_window_begin_resize_drag_for_device(
self.as_ref().to_glib_none().0,
edge.to_glib(),
device.to_glib_none().0,
button,
root_x,
root_y,
timestamp,
);
}
}
fn coords_from_parent(&self, parent_x: f64, parent_y: f64) -> (f64, f64) {
unsafe {
let mut x = mem::MaybeUninit::uninit();
let mut y = mem::MaybeUninit::uninit();
gdk_sys::gdk_window_coords_from_parent(
self.as_ref().to_glib_none().0,
parent_x,
parent_y,
x.as_mut_ptr(),
y.as_mut_ptr(),
);
let x = x.assume_init();
let y = y.assume_init();
(x, y)
}
}
fn coords_to_parent(&self, x: f64, y: f64) -> (f64, f64) {
unsafe {
let mut parent_x = mem::MaybeUninit::uninit();
let mut parent_y = mem::MaybeUninit::uninit();
gdk_sys::gdk_window_coords_to_parent(
self.as_ref().to_glib_none().0,
x,
y,
parent_x.as_mut_ptr(),
parent_y.as_mut_ptr(),
);
let parent_x = parent_x.assume_init();
let parent_y = parent_y.assume_init();
(parent_x, parent_y)
}
}
#[cfg(any(feature = "v3_16", feature = "dox"))]
fn create_gl_context(&self) -> Result<GLContext, glib::Error> {
unsafe {
let mut error = ptr::null_mut();
let ret =
gdk_sys::gdk_window_create_gl_context(self.as_ref().to_glib_none().0, &mut error);
if error.is_null() {
Ok(from_glib_full(ret))
} else {
Err(from_glib_full(error))
}
}
}
fn create_similar_image_surface(
&self,
format: i32,
width: i32,
height: i32,
scale: i32,
) -> Option<cairo::Surface> {
unsafe {
from_glib_full(gdk_sys::gdk_window_create_similar_image_surface(
self.as_ref().to_glib_none().0,
format,
width,
height,
scale,
))
}
}
fn deiconify(&self) {
unsafe {
gdk_sys::gdk_window_deiconify(self.as_ref().to_glib_none().0);
}
}
fn destroy(&self) {
unsafe {
gdk_sys::gdk_window_destroy(self.as_ref().to_glib_none().0);
}
}
fn destroy_notify(&self) {
unsafe {
gdk_sys::gdk_window_destroy_notify(self.as_ref().to_glib_none().0);
}
}
#[cfg(any(feature = "v3_22", feature = "dox"))]
fn end_draw_frame(&self, context: &DrawingContext) {
unsafe {
gdk_sys::gdk_window_end_draw_frame(
self.as_ref().to_glib_none().0,
context.to_glib_none().0,
);
}
}
fn end_paint(&self) {
unsafe {
gdk_sys::gdk_window_end_paint(self.as_ref().to_glib_none().0);
}
}
fn ensure_native(&self) -> bool {
unsafe {
from_glib(gdk_sys::gdk_window_ensure_native(
self.as_ref().to_glib_none().0,
))
}
}
fn focus(&self, timestamp: u32) {
unsafe {
gdk_sys::gdk_window_focus(self.as_ref().to_glib_none().0, timestamp);
}
}
fn freeze_toplevel_updates_libgtk_only(&self) {
unsafe {
gdk_sys::gdk_window_freeze_toplevel_updates_libgtk_only(self.as_ref().to_glib_none().0);
}
}
fn freeze_updates(&self) {
unsafe {
gdk_sys::gdk_window_freeze_updates(self.as_ref().to_glib_none().0);
}
}
fn fullscreen(&self) {
unsafe {
gdk_sys::gdk_window_fullscreen(self.as_ref().to_glib_none().0);
}
}
#[cfg(any(feature = "v3_18", feature = "dox"))]
fn fullscreen_on_monitor(&self, monitor: i32) {
unsafe {
gdk_sys::gdk_window_fullscreen_on_monitor(self.as_ref().to_glib_none().0, monitor);
}
}
fn geometry_changed(&self) {
unsafe {
gdk_sys::gdk_window_geometry_changed(self.as_ref().to_glib_none().0);
}
}
fn get_accept_focus(&self) -> bool {
unsafe {
from_glib(gdk_sys::gdk_window_get_accept_focus(
self.as_ref().to_glib_none().0,
))
}
}
fn get_children(&self) -> Vec<Window> {
unsafe {
FromGlibPtrContainer::from_glib_container(gdk_sys::gdk_window_get_children(
self.as_ref().to_glib_none().0,
))
}
}
//fn get_children_with_user_data(&self, user_data: /*Unimplemented*/Option<Fundamental: Pointer>) -> Vec<Window> {
// unsafe { TODO: call gdk_sys:gdk_window_get_children_with_user_data() }
//}
fn get_clip_region(&self) -> Option<cairo::Region> {
unsafe {
from_glib_full(gdk_sys::gdk_window_get_clip_region(
self.as_ref().to_glib_none().0,
))
}
}
fn get_composited(&self) -> bool {
unsafe {
from_glib(gdk_sys::gdk_window_get_composited(
self.as_ref().to_glib_none().0,
))
}
}
fn get_cursor(&self) -> Option<Cursor> {
unsafe {
from_glib_none(gdk_sys::gdk_window_get_cursor(
self.as_ref().to_glib_none().0,
))
}
}
fn get_decorations(&self) -> Option<WMDecoration> {
unsafe {
let mut decorations = mem::MaybeUninit::uninit();
let ret = from_glib(gdk_sys::gdk_window_get_decorations(
self.as_ref().to_glib_none().0,
decorations.as_mut_ptr(),
));
let decorations = decorations.assume_init();
if ret {
Some(from_glib(decorations))
} else {
None
}
}
}
fn get_device_cursor(&self, device: &Device) -> Option<Cursor> {
unsafe {
from_glib_none(gdk_sys::gdk_window_get_device_cursor(
self.as_ref().to_glib_none().0,
device.to_glib_none().0,
))
}
}
fn get_device_events(&self, device: &Device) -> EventMask {
unsafe {
from_glib(gdk_sys::gdk_window_get_device_events(
self.as_ref().to_glib_none().0,
device.to_glib_none().0,
))
}
}
fn get_device_position(&self, device: &Device) -> (Option<Window>, i32, i32, ModifierType) {
unsafe {
let mut x = mem::MaybeUninit::uninit();
let mut y = mem::MaybeUninit::uninit();
let mut mask = mem::MaybeUninit::uninit();
let ret = from_glib_none(gdk_sys::gdk_window_get_device_position(
self.as_ref().to_glib_none().0,
device.to_glib_none().0,
x.as_mut_ptr(),
y.as_mut_ptr(),
mask.as_mut_ptr(),
));
let x = x.assume_init();
let y = y.assume_init();
let mask = mask.assume_init();
(ret, x, y, from_glib(mask))
}
}
fn get_device_position_double(
&self,
device: &Device,
) -> (Option<Window>, f64, f64, ModifierType) {
unsafe {
let mut x = mem::MaybeUninit::uninit();
let mut y = mem::MaybeUninit::uninit();
let mut mask = mem::MaybeUninit::uninit();
let ret = from_glib_none(gdk_sys::gdk_window_get_device_position_double(
self.as_ref().to_glib_none().0,
device.to_glib_none().0,
x.as_mut_ptr(),
y.as_mut_ptr(),
mask.as_mut_ptr(),
));
let x = x.assume_init();
let y = y.assume_init();
let mask = mask.assume_init();
(ret, x, y, from_glib(mask))
}
}
fn get_display(&self) -> Display {
unsafe {
from_glib_none(gdk_sys::gdk_window_get_display(
self.as_ref().to_glib_none().0,
))
}
}
fn get_drag_protocol(&self) -> (DragProtocol, Window) {
unsafe {
let mut target = ptr::null_mut();
let ret = from_glib(gdk_sys::gdk_window_get_drag_protocol(
self.as_ref().to_glib_none().0,
&mut target,
));
(ret, from_glib_full(target))
}
}
fn get_effective_parent(&self) -> Option<Window> {
unsafe {
from_glib_none(gdk_sys::gdk_window_get_effective_parent(
self.as_ref().to_glib_none().0,
))
}
}
fn get_effective_toplevel(&self) -> Window {
unsafe {
from_glib_none(gdk_sys::gdk_window_get_effective_toplevel(
self.as_ref().to_glib_none().0,
))
}
}
fn get_event_compression(&self) -> bool {
unsafe {
from_glib(gdk_sys::gdk_window_get_event_compression(
self.as_ref().to_glib_none().0,
))
}
}
fn get_events(&self) -> EventMask {
unsafe {
from_glib(gdk_sys::gdk_window_get_events(
self.as_ref().to_glib_none().0,
))
}
}
fn get_focus_on_map(&self) -> bool {
unsafe {
from_glib(gdk_sys::gdk_window_get_focus_on_map(
self.as_ref().to_glib_none().0,
))
}
}
fn get_frame_clock(&self) -> Option<FrameClock> {
unsafe {
from_glib_none(gdk_sys::gdk_window_get_frame_clock(
self.as_ref().to_glib_none().0,
))
}
}
fn get_frame_extents(&self) -> Rectangle {
unsafe {
let mut rect = Rectangle::uninitialized();
gdk_sys::gdk_window_get_frame_extents(
self.as_ref().to_glib_none().0,
rect.to_glib_none_mut().0,
);
rect
}
}
fn get_fullscreen_mode(&self) -> FullscreenMode {
unsafe {
from_glib(gdk_sys::gdk_window_get_fullscreen_mode(
self.as_ref().to_glib_none().0,
))
}
}
fn get_geometry(&self) -> (i32, i32, i32, i32) {
unsafe {
let mut x = mem::MaybeUninit::uninit();
let mut y = mem::MaybeUninit::uninit();
let mut width = mem::MaybeUninit::uninit();
let mut height = mem::MaybeUninit::uninit();
gdk_sys::gdk_window_get_geometry(
self.as_ref().to_glib_none().0,
x.as_mut_ptr(),
y.as_mut_ptr(),
width.as_mut_ptr(),
height.as_mut_ptr(),
);
let x = x.assume_init();
let y = y.assume_init();
let width = width.assume_init();
let height = height.assume_init();
(x, y, width, height)
}
}
fn get_group(&self) -> Option<Window> {
unsafe {
from_glib_none(gdk_sys::gdk_window_get_group(
self.as_ref().to_glib_none().0,
))
}
}
fn get_height(&self) -> i32 {
unsafe { gdk_sys::gdk_window_get_height(self.as_ref().to_glib_none().0) }
}
fn get_modal_hint(&self) -> bool {
unsafe {
from_glib(gdk_sys::gdk_window_get_modal_hint(
self.as_ref().to_glib_none().0,
))
}
}
fn get_origin(&self) -> (i32, i32, i32) {
unsafe {
let mut x = mem::MaybeUninit::uninit();
let mut y = mem::MaybeUninit::uninit();
let ret = gdk_sys::gdk_window_get_origin(
self.as_ref().to_glib_none().0,
x.as_mut_ptr(),
y.as_mut_ptr(),
);
let x = x.assume_init();
let y = y.assume_init();
(ret, x, y)
}
}
fn get_parent(&self) -> Option<Window> {
unsafe {
from_glib_none(gdk_sys::gdk_window_get_parent(
self.as_ref().to_glib_none().0,
))
}
}
#[cfg(any(feature = "v3_18", feature = "dox"))]
fn get_pass_through(&self) -> bool {
unsafe {
from_glib(gdk_sys::gdk_window_get_pass_through(
self.as_ref().to_glib_none().0,
))
}
}
fn get_position(&self) -> (i32, i32) {
unsafe {
let mut x = mem::MaybeUninit::uninit();
let mut y = mem::MaybeUninit::uninit();
gdk_sys::gdk_window_get_position(
self.as_ref().to_glib_none().0,
x.as_mut_ptr(),
y.as_mut_ptr(),
);
let x = x.assume_init();
let y = y.assume_init();
(x, y)
}
}
fn get_root_coords(&self, x: i32, y: i32) -> (i32, i32) {
unsafe {
let mut root_x = mem::MaybeUninit::uninit();
let mut root_y = mem::MaybeUninit::uninit();
gdk_sys::gdk_window_get_root_coords(
self.as_ref().to_glib_none().0,
x,
y,
root_x.as_mut_ptr(),
root_y.as_mut_ptr(),
);
let root_x = root_x.assume_init();
let root_y = root_y.assume_init();
(root_x, root_y)
}
}
fn get_root_origin(&self) -> (i32, i32) {
unsafe {
let mut x = mem::MaybeUninit::uninit();
let mut y = mem::MaybeUninit::uninit();
gdk_sys::gdk_window_get_root_origin(
self.as_ref().to_glib_none().0,
x.as_mut_ptr(),
y.as_mut_ptr(),
);
let x = x.assume_init();
let y = y.assume_init();
(x, y)
}
}
fn get_scale_factor(&self) -> i32 {
unsafe { gdk_sys::gdk_window_get_scale_factor(self.as_ref().to_glib_none().0) }
}
fn get_screen(&self) -> Screen {
unsafe {
from_glib_none(gdk_sys::gdk_window_get_screen(
self.as_ref().to_glib_none().0,
))
}
}
fn get_source_events(&self, source: InputSource) -> EventMask {
unsafe {
from_glib(gdk_sys::gdk_window_get_source_events(
self.as_ref().to_glib_none().0,
source.to_glib(),
))
}
}
fn get_state(&self) -> WindowState {
unsafe {
from_glib(gdk_sys::gdk_window_get_state(
self.as_ref().to_glib_none().0,
))
}
}
fn get_support_multidevice(&self) -> bool {
unsafe {
from_glib(gdk_sys::gdk_window_get_support_multidevice(
self.as_ref().to_glib_none().0,
))
}
}
fn get_toplevel(&self) -> Window {
unsafe {
from_glib_none(gdk_sys::gdk_window_get_toplevel(
self.as_ref().to_glib_none().0,
))
}
}
fn get_type_hint(&self) -> WindowTypeHint {
unsafe {
from_glib(gdk_sys::gdk_window_get_type_hint(
self.as_ref().to_glib_none().0,
))
}
}
fn get_update_area(&self) -> Option<cairo::Region> {
unsafe {
from_glib_full(gdk_sys::gdk_window_get_update_area(
self.as_ref().to_glib_none().0,
))
}
}
fn get_visible_region(&self) -> Option<cairo::Region> {
unsafe {
from_glib_full(gdk_sys::gdk_window_get_visible_region(
self.as_ref().to_glib_none().0,
))
}
}
fn get_visual(&self) -> Visual {
unsafe {
from_glib_none(gdk_sys::gdk_window_get_visual(
self.as_ref().to_glib_none().0,
))
}
}
fn get_width(&self) -> i32 {
unsafe { gdk_sys::gdk_window_get_width(self.as_ref().to_glib_none().0) }
}
fn get_window_type(&self) -> WindowType {
unsafe {
from_glib(gdk_sys::gdk_window_get_window_type(
self.as_ref().to_glib_none().0,
))
}
}
fn has_native(&self) -> bool {
unsafe {
from_glib(gdk_sys::gdk_window_has_native(
self.as_ref().to_glib_none().0,
))
}
}
fn hide(&self) {
unsafe {
gdk_sys::gdk_window_hide(self.as_ref().to_glib_none().0);
}
}
fn iconify(&self) {
unsafe {
gdk_sys::gdk_window_iconify(self.as_ref().to_glib_none().0);
}
}
fn input_shape_combine_region(
&self,
shape_region: &cairo::Region,
offset_x: i32,
offset_y: i32,
) {
unsafe {
gdk_sys::gdk_window_input_shape_combine_region(
self.as_ref().to_glib_none().0,
shape_region.to_glib_none().0,
offset_x,
offset_y,
);
}
}
fn invalidate_maybe_recurse(
&self,
region: &cairo::Region,
child_func: Option<&mut dyn (FnMut(&Window) -> bool)>,
) {
let child_func_data: Option<&mut dyn (FnMut(&Window) -> bool)> = child_func;
unsafe extern "C" fn child_func_func(
window: *mut gdk_sys::GdkWindow,
user_data: glib_sys::gpointer,
) -> glib_sys::gboolean {
let window = from_glib_borrow(window);
let callback: *mut Option<&mut dyn (FnMut(&Window) -> bool)> =
user_data as *const _ as usize as *mut Option<&mut dyn (FnMut(&Window) -> bool)>;
let res = if let Some(ref mut callback) = *callback {
callback(&window)
} else {
panic!("cannot get closure...")
};
res.to_glib()
}
let child_func = if child_func_data.is_some() {
Some(child_func_func as _)
} else {
None
};
let super_callback0: &Option<&mut dyn (FnMut(&Window) -> bool)> = &child_func_data;
unsafe {
gdk_sys::gdk_window_invalidate_maybe_recurse(
self.as_ref().to_glib_none().0,
region.to_glib_none().0,
child_func,
super_callback0 as *const _ as usize as *mut _,
);
}
}
fn invalidate_rect(&self, rect: Option<&Rectangle>, invalidate_children: bool) {
unsafe {
gdk_sys::gdk_window_invalidate_rect(
self.as_ref().to_glib_none().0,
rect.to_glib_none().0,
invalidate_children.to_glib(),
);
}
}
fn invalidate_region(&self, region: &cairo::Region, invalidate_children: bool) {
unsafe {
gdk_sys::gdk_window_invalidate_region(
self.as_ref().to_glib_none().0,
region.to_glib_none().0,
invalidate_children.to_glib(),
);
}
}
fn is_destroyed(&self) -> bool {
unsafe {
from_glib(gdk_sys::gdk_window_is_destroyed(
self.as_ref().to_glib_none().0,
))
}
}
fn is_input_only(&self) -> bool {
unsafe {
from_glib(gdk_sys::gdk_window_is_input_only(
self.as_ref().to_glib_none().0,
))
}
}
fn is_shaped(&self) -> bool {
unsafe {
from_glib(gdk_sys::gdk_window_is_shaped(
self.as_ref().to_glib_none().0,
))
}
}
fn is_viewable(&self) -> bool {
unsafe {
from_glib(gdk_sys::gdk_window_is_viewable(
self.as_ref().to_glib_none().0,
))
}
}
fn is_visible(&self) -> bool {
unsafe {
from_glib(gdk_sys::gdk_window_is_visible(
self.as_ref().to_glib_none().0,
))
}
}
fn lower(&self) {
unsafe {
gdk_sys::gdk_window_lower(self.as_ref().to_glib_none().0);
}
}
#[cfg(any(feature = "v3_16", feature = "dox"))]
fn mark_paint_from_clip(&self, cr: &cairo::Context) {
unsafe {
gdk_sys::gdk_window_mark_paint_from_clip(
self.as_ref().to_glib_none().0,
mut_override(cr.to_glib_none().0),
);
}
}
fn maximize(&self) {
unsafe {
gdk_sys::gdk_window_maximize(self.as_ref().to_glib_none().0);
}
}
fn merge_child_input_shapes(&self) {
unsafe {
gdk_sys::gdk_window_merge_child_input_shapes(self.as_ref().to_glib_none().0);
}
}
fn merge_child_shapes(&self) {
unsafe {
gdk_sys::gdk_window_merge_child_shapes(self.as_ref().to_glib_none().0);
}
}
fn move_(&self, x: i32, y: i32) {
unsafe {
gdk_sys::gdk_window_move(self.as_ref().to_glib_none().0, x, y);
}
}
fn move_region(&self, region: &cairo::Region, dx: i32, dy: i32) {
unsafe {
gdk_sys::gdk_window_move_region(
self.as_ref().to_glib_none().0,
region.to_glib_none().0,
dx,
dy,
);
}
}
fn move_resize(&self, x: i32, y: i32, width: i32, height: i32) {
unsafe {
gdk_sys::gdk_window_move_resize(self.as_ref().to_glib_none().0, x, y, width, height);
}
}
#[cfg(any(feature = "v3_24", feature = "dox"))]
fn move_to_rect(
&self,
rect: &Rectangle,
rect_anchor: Gravity,
window_anchor: Gravity,
anchor_hints: AnchorHints,
rect_anchor_dx: i32,
rect_anchor_dy: i32,
) {
unsafe {
gdk_sys::gdk_window_move_to_rect(
self.as_ref().to_glib_none().0,
rect.to_glib_none().0,
rect_anchor.to_glib(),
window_anchor.to_glib(),
anchor_hints.to_glib(),
rect_anchor_dx,
rect_anchor_dy,
);
}
}
fn peek_children(&self) -> Vec<Window> {
unsafe {
FromGlibPtrContainer::from_glib_none(gdk_sys::gdk_window_peek_children(
self.as_ref().to_glib_none().0,
))
}
}
fn process_updates(&self, update_children: bool) {
unsafe {
gdk_sys::gdk_window_process_updates(
self.as_ref().to_glib_none().0,
update_children.to_glib(),
);
}
}
fn raise(&self) {
unsafe {
gdk_sys::gdk_window_raise(self.as_ref().to_glib_none().0);
}
}
fn register_dnd(&self) {
unsafe {
gdk_sys::gdk_window_register_dnd(self.as_ref().to_glib_none().0);
}
}
//fn remove_filter(&self, function: /*Unimplemented*/Fn(/*Unimplemented*/XEvent, &Event) -> /*Ignored*/FilterReturn, data: /*Unimplemented*/Option<Fundamental: Pointer>) {
// unsafe { TODO: call gdk_sys:gdk_window_remove_filter() }
//}
fn reparent<P: IsA<Window>>(&self, new_parent: &P, x: i32, y: i32) {
unsafe {
gdk_sys::gdk_window_reparent(
self.as_ref().to_glib_none().0,
new_parent.as_ref().to_glib_none().0,
x,
y,
);
}
}
fn resize(&self, width: i32, height: i32) {
unsafe {
gdk_sys::gdk_window_resize(self.as_ref().to_glib_none().0, width, height);
}
}
fn restack<P: IsA<Window>>(&self, sibling: Option<&P>, above: bool) {
unsafe {
gdk_sys::gdk_window_restack(
self.as_ref().to_glib_none().0,
sibling.map(|p| p.as_ref()).to_glib_none().0,
above.to_glib(),
);
}
}
fn scroll(&self, dx: i32, dy: i32) {
unsafe {
gdk_sys::gdk_window_scroll(self.as_ref().to_glib_none().0, dx, dy);
}
}
fn set_accept_focus(&self, accept_focus: bool) {
unsafe {
gdk_sys::gdk_window_set_accept_focus(
self.as_ref().to_glib_none().0,
accept_focus.to_glib(),
);
}
}
fn set_background_rgba(&self, rgba: &RGBA) {
unsafe {
gdk_sys::gdk_window_set_background_rgba(
self.as_ref().to_glib_none().0,
rgba.to_glib_none().0,
);
}
}
fn set_child_input_shapes(&self) {
unsafe {
gdk_sys::gdk_window_set_child_input_shapes(self.as_ref().to_glib_none().0);
}
}
fn set_child_shapes(&self) {
unsafe {
gdk_sys::gdk_window_set_child_shapes(self.as_ref().to_glib_none().0);
}
}
fn set_composited(&self, composited: bool) {
unsafe {
gdk_sys::gdk_window_set_composited(
self.as_ref().to_glib_none().0,
composited.to_glib(),
);
}
}
fn set_cursor(&self, cursor: Option<&Cursor>) {
unsafe {
gdk_sys::gdk_window_set_cursor(self.as_ref().to_glib_none().0, cursor.to_glib_none().0);
}
}
fn set_decorations(&self, decorations: WMDecoration) {
unsafe {
gdk_sys::gdk_window_set_decorations(
self.as_ref().to_glib_none().0,
decorations.to_glib(),
);
}
}
fn set_device_cursor(&self, device: &Device, cursor: &Cursor) {
unsafe {
gdk_sys::gdk_window_set_device_cursor(
self.as_ref().to_glib_none().0,
device.to_glib_none().0,
cursor.to_glib_none().0,
);
}
}
fn set_device_events(&self, device: &Device, event_mask: EventMask) {
unsafe {
gdk_sys::gdk_window_set_device_events(
self.as_ref().to_glib_none().0,
device.to_glib_none().0,
event_mask.to_glib(),
);
}
}
fn set_event_compression(&self, event_compression: bool) {
unsafe {
gdk_sys::gdk_window_set_event_compression(
self.as_ref().to_glib_none().0,
event_compression.to_glib(),
);
}
}
fn set_events(&self, event_mask: EventMask) {
unsafe {
gdk_sys::gdk_window_set_events(self.as_ref().to_glib_none().0, event_mask.to_glib());
}
}
fn set_focus_on_map(&self, focus_on_map: bool) {
unsafe {
gdk_sys::gdk_window_set_focus_on_map(
self.as_ref().to_glib_none().0,
focus_on_map.to_glib(),
);
}
}
fn set_fullscreen_mode(&self, mode: FullscreenMode) {
unsafe {
gdk_sys::gdk_window_set_fullscreen_mode(self.as_ref().to_glib_none().0, mode.to_glib());
}
}
fn set_functions(&self, functions: WMFunction) {
unsafe {
gdk_sys::gdk_window_set_functions(self.as_ref().to_glib_none().0, functions.to_glib());
}
}
fn set_geometry_hints(&self, geometry: &Geometry, geom_mask: WindowHints) {
unsafe {
gdk_sys::gdk_window_set_geometry_hints(
self.as_ref().to_glib_none().0,
geometry.to_glib_none().0,
geom_mask.to_glib(),
);
}
}
fn set_group<P: IsA<Window>>(&self, leader: Option<&P>) {
unsafe {
gdk_sys::gdk_window_set_group(
self.as_ref().to_glib_none().0,
leader.map(|p| p.as_ref()).to_glib_none().0,
);
}
}
fn set_icon_list(&self, pixbufs: &[gdk_pixbuf::Pixbuf]) {
unsafe {
gdk_sys::gdk_window_set_icon_list(
self.as_ref().to_glib_none().0,
pixbufs.to_glib_none().0,
);
}
}
fn set_icon_name(&self, name: Option<&str>) {
unsafe {
gdk_sys::gdk_window_set_icon_name(
self.as_ref().to_glib_none().0,
name.to_glib_none().0,
);
}
}
//fn set_invalidate_handler<P: Fn(&Window, &cairo::Region) + 'static>(&self, handler: P) {
// unsafe { TODO: call gdk_sys:gdk_window_set_invalidate_handler() }
//}
fn set_keep_above(&self, setting: bool) {
unsafe {
gdk_sys::gdk_window_set_keep_above(self.as_ref().to_glib_none().0, setting.to_glib());
}
}
fn set_keep_below(&self, setting: bool) {
unsafe {
gdk_sys::gdk_window_set_keep_below(self.as_ref().to_glib_none().0, setting.to_glib());
}
}
fn set_modal_hint(&self, modal: bool) {
unsafe {
gdk_sys::gdk_window_set_modal_hint(self.as_ref().to_glib_none().0, modal.to_glib());
}
}
fn set_opacity(&self, opacity: f64) {
unsafe {
gdk_sys::gdk_window_set_opacity(self.as_ref().to_glib_none().0, opacity);
}
}
fn set_opaque_region(&self, region: Option<&cairo::Region>) {
unsafe {
gdk_sys::gdk_window_set_opaque_region(
self.as_ref().to_glib_none().0,
mut_override(region.to_glib_none().0),
);
}
}
fn set_override_redirect(&self, override_redirect: bool) {
unsafe {
gdk_sys::gdk_window_set_override_redirect(
self.as_ref().to_glib_none().0,
override_redirect.to_glib(),
);
}
}
#[cfg(any(feature = "v3_18", feature = "dox"))]
fn set_pass_through(&self, pass_through: bool) {
unsafe {
gdk_sys::gdk_window_set_pass_through(
self.as_ref().to_glib_none().0,
pass_through.to_glib(),
);
}
}
fn set_role(&self, role: &str) {
unsafe {
gdk_sys::gdk_window_set_role(self.as_ref().to_glib_none().0, role.to_glib_none().0);
}
}
fn set_shadow_width(&self, left: i32, right: i32, top: i32, bottom: i32) {
unsafe {
gdk_sys::gdk_window_set_shadow_width(
self.as_ref().to_glib_none().0,
left,
right,
top,
bottom,
);
}
}
fn set_skip_pager_hint(&self, skips_pager: bool) {
unsafe {
gdk_sys::gdk_window_set_skip_pager_hint(
self.as_ref().to_glib_none().0,
skips_pager.to_glib(),
);
}
}
fn set_skip_taskbar_hint(&self, skips_taskbar: bool) {
unsafe {
gdk_sys::gdk_window_set_skip_taskbar_hint(
self.as_ref().to_glib_none().0,
skips_taskbar.to_glib(),
);
}
}
fn set_source_events(&self, source: InputSource, event_mask: EventMask) {
unsafe {
gdk_sys::gdk_window_set_source_events(
self.as_ref().to_glib_none().0,
source.to_glib(),
event_mask.to_glib(),
);
}
}
fn set_startup_id(&self, startup_id: &str) {
unsafe {
gdk_sys::gdk_window_set_startup_id(
self.as_ref().to_glib_none().0,
startup_id.to_glib_none().0,
);
}
}
fn set_static_gravities(&self, use_static: bool) -> bool {
unsafe {
from_glib(gdk_sys::gdk_window_set_static_gravities(
self.as_ref().to_glib_none().0,
use_static.to_glib(),
))
}
}
fn set_support_multidevice(&self, support_multidevice: bool) {
unsafe {
gdk_sys::gdk_window_set_support_multidevice(
self.as_ref().to_glib_none().0,
support_multidevice.to_glib(),
);
}
}
fn set_title(&self, title: &str) {
unsafe {
gdk_sys::gdk_window_set_title(self.as_ref().to_glib_none().0, title.to_glib_none().0);
}
}
fn set_transient_for<P: IsA<Window>>(&self, parent: &P) {
unsafe {
gdk_sys::gdk_window_set_transient_for(
self.as_ref().to_glib_none().0,
parent.as_ref().to_glib_none().0,
);
}
}
fn set_type_hint(&self, hint: WindowTypeHint) {
unsafe {
gdk_sys::gdk_window_set_type_hint(self.as_ref().to_glib_none().0, hint.to_glib());
}
}
fn set_urgency_hint(&self, urgent: bool) {
unsafe {
gdk_sys::gdk_window_set_urgency_hint(self.as_ref().to_glib_none().0, urgent.to_glib());
}
}
fn shape_combine_region(
&self,
shape_region: Option<&cairo::Region>,
offset_x: i32,
offset_y: i32,
) {
unsafe {
gdk_sys::gdk_window_shape_combine_region(
self.as_ref().to_glib_none().0,
shape_region.to_glib_none().0,
offset_x,
offset_y,
);
}
}
fn show(&self) {
unsafe {
gdk_sys::gdk_window_show(self.as_ref().to_glib_none().0);
}
}
fn show_unraised(&self) {
unsafe {
gdk_sys::gdk_window_show_unraised(self.as_ref().to_glib_none().0);
}
}
fn show_window_menu(&self, event: &mut Event) -> bool {
unsafe {
from_glib(gdk_sys::gdk_window_show_window_menu(
self.as_ref().to_glib_none().0,
event.to_glib_none_mut().0,
))
}
}
fn stick(&self) {
unsafe {
gdk_sys::gdk_window_stick(self.as_ref().to_glib_none().0);
}
}
fn thaw_toplevel_updates_libgtk_only(&self) {
unsafe {
gdk_sys::gdk_window_thaw_toplevel_updates_libgtk_only(self.as_ref().to_glib_none().0);
}
}
fn thaw_updates(&self) {
unsafe {
gdk_sys::gdk_window_thaw_updates(self.as_ref().to_glib_none().0);
}
}
fn unfullscreen(&self) {
unsafe {
gdk_sys::gdk_window_unfullscreen(self.as_ref().to_glib_none().0);
}
}
fn unmaximize(&self) {
unsafe {
gdk_sys::gdk_window_unmaximize(self.as_ref().to_glib_none().0);
}
}
fn unstick(&self) {
unsafe {
gdk_sys::gdk_window_unstick(self.as_ref().to_glib_none().0);
}
}
<|fim▁hole|> }
}
fn connect_create_surface<F: Fn(&Self, i32, i32) -> cairo::Surface + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn create_surface_trampoline<
P,
F: Fn(&P, i32, i32) -> cairo::Surface + 'static,
>(
this: *mut gdk_sys::GdkWindow,
width: libc::c_int,
height: libc::c_int,
f: glib_sys::gpointer,
) -> *mut cairo_sys::cairo_surface_t
where
P: IsA<Window>,
{
let f: &F = &*(f as *const F);
f(
&Window::from_glib_borrow(this).unsafe_cast_ref(),
width,
height,
)
.to_glib_full()
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"create-surface\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
create_surface_trampoline::<Self, F> as *const (),
)),
Box_::into_raw(f),
)
}
}
//fn connect_from_embedder<Unsupported or ignored types>(&self, f: F) -> SignalHandlerId {
// Out offscreen_x: *.Double
// Out offscreen_y: *.Double
//}
//#[cfg(any(feature = "v3_22", feature = "dox"))]
//fn connect_moved_to_rect<Unsupported or ignored types>(&self, f: F) -> SignalHandlerId {
// Unimplemented flipped_rect: *.Pointer
// Unimplemented final_rect: *.Pointer
//}
fn connect_pick_embedded_child<F: Fn(&Self, f64, f64) -> Option<Window> + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn pick_embedded_child_trampoline<
P,
F: Fn(&P, f64, f64) -> Option<Window> + 'static,
>(
this: *mut gdk_sys::GdkWindow,
x: libc::c_double,
y: libc::c_double,
f: glib_sys::gpointer,
) -> *mut gdk_sys::GdkWindow
where
P: IsA<Window>,
{
let f: &F = &*(f as *const F);
f(&Window::from_glib_borrow(this).unsafe_cast_ref(), x, y) /*Not checked*/
.to_glib_none()
.0
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"pick-embedded-child\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
pick_embedded_child_trampoline::<Self, F> as *const (),
)),
Box_::into_raw(f),
)
}
}
//fn connect_to_embedder<Unsupported or ignored types>(&self, f: F) -> SignalHandlerId {
// Out embedder_x: *.Double
// Out embedder_y: *.Double
//}
fn connect_property_cursor_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_cursor_trampoline<P, F: Fn(&P) + 'static>(
this: *mut gdk_sys::GdkWindow,
_param_spec: glib_sys::gpointer,
f: glib_sys::gpointer,
) where
P: IsA<Window>,
{
let f: &F = &*(f as *const F);
f(&Window::from_glib_borrow(this).unsafe_cast_ref())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::cursor\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_cursor_trampoline::<Self, F> as *const (),
)),
Box_::into_raw(f),
)
}
}
}
impl fmt::Display for Window {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Window")
}
}<|fim▁end|> | fn withdraw(&self) {
unsafe {
gdk_sys::gdk_window_withdraw(self.as_ref().to_glib_none().0); |
<|file_name|>monitor-threaded.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#-*- coding: utf-8 -*-
#
# Copyright (c) 2010 Jean-Baptiste Denis.
#
# This is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License version 3 and superior as published by the Free
# Software Foundation.
#
# A copy of the license has been included in the COPYING file.
import sys
import os
import logging
import threading
try:
# first we try system wide
import treewatcher
except ImportError:
# if it fails, we try it from the project source directory
sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.path.pardir))
import treewatcher
from treewatcher import ThreadedEventsCallbacks, choose_source_tree_monitor
_LOGGER = logging.getLogger('_LOGGER')
_LOGGER.setLevel(logging.INFO)
_LOGGER.addHandler(logging.StreamHandler())
class MonitorCallbacks(ThreadedEventsCallbacks):
"""
Example callbacks which will output the event and path
This is a threaded type callbacks object : they will be
called from a different thread of the monitor.
We need to use logging here to prevent messy output.
You need to protect shared state from concurrent access
using Lock for example
"""
def create(self, path, is_dir):
""" callback called on a 'IN_CREATE' event """
_LOGGER.info("create: %s %s %s" % (path, is_dir, threading.current_thread().name))
def delete(self, path, is_dir):
""" callback called on a 'IN_DELETE' event """
_LOGGER.info("delete: %s %s %s" % (path, is_dir, threading.current_thread().name))
def close_write(self, path, is_dir):<|fim▁hole|>
def moved_from(self, path, is_dir):
""" callback called on a 'IN_MOVED_FROM' event """
_LOGGER.info("moved_from: %s %s %s" % (path, is_dir, threading.current_thread().name))
def moved_to(self, path, is_dir):
""" callback called on a 'IN_MOVED_TO' event """
_LOGGER.info("moved_to: %s %s %s" % (path, is_dir, threading.current_thread().name))
def modify(self, path, is_dir):
""" callback called on a 'IN_MODIFY' event """
_LOGGER.info("modify: %s %s %s" % (path, is_dir, threading.current_thread().name))
def attrib(self, path, is_dir):
""" callback called on a 'IN_ATTRIB' event """
_LOGGER.info("attrib: %s %s %s" % (path, is_dir, threading.current_thread().name))
def unmount(self, path, is_dir):
""" callback called on a 'IN_UNMOUNT' event """
_LOGGER.info("unmount: %s %s %s" % (path, is_dir, threading.current_thread().name))
if __name__ == '__main__':
# Yeah, command line parsing
if len(sys.argv) < 2:
print "usage:", sys.argv[0], "directory"
sys.exit(1)
# we check if the provided string is a valid directory
path_to_watch = sys.argv[1]
if not os.path.isdir(path_to_watch):
print path_to_watch, "is not a valid directory."
sys.exit(2)
# We instanciate our callbacks object
callbacks = MonitorCallbacks()
# we get a source tree monitor
stm = choose_source_tree_monitor()
# we set our callbacks
stm.set_events_callbacks(callbacks)
# we will use two threads to handle callbacks
stm.set_workers_number(2)
# we start the monitor
stm.start()
# after that, we can add the directory we want to watch
stm.add_source_dir(path_to_watch)
print "Watching directory", path_to_watch
print "Open a new terminal, and create/remove some folders and files in the", path_to_watch, "directory"
print "Ctrl-C to exit..."
try:
# without specific arguments, the next call will block forever
# open a terminal, and create/remove some folders and files
# this will last forever. use Ctrl-C to exit.
stm.process_events()
# see monitor-timeout-serial.py for an example with a timeout argument
except KeyboardInterrupt:
print "Stopping monitor."
finally:
# clean stop
stm.stop()<|fim▁end|> | """ callback called on a 'IN_CLOSE_WRITE' event """
_LOGGER.info("close_write: %s %s %s" % (path, is_dir, threading.current_thread().name))
|
<|file_name|>supersocket.py<|end_file_name|><|fim▁begin|># This file is part of Scapy
# See http://www.secdev.org/projects/scapy for more information
# Copyright (C) Philippe Biondi <[email protected]>
# This program is published under a GPLv2 license
"""
SuperSocket.
"""
from __future__ import absolute_import
from select import select, error as select_error<|fim▁hole|>import time
from scapy.config import conf
from scapy.consts import LINUX, DARWIN, WINDOWS
from scapy.data import MTU, ETH_P_IP
from scapy.compat import raw, bytes_encode
from scapy.error import warning, log_runtime
import scapy.modules.six as six
import scapy.packet
from scapy.utils import PcapReader, tcpdump
class _SuperSocket_metaclass(type):
def __repr__(self):
if self.desc is not None:
return "<%s: %s>" % (self.__name__, self.desc)
else:
return "<%s>" % self.__name__
class SuperSocket(six.with_metaclass(_SuperSocket_metaclass)):
desc = None
closed = 0
nonblocking_socket = False
read_allowed_exceptions = ()
def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0): # noqa: E501
self.ins = socket.socket(family, type, proto)
self.outs = self.ins
self.promisc = None
def send(self, x):
sx = raw(x)
try:
x.sent_time = time.time()
except AttributeError:
pass
return self.outs.send(sx)
def recv_raw(self, x=MTU):
"""Returns a tuple containing (cls, pkt_data, time)"""
return conf.raw_layer, self.ins.recv(x), None
def recv(self, x=MTU):
cls, val, ts = self.recv_raw(x)
if not val or not cls:
return
try:
pkt = cls(val)
except KeyboardInterrupt:
raise
except Exception:
if conf.debug_dissector:
from scapy.sendrecv import debug
debug.crashed_on = (cls, val)
raise
pkt = conf.raw_layer(val)
if ts:
pkt.time = ts
return pkt
def fileno(self):
return self.ins.fileno()
def close(self):
if self.closed:
return
self.closed = True
if getattr(self, "outs", None):
if getattr(self, "ins", None) != self.outs:
if WINDOWS or self.outs.fileno() != -1:
self.outs.close()
if getattr(self, "ins", None):
if WINDOWS or self.ins.fileno() != -1:
self.ins.close()
def sr(self, *args, **kargs):
from scapy import sendrecv
return sendrecv.sndrcv(self, *args, **kargs)
def sr1(self, *args, **kargs):
from scapy import sendrecv
a, b = sendrecv.sndrcv(self, *args, **kargs)
if len(a) > 0:
return a[0][1]
else:
return None
def sniff(self, *args, **kargs):
from scapy import sendrecv
return sendrecv.sniff(opened_socket=self, *args, **kargs)
def tshark(self, *args, **kargs):
from scapy import sendrecv
return sendrecv.tshark(opened_socket=self, *args, **kargs)
@staticmethod
def select(sockets, remain=conf.recv_poll_rate):
"""This function is called during sendrecv() routine to select
the available sockets.
:param sockets: an array of sockets that need to be selected
:returns: an array of sockets that were selected and
the function to be called next to get the packets (i.g. recv)
"""
try:
inp, _, _ = select(sockets, [], [], remain)
except (IOError, select_error) as exc:
# select.error has no .errno attribute
if exc.args[0] != errno.EINTR:
raise
return inp, None
def __del__(self):
"""Close the socket"""
self.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
"""Close the socket"""
self.close()
class L3RawSocket(SuperSocket):
desc = "Layer 3 using Raw sockets (PF_INET/SOCK_RAW)"
def __init__(self, type=ETH_P_IP, filter=None, iface=None, promisc=None, nofilter=0): # noqa: E501
self.outs = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW) # noqa: E501
self.outs.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1)
self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) # noqa: E501
if iface is not None:
self.ins.bind((iface, type))
def recv(self, x=MTU):
pkt, sa_ll = self.ins.recvfrom(x)
if sa_ll[2] == socket.PACKET_OUTGOING:
return None
if sa_ll[3] in conf.l2types:
cls = conf.l2types[sa_ll[3]]
lvl = 2
elif sa_ll[1] in conf.l3types:
cls = conf.l3types[sa_ll[1]]
lvl = 3
else:
cls = conf.default_l2
warning("Unable to guess type (interface=%s protocol=%#x family=%i). Using %s", sa_ll[0], sa_ll[1], sa_ll[3], cls.name) # noqa: E501
lvl = 3
try:
pkt = cls(pkt)
except KeyboardInterrupt:
raise
except Exception:
if conf.debug_dissector:
raise
pkt = conf.raw_layer(pkt)
if lvl == 2:
pkt = pkt.payload
if pkt is not None:
from scapy.arch import get_last_packet_timestamp
pkt.time = get_last_packet_timestamp(self.ins)
return pkt
def send(self, x):
try:
sx = raw(x)
x.sent_time = time.time()
self.outs.sendto(sx, (x.dst, 0))
except socket.error as msg:
log_runtime.error(msg)
class SimpleSocket(SuperSocket):
desc = "wrapper around a classic socket"
def __init__(self, sock):
self.ins = sock
self.outs = sock
class StreamSocket(SimpleSocket):
desc = "transforms a stream socket into a layer 2"
nonblocking_socket = True
def __init__(self, sock, basecls=None):
if basecls is None:
basecls = conf.raw_layer
SimpleSocket.__init__(self, sock)
self.basecls = basecls
def recv(self, x=MTU):
pkt = self.ins.recv(x, socket.MSG_PEEK)
x = len(pkt)
if x == 0:
return None
pkt = self.basecls(pkt)
pad = pkt.getlayer(conf.padding_layer)
if pad is not None and pad.underlayer is not None:
del(pad.underlayer.payload)
from scapy.packet import NoPayload
while pad is not None and not isinstance(pad, NoPayload):
x -= len(pad.load)
pad = pad.payload
self.ins.recv(x)
return pkt
class SSLStreamSocket(StreamSocket):
desc = "similar usage than StreamSocket but specialized for handling SSL-wrapped sockets" # noqa: E501
def __init__(self, sock, basecls=None):
self._buf = b""
super(SSLStreamSocket, self).__init__(sock, basecls)
# 65535, the default value of x is the maximum length of a TLS record
def recv(self, x=65535):
pkt = None
if self._buf != b"":
try:
pkt = self.basecls(self._buf)
except Exception:
# We assume that the exception is generated by a buffer underflow # noqa: E501
pass
if not pkt:
buf = self.ins.recv(x)
if len(buf) == 0:
raise socket.error((100, "Underlying stream socket tore down"))
self._buf += buf
x = len(self._buf)
pkt = self.basecls(self._buf)
pad = pkt.getlayer(conf.padding_layer)
if pad is not None and pad.underlayer is not None:
del(pad.underlayer.payload)
while pad is not None and not isinstance(pad, scapy.packet.NoPayload):
x -= len(pad.load)
pad = pad.payload
self._buf = self._buf[x:]
return pkt
class L2ListenTcpdump(SuperSocket):
desc = "read packets at layer 2 using tcpdump"
def __init__(self, iface=None, promisc=None, filter=None, nofilter=False,
prog=None, *arg, **karg):
self.outs = None
args = ['-w', '-', '-s', '65535']
if iface is not None:
if WINDOWS:
try:
args.extend(['-i', iface.pcap_name])
except AttributeError:
args.extend(['-i', iface])
else:
args.extend(['-i', iface])
elif WINDOWS or DARWIN:
args.extend(['-i', conf.iface.pcap_name if WINDOWS else conf.iface]) # noqa: E501
if not promisc:
args.append('-p')
if not nofilter:
if conf.except_filter:
if filter:
filter = "(%s) and not (%s)" % (filter, conf.except_filter)
else:
filter = "not (%s)" % conf.except_filter
if filter is not None:
args.append(filter)
self.tcpdump_proc = tcpdump(None, prog=prog, args=args, getproc=True)
self.ins = PcapReader(self.tcpdump_proc.stdout)
def recv(self, x=MTU):
return self.ins.recv(x)
def close(self):
SuperSocket.close(self)
self.tcpdump_proc.kill()
class TunTapInterface(SuperSocket):
"""A socket to act as the host's peer of a tun / tap interface.
"""
desc = "Act as the host's peer of a tun / tap interface"
def __init__(self, iface=None, mode_tun=None, *arg, **karg):
self.iface = conf.iface if iface is None else iface
self.mode_tun = ("tun" in self.iface) if mode_tun is None else mode_tun
self.closed = True
self.open()
def open(self):
"""Open the TUN or TAP device."""
if not self.closed:
return
self.outs = self.ins = open(
"/dev/net/tun" if LINUX else ("/dev/%s" % self.iface), "r+b",
buffering=0
)
if LINUX:
from fcntl import ioctl
# TUNSETIFF = 0x400454ca
# IFF_TUN = 0x0001
# IFF_TAP = 0x0002
# IFF_NO_PI = 0x1000
ioctl(self.ins, 0x400454ca, struct.pack(
"16sH", bytes_encode(self.iface),
0x0001 if self.mode_tun else 0x1002,
))
self.closed = False
def __call__(self, *arg, **karg):
"""Needed when using an instantiated TunTapInterface object for
conf.L2listen, conf.L2socket or conf.L3socket.
"""
return self
def recv(self, x=MTU):
if self.mode_tun:
data = os.read(self.ins.fileno(), x + 4)
proto = struct.unpack('!H', data[2:4])[0]
return conf.l3types.get(proto, conf.raw_layer)(data[4:])
return conf.l2types.get(1, conf.raw_layer)(
os.read(self.ins.fileno(), x)
)
def send(self, x):
sx = raw(x)
if hasattr(x, "sent_time"):
x.sent_time = time.time()
if self.mode_tun:
try:
proto = conf.l3types[type(x)]
except KeyError:
log_runtime.warning(
"Cannot find layer 3 protocol value to send %s in "
"conf.l3types, using 0",
x.name if hasattr(x, "name") else type(x).__name__
)
proto = 0
sx = struct.pack('!HH', 0, proto) + sx
try:
os.write(self.outs.fileno(), sx)
except socket.error:
log_runtime.error("%s send", self.__class__.__name__, exc_info=True) # noqa: E501<|fim▁end|> | import errno
import os
import socket
import struct |
<|file_name|>gamecards.js<|end_file_name|><|fim▁begin|>(function ($) {
$(document).ready(function(){
$("#edit-title-0-value").change(update);
$("#edit-field-carac1-0-value").click(update);
$("#edit-field-carac1-0-value").change(update);
$("#edit-field-carac2-0-value").change(update);
$("#edit-field-carac3-0-value").change(update);
$("#edit-field-carac4-0-value").change(update);
$("#edit-field-skill-0-value").change(update);
$("#edit-field-question-0-value").change(update);
$("#edit-field-answer-0-value").change(update);
$("#edit-field-img-game-card-0-upload").change(update);
$("#edit-field-upload_image_verso").change(update);
var bgimagerecto = undefined;
var bgimageverso = undefined;
if($('span.file--image > a').length == 1) {
if($('#edit-field-img-game-card-0-remove-button')) {
console.log("length11");
bgimagerecto = $("span.file--image > a:eq(0)").attr('href');
}
else {
console.log("length12");
bgimageverso = $("span.file--image > a:eq(0)").attr('href');
}
}
if($('span.file--image > a').length == 2) {
console.log("length2");
bgimagerecto = $("span.file--image > a:eq(0)").attr('href');
bgimageverso = $("span.file--image > a:eq(1)").attr('href');
}
if (bgimagerecto !== undefined) {
console.log("imagerecto");
$('#gamecardrectolayout').css('background-image', 'url( ' + bgimagerecto + ')');
$('.field--name-field-img-game-card .ajax-new-content').addClass('processed');
}
if (bgimageverso !== undefined) {
console.log("imageverso");
$('#gamecardversolayout').css('background-image', 'url( ' + bgimageverso + ')');
$('.field--name-field-upload-image-verso .ajax-new-content').addClass('processed');
}
$(document).ajaxComplete(function(event, xhr, settings) {
//RECTO
console.log(event.target);
console.log("azer " + bgimagerecto);
console.log("qsdf " + bgimageverso);
if(~settings.url.indexOf("field_img_game_card")) {
console.log('entering recto');
if ($('.field--name-field-img-game-card .ajax-new-content').hasClass('processed')) {
console.log("remove recto");
//$('.ajax-new-content').remove();
$('#gamecardrectolayout').removeAttr('style');
$('.field--name-field-img-game-card .ajax-new-content').removeClass('processed');
return;
}
if(!$('#edit-field-img-game-card-0-remove-button')) {
console.log("remoooooove");
$('#gamecardrectolayout').removeAttr('style');
$('.field--name-field-img-game-card .ajax-new-content').removeClass('processed');
return;
}
console.log("addingrecto");
$('.field--name-field-img-game-card .ajax-new-content').addClass('processed');
bgimagerecto = $("span.file--image > a:eq(0)").attr('href'); //Manage here when single or double
if (bgimagerecto !== undefined) {
console.log("gorecto");
$('#gamecardrectolayout').css('background-image', 'url( ' + bgimagerecto + ')');
}
return;
}
//VERSO
if(~settings.url.indexOf("field_upload_image_verso")) {
if ($('.field--name-field-upload-image-verso .ajax-new-content').hasClass('processed') || !$('#edit-field-upload-image-verso-0-remove-button')) {
console.log("remove verso");
//$('.ajax-new-content').remove();
$('#gamecardversolayout').removeAttr('style');
$('.field--name-field-upload-image-verso .ajax-new-content').removeClass('processed');
return;
}
console.log("adding verso");
$('.field--name-field-upload-image-verso .ajax-new-content').addClass('processed');
if($('span.file--image > a').length == 1) bgimageverso = $("span.file--image > a:eq(0)").attr('href');
if($('span.file--image > a').length == 2) bgimageverso = $("span.file--image > a:eq(1)").attr('href');
if (bgimageverso !== undefined) {
console.log("Verso added");
$('#gamecardversolayout').css('background-image', 'url( ' + bgimageverso + ')');
}
}
});
});
function update(){
var cardname = (($("#edit-title-0-value").val() != "") ? $("#edit-title-0-value").val() : "");
var carac1 = (($("#edit-field-carac1-0-value").val() != "") ? $("#edit-field-carac1-0-value").val() : "");<|fim▁hole|> var carac2 = (($("#edit-field-carac2-0-value").val() != "") ? $("#edit-field-carac2-0-value").val() : "");
var carac3 = (($("#edit-field-carac3-0-value").val() != "") ? $("#edit-field-carac3-0-value").val() : "");
var carac4 = (($("#edit-field-carac4-0-value").val() != "") ? $("#edit-field-carac4-0-value").val() : "");
var skill = (($("#edit-field-skill-0-value").val() != "") ? $("#edit-field-skill-0-value").val() : "") ;
var question = (($("#edit-field-question-0-value").val() != "") ? $("#edit-field-question-0-value").val() : "");
var answer = (($("#edit-field-answer-0-value").val() != "") ? $("#edit-field-answer-0-value").val() : "") ;
var rectoImg = (($("#edit-field-img-game-card-0-upload").val() != "") ? $("#edit-field-img-game-card-0-upload").val() : "");
var versoImg = (($("#edit-field-upload_image_verso").val() != "") ? $("#edit-field-upload_image_verso").val() : "");
if(rectoImg !== undefined) {
if (rectoImg != null) {
$('#gamecardrectolayout').css('background-image', 'url("' + rectoImg + '")');
}
else {
rectoImg = $("span.file--image > a:eq(0)").attr('href');
$('#gamecardrectolayout').css('background-image', 'url( ' + rectoImg + ')');
}
}
if(versoImg !== undefined) {
if (versoImg != null) {
$('#gamecardrectolayout').css('background-image', 'url("' + versoImg + '")');
}
else {
versoImg = $("span.file--image > a:eq(1)").attr('href');
$('#gamecardrectolayout').css('background-image', 'url( ' + versoImg + ')');
}
}
$('#displayCardname').html(cardname);
$('#displayCarac1').html(carac1);
$('#displayCarac2').html(carac2);
$('#displayCarac3').html(carac3);
$('#displayCarac4').html(carac4);
$('#displaySkill').html(skill);
$('#displayQuestion').html(question);
$('#displayAnswer').html(answer);
}
})(jQuery);<|fim▁end|> | |
<|file_name|>classDisplayNameHandler.ts<|end_file_name|><|fim▁begin|>import babylon from '../../babel-parser'
import Documentation from '../../Documentation'
import resolveExportedComponent from '../../utils/resolveExportedComponent'
import classDisplayNameHandler from '../classDisplayNameHandler'
jest.mock('../../Documentation')
function parse(src: string) {
const ast = babylon().parse(src)
return resolveExportedComponent(ast)[0]
}
describe('classDisplayNameHandler', () => {
let documentation: Documentation
beforeEach(() => {
documentation = new Documentation('dummy/path')
})
it('should extract the name of the component from the classname', () => {
const src = `
@Component
export default class Decorum extends Vue{
}
`
const def = parse(src).get('default')
if (def) {
classDisplayNameHandler(documentation, def)
}
expect(documentation.set).toHaveBeenCalledWith('displayName', 'Decorum')
})
it('should extract the name of the component from the decorators', () => {<|fim▁hole|> }
`
const def = parse(src).get('default')
if (def) {
classDisplayNameHandler(documentation, def)
}
expect(documentation.set).toHaveBeenCalledWith('displayName', 'decorum')
})
})<|fim▁end|> | const src = `
@Component({name: 'decorum'})
export default class Test extends Vue{ |
<|file_name|>gr-coverage-layer.ts<|end_file_name|><|fim▁begin|>/**
* @license<|fim▁hole|> * Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {PolymerElement} from '@polymer/polymer/polymer-element';
import {htmlTemplate} from './gr-coverage-layer_html';
import {CoverageRange, CoverageType, DiffLayer} from '../../../types/types';
import {customElement, property} from '@polymer/decorators';
declare global {
interface HTMLElementTagNameMap {
'gr-coverage-layer': GrCoverageLayer;
}
}
const TOOLTIP_MAP = new Map([
[CoverageType.COVERED, 'Covered by tests.'],
[CoverageType.NOT_COVERED, 'Not covered by tests.'],
[CoverageType.PARTIALLY_COVERED, 'Partially covered by tests.'],
[CoverageType.NOT_INSTRUMENTED, 'Not instrumented by any tests.'],
]);
@customElement('gr-coverage-layer')
export class GrCoverageLayer extends PolymerElement implements DiffLayer {
static get template() {
return htmlTemplate;
}
/**
* Must be sorted by code_range.start_line.
* Must only contain ranges that match the side.
*/
@property({type: Array})
coverageRanges: CoverageRange[] = [];
@property({type: String})
side?: string;
/**
* We keep track of the line number from the previous annotate() call,
* and also of the index of the coverage range that had matched.
* annotate() calls are coming in with increasing line numbers and
* coverage ranges are sorted by line number. So this is a very simple
* and efficient way for finding the coverage range that matches a given
* line number.
*/
@property({type: Number})
_lineNumber = 0;
@property({type: Number})
_index = 0;
/**
* Layer method to add annotations to a line.
*
* @param _el Not used for this layer. (unused parameter)
* @param lineNumberEl The <td> element with the line number.
* @param line Not used for this layer.
*/
annotate(_el: HTMLElement, lineNumberEl: HTMLElement) {
if (
!this.side ||
!lineNumberEl ||
!lineNumberEl.classList.contains(this.side)
) {
return;
}
let elementLineNumber;
const dataValue = lineNumberEl.getAttribute('data-value');
if (dataValue) {
elementLineNumber = Number(dataValue);
}
if (!elementLineNumber || elementLineNumber < 1) return;
// If the line number is smaller than before, then we have to reset our
// algorithm and start searching the coverage ranges from the beginning.
// That happens for example when you expand diff sections.
if (elementLineNumber < this._lineNumber) {
this._index = 0;
}
this._lineNumber = elementLineNumber;
// We simply loop through all the coverage ranges until we find one that
// matches the line number.
while (this._index < this.coverageRanges.length) {
const coverageRange = this.coverageRanges[this._index];
// If the line number has moved past the current coverage range, then
// try the next coverage range.
if (this._lineNumber > coverageRange.code_range.end_line) {
this._index++;
continue;
}
// If the line number has not reached the next coverage range (and the
// range before also did not match), then this line has not been
// instrumented. Nothing to do for this line.
if (this._lineNumber < coverageRange.code_range.start_line) {
return;
}
// The line number is within the current coverage range. Style it!
lineNumberEl.classList.add(coverageRange.type);
lineNumberEl.title = TOOLTIP_MAP.get(coverageRange.type) || '';
return;
}
}
}<|fim▁end|> | |
<|file_name|>file_name.py<|end_file_name|><|fim▁begin|>import os
from jedi._compatibility import FileNotFoundError, force_unicode, scandir
from jedi.api import classes
from jedi.api.strings import StringName, get_quote_ending
from jedi.api.helpers import match
from jedi.inference.helpers import get_str_or_none
class PathName(StringName):
api_type = u'path'
def complete_file_name(inference_state, module_context, start_leaf, quote, string,
like_name, signatures_callback, code_lines, position, fuzzy):
# First we want to find out what can actually be changed as a name.
like_name_length = len(os.path.basename(string))
addition = _get_string_additions(module_context, start_leaf)
if string.startswith('~'):
string = os.path.expanduser(string)
if addition is None:
return
string = addition + string
# Here we use basename again, because if strings are added like
# `'foo' + 'bar`, it should complete to `foobar/`.
must_start_with = os.path.basename(string)
string = os.path.dirname(string)
sigs = signatures_callback(*position)
is_in_os_path_join = sigs and all(s.full_name == 'os.path.join' for s in sigs)
if is_in_os_path_join:
to_be_added = _add_os_path_join(module_context, start_leaf, sigs[0].bracket_start)
if to_be_added is None:
is_in_os_path_join = False
else:
string = to_be_added + string
base_path = os.path.join(inference_state.project.path, string)
try:
listed = sorted(scandir(base_path), key=lambda e: e.name)
# OSError: [Errno 36] File name too long: '...'
except (FileNotFoundError, OSError):
return
quote_ending = get_quote_ending(quote, code_lines, position)
for entry in listed:
name = entry.name
if match(name, must_start_with, fuzzy=fuzzy):
if is_in_os_path_join or not entry.is_dir():
name += quote_ending
else:
name += os.path.sep
yield classes.Completion(
inference_state,
PathName(inference_state, name[len(must_start_with) - like_name_length:]),
stack=None,
like_name_length=like_name_length,
is_fuzzy=fuzzy,
)
def _get_string_additions(module_context, start_leaf):
def iterate_nodes():
node = addition.parent
was_addition = True
for child_node in reversed(node.children[:node.children.index(addition)]):
if was_addition:
was_addition = False
yield child_node
continue
if child_node != '+':
break
was_addition = True
addition = start_leaf.get_previous_leaf()
if addition != '+':
return ''
context = module_context.create_context(start_leaf)
return _add_strings(context, reversed(list(iterate_nodes())))
def _add_strings(context, nodes, add_slash=False):
string = ''
first = True
for child_node in nodes:
values = context.infer_node(child_node)
if len(values) != 1:
return None
c, = values
s = get_str_or_none(c)
if s is None:
return None
if not first and add_slash:<|fim▁hole|> return string
def _add_os_path_join(module_context, start_leaf, bracket_start):
def check(maybe_bracket, nodes):
if maybe_bracket.start_pos != bracket_start:
return None
if not nodes:
return ''
context = module_context.create_context(nodes[0])
return _add_strings(context, nodes, add_slash=True) or ''
if start_leaf.type == 'error_leaf':
# Unfinished string literal, like `join('`
value_node = start_leaf.parent
index = value_node.children.index(start_leaf)
if index > 0:
error_node = value_node.children[index - 1]
if error_node.type == 'error_node' and len(error_node.children) >= 2:
index = -2
if error_node.children[-1].type == 'arglist':
arglist_nodes = error_node.children[-1].children
index -= 1
else:
arglist_nodes = []
return check(error_node.children[index + 1], arglist_nodes[::2])
return None
# Maybe an arglist or some weird error case. Therefore checked below.
searched_node_child = start_leaf
while searched_node_child.parent is not None \
and searched_node_child.parent.type not in ('arglist', 'trailer', 'error_node'):
searched_node_child = searched_node_child.parent
if searched_node_child.get_first_leaf() is not start_leaf:
return None
searched_node = searched_node_child.parent
if searched_node is None:
return None
index = searched_node.children.index(searched_node_child)
arglist_nodes = searched_node.children[:index]
if searched_node.type == 'arglist':
trailer = searched_node.parent
if trailer.type == 'error_node':
trailer_index = trailer.children.index(searched_node)
assert trailer_index >= 2
assert trailer.children[trailer_index - 1] == '('
return check(trailer.children[trailer_index - 1], arglist_nodes[::2])
elif trailer.type == 'trailer':
return check(trailer.children[0], arglist_nodes[::2])
elif searched_node.type == 'trailer':
return check(searched_node.children[0], [])
elif searched_node.type == 'error_node':
# Stuff like `join(""`
return check(arglist_nodes[-1], [])<|fim▁end|> | string += os.path.sep
string += force_unicode(s)
first = False |
<|file_name|>FriendFacade.java<|end_file_name|><|fim▁begin|>package com.halle.facade;
import java.util.List;
import javax.ejb.Local;
import com.halle.exception.ApplicationException;
import com.halle.model.Friend;
<|fim▁hole|>public interface FriendFacade {
void inviteByPhone(final String token, final String name, final String phoneFriend) throws ApplicationException;
List<Friend> findAllFriend(final String token, String status) throws ApplicationException;
}<|fim▁end|> | @Local |
<|file_name|>template.py<|end_file_name|><|fim▁begin|>"""
sentry.interfaces.template
~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
__all__ = ('Template',)
from sentry.interfaces.base import Interface, InterfaceValidationError
from sentry.interfaces.stacktrace import get_context
from sentry.utils.safe import trim
class Template(Interface):
"""
A rendered template (generally used like a single frame in a stacktrace).
The attributes ``filename``, ``context_line``, and ``lineno`` are required.
>>> {
>>> "abs_path": "/real/file/name.html"
>>> "filename": "file/name.html",
>>> "pre_context": [
>>> "line1",
>>> "line2"
>>> ],
>>> "context_line": "line3",
>>> "lineno": 3,
>>> "post_context": [
>>> "line4",
>>> "line5"
>>> ],
>>> }
.. note:: This interface can be passed as the 'template' key in addition
to the full interface path.
"""
score = 1100
@classmethod
def to_python(cls, data):
if not data.get('filename'):
raise InterfaceValidationError("Missing 'filename'")
if not data.get('context_line'):
raise InterfaceValidationError("Missing 'context_line'")
if not data.get('lineno'):
raise InterfaceValidationError("Missing 'lineno'")
kwargs = {
'abs_path': trim(data.get('abs_path', None), 256),
'filename': trim(data['filename'], 256),
'context_line': trim(data.get('context_line', None), 256),
'lineno': int(data['lineno']),
# TODO(dcramer): trim pre/post_context
'pre_context': data.get('pre_context'),
'post_context': data.get('post_context'),
}
return cls(**kwargs)
def get_alias(self):
return 'template'
def get_path(self):
return 'sentry.interfaces.Template'
def get_hash(self):
return [self.filename, self.context_line]
def to_string(self, event, is_public=False, **kwargs):
context = get_context(
lineno=self.lineno,
context_line=self.context_line,
pre_context=self.pre_context,
post_context=self.post_context,
filename=self.filename,
)
result = [
'Stacktrace (most recent call last):', '',
self.get_traceback(event, context)
]
return '\n'.join(result)
def get_traceback(self, event, context):
result = [
event.message, '',
'File "%s", line %s' % (self.filename, self.lineno), '',
]
result.extend([n[1].strip('\n') for n in context])
return '\n'.join(result)
def get_api_context(self, is_public=False):
return {
'lineNo': self.lineno,
'filename': self.filename,
'context': get_context(
lineno=self.lineno,
context_line=self.context_line,
pre_context=self.pre_context,
post_context=self.post_context,
filename=self.filename,<|fim▁hole|> }<|fim▁end|> | ), |
<|file_name|>GrouperSlotAttribute.cpp<|end_file_name|><|fim▁begin|>/**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2017 UniPro <[email protected]>
* http://ugene.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <U2Lang/IntegralBusType.h>
#include "GrouperSlotAttribute.h"
namespace U2 {
GrouperOutSlotAttribute::GrouperOutSlotAttribute(const Descriptor &d, const DataTypePtr type, bool required, const QVariant &defaultValue)
: Attribute(d, type, required, defaultValue)
{
}
GrouperOutSlotAttribute::~GrouperOutSlotAttribute() {
}
Attribute *GrouperOutSlotAttribute::clone() {
return new GrouperOutSlotAttribute(*this);
}
AttributeGroup GrouperOutSlotAttribute::getGroup() {
return GROUPER_SLOT_GROUP;
}
QList<GrouperOutSlot> &GrouperOutSlotAttribute::getOutSlots() {
return outSlots;
}
const QList<GrouperOutSlot> &GrouperOutSlotAttribute::getOutSlots() const {
return outSlots;
}
void GrouperOutSlotAttribute::addOutSlot(const GrouperOutSlot &outSlot) {
outSlots.append(outSlot);
}
void GrouperOutSlotAttribute::updateActorIds(const QMap<ActorId, ActorId> &actorIdsMap) {
QList<GrouperOutSlot> newOutSlots;
foreach (const GrouperOutSlot &gSlot, outSlots) {
QString slotStr = gSlot.getInSlotStr();
slotStr = GrouperOutSlot::readable2busMap(slotStr);
Workflow::IntegralBusType::remapSlotString(slotStr, actorIdsMap);
slotStr = GrouperOutSlot::busMap2readable(slotStr);
GrouperOutSlot newGSlot(gSlot);
newGSlot.setInSlotStr(slotStr);
newOutSlots << newGSlot;
}
outSlots = newOutSlots;
}
GroupSlotAttribute::GroupSlotAttribute(const Descriptor &d, const DataTypePtr type, bool required, const QVariant &defaultValue)
: Attribute(d, type, required, defaultValue)
{
}
Attribute *GroupSlotAttribute::clone() {<|fim▁hole|> return new GroupSlotAttribute(*this);
}
void GroupSlotAttribute::updateActorIds(const QMap<ActorId, ActorId> &actorIdsMap) {
QString slotStr = this->getAttributeValueWithoutScript<QString>();
slotStr = GrouperOutSlot::readable2busMap(slotStr);
Workflow::IntegralBusType::remapSlotString(slotStr, actorIdsMap);
slotStr = GrouperOutSlot::busMap2readable(slotStr);
this->setAttributeValue(slotStr);
}
void GroupSlotAttribute::setAttributeValue(const QVariant &newVal) {
QString slotStr = newVal.toString();
Attribute::setAttributeValue(GrouperOutSlot::busMap2readable(slotStr));
}
} // U2<|fim▁end|> | |
<|file_name|>build.rs<|end_file_name|><|fim▁begin|><|fim▁hole|> let target_arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();
let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
if target_arch == "wasm32" || target_os == "hermit" {
println!("cargo:rustc-cfg=feature=\"std\"");
}
}<|fim▁end|> | fn main() { |
<|file_name|>version.go<|end_file_name|><|fim▁begin|>// Copyright (c) 2015 Serge Gebhardt. All rights reserved.
//
// Use of this source code is governed by the ISC
// license that can be found in the LICENSE file.
package command
import (
"bytes"
"fmt"
"github.com/mitchellh/cli"
"github.com/sgeb/go-acd"
)
type VersionCommand struct {
AppName string
Revision string
Version string
VersionPrerelease string
Ui cli.Ui
}
func (c *VersionCommand) Help() string {
return ""
}
func (c *VersionCommand) Run(_ []string) int {
var versionString bytes.Buffer
fmt.Fprintf(&versionString, "%s v%s", c.AppName, c.Version)<|fim▁hole|> fmt.Fprintf(&versionString, "-%s", c.VersionPrerelease)
if c.Revision != "" {
fmt.Fprintf(&versionString, " (%s)", c.Revision)
}
}
fmt.Fprintln(&versionString, "")
fmt.Fprintf(&versionString, "using go-acd v%s", acd.LibraryVersion)
c.Ui.Output(versionString.String())
return 0
}
func (c *VersionCommand) Synopsis() string {
return fmt.Sprintf("Prints the %s version", c.AppName)
}<|fim▁end|> | if c.VersionPrerelease != "" { |
<|file_name|>has_element_with_class_name.js<|end_file_name|><|fim▁begin|>/**
* High performant way to check whether an element with a specific class name is in the given document
* Optimized for being heavily executed
* Unleashes the power of live node lists
*
* @param {Object} doc The document object of the context where to check
* @param {String} tagName Upper cased tag name
* @example
* wysihtml5.dom.hasElementWithClassName(document, "foobar");
*/
(function(wysihtml5) {
var LIVE_CACHE = {},
DOCUMENT_IDENTIFIER = 1;
function _getDocumentIdentifier(doc) {
return doc._wysihtml5_identifier || (doc._wysihtml5_identifier = DOCUMENT_IDENTIFIER++);
}
wysihtml5.dom.hasElementWithClassName = function(doc, className) {
// getElementsByClassName is not supported by IE<9
// but is sometimes mocked via library code (which then doesn't return live node lists)
if (!wysihtml5.browser.supportsNativeGetElementsByClassName()) {<|fim▁hole|> return !!doc.querySelector("." + className);
}
var key = _getDocumentIdentifier(doc) + ":" + className,
cacheEntry = LIVE_CACHE[key];
if (!cacheEntry) {
cacheEntry = LIVE_CACHE[key] = doc.getElementsByClassName(className);
}
return cacheEntry.length > 0;
};
})(wysihtml5);<|fim▁end|> | |
<|file_name|>base.py<|end_file_name|><|fim▁begin|>from sqlalchemy import inspection, event, Column, Integer, ForeignKey
from sqlalchemy.orm import session, query
from sqlalchemy.sql import expression
from sqlalchemy.ext.declarative import declared_attr
import sqlalchemy
__all__ = [
'Base',
'TenantSession',
'TenantConflict',
'UnboundTenantError'
]
SQLA_VERSION_8 = sqlalchemy.__version__.startswith('0.8')
class UnboundTenantError(Exception):
pass
class TenantConflict(Exception):
pass
class Base(object):
__multitenant__ = True
__plural_tablename__ = None
@classmethod
def tenant_class(cls, tenant_cls):
cls._tenant_cls = tenant_cls
event.listen(tenant_cls, 'after_insert', after_tenant_insert)
event.listen(tenant_cls, 'before_delete', before_tenant_delete)
return tenant_cls
@declared_attr
def tenant_id(cls):
if not cls.__multitenant__:
return None
return Column(
Integer, ForeignKey("%s.id" % cls._tenant_cls.__tablename__),
index=True)
# abandoning this for now as it causes unexpected SQLAlchemy error
#@declared_attr
#def tenant(cls):
#if not cls.__multitenant__:
#return None
#return relationship(
#cls._tenant_cls, primaryjoin=(cls.tenant_id ==
#cls._tenant_cls.id),
#backref=cls._tenant_cls.__tablename__)
def after_tenant_insert(mapper, connection, target):
# create user
# create views
# revoke all on user
pass
def before_tenant_delete(mapper, connection, target):
# backup data?
# drop views
# drop user
# drop data
pass
class TenantSession(session.Session):
def __init__(self, query_cls=None, *args, **kwargs):
self.tenant = None
<|fim▁hole|> query_cls=query_cls, *args, **kwargs)
def query(self, *args, **kwargs):
kwargs.setdefault('safe', True)
return super(TenantSession, self).query(*args, **kwargs)
def add(self, instance, *args, **kwargs):
self.check_instance(instance)
instance.tenant_id = self.tenant.id
super(TenantSession, self).add(instance, *args, **kwargs)
def delete(self, instance, *args, **kwargs):
self.check_instance(instance)
super(TenantSession, self).delete(instance, *args, **kwargs)
def merge(self, instance, *args, **kwargs):
self.check_instance(instance)
super(TenantSession, self).merge(instance, *args, **kwargs)
def check_instance(self, instance):
if instance.__multitenant__ and self.tenant is None:
raise UnboundTenantError(
"Tried to do a tenant-safe operation in a tenantless context.")
if instance.__multitenant__ and instance.tenant_id is not None and \
instance.tenant_id != self.tenant.id:
raise TenantConflict((
"Tried to use a %r with tenant_id %r in a session with " +
"tenant_id %r") % (
type(instance), instance.tenant_id, self.tenant.id))
class TenantQuery(query.Query):
def __init__(self, *args, **kwargs):
self._safe = kwargs.pop('safe', True)
super(TenantQuery, self).__init__(*args, **kwargs)
@property
def _from_obj(self):
# we only do the multitenant processing on accessing the _from_obj /
# froms properties, rather than have a wrapper object, because it
# wasn't possible to implement the right magic methods and still have
# the wrapper object evaluate to the underlying sequence.
# This approach is fine because adding a given criterion is idempotent.
if getattr(self, '_from_obj_', None) is None:
self._from_obj_ = ()
for from_ in self._from_obj_:
_process_from(from_, self)
return self._from_obj_
@_from_obj.setter
def _from_obj(self, value):
self._from_obj_ = value
def _join_to_left(self, *args, **kwargs):
right = args[1 if SQLA_VERSION_8 else 2]
super(TenantQuery, self)._join_to_left(*args, **kwargs)
_process_from(inspection.inspect(right).selectable, self)
class TenantQueryContext(query.QueryContext):
@property
def froms(self):
if getattr(self, '_froms', None) is None:
self._froms = []
for from_ in self._froms:
_process_from(from_, self.query, self)
return self._froms
@froms.setter
def froms(self, value):
self._froms = value
# monkey patch to avoid needing changes to SQLAlchemy
query.QueryContext = TenantQueryContext
def _process_from(from_, query, query_context=None):
if not getattr(query, '_safe', None):
return
tenant_id_col = from_.c.get('tenant_id')
if tenant_id_col is not None:
if query.session.tenant is None:
raise UnboundTenantError(
"Tried to do a tenant-bound query in a tenantless context.")
# logic copied from orm.Query.filter, in order to be able to modify
# the existing query in place
criterion = expression._literal_as_text(
tenant_id_col == query.session.tenant.id)
criterion = query._adapt_clause(criterion, True, True)
if query_context is None:
if query._criterion is not None:
query._criterion = query._criterion & criterion
else:
query._criterion = criterion
else:
if query_context.whereclause is not None:
query_context.whereclause = (
query_context.whereclause & criterion)
else:
query_context.whereclause = criterion<|fim▁end|> | query_cls = query_cls or TenantQuery
super(TenantSession, self).__init__( |
<|file_name|>multistore.go<|end_file_name|><|fim▁begin|>package chunkstore
import (
"errors"
. "github.com/huin/chunkymonkey/types"
)
// MultiStore provides the ability to load a chunk from one or more potential
// sources of chunk data. The primary purpose of this is to read from a
// persistant store first, then fall back to generating a chunk if the
// persistant store does not have it. MultiStore implements IChunkStore.
type MultiStore struct {
readStores []IChunkStore
writeStore IChunkStore
}
func NewMultiStore(readStores []IChunkStore, writeStore IChunkStore) *MultiStore {
s := &MultiStore{
readStores: readStores,
writeStore: writeStore,
}
return s
}
func (s *MultiStore) ReadChunk(chunkLoc ChunkXz) (reader IChunkReader, err error) {
for _, store := range s.readStores {
result := <-store.ReadChunk(chunkLoc)
if result.Err == nil {
return result.Reader, result.Err
} else {
if _, ok := result.Err.(NoSuchChunkError); ok {
// Fall through to next chunk store.<|fim▁hole|> return nil, result.Err
}
}
return nil, NoSuchChunkError(false)
}
func (s *MultiStore) SupportsWrite() bool {
return s.writeStore != nil && s.writeStore.SupportsWrite()
}
func (s *MultiStore) Writer() IChunkWriter {
if s.writeStore != nil {
return s.writeStore.Writer()
}
return nil
}
func (s *MultiStore) WriteChunk(writer IChunkWriter) error {
if s.writeStore == nil {
return errors.New("writes not supported")
}
s.writeStore.WriteChunk(writer)
return nil
}<|fim▁end|> | continue
} |
<|file_name|>window.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use app_units::Au;
use base64;
use bluetooth_traits::BluetoothRequest;
use canvas_traits::webgl::WebGLChan;
use cssparser::{Parser, ParserInput};
use devtools_traits::{ScriptToDevtoolsControlMsg, TimelineMarker, TimelineMarkerType};
use dom::bindings::cell::DomRefCell;
use dom::bindings::codegen::Bindings::DocumentBinding::{DocumentMethods, DocumentReadyState};
use dom::bindings::codegen::Bindings::FunctionBinding::Function;
use dom::bindings::codegen::Bindings::PermissionStatusBinding::PermissionState;
use dom::bindings::codegen::Bindings::RequestBinding::RequestInit;
use dom::bindings::codegen::Bindings::WindowBinding::{self, FrameRequestCallback, WindowMethods};
use dom::bindings::codegen::Bindings::WindowBinding::{ScrollBehavior, ScrollToOptions};
use dom::bindings::codegen::UnionTypes::RequestOrUSVString;
use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::inheritance::Castable;
use dom::bindings::num::Finite;
use dom::bindings::refcounted::Trusted;
use dom::bindings::reflector::DomObject;
use dom::bindings::root::{Dom, DomRoot, MutNullableDom};
use dom::bindings::str::{DOMString, USVString};
use dom::bindings::structuredclone::StructuredCloneData;
use dom::bindings::trace::RootedTraceableBox;
use dom::bindings::utils::{GlobalStaticData, WindowProxyHandler};
use dom::bluetooth::BluetoothExtraPermissionData;
use dom::crypto::Crypto;
use dom::cssstyledeclaration::{CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner};
use dom::customelementregistry::CustomElementRegistry;
use dom::document::{AnimationFrameCallback, Document};
use dom::element::Element;
use dom::globalscope::GlobalScope;
use dom::history::History;
use dom::location::Location;
use dom::mediaquerylist::{MediaQueryList, WeakMediaQueryListVec};
use dom::messageevent::MessageEvent;
use dom::navigator::Navigator;
use dom::node::{Node, NodeDamage, document_from_node, from_untrusted_node_address};
use dom::performance::Performance;
use dom::promise::Promise;
use dom::screen::Screen;
use dom::storage::Storage;
use dom::testrunner::TestRunner;
use dom::windowproxy::WindowProxy;
use dom::worklet::Worklet;
use dom::workletglobalscope::WorkletGlobalScopeType;
use dom_struct::dom_struct;
use euclid::{Point2D, Vector2D, Rect, Size2D, TypedPoint2D, TypedScale, TypedSize2D};
use fetch;
use ipc_channel::ipc::IpcSender;
use ipc_channel::router::ROUTER;<|fim▁hole|>use js::rust::HandleValue;
use layout_image::fetch_image_for_layout;
use microtask::MicrotaskQueue;
use msg::constellation_msg::PipelineId;
use net_traits::{ResourceThreads, ReferrerPolicy};
use net_traits::image_cache::{ImageCache, ImageResponder, ImageResponse};
use net_traits::image_cache::{PendingImageId, PendingImageResponse};
use net_traits::storage_thread::StorageType;
use num_traits::ToPrimitive;
use profile_traits::ipc as ProfiledIpc;
use profile_traits::mem::ProfilerChan as MemProfilerChan;
use profile_traits::time::ProfilerChan as TimeProfilerChan;
use script_layout_interface::{TrustedNodeAddress, PendingImageState};
use script_layout_interface::message::{Msg, Reflow, QueryMsg, ReflowGoal, ScriptReflow};
use script_layout_interface::reporter::CSSErrorReporter;
use script_layout_interface::rpc::{ContentBoxResponse, ContentBoxesResponse, LayoutRPC};
use script_layout_interface::rpc::{NodeScrollIdResponse, ResolvedStyleResponse, TextIndexResponse};
use script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort, ScriptThreadEventCategory, Runtime};
use script_thread::{ImageCacheMsg, MainThreadScriptChan, MainThreadScriptMsg};
use script_thread::{ScriptThread, SendableMainThreadScriptChan};
use script_traits::{ConstellationControlMsg, DocumentState, LoadData};
use script_traits::{ScriptToConstellationChan, ScriptMsg, ScrollState, TimerEvent, TimerEventId};
use script_traits::{TimerSchedulerMsg, UntrustedNodeAddress, WindowSizeData, WindowSizeType};
use script_traits::webdriver_msg::{WebDriverJSError, WebDriverJSResult};
use selectors::attr::CaseSensitivity;
use servo_arc;
use servo_config::opts;
use servo_geometry::{f32_rect_to_au_rect, MaxRect};
use servo_url::{Host, MutableOrigin, ImmutableOrigin, ServoUrl};
use std::borrow::ToOwned;
use std::cell::Cell;
use std::collections::{HashMap, HashSet};
use std::collections::hash_map::Entry;
use std::default::Default;
use std::env;
use std::fs;
use std::io::{Write, stderr, stdout};
use std::mem;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Sender, channel};
use std::sync::mpsc::TryRecvError::{Disconnected, Empty};
use style::media_queries;
use style::parser::ParserContext as CssParserContext;
use style::properties::{ComputedValues, PropertyId};
use style::selector_parser::PseudoElement;
use style::str::HTML_SPACE_CHARACTERS;
use style::stylesheets::CssRuleType;
use style_traits::{CSSPixel, DevicePixel, ParsingMode};
use task::TaskCanceller;
use task_source::dom_manipulation::DOMManipulationTaskSource;
use task_source::file_reading::FileReadingTaskSource;
use task_source::history_traversal::HistoryTraversalTaskSource;
use task_source::networking::NetworkingTaskSource;
use task_source::performance_timeline::PerformanceTimelineTaskSource;
use task_source::user_interaction::UserInteractionTaskSource;
use time;
use timers::{IsInterval, TimerCallback};
#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
use tinyfiledialogs::{self, MessageBoxIcon};
use url::Position;
use webdriver_handlers::jsval_to_webdriver;
use webrender_api::{ExternalScrollId, DeviceIntPoint, DeviceUintSize, DocumentId};
use webvr_traits::WebVRMsg;
/// Current state of the window object
#[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)]
enum WindowState {
Alive,
Zombie, // Pipeline is closed, but the window hasn't been GCed yet.
}
/// Extra information concerning the reason for reflowing.
#[derive(Debug, MallocSizeOf)]
pub enum ReflowReason {
CachedPageNeededReflow,
RefreshTick,
FirstLoad,
KeyEvent,
MouseEvent,
Query,
Timer,
Viewport,
WindowResize,
DOMContentLoaded,
DocumentLoaded,
StylesheetLoaded,
ImageLoaded,
RequestAnimationFrame,
WebFontLoaded,
WorkletLoaded,
FramedContentChanged,
IFrameLoadEvent,
MissingExplicitReflow,
ElementStateChanged,
}
#[dom_struct]
pub struct Window {
globalscope: GlobalScope,
#[ignore_malloc_size_of = "trait objects are hard"]
script_chan: MainThreadScriptChan,
#[ignore_malloc_size_of = "task sources are hard"]
dom_manipulation_task_source: DOMManipulationTaskSource,
#[ignore_malloc_size_of = "task sources are hard"]
user_interaction_task_source: UserInteractionTaskSource,
#[ignore_malloc_size_of = "task sources are hard"]
networking_task_source: NetworkingTaskSource,
#[ignore_malloc_size_of = "task sources are hard"]
history_traversal_task_source: HistoryTraversalTaskSource,
#[ignore_malloc_size_of = "task sources are hard"]
file_reading_task_source: FileReadingTaskSource,
#[ignore_malloc_size_of = "task sources are hard"]
performance_timeline_task_source: PerformanceTimelineTaskSource,
navigator: MutNullableDom<Navigator>,
#[ignore_malloc_size_of = "Arc"]
image_cache: Arc<ImageCache>,
#[ignore_malloc_size_of = "channels are hard"]
image_cache_chan: Sender<ImageCacheMsg>,
window_proxy: MutNullableDom<WindowProxy>,
document: MutNullableDom<Document>,
location: MutNullableDom<Location>,
history: MutNullableDom<History>,
custom_element_registry: MutNullableDom<CustomElementRegistry>,
performance: MutNullableDom<Performance>,
navigation_start: Cell<u64>,
navigation_start_precise: Cell<u64>,
screen: MutNullableDom<Screen>,
session_storage: MutNullableDom<Storage>,
local_storage: MutNullableDom<Storage>,
status: DomRefCell<DOMString>,
/// For sending timeline markers. Will be ignored if
/// no devtools server
devtools_markers: DomRefCell<HashSet<TimelineMarkerType>>,
#[ignore_malloc_size_of = "channels are hard"]
devtools_marker_sender: DomRefCell<Option<IpcSender<Option<TimelineMarker>>>>,
/// Pending resize event, if any.
resize_event: Cell<Option<(WindowSizeData, WindowSizeType)>>,
/// Parent id associated with this page, if any.
parent_info: Option<PipelineId>,
/// Global static data related to the DOM.
dom_static: GlobalStaticData,
/// The JavaScript runtime.
#[ignore_malloc_size_of = "Rc<T> is hard"]
js_runtime: DomRefCell<Option<Rc<Runtime>>>,
/// A handle for communicating messages to the layout thread.
#[ignore_malloc_size_of = "channels are hard"]
layout_chan: Sender<Msg>,
/// A handle to perform RPC calls into the layout, quickly.
#[ignore_malloc_size_of = "trait objects are hard"]
layout_rpc: Box<LayoutRPC + Send + 'static>,
/// The current size of the window, in pixels.
window_size: Cell<Option<WindowSizeData>>,
/// A handle for communicating messages to the bluetooth thread.
#[ignore_malloc_size_of = "channels are hard"]
bluetooth_thread: IpcSender<BluetoothRequest>,
bluetooth_extra_permission_data: BluetoothExtraPermissionData,
/// An enlarged rectangle around the page contents visible in the viewport, used
/// to prevent creating display list items for content that is far away from the viewport.
page_clip_rect: Cell<Rect<Au>>,
/// Flag to suppress reflows. The first reflow will come either with
/// RefreshTick or with FirstLoad. Until those first reflows, we want to
/// suppress others like MissingExplicitReflow.
suppress_reflow: Cell<bool>,
/// A counter of the number of pending reflows for this window.
pending_reflow_count: Cell<u32>,
/// A channel for communicating results of async scripts back to the webdriver server
#[ignore_malloc_size_of = "channels are hard"]
webdriver_script_chan: DomRefCell<Option<IpcSender<WebDriverJSResult>>>,
/// The current state of the window object
current_state: Cell<WindowState>,
current_viewport: Cell<Rect<Au>>,
/// A flag to prevent async events from attempting to interact with this window.
#[ignore_malloc_size_of = "defined in std"]
ignore_further_async_events: DomRefCell<Arc<AtomicBool>>,
error_reporter: CSSErrorReporter,
/// A list of scroll offsets for each scrollable element.
scroll_offsets: DomRefCell<HashMap<UntrustedNodeAddress, Vector2D<f32>>>,
/// All the MediaQueryLists we need to update
media_query_lists: WeakMediaQueryListVec,
test_runner: MutNullableDom<TestRunner>,
/// A handle for communicating messages to the WebGL thread, if available.
#[ignore_malloc_size_of = "channels are hard"]
webgl_chan: Option<WebGLChan>,
/// A handle for communicating messages to the webvr thread, if available.
#[ignore_malloc_size_of = "channels are hard"]
webvr_chan: Option<IpcSender<WebVRMsg>>,
/// A map for storing the previous permission state read results.
permission_state_invocation_results: DomRefCell<HashMap<String, PermissionState>>,
/// All of the elements that have an outstanding image request that was
/// initiated by layout during a reflow. They are stored in the script thread
/// to ensure that the element can be marked dirty when the image data becomes
/// available at some point in the future.
pending_layout_images: DomRefCell<HashMap<PendingImageId, Vec<Dom<Node>>>>,
/// Directory to store unminified scripts for this window if unminify-js
/// opt is enabled.
unminified_js_dir: DomRefCell<Option<String>>,
/// Worklets
test_worklet: MutNullableDom<Worklet>,
/// <https://drafts.css-houdini.org/css-paint-api-1/#paint-worklet>
paint_worklet: MutNullableDom<Worklet>,
/// The Webrender Document id associated with this window.
#[ignore_malloc_size_of = "defined in webrender_api"]
webrender_document: DocumentId,
/// Flag to identify whether mutation observers are present(true)/absent(false)
exists_mut_observer: Cell<bool>,
}
impl Window {
pub fn get_exists_mut_observer(&self) -> bool {
self.exists_mut_observer.get()
}
pub fn set_exists_mut_observer(&self) {
self.exists_mut_observer.set(true);
}
#[allow(unsafe_code)]
pub fn clear_js_runtime_for_script_deallocation(&self) {
unsafe {
*self.js_runtime.borrow_for_script_deallocation() = None;
self.window_proxy.set(None);
self.current_state.set(WindowState::Zombie);
self.ignore_further_async_events.borrow().store(true, Ordering::Relaxed);
}
}
/// Get a sender to the time profiler thread.
pub fn time_profiler_chan(&self) -> &TimeProfilerChan {
self.globalscope.time_profiler_chan()
}
pub fn origin(&self) -> &MutableOrigin {
self.globalscope.origin()
}
pub fn get_cx(&self) -> *mut JSContext {
self.js_runtime.borrow().as_ref().unwrap().cx()
}
pub fn dom_manipulation_task_source(&self) -> DOMManipulationTaskSource {
self.dom_manipulation_task_source.clone()
}
pub fn user_interaction_task_source(&self) -> UserInteractionTaskSource {
self.user_interaction_task_source.clone()
}
pub fn networking_task_source(&self) -> NetworkingTaskSource {
self.networking_task_source.clone()
}
pub fn history_traversal_task_source(&self) -> Box<ScriptChan + Send> {
self.history_traversal_task_source.clone()
}
pub fn file_reading_task_source(&self) -> FileReadingTaskSource {
self.file_reading_task_source.clone()
}
pub fn performance_timeline_task_source(&self) -> PerformanceTimelineTaskSource {
self.performance_timeline_task_source.clone()
}
pub fn main_thread_script_chan(&self) -> &Sender<MainThreadScriptMsg> {
&self.script_chan.0
}
pub fn parent_info(&self) -> Option<PipelineId> {
self.parent_info
}
pub fn new_script_pair(&self) -> (Box<ScriptChan + Send>, Box<ScriptPort + Send>) {
let (tx, rx) = channel();
(Box::new(SendableMainThreadScriptChan(tx)), Box::new(rx))
}
pub fn image_cache(&self) -> Arc<ImageCache> {
self.image_cache.clone()
}
/// This can panic if it is called after the browsing context has been discarded
pub fn window_proxy(&self) -> DomRoot<WindowProxy> {
self.window_proxy.get().unwrap()
}
/// Returns the window proxy if it has not been discarded.
/// <https://html.spec.whatwg.org/multipage/#a-browsing-context-is-discarded>
pub fn undiscarded_window_proxy(&self) -> Option<DomRoot<WindowProxy>> {
self.window_proxy.get()
.and_then(|window_proxy| if window_proxy.is_browsing_context_discarded() {
None
} else {
Some(window_proxy)
})
}
pub fn bluetooth_thread(&self) -> IpcSender<BluetoothRequest> {
self.bluetooth_thread.clone()
}
pub fn bluetooth_extra_permission_data(&self) -> &BluetoothExtraPermissionData {
&self.bluetooth_extra_permission_data
}
pub fn css_error_reporter(&self) -> &CSSErrorReporter {
&self.error_reporter
}
/// Sets a new list of scroll offsets.
///
/// This is called when layout gives us new ones and WebRender is in use.
pub fn set_scroll_offsets(&self, offsets: HashMap<UntrustedNodeAddress, Vector2D<f32>>) {
*self.scroll_offsets.borrow_mut() = offsets
}
pub fn current_viewport(&self) -> Rect<Au> {
self.current_viewport.clone().get()
}
pub fn webgl_chan(&self) -> Option<WebGLChan> {
self.webgl_chan.clone()
}
pub fn webvr_thread(&self) -> Option<IpcSender<WebVRMsg>> {
self.webvr_chan.clone()
}
fn new_paint_worklet(&self) -> DomRoot<Worklet> {
debug!("Creating new paint worklet.");
Worklet::new(self, WorkletGlobalScopeType::Paint)
}
pub fn permission_state_invocation_results(&self) -> &DomRefCell<HashMap<String, PermissionState>> {
&self.permission_state_invocation_results
}
pub fn pending_image_notification(&self, response: PendingImageResponse) {
//XXXjdm could be more efficient to send the responses to the layout thread,
// rather than making the layout thread talk to the image cache to
// obtain the same data.
let mut images = self.pending_layout_images.borrow_mut();
let nodes = images.entry(response.id);
let nodes = match nodes {
Entry::Occupied(nodes) => nodes,
Entry::Vacant(_) => return,
};
for node in nodes.get() {
node.dirty(NodeDamage::OtherNodeDamage);
}
match response.response {
ImageResponse::MetadataLoaded(_) => {}
ImageResponse::Loaded(_, _) |
ImageResponse::PlaceholderLoaded(_, _) |
ImageResponse::None => { nodes.remove(); }
}
self.add_pending_reflow();
}
}
#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
fn display_alert_dialog(message: &str) {
if !opts::get().headless {
tinyfiledialogs::message_box_ok("Alert!", message, MessageBoxIcon::Warning);
}
}
#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
fn display_alert_dialog(_message: &str) {
// tinyfiledialogs not supported on Android
}
// https://html.spec.whatwg.org/multipage/#atob
pub fn base64_btoa(input: DOMString) -> Fallible<DOMString> {
// "The btoa() method must throw an InvalidCharacterError exception if
// the method's first argument contains any character whose code point
// is greater than U+00FF."
if input.chars().any(|c: char| c > '\u{FF}') {
Err(Error::InvalidCharacter)
} else {
// "Otherwise, the user agent must convert that argument to a
// sequence of octets whose nth octet is the eight-bit
// representation of the code point of the nth character of
// the argument,"
let octets = input.chars().map(|c: char| c as u8).collect::<Vec<u8>>();
// "and then must apply the base64 algorithm to that sequence of
// octets, and return the result. [RFC4648]"
Ok(DOMString::from(base64::encode(&octets)))
}
}
// https://html.spec.whatwg.org/multipage/#atob
pub fn base64_atob(input: DOMString) -> Fallible<DOMString> {
// "Remove all space characters from input."
fn is_html_space(c: char) -> bool {
HTML_SPACE_CHARACTERS.iter().any(|&m| m == c)
}
let without_spaces = input.chars()
.filter(|&c| !is_html_space(c))
.collect::<String>();
let mut input = &*without_spaces;
// "If the length of input divides by 4 leaving no remainder, then:
// if input ends with one or two U+003D EQUALS SIGN (=) characters,
// remove them from input."
if input.len() % 4 == 0 {
if input.ends_with("==") {
input = &input[..input.len() - 2]
} else if input.ends_with("=") {
input = &input[..input.len() - 1]
}
}
// "If the length of input divides by 4 leaving a remainder of 1,
// throw an InvalidCharacterError exception and abort these steps."
if input.len() % 4 == 1 {
return Err(Error::InvalidCharacter)
}
// "If input contains a character that is not in the following list of
// characters and character ranges, throw an InvalidCharacterError
// exception and abort these steps:
//
// U+002B PLUS SIGN (+)
// U+002F SOLIDUS (/)
// Alphanumeric ASCII characters"
if input.chars().any(|c| c != '+' && c != '/' && !c.is_alphanumeric()) {
return Err(Error::InvalidCharacter)
}
match base64::decode(&input) {
Ok(data) => Ok(DOMString::from(data.iter().map(|&b| b as char).collect::<String>())),
Err(..) => Err(Error::InvalidCharacter)
}
}
impl WindowMethods for Window {
// https://html.spec.whatwg.org/multipage/#dom-alert
fn Alert_(&self) {
self.Alert(DOMString::new());
}
// https://html.spec.whatwg.org/multipage/#dom-alert
fn Alert(&self, s: DOMString) {
// Print to the console.
// Ensure that stderr doesn't trample through the alert() we use to
// communicate test results (see executorservo.py in wptrunner).
{
let stderr = stderr();
let mut stderr = stderr.lock();
let stdout = stdout();
let mut stdout = stdout.lock();
writeln!(&mut stdout, "ALERT: {}", s).unwrap();
stdout.flush().unwrap();
stderr.flush().unwrap();
}
let (sender, receiver) = ProfiledIpc::channel(self.global().time_profiler_chan().clone()).unwrap();
self.send_to_constellation(ScriptMsg::Alert(s.to_string(), sender));
let should_display_alert_dialog = receiver.recv().unwrap();
if should_display_alert_dialog {
display_alert_dialog(&s);
}
}
// https://html.spec.whatwg.org/multipage/#dom-window-closed
fn Closed(&self) -> bool {
self.window_proxy.get()
.map(|ref proxy| proxy.is_browsing_context_discarded())
.unwrap_or(true)
}
// https://html.spec.whatwg.org/multipage/#dom-window-close
fn Close(&self) {
self.main_thread_script_chan()
.send(MainThreadScriptMsg::ExitWindow(self.upcast::<GlobalScope>().pipeline_id()))
.unwrap();
}
// https://html.spec.whatwg.org/multipage/#dom-document-2
fn Document(&self) -> DomRoot<Document> {
self.document.get().expect("Document accessed before initialization.")
}
// https://html.spec.whatwg.org/multipage/#dom-history
fn History(&self) -> DomRoot<History> {
self.history.or_init(|| History::new(self))
}
// https://html.spec.whatwg.org/multipage/#dom-window-customelements
fn CustomElements(&self) -> DomRoot<CustomElementRegistry> {
self.custom_element_registry.or_init(|| CustomElementRegistry::new(self))
}
// https://html.spec.whatwg.org/multipage/#dom-location
fn Location(&self) -> DomRoot<Location> {
self.location.or_init(|| Location::new(self))
}
// https://html.spec.whatwg.org/multipage/#dom-sessionstorage
fn SessionStorage(&self) -> DomRoot<Storage> {
self.session_storage.or_init(|| Storage::new(self, StorageType::Session))
}
// https://html.spec.whatwg.org/multipage/#dom-localstorage
fn LocalStorage(&self) -> DomRoot<Storage> {
self.local_storage.or_init(|| Storage::new(self, StorageType::Local))
}
// https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#dfn-GlobalCrypto
fn Crypto(&self) -> DomRoot<Crypto> {
self.upcast::<GlobalScope>().crypto()
}
// https://html.spec.whatwg.org/multipage/#dom-frameelement
fn GetFrameElement(&self) -> Option<DomRoot<Element>> {
// Steps 1-3.
let window_proxy = self.window_proxy.get()?;
// Step 4-5.
let container = window_proxy.frame_element()?;
// Step 6.
let container_doc = document_from_node(container);
let current_doc = GlobalScope::current().expect("No current global object").as_window().Document();
if !current_doc.origin().same_origin_domain(container_doc.origin()) {
return None;
}
// Step 7.
Some(DomRoot::from_ref(container))
}
// https://html.spec.whatwg.org/multipage/#dom-navigator
fn Navigator(&self) -> DomRoot<Navigator> {
self.navigator.or_init(|| Navigator::new(self))
}
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout
unsafe fn SetTimeout(&self, _cx: *mut JSContext, callback: Rc<Function>, timeout: i32,
args: Vec<HandleValue>) -> i32 {
self.upcast::<GlobalScope>().set_timeout_or_interval(
TimerCallback::FunctionTimerCallback(callback),
args,
timeout,
IsInterval::NonInterval)
}
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout
unsafe fn SetTimeout_(&self, _cx: *mut JSContext, callback: DOMString,
timeout: i32, args: Vec<HandleValue>) -> i32 {
self.upcast::<GlobalScope>().set_timeout_or_interval(
TimerCallback::StringTimerCallback(callback),
args,
timeout,
IsInterval::NonInterval)
}
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-cleartimeout
fn ClearTimeout(&self, handle: i32) {
self.upcast::<GlobalScope>().clear_timeout_or_interval(handle);
}
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval
unsafe fn SetInterval(&self, _cx: *mut JSContext, callback: Rc<Function>,
timeout: i32, args: Vec<HandleValue>) -> i32 {
self.upcast::<GlobalScope>().set_timeout_or_interval(
TimerCallback::FunctionTimerCallback(callback),
args,
timeout,
IsInterval::Interval)
}
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval
unsafe fn SetInterval_(&self, _cx: *mut JSContext, callback: DOMString,
timeout: i32, args: Vec<HandleValue>) -> i32 {
self.upcast::<GlobalScope>().set_timeout_or_interval(
TimerCallback::StringTimerCallback(callback),
args,
timeout,
IsInterval::Interval)
}
// https://html.spec.whatwg.org/multipage/#dom-windowtimers-clearinterval
fn ClearInterval(&self, handle: i32) {
self.ClearTimeout(handle);
}
// https://html.spec.whatwg.org/multipage/#dom-window
fn Window(&self) -> DomRoot<WindowProxy> {
self.window_proxy()
}
// https://html.spec.whatwg.org/multipage/#dom-self
fn Self_(&self) -> DomRoot<WindowProxy> {
self.window_proxy()
}
// https://html.spec.whatwg.org/multipage/#dom-frames
fn Frames(&self) -> DomRoot<WindowProxy> {
self.window_proxy()
}
// https://html.spec.whatwg.org/multipage/#dom-parent
fn GetParent(&self) -> Option<DomRoot<WindowProxy>> {
// Steps 1-3.
let window_proxy = self.undiscarded_window_proxy()?;
// Step 4.
if let Some(parent) = window_proxy.parent() {
return Some(DomRoot::from_ref(parent));
}
// Step 5.
Some(window_proxy)
}
// https://html.spec.whatwg.org/multipage/#dom-top
fn GetTop(&self) -> Option<DomRoot<WindowProxy>> {
// Steps 1-3.
let window_proxy = self.undiscarded_window_proxy()?;
// Steps 4-5.
Some(DomRoot::from_ref(window_proxy.top()))
}
// https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/
// NavigationTiming/Overview.html#sec-window.performance-attribute
fn Performance(&self) -> DomRoot<Performance> {
self.performance.or_init(|| {
let global_scope = self.upcast::<GlobalScope>();
Performance::new(global_scope, self.navigation_start.get(),
self.navigation_start_precise.get())
})
}
// https://html.spec.whatwg.org/multipage/#globaleventhandlers
global_event_handlers!();
// https://html.spec.whatwg.org/multipage/#windoweventhandlers
window_event_handlers!();
// https://developer.mozilla.org/en-US/docs/Web/API/Window/screen
fn Screen(&self) -> DomRoot<Screen> {
self.screen.or_init(|| Screen::new(self))
}
// https://html.spec.whatwg.org/multipage/#dom-windowbase64-btoa
fn Btoa(&self, btoa: DOMString) -> Fallible<DOMString> {
base64_btoa(btoa)
}
// https://html.spec.whatwg.org/multipage/#dom-windowbase64-atob
fn Atob(&self, atob: DOMString) -> Fallible<DOMString> {
base64_atob(atob)
}
/// <https://html.spec.whatwg.org/multipage/#dom-window-requestanimationframe>
fn RequestAnimationFrame(&self, callback: Rc<FrameRequestCallback>) -> u32 {
self.Document()
.request_animation_frame(AnimationFrameCallback::FrameRequestCallback { callback })
}
/// <https://html.spec.whatwg.org/multipage/#dom-window-cancelanimationframe>
fn CancelAnimationFrame(&self, ident: u32) {
let doc = self.Document();
doc.cancel_animation_frame(ident);
}
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-window-postmessage
unsafe fn PostMessage(&self,
cx: *mut JSContext,
message: HandleValue,
origin: DOMString)
-> ErrorResult {
// Step 3-5.
let origin = match &origin[..] {
"*" => None,
"/" => {
// TODO(#12715): Should be the origin of the incumbent settings
// object, not self's.
Some(self.Document().origin().immutable().clone())
},
url => match ServoUrl::parse(&url) {
Ok(url) => Some(url.origin().clone()),
Err(_) => return Err(Error::Syntax),
}
};
// Step 1-2, 6-8.
// TODO(#12717): Should implement the `transfer` argument.
let data = StructuredCloneData::write(cx, message)?;
// Step 9.
self.post_message(origin, data);
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-window-captureevents
fn CaptureEvents(&self) {
// This method intentionally does nothing
}
// https://html.spec.whatwg.org/multipage/#dom-window-releaseevents
fn ReleaseEvents(&self) {
// This method intentionally does nothing
}
// check-tidy: no specs after this line
fn Debug(&self, message: DOMString) {
debug!("{}", message);
}
#[allow(unsafe_code)]
fn Gc(&self) {
unsafe {
JS_GC(JS_GetRuntime(self.get_cx()));
}
}
#[allow(unsafe_code)]
fn Trap(&self) {
#[cfg(feature = "unstable")]
unsafe { ::std::intrinsics::breakpoint() }
}
#[allow(unsafe_code)]
unsafe fn WebdriverCallback(&self, cx: *mut JSContext, val: HandleValue) {
let rv = jsval_to_webdriver(cx, val);
let opt_chan = self.webdriver_script_chan.borrow_mut().take();
if let Some(chan) = opt_chan {
chan.send(rv).unwrap();
}
}
fn WebdriverTimeout(&self) {
let opt_chan = self.webdriver_script_chan.borrow_mut().take();
if let Some(chan) = opt_chan {
chan.send(Err(WebDriverJSError::Timeout)).unwrap();
}
}
// https://drafts.csswg.org/cssom/#dom-window-getcomputedstyle
fn GetComputedStyle(&self,
element: &Element,
pseudo: Option<DOMString>) -> DomRoot<CSSStyleDeclaration> {
// Steps 1-4.
let pseudo = match pseudo.map(|mut s| { s.make_ascii_lowercase(); s }) {
Some(ref pseudo) if pseudo == ":before" || pseudo == "::before" =>
Some(PseudoElement::Before),
Some(ref pseudo) if pseudo == ":after" || pseudo == "::after" =>
Some(PseudoElement::After),
_ => None
};
// Step 5.
CSSStyleDeclaration::new(self,
CSSStyleOwner::Element(Dom::from_ref(element)),
pseudo,
CSSModificationAccess::Readonly)
}
// https://drafts.csswg.org/cssom-view/#dom-window-innerheight
//TODO Include Scrollbar
fn InnerHeight(&self) -> i32 {
self.window_size.get()
.and_then(|e| e.initial_viewport.height.to_i32())
.unwrap_or(0)
}
// https://drafts.csswg.org/cssom-view/#dom-window-innerwidth
//TODO Include Scrollbar
fn InnerWidth(&self) -> i32 {
self.window_size.get()
.and_then(|e| e.initial_viewport.width.to_i32())
.unwrap_or(0)
}
// https://drafts.csswg.org/cssom-view/#dom-window-scrollx
fn ScrollX(&self) -> i32 {
self.current_viewport.get().origin.x.to_px()
}
// https://drafts.csswg.org/cssom-view/#dom-window-pagexoffset
fn PageXOffset(&self) -> i32 {
self.ScrollX()
}
// https://drafts.csswg.org/cssom-view/#dom-window-scrolly
fn ScrollY(&self) -> i32 {
self.current_viewport.get().origin.y.to_px()
}
// https://drafts.csswg.org/cssom-view/#dom-window-pageyoffset
fn PageYOffset(&self) -> i32 {
self.ScrollY()
}
// https://drafts.csswg.org/cssom-view/#dom-window-scroll
fn Scroll(&self, options: &ScrollToOptions) {
// Step 1
let left = options.left.unwrap_or(0.0f64);
let top = options.top.unwrap_or(0.0f64);
self.scroll(left, top, options.parent.behavior);
}
// https://drafts.csswg.org/cssom-view/#dom-window-scroll
fn Scroll_(&self, x: f64, y: f64) {
self.scroll(x, y, ScrollBehavior::Auto);
}
// https://drafts.csswg.org/cssom-view/#dom-window-scrollto
fn ScrollTo(&self, options: &ScrollToOptions) {
self.Scroll(options);
}
// https://drafts.csswg.org/cssom-view/#dom-window-scrollto
fn ScrollTo_(&self, x: f64, y: f64) {
self.scroll(x, y, ScrollBehavior::Auto);
}
// https://drafts.csswg.org/cssom-view/#dom-window-scrollby
fn ScrollBy(&self, options: &ScrollToOptions) {
// Step 1
let x = options.left.unwrap_or(0.0f64);
let y = options.top.unwrap_or(0.0f64);
self.ScrollBy_(x, y);
self.scroll(x, y, options.parent.behavior);
}
// https://drafts.csswg.org/cssom-view/#dom-window-scrollby
fn ScrollBy_(&self, x: f64, y: f64) {
// Step 3
let left = x + self.ScrollX() as f64;
// Step 4
let top = y + self.ScrollY() as f64;
// Step 5
self.scroll(left, top, ScrollBehavior::Auto);
}
// https://drafts.csswg.org/cssom-view/#dom-window-resizeto
fn ResizeTo(&self, width: i32, height: i32) {
// Step 1
//TODO determine if this operation is allowed
let dpr = self.device_pixel_ratio();
let size = TypedSize2D::new(width, height).to_f32() * dpr;
self.send_to_constellation(ScriptMsg::ResizeTo(size.to_u32()));
}
// https://drafts.csswg.org/cssom-view/#dom-window-resizeby
fn ResizeBy(&self, x: i32, y: i32) {
let (size, _) = self.client_window();
// Step 1
self.ResizeTo(x + size.width.to_i32().unwrap_or(1), y + size.height.to_i32().unwrap_or(1))
}
// https://drafts.csswg.org/cssom-view/#dom-window-moveto
fn MoveTo(&self, x: i32, y: i32) {
// Step 1
//TODO determine if this operation is allowed
let dpr = self.device_pixel_ratio();
let point = TypedPoint2D::new(x, y).to_f32() * dpr;
self.send_to_constellation(ScriptMsg::MoveTo(point.to_i32()));
}
// https://drafts.csswg.org/cssom-view/#dom-window-moveby
fn MoveBy(&self, x: i32, y: i32) {
let (_, origin) = self.client_window();
// Step 1
self.MoveTo(x + origin.x, y + origin.y)
}
// https://drafts.csswg.org/cssom-view/#dom-window-screenx
fn ScreenX(&self) -> i32 {
let (_, origin) = self.client_window();
origin.x
}
// https://drafts.csswg.org/cssom-view/#dom-window-screeny
fn ScreenY(&self) -> i32 {
let (_, origin) = self.client_window();
origin.y
}
// https://drafts.csswg.org/cssom-view/#dom-window-outerheight
fn OuterHeight(&self) -> i32 {
let (size, _) = self.client_window();
size.height.to_i32().unwrap_or(1)
}
// https://drafts.csswg.org/cssom-view/#dom-window-outerwidth
fn OuterWidth(&self) -> i32 {
let (size, _) = self.client_window();
size.width.to_i32().unwrap_or(1)
}
// https://drafts.csswg.org/cssom-view/#dom-window-devicepixelratio
fn DevicePixelRatio(&self) -> Finite<f64> {
Finite::wrap(self.device_pixel_ratio().get() as f64)
}
// https://html.spec.whatwg.org/multipage/#dom-window-status
fn Status(&self) -> DOMString {
self.status.borrow().clone()
}
// https://html.spec.whatwg.org/multipage/#dom-window-status
fn SetStatus(&self, status: DOMString) {
*self.status.borrow_mut() = status
}
// https://drafts.csswg.org/cssom-view/#dom-window-matchmedia
fn MatchMedia(&self, query: DOMString) -> DomRoot<MediaQueryList> {
let mut input = ParserInput::new(&query);
let mut parser = Parser::new(&mut input);
let url = self.get_url();
let quirks_mode = self.Document().quirks_mode();
let context = CssParserContext::new_for_cssom(&url, Some(CssRuleType::Media),
ParsingMode::DEFAULT,
quirks_mode);
let media_query_list = media_queries::parse_media_query_list(&context, &mut parser,
self.css_error_reporter());
let document = self.Document();
let mql = MediaQueryList::new(&document, media_query_list);
self.media_query_lists.push(&*mql);
mql
}
#[allow(unrooted_must_root)]
// https://fetch.spec.whatwg.org/#fetch-method
fn Fetch(&self, input: RequestOrUSVString, init: RootedTraceableBox<RequestInit>) -> Rc<Promise> {
fetch::Fetch(&self.upcast(), input, init)
}
fn TestRunner(&self) -> DomRoot<TestRunner> {
self.test_runner.or_init(|| TestRunner::new(self.upcast()))
}
// https://html.spec.whatwg.org/multipage/#dom-name
fn SetName(&self, name: DOMString) {
self.window_proxy().set_name(name);
}
// https://html.spec.whatwg.org/multipage/#dom-name
fn Name(&self) -> DOMString {
self.window_proxy().get_name()
}
// https://html.spec.whatwg.org/multipage/#dom-origin
fn Origin(&self) -> USVString {
USVString(self.origin().immutable().ascii_serialization())
}
}
impl Window {
// https://drafts.css-houdini.org/css-paint-api-1/#paint-worklet
pub fn paint_worklet(&self) -> DomRoot<Worklet> {
self.paint_worklet.or_init(|| self.new_paint_worklet())
}
pub fn task_canceller(&self) -> TaskCanceller {
TaskCanceller {
cancelled: Some(self.ignore_further_async_events.borrow().clone()),
}
}
pub fn get_navigation_start(&self) -> u64 {
self.navigation_start_precise.get()
}
pub fn has_document(&self) -> bool {
self.document.get().is_some()
}
/// Cancels all the tasks associated with that window.
///
/// This sets the current `ignore_further_async_events` sentinel value to
/// `true` and replaces it with a brand new one for future tasks.
pub fn cancel_all_tasks(&self) {
let cancelled = mem::replace(&mut *self.ignore_further_async_events.borrow_mut(), Default::default());
cancelled.store(true, Ordering::Relaxed);
}
pub fn clear_js_runtime(&self) {
// We tear down the active document, which causes all the attached
// nodes to dispose of their layout data. This messages the layout
// thread, informing it that it can safely free the memory.
self.Document().upcast::<Node>().teardown();
// Clean up any active promises
// https://github.com/servo/servo/issues/15318
if let Some(custom_elements) = self.custom_element_registry.get() {
custom_elements.teardown();
}
// The above code may not catch all DOM objects (e.g. DOM
// objects removed from the tree that haven't been collected
// yet). There should not be any such DOM nodes with layout
// data, but if there are, then when they are dropped, they
// will attempt to send a message to the closed layout thread.
// This causes memory safety issues, because the DOM node uses
// the layout channel from its window, and the window has
// already been GC'd. For nodes which do not have a live
// pointer, we can avoid this by GCing now:
self.Gc();
// but there may still be nodes being kept alive by user
// script.
// TODO: ensure that this doesn't happen!
self.current_state.set(WindowState::Zombie);
*self.js_runtime.borrow_mut() = None;
self.window_proxy.set(None);
self.ignore_further_async_events.borrow().store(true, Ordering::SeqCst);
}
/// <https://drafts.csswg.org/cssom-view/#dom-window-scroll>
pub fn scroll(&self, x_: f64, y_: f64, behavior: ScrollBehavior) {
// Step 3
let xfinite = if x_.is_finite() { x_ } else { 0.0f64 };
let yfinite = if y_.is_finite() { y_ } else { 0.0f64 };
// Step 4
if self.window_size.get().is_none() {
return;
}
// Step 5
//TODO remove scrollbar width
let width = self.InnerWidth() as f64;
// Step 6
//TODO remove scrollbar height
let height = self.InnerHeight() as f64;
// Step 7 & 8
//TODO use overflow direction
let body = self.Document().GetBody();
let (x, y) = match body {
Some(e) => {
let content_size = e.upcast::<Node>().bounding_content_box_or_zero();
let content_height = content_size.size.height.to_f64_px();
let content_width = content_size.size.width.to_f64_px();
(xfinite.min(content_width - width).max(0.0f64),
yfinite.min(content_height - height).max(0.0f64))
},
None => {
(xfinite.max(0.0f64), yfinite.max(0.0f64))
}
};
// Step 10
//TODO handling ongoing smooth scrolling
if x == self.ScrollX() as f64 && y == self.ScrollY() as f64 {
return;
}
//TODO Step 11
//let document = self.Document();
// Step 12
let global_scope = self.upcast::<GlobalScope>();
let x = x.to_f32().unwrap_or(0.0f32);
let y = y.to_f32().unwrap_or(0.0f32);
self.update_viewport_for_scroll(x, y);
self.perform_a_scroll(x,
y,
global_scope.pipeline_id().root_scroll_id(),
behavior,
None);
}
/// <https://drafts.csswg.org/cssom-view/#perform-a-scroll>
pub fn perform_a_scroll(&self,
x: f32,
y: f32,
scroll_id: ExternalScrollId,
_behavior: ScrollBehavior,
_element: Option<&Element>) {
// TODO Step 1
// TODO(mrobinson, #18709): Add smooth scrolling support to WebRender so that we can
// properly process ScrollBehavior here.
self.layout_chan.send(Msg::UpdateScrollStateFromScript(ScrollState {
scroll_id,
scroll_offset: Vector2D::new(-x, -y),
})).unwrap();
}
pub fn update_viewport_for_scroll(&self, x: f32, y: f32) {
let size = self.current_viewport.get().size;
let new_viewport = Rect::new(Point2D::new(Au::from_f32_px(x), Au::from_f32_px(y)), size);
self.current_viewport.set(new_viewport)
}
pub fn device_pixel_ratio(&self) -> TypedScale<f32, CSSPixel, DevicePixel> {
self.window_size.get().map_or(TypedScale::new(1.0), |data| data.device_pixel_ratio)
}
fn client_window(&self) -> (TypedSize2D<u32, CSSPixel>, TypedPoint2D<i32, CSSPixel>) {
let timer_profile_chan = self.global().time_profiler_chan().clone();
let (send, recv) =
ProfiledIpc::channel::<(DeviceUintSize, DeviceIntPoint)>(timer_profile_chan).unwrap();
self.send_to_constellation(ScriptMsg::GetClientWindow(send));
let (size, point) = recv.recv().unwrap_or((TypedSize2D::zero(), TypedPoint2D::zero()));
let dpr = self.device_pixel_ratio();
((size.to_f32() / dpr).to_u32(), (point.to_f32() / dpr).to_i32())
}
/// Advances the layout animation clock by `delta` milliseconds, and then
/// forces a reflow if `tick` is true.
pub fn advance_animation_clock(&self, delta: i32, tick: bool) {
self.layout_chan.send(Msg::AdvanceClockMs(delta, tick)).unwrap();
}
/// Reflows the page unconditionally if possible and not suppressed. This
/// method will wait for the layout thread to complete (but see the `TODO`
/// below). If there is no window size yet, the page is presumed invisible
/// and no reflow is performed. If reflow is suppressed, no reflow will be
/// performed for ForDisplay goals.
///
/// TODO(pcwalton): Only wait for style recalc, since we have
/// off-main-thread layout.
///
/// Returns true if layout actually happened, false otherwise.
#[allow(unsafe_code)]
pub fn force_reflow(&self, reflow_goal: ReflowGoal, reason: ReflowReason) -> bool {
// Check if we need to unsuppress reflow. Note that this needs to be
// *before* any early bailouts, or reflow might never be unsuppresed!
match reason {
ReflowReason::FirstLoad |
ReflowReason::RefreshTick => self.suppress_reflow.set(false),
_ => (),
}
// If there is no window size, we have nothing to do.
let window_size = match self.window_size.get() {
Some(window_size) => window_size,
None => return false,
};
let for_display = reflow_goal == ReflowGoal::Full;
if for_display && self.suppress_reflow.get() {
debug!("Suppressing reflow pipeline {} for reason {:?} before FirstLoad or RefreshTick",
self.upcast::<GlobalScope>().pipeline_id(), reason);
return false;
}
debug!("script: performing reflow for reason {:?}", reason);
let marker = if self.need_emit_timeline_marker(TimelineMarkerType::Reflow) {
Some(TimelineMarker::start("Reflow".to_owned()))
} else {
None
};
// Layout will let us know when it's done.
let (join_chan, join_port) = channel();
// On debug mode, print the reflow event information.
if opts::get().relayout_event {
debug_reflow_events(self.upcast::<GlobalScope>().pipeline_id(), &reflow_goal, &reason);
}
let document = self.Document();
let stylesheets_changed = document.flush_stylesheets_for_reflow();
// Send new document and relevant styles to layout.
let needs_display = reflow_goal.needs_display();
let reflow = ScriptReflow {
reflow_info: Reflow {
page_clip_rect: self.page_clip_rect.get(),
},
document: self.Document().upcast::<Node>().to_trusted_node_address(),
stylesheets_changed,
window_size,
reflow_goal,
script_join_chan: join_chan,
dom_count: self.Document().dom_count(),
};
self.layout_chan.send(Msg::Reflow(reflow)).unwrap();
debug!("script: layout forked");
let complete = match join_port.try_recv() {
Err(Empty) => {
info!("script: waiting on layout");
join_port.recv().unwrap()
}
Ok(reflow_complete) => reflow_complete,
Err(Disconnected) => {
panic!("Layout thread failed while script was waiting for a result.");
}
};
debug!("script: layout joined");
// Pending reflows require display, so only reset the pending reflow count if this reflow
// was to be displayed.
if needs_display {
self.pending_reflow_count.set(0);
}
if let Some(marker) = marker {
self.emit_timeline_marker(marker.end());
}
for image in complete.pending_images {
let id = image.id;
let js_runtime = self.js_runtime.borrow();
let js_runtime = js_runtime.as_ref().unwrap();
let node = unsafe { from_untrusted_node_address(js_runtime.rt(), image.node) };
if let PendingImageState::Unrequested(ref url) = image.state {
fetch_image_for_layout(url.clone(), &*node, id, self.image_cache.clone());
}
let mut images = self.pending_layout_images.borrow_mut();
let nodes = images.entry(id).or_insert(vec![]);
if nodes.iter().find(|n| &***n as *const _ == &*node as *const _).is_none() {
let (responder, responder_listener) =
ProfiledIpc::channel(self.global().time_profiler_chan().clone()).unwrap();
let pipeline = self.upcast::<GlobalScope>().pipeline_id();
let image_cache_chan = self.image_cache_chan.clone();
ROUTER.add_route(responder_listener.to_opaque(), Box::new(move |message| {
let _ = image_cache_chan.send((pipeline, message.to().unwrap()));
}));
self.image_cache.add_listener(id, ImageResponder::new(responder, id));
nodes.push(Dom::from_ref(&*node));
}
}
unsafe {
ScriptThread::note_newly_transitioning_nodes(complete.newly_transitioning_nodes);
}
true
}
/// Reflows the page if it's possible to do so and the page is dirty. This
/// method will wait for the layout thread to complete (but see the `TODO`
/// below). If there is no window size yet, the page is presumed invisible
/// and no reflow is performed.
///
/// TODO(pcwalton): Only wait for style recalc, since we have
/// off-main-thread layout.
///
/// Returns true if layout actually happened, false otherwise.
/// This return value is useful for script queries, that wait for a lock
/// that layout might hold if the first layout hasn't happened yet (which
/// may happen in the only case a query reflow may bail out, that is, if the
/// viewport size is not present). See #11223 for an example of that.
pub fn reflow(&self, reflow_goal: ReflowGoal, reason: ReflowReason) -> bool {
let for_display = reflow_goal == ReflowGoal::Full;
let mut issued_reflow = false;
if !for_display || self.Document().needs_reflow() {
issued_reflow = self.force_reflow(reflow_goal, reason);
// If window_size is `None`, we don't reflow, so the document stays
// dirty. Otherwise, we shouldn't need a reflow immediately after a
// reflow, except if we're waiting for a deferred paint.
assert!(!self.Document().needs_reflow() ||
(!for_display && self.Document().needs_paint()) ||
self.window_size.get().is_none() ||
self.suppress_reflow.get());
} else {
debug!("Document doesn't need reflow - skipping it (reason {:?})", reason);
}
// If writing a screenshot, check if the script has reached a state
// where it's safe to write the image. This means that:
// 1) The reflow is for display (otherwise it could be a query)
// 2) The html element doesn't contain the 'reftest-wait' class
// 3) The load event has fired.
// When all these conditions are met, notify the constellation
// that this pipeline is ready to write the image (from the script thread
// perspective at least).
if (opts::get().output_file.is_some() ||
opts::get().exit_after_load ||
opts::get().webdriver_port.is_some()) && for_display {
let document = self.Document();
// Checks if the html element has reftest-wait attribute present.
// See http://testthewebforward.org/docs/reftests.html
let html_element = document.GetDocumentElement();
let reftest_wait = html_element.map_or(false, |elem| {
elem.has_class(&atom!("reftest-wait"), CaseSensitivity::CaseSensitive)
});
let ready_state = document.ReadyState();
let pending_images = self.pending_layout_images.borrow().is_empty();
if ready_state == DocumentReadyState::Complete && !reftest_wait && pending_images {
let event = ScriptMsg::SetDocumentState(DocumentState::Idle);
self.send_to_constellation(event);
}
}
issued_reflow
}
pub fn layout_reflow(&self, query_msg: QueryMsg) -> bool {
self.reflow(ReflowGoal::LayoutQuery(query_msg, time::precise_time_ns()), ReflowReason::Query)
}
pub fn layout(&self) -> &LayoutRPC {
&*self.layout_rpc
}
pub fn content_box_query(&self, content_box_request: TrustedNodeAddress) -> Option<Rect<Au>> {
if !self.layout_reflow(QueryMsg::ContentBoxQuery(content_box_request)) {
return None;
}
let ContentBoxResponse(rect) = self.layout_rpc.content_box();
rect
}
pub fn content_boxes_query(&self, content_boxes_request: TrustedNodeAddress) -> Vec<Rect<Au>> {
if !self.layout_reflow(QueryMsg::ContentBoxesQuery(content_boxes_request)) {
return vec![];
}
let ContentBoxesResponse(rects) = self.layout_rpc.content_boxes();
rects
}
pub fn client_rect_query(&self, node_geometry_request: TrustedNodeAddress) -> Rect<i32> {
if !self.layout_reflow(QueryMsg::NodeGeometryQuery(node_geometry_request)) {
return Rect::zero();
}
self.layout_rpc.node_geometry().client_rect
}
pub fn scroll_area_query(&self, node: TrustedNodeAddress) -> Rect<i32> {
if !self.layout_reflow(QueryMsg::NodeScrollGeometryQuery(node)) {
return Rect::zero();
}
self.layout_rpc.node_scroll_area().client_rect
}
pub fn scroll_offset_query(&self, node: &Node) -> Vector2D<f32> {
if let Some(scroll_offset) = self.scroll_offsets
.borrow()
.get(&node.to_untrusted_node_address()) {
return *scroll_offset
}
Vector2D::new(0.0, 0.0)
}
// https://drafts.csswg.org/cssom-view/#element-scrolling-members
pub fn scroll_node(
&self,
node: &Node,
x_: f64,
y_: f64,
behavior: ScrollBehavior
) {
if !self.layout_reflow(QueryMsg::NodeScrollIdQuery(node.to_trusted_node_address())) {
return;
}
// The scroll offsets are immediatly updated since later calls
// to topScroll and others may access the properties before
// webrender has a chance to update the offsets.
self.scroll_offsets.borrow_mut().insert(node.to_untrusted_node_address(),
Vector2D::new(x_ as f32, y_ as f32));
let NodeScrollIdResponse(scroll_id) = self.layout_rpc.node_scroll_id();
// Step 12
self.perform_a_scroll(x_.to_f32().unwrap_or(0.0f32),
y_.to_f32().unwrap_or(0.0f32),
scroll_id,
behavior,
None);
}
pub fn resolved_style_query(&self,
element: TrustedNodeAddress,
pseudo: Option<PseudoElement>,
property: PropertyId) -> DOMString {
if !self.layout_reflow(QueryMsg::ResolvedStyleQuery(element, pseudo, property)) {
return DOMString::new();
}
let ResolvedStyleResponse(resolved) = self.layout_rpc.resolved_style();
DOMString::from(resolved)
}
#[allow(unsafe_code)]
pub fn offset_parent_query(&self, node: TrustedNodeAddress) -> (Option<DomRoot<Element>>, Rect<Au>) {
if !self.layout_reflow(QueryMsg::OffsetParentQuery(node)) {
return (None, Rect::zero());
}
let response = self.layout_rpc.offset_parent();
let js_runtime = self.js_runtime.borrow();
let js_runtime = js_runtime.as_ref().unwrap();
let element = response.node_address.and_then(|parent_node_address| {
let node = unsafe { from_untrusted_node_address(js_runtime.rt(), parent_node_address) };
DomRoot::downcast(node)
});
(element, response.rect)
}
pub fn style_query(&self, node: TrustedNodeAddress) -> Option<servo_arc::Arc<ComputedValues>> {
if !self.layout_reflow(QueryMsg::StyleQuery(node)) {
return None
}
self.layout_rpc.style().0
}
pub fn text_index_query(
&self,
node: TrustedNodeAddress,
point_in_node: Point2D<f32>
) -> TextIndexResponse {
if !self.layout_reflow(QueryMsg::TextIndexQuery(node, point_in_node)) {
return TextIndexResponse(None);
}
self.layout_rpc.text_index()
}
#[allow(unsafe_code)]
pub fn init_window_proxy(&self, window_proxy: &WindowProxy) {
assert!(self.window_proxy.get().is_none());
self.window_proxy.set(Some(&window_proxy));
}
#[allow(unsafe_code)]
pub fn init_document(&self, document: &Document) {
assert!(self.document.get().is_none());
assert!(document.window() == self);
self.document.set(Some(&document));
if !opts::get().unminify_js {
return;
}
// Create a folder for the document host to store unminified scripts.
if let Some(&Host::Domain(ref host)) = document.url().origin().host() {
let mut path = env::current_dir().unwrap();
path.push("unminified-js");
path.push(host);
let _ = fs::remove_dir_all(&path);
match fs::create_dir_all(&path) {
Ok(_) => {
*self.unminified_js_dir.borrow_mut() = Some(path.into_os_string().into_string().unwrap());
debug!("Created folder for {:?} unminified scripts {:?}", host, self.unminified_js_dir.borrow());
},
Err(_) => warn!("Could not create unminified dir for {:?}", host),
}
}
}
/// Commence a new URL load which will either replace this window or scroll to a fragment.
pub fn load_url(&self, url: ServoUrl, replace: bool, force_reload: bool,
referrer_policy: Option<ReferrerPolicy>) {
let doc = self.Document();
let referrer_policy = referrer_policy.or(doc.get_referrer_policy());
// https://html.spec.whatwg.org/multipage/#navigating-across-documents
if !force_reload && url.as_url()[..Position::AfterQuery] ==
doc.url().as_url()[..Position::AfterQuery] {
// Step 5
if let Some(fragment) = url.fragment() {
doc.check_and_scroll_fragment(fragment);
doc.set_url(url.clone());
return
}
}
let pipeline_id = self.upcast::<GlobalScope>().pipeline_id();
self.main_thread_script_chan().send(
MainThreadScriptMsg::Navigate(pipeline_id,
LoadData::new(url, Some(pipeline_id), referrer_policy, Some(doc.url())), replace)).unwrap();
}
pub fn handle_fire_timer(&self, timer_id: TimerEventId) {
self.upcast::<GlobalScope>().fire_timer(timer_id);
self.reflow(ReflowGoal::Full, ReflowReason::Timer);
}
pub fn set_window_size(&self, size: WindowSizeData) {
self.window_size.set(Some(size));
}
pub fn window_size(&self) -> Option<WindowSizeData> {
self.window_size.get()
}
pub fn get_url(&self) -> ServoUrl {
self.Document().url()
}
pub fn layout_chan(&self) -> &Sender<Msg> {
&self.layout_chan
}
pub fn windowproxy_handler(&self) -> WindowProxyHandler {
WindowProxyHandler(self.dom_static.windowproxy_handler.0)
}
pub fn get_pending_reflow_count(&self) -> u32 {
self.pending_reflow_count.get()
}
pub fn add_pending_reflow(&self) {
self.pending_reflow_count.set(self.pending_reflow_count.get() + 1);
}
pub fn set_resize_event(&self, event: WindowSizeData, event_type: WindowSizeType) {
self.resize_event.set(Some((event, event_type)));
}
pub fn steal_resize_event(&self) -> Option<(WindowSizeData, WindowSizeType)> {
let event = self.resize_event.get();
self.resize_event.set(None);
event
}
pub fn set_page_clip_rect_with_new_viewport(&self, viewport: Rect<f32>) -> bool {
let rect = f32_rect_to_au_rect(viewport.clone());
self.current_viewport.set(rect);
// We use a clipping rectangle that is five times the size of the of the viewport,
// so that we don't collect display list items for areas too far outside the viewport,
// but also don't trigger reflows every time the viewport changes.
static VIEWPORT_EXPANSION: f32 = 2.0; // 2 lengths on each side plus original length is 5 total.
let proposed_clip_rect = f32_rect_to_au_rect(
viewport.inflate(viewport.size.width * VIEWPORT_EXPANSION,
viewport.size.height * VIEWPORT_EXPANSION));
let clip_rect = self.page_clip_rect.get();
if proposed_clip_rect == clip_rect {
return false;
}
let had_clip_rect = clip_rect != MaxRect::max_rect();
if had_clip_rect && !should_move_clip_rect(clip_rect, viewport) {
return false;
}
self.page_clip_rect.set(proposed_clip_rect);
// If we didn't have a clip rect, the previous display doesn't need rebuilding
// because it was built for infinite clip (MaxRect::amax_rect()).
had_clip_rect
}
// https://html.spec.whatwg.org/multipage/#accessing-other-browsing-contexts
pub fn IndexedGetter(&self, _index: u32, _found: &mut bool) -> Option<DomRoot<Window>> {
None
}
pub fn suspend(&self) {
// Suspend timer events.
self.upcast::<GlobalScope>().suspend();
// Set the window proxy to be a cross-origin window.
if self.window_proxy().currently_active() == Some(self.global().pipeline_id()) {
self.window_proxy().unset_currently_active();
}
// A hint to the JS runtime that now would be a good time to
// GC any unreachable objects generated by user script,
// or unattached DOM nodes. Attached DOM nodes can't be GCd yet,
// as the document might be reactivated later.
self.Gc();
}
pub fn resume(&self) {
// Resume timer events.
self.upcast::<GlobalScope>().resume();
// Set the window proxy to be this object.
self.window_proxy().set_currently_active(self);
// Push the document title to the compositor since we are
// activating this document due to a navigation.
self.Document().title_changed();
}
pub fn need_emit_timeline_marker(&self, timeline_type: TimelineMarkerType) -> bool {
let markers = self.devtools_markers.borrow();
markers.contains(&timeline_type)
}
pub fn emit_timeline_marker(&self, marker: TimelineMarker) {
let sender = self.devtools_marker_sender.borrow();
let sender = sender.as_ref().expect("There is no marker sender");
sender.send(Some(marker)).unwrap();
}
pub fn set_devtools_timeline_markers(&self,
markers: Vec<TimelineMarkerType>,
reply: IpcSender<Option<TimelineMarker>>) {
*self.devtools_marker_sender.borrow_mut() = Some(reply);
self.devtools_markers.borrow_mut().extend(markers.into_iter());
}
pub fn drop_devtools_timeline_markers(&self, markers: Vec<TimelineMarkerType>) {
let mut devtools_markers = self.devtools_markers.borrow_mut();
for marker in markers {
devtools_markers.remove(&marker);
}
if devtools_markers.is_empty() {
*self.devtools_marker_sender.borrow_mut() = None;
}
}
pub fn set_webdriver_script_chan(&self, chan: Option<IpcSender<WebDriverJSResult>>) {
*self.webdriver_script_chan.borrow_mut() = chan;
}
pub fn is_alive(&self) -> bool {
self.current_state.get() == WindowState::Alive
}
// https://html.spec.whatwg.org/multipage/#top-level-browsing-context
pub fn is_top_level(&self) -> bool {
self.parent_info.is_none()
}
pub fn evaluate_media_queries_and_report_changes(&self) {
self.media_query_lists.evaluate_and_report_changes();
}
/// Slow down/speed up timers based on visibility.
pub fn alter_resource_utilization(&self, visible: bool) {
if visible {
self.upcast::<GlobalScope>().speed_up_timers();
} else {
self.upcast::<GlobalScope>().slow_down_timers();
}
}
pub fn unminified_js_dir(&self) -> Option<String> {
self.unminified_js_dir.borrow().clone()
}
pub fn set_navigation_start(&self) {
let current_time = time::get_time();
let now = (current_time.sec * 1000 + current_time.nsec as i64 / 1000000) as u64;
self.navigation_start.set(now);
self.navigation_start_precise.set(time::precise_time_ns());
}
fn send_to_constellation(&self, msg: ScriptMsg) {
self.upcast::<GlobalScope>()
.script_to_constellation_chan()
.send(msg)
.unwrap();
}
pub fn webrender_document(&self) -> DocumentId {
self.webrender_document
}
}
impl Window {
#[allow(unsafe_code)]
pub fn new(
runtime: Rc<Runtime>,
script_chan: MainThreadScriptChan,
dom_manipulation_task_source: DOMManipulationTaskSource,
user_interaction_task_source: UserInteractionTaskSource,
networking_task_source: NetworkingTaskSource,
history_traversal_task_source: HistoryTraversalTaskSource,
file_reading_task_source: FileReadingTaskSource,
performance_timeline_task_source: PerformanceTimelineTaskSource,
image_cache_chan: Sender<ImageCacheMsg>,
image_cache: Arc<ImageCache>,
resource_threads: ResourceThreads,
bluetooth_thread: IpcSender<BluetoothRequest>,
mem_profiler_chan: MemProfilerChan,
time_profiler_chan: TimeProfilerChan,
devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
constellation_chan: ScriptToConstellationChan,
control_chan: IpcSender<ConstellationControlMsg>,
scheduler_chan: IpcSender<TimerSchedulerMsg>,
timer_event_chan: IpcSender<TimerEvent>,
layout_chan: Sender<Msg>,
pipelineid: PipelineId,
parent_info: Option<PipelineId>,
window_size: Option<WindowSizeData>,
origin: MutableOrigin,
navigation_start: u64,
navigation_start_precise: u64,
webgl_chan: Option<WebGLChan>,
webvr_chan: Option<IpcSender<WebVRMsg>>,
microtask_queue: Rc<MicrotaskQueue>,
webrender_document: DocumentId,
) -> DomRoot<Self> {
let layout_rpc: Box<LayoutRPC + Send> = {
let (rpc_send, rpc_recv) = channel();
layout_chan.send(Msg::GetRPC(rpc_send)).unwrap();
rpc_recv.recv().unwrap()
};
let error_reporter = CSSErrorReporter {
pipelineid,
script_chan: Arc::new(Mutex::new(control_chan)),
};
let win = Box::new(Self {
globalscope: GlobalScope::new_inherited(
pipelineid,
devtools_chan,
mem_profiler_chan,
time_profiler_chan,
constellation_chan,
scheduler_chan,
resource_threads,
timer_event_chan,
origin,
microtask_queue,
),
script_chan,
dom_manipulation_task_source,
user_interaction_task_source,
networking_task_source,
history_traversal_task_source,
file_reading_task_source,
performance_timeline_task_source,
image_cache_chan,
image_cache,
navigator: Default::default(),
location: Default::default(),
history: Default::default(),
custom_element_registry: Default::default(),
window_proxy: Default::default(),
document: Default::default(),
performance: Default::default(),
navigation_start: Cell::new(navigation_start),
navigation_start_precise: Cell::new(navigation_start_precise),
screen: Default::default(),
session_storage: Default::default(),
local_storage: Default::default(),
status: DomRefCell::new(DOMString::new()),
parent_info,
dom_static: GlobalStaticData::new(),
js_runtime: DomRefCell::new(Some(runtime.clone())),
bluetooth_thread,
bluetooth_extra_permission_data: BluetoothExtraPermissionData::new(),
page_clip_rect: Cell::new(MaxRect::max_rect()),
resize_event: Default::default(),
layout_chan,
layout_rpc,
window_size: Cell::new(window_size),
current_viewport: Cell::new(Rect::zero()),
suppress_reflow: Cell::new(true),
pending_reflow_count: Default::default(),
current_state: Cell::new(WindowState::Alive),
devtools_marker_sender: Default::default(),
devtools_markers: Default::default(),
webdriver_script_chan: Default::default(),
ignore_further_async_events: Default::default(),
error_reporter,
scroll_offsets: Default::default(),
media_query_lists: WeakMediaQueryListVec::new(),
test_runner: Default::default(),
webgl_chan,
webvr_chan,
permission_state_invocation_results: Default::default(),
pending_layout_images: Default::default(),
unminified_js_dir: Default::default(),
test_worklet: Default::default(),
paint_worklet: Default::default(),
webrender_document,
exists_mut_observer: Cell::new(false),
});
unsafe {
WindowBinding::Wrap(runtime.cx(), win)
}
}
pub fn pipeline_id(&self) -> Option<PipelineId> {
Some(self.upcast::<GlobalScope>().pipeline_id())
}
}
fn should_move_clip_rect(clip_rect: Rect<Au>, new_viewport: Rect<f32>) -> bool {
let clip_rect = Rect::new(Point2D::new(clip_rect.origin.x.to_f32_px(),
clip_rect.origin.y.to_f32_px()),
Size2D::new(clip_rect.size.width.to_f32_px(),
clip_rect.size.height.to_f32_px()));
// We only need to move the clip rect if the viewport is getting near the edge of
// our preexisting clip rect. We use half of the size of the viewport as a heuristic
// for "close."
static VIEWPORT_SCROLL_MARGIN_SIZE: f32 = 0.5;
let viewport_scroll_margin = new_viewport.size * VIEWPORT_SCROLL_MARGIN_SIZE;
(clip_rect.origin.x - new_viewport.origin.x).abs() <= viewport_scroll_margin.width ||
(clip_rect.max_x() - new_viewport.max_x()).abs() <= viewport_scroll_margin.width ||
(clip_rect.origin.y - new_viewport.origin.y).abs() <= viewport_scroll_margin.height ||
(clip_rect.max_y() - new_viewport.max_y()).abs() <= viewport_scroll_margin.height
}
fn debug_reflow_events(id: PipelineId, reflow_goal: &ReflowGoal, reason: &ReflowReason) {
let mut debug_msg = format!("**** pipeline={}", id);
debug_msg.push_str(match *reflow_goal {
ReflowGoal::Full => "\tFull",
ReflowGoal::TickAnimations => "\tTickAnimations",
ReflowGoal::LayoutQuery(ref query_msg, _) => match query_msg {
&QueryMsg::ContentBoxQuery(_n) => "\tContentBoxQuery",
&QueryMsg::ContentBoxesQuery(_n) => "\tContentBoxesQuery",
&QueryMsg::NodesFromPointQuery(..) => "\tNodesFromPointQuery",
&QueryMsg::NodeGeometryQuery(_n) => "\tNodeGeometryQuery",
&QueryMsg::NodeScrollGeometryQuery(_n) => "\tNodeScrollGeometryQuery",
&QueryMsg::NodeScrollIdQuery(_n) => "\tNodeScrollIdQuery",
&QueryMsg::ResolvedStyleQuery(_, _, _) => "\tResolvedStyleQuery",
&QueryMsg::OffsetParentQuery(_n) => "\tOffsetParentQuery",
&QueryMsg::StyleQuery(_n) => "\tStyleQuery",
&QueryMsg::TextIndexQuery(..) => "\tTextIndexQuery",
&QueryMsg::ElementInnerTextQuery(_) => "\tElementInnerTextQuery",
},
});
debug_msg.push_str(match *reason {
ReflowReason::CachedPageNeededReflow => "\tCachedPageNeededReflow",
ReflowReason::RefreshTick => "\tRefreshTick",
ReflowReason::FirstLoad => "\tFirstLoad",
ReflowReason::KeyEvent => "\tKeyEvent",
ReflowReason::MouseEvent => "\tMouseEvent",
ReflowReason::Query => "\tQuery",
ReflowReason::Timer => "\tTimer",
ReflowReason::Viewport => "\tViewport",
ReflowReason::WindowResize => "\tWindowResize",
ReflowReason::DOMContentLoaded => "\tDOMContentLoaded",
ReflowReason::DocumentLoaded => "\tDocumentLoaded",
ReflowReason::StylesheetLoaded => "\tStylesheetLoaded",
ReflowReason::ImageLoaded => "\tImageLoaded",
ReflowReason::RequestAnimationFrame => "\tRequestAnimationFrame",
ReflowReason::WebFontLoaded => "\tWebFontLoaded",
ReflowReason::WorkletLoaded => "\tWorkletLoaded",
ReflowReason::FramedContentChanged => "\tFramedContentChanged",
ReflowReason::IFrameLoadEvent => "\tIFrameLoadEvent",
ReflowReason::MissingExplicitReflow => "\tMissingExplicitReflow",
ReflowReason::ElementStateChanged => "\tElementStateChanged",
});
println!("{}", debug_msg);
}
impl Window {
// https://html.spec.whatwg.org/multipage/#dom-window-postmessage step 7.
pub fn post_message(
&self,
target_origin: Option<ImmutableOrigin>,
serialize_with_transfer_result: StructuredCloneData,
) {
let this = Trusted::new(self);
let task = task!(post_serialised_message: move || {
let this = this.root();
// Step 7.1.
if let Some(target_origin) = target_origin {
if !target_origin.same_origin(this.Document().origin()) {
return;
}
}
// Steps 7.2.-7.5.
let cx = this.get_cx();
let obj = this.reflector().get_jsobject();
let _ac = JSAutoCompartment::new(cx, obj.get());
rooted!(in(cx) let mut message_clone = UndefinedValue());
serialize_with_transfer_result.read(
this.upcast(),
message_clone.handle_mut(),
);
// Step 7.6.
// TODO: MessagePort array.
// Step 7.7.
// TODO(#12719): Set the other attributes.
MessageEvent::dispatch_jsval(
this.upcast(),
this.upcast(),
message_clone.handle(),
);
});
// FIXME(nox): Why are errors silenced here?
// TODO(#12718): Use the "posted message task source".
let _ = self.script_chan.send(CommonScriptMsg::Task(
ScriptThreadEventCategory::DomEvent,
Box::new(self.task_canceller().wrap_task(task)),
self.pipeline_id()
));
}
}<|fim▁end|> | use js::jsapi::{JSAutoCompartment, JSContext};
use js::jsapi::{JS_GC, JS_GetRuntime};
use js::jsval::UndefinedValue; |
<|file_name|>negative.js<|end_file_name|><|fim▁begin|>var Traverse = require('.');
var assert = require('assert');
exports['negative update test'] = function () {
var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ];
var fixed = Traverse.map(obj, function (x) {
if (x < 0) this.update(x + 128);
});<|fim▁hole|> );
assert.deepEqual(obj,
[ 5, 6, -3, [ 7, 8, -2, 1 ], { f: 10, g: -13 } ],
'Original references not modified'
);
}<|fim▁end|> |
assert.deepEqual(fixed,
[ 5, 6, 125, [ 7, 8, 126, 1 ], { f: 10, g: 115 } ],
'Negative values += 128' |
<|file_name|>database.py<|end_file_name|><|fim▁begin|>from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
<|fim▁hole|> bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()
def init_db():
import igsql.model
Base.metadata.create_all(bind=engine)<|fim▁end|> | engine = create_engine('postgresql://igsql:[email protected]/igsql')
db_session = scoped_session(sessionmaker(autocommit=False,
autoflush=False, |
<|file_name|>testing.py<|end_file_name|><|fim▁begin|>from plone.app.testing import PloneWithPackageLayer
from plone.app.testing import IntegrationTesting
from plone.app.testing import FunctionalTesting
import groupdocs.comparison
GROUPDOCS_COMPARISON = PloneWithPackageLayer(
zcml_package=groupdocs.comparison,
zcml_filename='testing.zcml',
gs_profile_id='groupdocs.comparison:testing',<|fim▁hole|>
GROUPDOCS_COMPARISON_INTEGRATION = IntegrationTesting(
bases=(GROUPDOCS_COMPARISON, ),
name="GROUPDOCS_COMPARISON_INTEGRATION")
GROUPDOCS_COMPARISON_FUNCTIONAL = FunctionalTesting(
bases=(GROUPDOCS_COMPARISON, ),
name="GROUPDOCS_COMPARISON_FUNCTIONAL")<|fim▁end|> | name="GROUPDOCS_COMPARISON") |
<|file_name|>mqiCBD.go<|end_file_name|><|fim▁begin|>package ibmmq
/*
Copyright (c) IBM Corporation 2018
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
Mark Taylor - Initial Contribution
*/
/*
#include <stdlib.h>
#include <string.h>
#include <cmqc.h>
*/
import "C"
/*
MQCBD is a structure containing the MQ Callback Descriptor
*/
type MQCBD struct {
CallbackType int32
Options int32
CallbackArea interface{}
CallbackFunction MQCB_FUNCTION
CallbackName string
MaxMsgLength int32
}
/*
NewMQCBD fills in default values for the MQCBD structure
*/
func NewMQCBD() *MQCBD {
cbd := new(MQCBD)
cbd.CallbackType = C.MQCBT_MESSAGE_CONSUMER
cbd.Options = C.MQCBDO_NONE
cbd.CallbackArea = nil
cbd.CallbackFunction = nil
cbd.CallbackName = ""
cbd.MaxMsgLength = C.MQCBD_FULL_MSG_LENGTH
return cbd
}<|fim▁hole|> mqcbd.Version = C.MQCBD_VERSION_1
mqcbd.CallbackType = C.MQLONG(gocbd.CallbackType)
mqcbd.Options = C.MQLONG(gocbd.Options) | C.MQCBDO_FAIL_IF_QUIESCING
// CallbackArea is always set to NULL here. The user's values are saved/restored elsewhere
mqcbd.CallbackArea = (C.MQPTR)(C.NULL)
setMQIString((*C.char)(&mqcbd.CallbackName[0]), gocbd.CallbackName, 128) // There's no MQI constant for the length
mqcbd.MaxMsgLength = C.MQLONG(gocbd.MaxMsgLength)
return
}
func copyCBDfromC(mqcbd *C.MQCBD, gocbd *MQCBD) {
// There are no modified output parameters
return
}<|fim▁end|> |
func copyCBDtoC(mqcbd *C.MQCBD, gocbd *MQCBD) {
setMQIString((*C.char)(&mqcbd.StrucId[0]), "CBD ", 4) |
<|file_name|>moveit_canceler.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python<|fim▁hole|>import roslib
roslib.load_manifest("denso_pendant_publisher")
roslib.load_manifest("actionlib_msgs")
import denso_pendant_publisher.msg
import std_msgs.msg
import actionlib_msgs.msg
rospy.init_node("moveit_canceler")
g_runnable = True
g_prev_status = None
def pendantCB(msg):
global g_runnable, g_prev_status
if g_prev_status:
if (not g_prev_status.button_cancel and msg.button_cancel) or (not g_prev_status.button_stop and msg.button_stop): # canceled or stopped
g_runnable = False
# here we should send cancel
cancel = actionlib_msgs.msg.GoalID()
cancel.id = ""
cancel_pub.publish(cancel)
rospy.loginfo("cancel")
g_prev_status = msg
sub = rospy.Subscriber("/denso_pendant_publisher/status", denso_pendant_publisher.msg.PendantStatus, pendantCB)
cancel_pub = rospy.Publisher("/arm_controller/follow_joint_trajectory/cancel", actionlib_msgs.msg.GoalID);
# cancel_pub = rospy.Publisher("/move_group/cancel", actionlib_msgs.msg.GoalID);
rospy.spin()<|fim▁end|> |
import rospy
import os |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# Copyright (C) 2015 Daniel Rodriguez
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from backtrader import Indicator
from backtrader.functions import *
# The modules below should/must define __all__ with the Indicator objects
# of prepend an "_" (underscore) to private classes/variables
from .basicops import *<|fim▁hole|>
# moving averages (so envelope and oscillators can be auto-generated)
from .sma import *
from .ema import *
from .smma import *
from .wma import *
from .dema import *
from .kama import *
from .zlema import *
# depends on moving averages
from .deviation import *
# depend on basicops, moving averages and deviations
from .atr import *
from .aroon import *
from .bollinger import *
from .cci import *
from .crossover import *
from .dpo import *
from .directionalmove import *
from .envelope import *
from .macd import *
from .momentum import *
from .oscillator import *
from .prettygoodoscillator import *
from .priceoscillator import *
from .rsi import *
from .stochastic import *
from .trix import *
from .williams import *<|fim▁end|> |
# base for moving averages
from .mabase import * |
<|file_name|>OracleLogBackup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# VM Backup extension
#
# Copyright 2014 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.<|fim▁hole|>#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import re
import sys
import subprocess
import threading
from workloadPatch.LogbackupPatch import LogBackupPatch
from time import sleep
from datetime import datetime
# Example of Parameter File Content:
# *.db_name='CDB1'
def parameterFileParser():
regX = re.compile(r"\*\..+=.+")
parameterFile = open(logbackup.parameterFilePath, 'r')
contents = parameterFile.read()
for match in regX.finditer(contents):
keyParameter = match.group().split('=')[0].lstrip('*\.')
valueParameter = [name.strip('\'') for name in match.group().split('=')[1].split(',')]
logbackup.oracleParameter[keyParameter] = valueParameter
def setLocation():
nowTimestamp = datetime.now()
nowTimestamp = nowTimestamp.strftime("%Y%m%d%H%M%S")
fullPath = logbackup.baseLocation + nowTimestamp
os.system('mkdir -m777 '+ fullPath)
return fullPath
def takeBackup():
print("logbackup: Taking a backup")
backupPath = setLocation()
if 'oracle' in logbackup.name.lower():
backupOracle = logbackup.command + " -s / as sysdba @" + "/var/lib/waagent/Microsoft.Azure.RecoveryServices.VMSnapshotLinux-1.0.9164.0/main/workloadPatch/scripts/logbackup.sql " + backupPath
argsForControlFile = ["su", "-", logbackup.cred_string, "-c", backupOracle]
snapshotControlFile = subprocess.Popen(argsForControlFile)
while snapshotControlFile.poll()==None:
sleep(1)
recoveryFileDest = logbackup.oracleParameter['db_recovery_file_dest']
dbName = logbackup.oracleParameter['db_name']
print(' logbackup: Archive log backup started at ', datetime.now().strftime("%Y%m%d%H%M%S"))
os.system('cp -R -f ' + recoveryFileDest[0] + '/' + dbName[0] + '/archivelog ' + backupPath)
print(' logbackup: Archive log backup complete at ', datetime.now().strftime("%Y%m%d%H%M%S"))
print("logbackup: Backup Complete")
def main():
global logbackup
logbackup = LogBackupPatch()
parameterFileParser()
takeBackup()
if __name__ == "__main__":
main()<|fim▁end|> | # You may obtain a copy of the License at |
<|file_name|>pydevconsole.py<|end_file_name|><|fim▁begin|>try:
from code import InteractiveConsole
except ImportError:
from pydevconsole_code_for_ironpython import InteractiveConsole
import os
import sys
try:
False
True
except NameError: # version < 2.3 -- didn't have the True/False builtins
import __builtin__
setattr(__builtin__, 'True', 1) # Python 3.0 does not accept __builtin__.True = 1 in its syntax
setattr(__builtin__, 'False', 0)
from pydev_console_utils import BaseStdIn, StdIn, BaseInterpreterInterface
try:
class ExecState:
FIRST_CALL = True
PYDEV_CONSOLE_RUN_IN_UI = False # Defines if we should run commands in the UI thread.
from org.python.pydev.core.uiutils import RunInUiThread # @UnresolvedImport
from java.lang import Runnable # @UnresolvedImport
class Command(Runnable):
def __init__(self, interpreter, line):
self.interpreter = interpreter
self.line = line
def run(self):
if ExecState.FIRST_CALL:
ExecState.FIRST_CALL = False
sys.stdout.write('\nYou are now in a console within Eclipse.\nUse it with care as it can halt the VM.\n')
sys.stdout.write('Typing a line with "PYDEV_CONSOLE_TOGGLE_RUN_IN_UI"\nwill start executing all the commands in the UI thread.\n\n')
if self.line == 'PYDEV_CONSOLE_TOGGLE_RUN_IN_UI':
ExecState.PYDEV_CONSOLE_RUN_IN_UI = not ExecState.PYDEV_CONSOLE_RUN_IN_UI
if ExecState.PYDEV_CONSOLE_RUN_IN_UI:
sys.stdout.write('Running commands in UI mode. WARNING: using sys.stdin (i.e.: calling raw_input()) WILL HALT ECLIPSE.\n')
else:
sys.stdout.write('No longer running commands in UI mode.\n')
self.more = False
else:
self.more = self.interpreter.push(self.line)
def Sync(runnable):
if ExecState.PYDEV_CONSOLE_RUN_IN_UI:
return RunInUiThread.sync(runnable)
else:
return runnable.run()
except:
# If things are not there, define a way in which there's no 'real' sync, only the default execution.
class Command:
def __init__(self, interpreter, line):
self.interpreter = interpreter
self.line = line
def run(self):
self.more = self.interpreter.push(self.line)
def Sync(runnable):
runnable.run()
try:
try:
execfile # Not in Py3k
except NameError:
from pydev_imports import execfile
import builtins # @UnresolvedImport -- only Py3K
builtins.execfile = execfile
except:
pass
# Pull in runfile, the interface to UMD that wraps execfile
from pydev_umd import runfile, _set_globals_function
try:
import builtins
builtins.runfile = runfile
except:
import __builtin__
__builtin__.runfile = runfile
#=======================================================================================================================
# InterpreterInterface
#=======================================================================================================================
class InterpreterInterface(BaseInterpreterInterface):
'''
The methods in this class should be registered in the xml-rpc server.
'''
def __init__(self, host, client_port, server):
BaseInterpreterInterface.__init__(self, server)
self.client_port = client_port
self.host = host
try:
import pydevd # @UnresolvedImport
if pydevd.GetGlobalDebugger() is None:
raise RuntimeError() # Work as if the debugger does not exist as it's not connected.
except:
self.namespace = globals()
else:
# Adapted from the code in pydevd
# patch provided by: Scott Schlesier - when script is run, it does not
# pretend pydevconsole is not the main module, and
# convince the file to be debugged that it was loaded as main
sys.modules['pydevconsole'] = sys.modules['__main__']
sys.modules['pydevconsole'].__name__ = 'pydevconsole'
from imp import new_module
m = new_module('__main__')
sys.modules['__main__'] = m
ns = m.__dict__
try:
ns['__builtins__'] = __builtins__
except NameError:
pass # Not there on Jython...
self.namespace = ns
self.interpreter = InteractiveConsole(self.namespace)
self._input_error_printed = False
def doAddExec(self, line):
command = Command(self.interpreter, line)
Sync(command)
return command.more
def getNamespace(self):
return self.namespace
def getCompletions(self, text, act_tok):
try:
from _pydev_completer import Completer
completer = Completer(self.namespace, None)
return completer.complete(act_tok)
except:
import traceback;traceback.print_exc()
return []
def close(self):
sys.exit(0)
try:
from pydev_ipython_console import InterpreterInterface
except:
sys.stderr.write('PyDev console: using default backend (IPython not available).\n')
pass # IPython not available, proceed as usual.
#=======================================================================================================================
# _DoExit
#=======================================================================================================================
def _DoExit(*args):
'''
We have to override the exit because calling sys.exit will only actually exit the main thread,
and as we're in a Xml-rpc server, that won't work.
'''
try:
import java.lang.System
java.lang.System.exit(1)
except ImportError:
if len(args) == 1:
os._exit(args[0])
else:
os._exit(0)
#=======================================================================================================================
# StartServer
#=======================================================================================================================
def StartServer(host, port, client_port):
# replace exit (see comments on method)
# note that this does not work in jython!!! (sys method can't be replaced).
sys.exit = _DoExit
from _pydev_xmlrpc_hook import InputHookedXMLRPCServer
try:
server = InputHookedXMLRPCServer((host, port), logRequests=False)
interpreter = InterpreterInterface(host, client_port, server)
except:
sys.stderr.write('Error starting server with host: %s, port: %s, client_port: %s\n' % (host, port, client_port))
raise
# Tell UMD the proper default namespace
_set_globals_function(interpreter.getNamespace)
# Functions for basic protocol
server.register_function(interpreter.addExec)
server.register_function(interpreter.getCompletions)
server.register_function(interpreter.getDescription)
server.register_function(interpreter.close)
# Functions so that the console can work as a debugger (i.e.: variables view, expressions...)<|fim▁hole|> # Functions for GUI main loop integration
server.register_function(interpreter.enableGui)
server.serve_forever()
#=======================================================================================================================
# main
#=======================================================================================================================
if __name__ == '__main__':
sys.stdin = BaseStdIn()
port, client_port = sys.argv[1:3]
import pydev_localhost
StartServer(pydev_localhost.get_localhost(), int(port), int(client_port))<|fim▁end|> | server.register_function(interpreter.connectToDebugger)
server.register_function(interpreter.hello)
|
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
"""Download GTFS file and generate JSON file.
Author: Panu Ranta, [email protected], https://14142.net/kartalla/about.html
"""
import argparse
import datetime
import hashlib
import json
import logging
import os
import resource
import shutil
import sys
import tempfile
import time
import zipfile
def _main():
parser = argparse.ArgumentParser()
parser.add_argument('config', help='JSON configuration file')
parser.add_argument('--only-download', action='store_true', help='Only download GTFS file')
parser.add_argument('--use-no-q-dirs', action='store_true', help='Do not use Q dirs')
args = parser.parse_args()
_init_logging()
start_time = time.time()
logging.debug('started {}'.format(sys.argv))
config = _load_config(args.config)<|fim▁hole|> gtfs_dir = _get_q_dir(config['gtfs_dir'], modify_date, not args.use_no_q_dirs)
gtfs_zip = _rename_gtfs_zip(gtfs_dir, downloaded_gtfs_zip, gtfs_name, modify_date)
if gtfs_zip and (not args.only_download):
log_dir = _get_q_dir(config['log_dir'], modify_date, not args.use_no_q_dirs)
_generate_json(gtfs_name, modify_date, gtfs_zip, config['json_dir'], log_dir)
logging.debug('took {} seconds, max mem: {} megabytes'.format(
int(time.time() - start_time), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024))
def _init_logging():
log_format = '%(asctime)s %(levelname)s %(filename)s:%(lineno)d %(funcName)s: %(message)s'
logging.basicConfig(filename='generate.log', format=log_format, level=logging.DEBUG)
def _progress(text):
print(text)
logging.debug(text)
def _progress_warning(text):
print('\033[31m{}\033[0m'.format(text))
logging.warning(text)
def _load_config(config_path):
with open(config_path) as config_file:
return json.load(config_file)
def _download_gtfs(url):
output_file, output_filename = tempfile.mkstemp(dir='.')
os.close(output_file)
curl_options = '--header "Accept-Encoding: gzip" --location'
command = 'curl {} "{}" > {}'.format(curl_options, url, output_filename)
_progress('downloading gtfs file into: {}'.format(os.path.relpath(output_filename)))
_execute_command(command)
return output_filename
def _execute_command(command):
if os.system(command) != 0:
raise SystemExit('failed to execute: {}'.format(command))
def _get_modify_date(zip_filename):
modify_times = _get_modify_times(zip_filename)
if len(modify_times) > 1:
_progress_warning('multiple modify times: {}'.format(modify_times))
return sorted(modify_times)[-1]
def _get_modify_times(zip_filename):
modify_times = set()
with zipfile.ZipFile(zip_filename) as zip_file:
for info in zip_file.infolist():
modify_times.add(datetime.datetime(*info.date_time).strftime('%Y%m%d'))
return modify_times
def _get_q_dir(base_dir, modify_date, create_q_dir):
if create_q_dir:
modify_month = int(modify_date[4:6])
q_dir = '{}_q{}'.format(modify_date[:4], 1 + ((modify_month - 1) // 3))
return os.path.join(base_dir, q_dir)
return base_dir
def _rename_gtfs_zip(gtfs_dir, old_filename, gtfs_name, modify_date):
_create_dir(gtfs_dir)
new_filename = os.path.join(gtfs_dir, '{}_{}.zip'.format(gtfs_name, modify_date))
if os.path.isfile(new_filename):
if _compare_files(old_filename, new_filename):
_progress('downloaded gtfs file is identical to: {}'.format(new_filename))
os.remove(old_filename)
return None
_rename_existing_file(new_filename)
os.rename(old_filename, new_filename)
_progress('renamed: {} -> {}'.format(old_filename, new_filename))
return new_filename
def _create_dir(new_dir):
if not os.path.isdir(new_dir):
os.makedirs(new_dir)
def _compare_files(filename_a, filename_b):
return _get_hash(filename_a) == _get_hash(filename_b)
def _get_hash(filename):
file_hash = hashlib.sha256()
with open(filename, 'rb') as input_file:
file_hash.update(input_file.read())
return file_hash.digest()
def _generate_json(gtfs_name, modify_date, gtfs_zip, json_dir, log_dir):
_create_dir(json_dir)
date_output_file = os.path.join(json_dir, '{}_{}.json'.format(gtfs_name, modify_date))
_rename_existing_file(date_output_file)
_create_dir(log_dir)
log_path = os.path.join(log_dir, 'gtfs2json_{}_{}_{}.log'.format(gtfs_name, modify_date,
_get_now_timestamp()))
_progress('generating json for {}'.format(gtfs_zip))
command = '{}/gtfs2json.py --log-file {} {} {}'.format(os.path.dirname(__file__), log_path,
gtfs_zip, date_output_file)
_execute_command(command)
_create_base_output_file(date_output_file, os.path.join(json_dir, '{}.json'.format(gtfs_name)))
def _create_base_output_file(date_output_file, base_output_file):
if os.path.isfile(base_output_file):
_progress('deleting {}'.format(base_output_file))
os.remove(base_output_file)
_progress('copying {} to {}'.format(date_output_file, base_output_file))
shutil.copyfile(date_output_file, base_output_file)
def _rename_existing_file(filename):
if os.path.isfile(filename):
suffix = filename.split('.')[-1]
new_filename = filename.replace('.{}'.format(suffix),
'_{}.{}'.format(_get_now_timestamp(), suffix))
os.rename(filename, new_filename)
_progress_warning('renamed existing {} file {} -> {}'.format(suffix, filename,
new_filename))
def _get_now_timestamp():
return datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
if __name__ == "__main__":
_main()<|fim▁end|> |
gtfs_name = config['name']
downloaded_gtfs_zip = _download_gtfs(config['url'])
modify_date = _get_modify_date(downloaded_gtfs_zip) |
<|file_name|>closure_promotion.rs<|end_file_name|><|fim▁begin|>// Copyright 2018 The Rust Project Developers. See the COPYRIGHT<|fim▁hole|>// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-compare-mode-nll
#![allow(const_err)]
// nll successfully compiles this.
fn main() {
let x: &'static _ = &|| { let z = 3; z }; //~ ERROR does not live long enough
}<|fim▁end|> | |
<|file_name|>juce_FileTreeComponent.cpp<|end_file_name|><|fim▁begin|>/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2020 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 6 End-User License
Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
End User License Agreement: www.juce.com/juce-6-licence
Privacy Policy: www.juce.com/juce-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
namespace juce
{
//==============================================================================
class FileListTreeItem : public TreeViewItem,
private TimeSliceClient,
private AsyncUpdater,
private ChangeListener
{
public:
FileListTreeItem (FileTreeComponent& treeComp,
DirectoryContentsList* parentContents,
int indexInContents,
const File& f,
TimeSliceThread& t)
: file (f),
owner (treeComp),
parentContentsList (parentContents),
indexInContentsList (indexInContents),
subContentsList (nullptr, false),
thread (t)
{
DirectoryContentsList::FileInfo fileInfo;
if (parentContents != nullptr
&& parentContents->getFileInfo (indexInContents, fileInfo))
{
fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
isDirectory = fileInfo.isDirectory;
}
else
{
isDirectory = true;
}
}
~FileListTreeItem() override
{
thread.removeTimeSliceClient (this);
clearSubItems();
removeSubContentsList();
}
//==============================================================================
bool mightContainSubItems() override { return isDirectory; }
String getUniqueName() const override { return file.getFullPathName(); }
int getItemHeight() const override { return owner.getItemHeight(); }
var getDragSourceDescription() override { return owner.getDragAndDropDescription(); }
void itemOpennessChanged (bool isNowOpen) override
{
if (isNowOpen)
{
clearSubItems();
isDirectory = file.isDirectory();
if (isDirectory)
{
if (subContentsList == nullptr)
{
jassert (parentContentsList != nullptr);
auto l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
l->setDirectory (file,
parentContentsList->isFindingDirectories(),
parentContentsList->isFindingFiles());
setSubContentsList (l, true);
}
changeListenerCallback (nullptr);
}
}
}
void removeSubContentsList()
{
if (subContentsList != nullptr)
{
subContentsList->removeChangeListener (this);
subContentsList.reset();
}
}
void setSubContentsList (DirectoryContentsList* newList, const bool canDeleteList)
{
removeSubContentsList();
subContentsList = OptionalScopedPointer<DirectoryContentsList> (newList, canDeleteList);
newList->addChangeListener (this);
}
bool selectFile (const File& target)
{
if (file == target)
{
setSelected (true, true);
return true;
}
<|fim▁hole|> {
setOpen (true);
for (int maxRetries = 500; --maxRetries > 0;)
{
for (int i = 0; i < getNumSubItems(); ++i)
if (auto* f = dynamic_cast<FileListTreeItem*> (getSubItem (i)))
if (f->selectFile (target))
return true;
// if we've just opened and the contents are still loading, wait for it..
if (subContentsList != nullptr && subContentsList->isStillLoading())
{
Thread::sleep (10);
rebuildItemsFromContentList();
}
else
{
break;
}
}
}
return false;
}
void changeListenerCallback (ChangeBroadcaster*) override
{
rebuildItemsFromContentList();
}
void rebuildItemsFromContentList()
{
clearSubItems();
if (isOpen() && subContentsList != nullptr)
{
for (int i = 0; i < subContentsList->getNumFiles(); ++i)
addSubItem (new FileListTreeItem (owner, subContentsList, i,
subContentsList->getFile(i), thread));
}
}
void paintItem (Graphics& g, int width, int height) override
{
ScopedLock lock (iconUpdate);
if (file != File())
{
updateIcon (true);
if (icon.isNull())
thread.addTimeSliceClient (this);
}
owner.getLookAndFeel().drawFileBrowserRow (g, width, height,
file, file.getFileName(),
&icon, fileSize, modTime,
isDirectory, isSelected(),
indexInContentsList, owner);
}
void itemClicked (const MouseEvent& e) override
{
owner.sendMouseClickMessage (file, e);
}
void itemDoubleClicked (const MouseEvent& e) override
{
TreeViewItem::itemDoubleClicked (e);
owner.sendDoubleClickMessage (file);
}
void itemSelectionChanged (bool) override
{
owner.sendSelectionChangeMessage();
}
int useTimeSlice() override
{
updateIcon (false);
return -1;
}
void handleAsyncUpdate() override
{
owner.repaint();
}
const File file;
private:
FileTreeComponent& owner;
DirectoryContentsList* parentContentsList;
int indexInContentsList;
OptionalScopedPointer<DirectoryContentsList> subContentsList;
bool isDirectory;
TimeSliceThread& thread;
CriticalSection iconUpdate;
Image icon;
String fileSize, modTime;
void updateIcon (const bool onlyUpdateIfCached)
{
if (icon.isNull())
{
auto hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
auto im = ImageCache::getFromHashCode (hashCode);
if (im.isNull() && ! onlyUpdateIfCached)
{
im = juce_createIconForFile (file);
if (im.isValid())
ImageCache::addImageToCache (im, hashCode);
}
if (im.isValid())
{
{
ScopedLock lock (iconUpdate);
icon = im;
}
triggerAsyncUpdate();
}
}
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FileListTreeItem)
};
//==============================================================================
FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
: DirectoryContentsDisplayComponent (listToShow),
itemHeight (22)
{
setRootItemVisible (false);
refresh();
}
FileTreeComponent::~FileTreeComponent()
{
deleteRootItem();
}
void FileTreeComponent::refresh()
{
deleteRootItem();
auto root = new FileListTreeItem (*this, nullptr, 0, directoryContentsList.getDirectory(),
directoryContentsList.getTimeSliceThread());
root->setSubContentsList (&directoryContentsList, false);
setRootItem (root);
}
//==============================================================================
File FileTreeComponent::getSelectedFile (const int index) const
{
if (auto* item = dynamic_cast<const FileListTreeItem*> (getSelectedItem (index)))
return item->file;
return {};
}
void FileTreeComponent::deselectAllFiles()
{
clearSelectedItems();
}
void FileTreeComponent::scrollToTop()
{
getViewport()->getVerticalScrollBar().setCurrentRangeStart (0);
}
void FileTreeComponent::setDragAndDropDescription (const String& description)
{
dragAndDropDescription = description;
}
void FileTreeComponent::setSelectedFile (const File& target)
{
if (auto* t = dynamic_cast<FileListTreeItem*> (getRootItem()))
if (! t->selectFile (target))
clearSelectedItems();
}
void FileTreeComponent::setItemHeight (int newHeight)
{
if (itemHeight != newHeight)
{
itemHeight = newHeight;
if (auto* root = getRootItem())
root->treeHasChanged();
}
}
} // namespace juce<|fim▁end|> |
if (target.isAChildOf (file))
|
<|file_name|>advertise.js<|end_file_name|><|fim▁begin|>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
'use strict';
var DebugLogtron = require('debug-logtron');
var fs = require('fs');
var crypto = require('crypto');
var HyperbahnClient = require('tchannel/hyperbahn/index.js');
module.exports = runTests;
if (require.main === module) {
runTests(require('../lib/hyperbahn-cluster.js'));
}
function runTests(HyperbahnCluster) {
HyperbahnCluster.test('can advertise', {
size: 5
}, function t(cluster, assert) {
var bob = cluster.remotes.bob;
var client = new HyperbahnClient({
serviceName: 'hello-bob',
callerName: 'hello-bob-test',
hostPortList: cluster.hostPortList,
tchannel: bob.channel,
logger: DebugLogtron('hyperbahnClient')
});
client.once('advertised', onResponse);
client.advertise();
function onResponse() {
var result = client.latestAdvertisementResult;
cluster.checkExitPeers(assert, {
serviceName: 'hello-bob',
hostPort: bob.channel.hostPort
});
assert.equal(result.head, null);<|fim▁hole|> 'expect to have at most 5 advertise results');
client.destroy();
assert.end();
}
});
HyperbahnCluster.test('can advertise using hostPortFile', {
size: 5
}, function t(cluster, assert) {
var bob = cluster.remotes.bob;
var hostPortFile;
do {
hostPortFile = '/tmp/host-' + crypto.randomBytes(4).readUInt32LE(0) + '.json';
} while (fs.existsSync(hostPortFile));
fs.writeFileSync(hostPortFile, JSON.stringify(cluster.hostPortList), 'utf8');
var client = new HyperbahnClient({
serviceName: 'hello-bob',
callerName: 'hello-bob-test',
hostPortFile: hostPortFile,
tchannel: bob.channel,
logger: DebugLogtron('hyperbahnClient')
});
assert.once('end', function cleanup() {
client.destroy();
if (fs.existsSync(hostPortFile)) {
fs.unlinkSync(hostPortFile);
}
});
client.once('advertised', onResponse);
client.advertise();
function onResponse() {
var result = client.latestAdvertisementResult;
cluster.checkExitPeers(assert, {
serviceName: 'hello-bob',
hostPort: bob.channel.hostPort
});
assert.equal(result.head, null);
// Because of duplicates in a size 5 cluster we know
// that we have at most 5 kValues
assert.ok(result.body.connectionCount <= 5,
'expect to have at most 5 advertise results');
assert.end();
}
});
}<|fim▁end|> |
// Because of duplicates in a size 5 cluster we know
// that we have at most 5 kValues
assert.ok(result.body.connectionCount <= 5, |
<|file_name|>index.js<|end_file_name|><|fim▁begin|>import PropTypes from 'prop-types'
import React from 'react'
import block from 'bem-cn-lite'
import { Field, reduxForm } from 'redux-form'
import { compose } from 'underscore'
import { connect } from 'react-redux'
import { renderTextInput } from '../text_input'
import { renderCheckboxInput } from '../checkbox_input'
import { signUp, updateAuthFormStateAndClearError } from '../../client/actions'
import { GDPRMessage } from 'desktop/components/react/gdpr/GDPRCheckbox'
function validate(values) {
const { accepted_terms_of_service, email, name, password } = values
const errors = {}
if (!name) errors.name = 'Required'
if (!email) errors.email = 'Required'
if (!password) errors.password = 'Required'
if (!accepted_terms_of_service)
errors.accepted_terms_of_service = 'Please agree to our terms to continue'
return errors
}
function SignUp(props) {
const {
error,
handleSubmit,
isLoading,
signUpAction,
updateAuthFormStateAndClearErrorAction,
} = props
const b = block('consignments-submission-sign-up')
return (
<div className={b()}>
<div className={b('title')}>Create an Account</div>
<div className={b('subtitle')}>
Already have an account?{' '}
<span
className={b('clickable')}
onClick={() => updateAuthFormStateAndClearErrorAction('logIn')}
>
Log in
</span>.
</div>
<form className={b('form')} onSubmit={handleSubmit(signUpAction)}>
<div className={b('row')}>
<div className={b('row-item')}>
<Field
name="name"
component={renderTextInput}
item={'name'}
label={'Full Name'}
autofocus
/>
</div>
</div>
<div className={b('row')}><|fim▁hole|> <Field
name="email"
component={renderTextInput}
item={'email'}
label={'Email'}
type={'email'}
/>
</div>
</div>
<div className={b('row')}>
<div className={b('row-item')}>
<Field
name="password"
component={renderTextInput}
item={'password'}
label={'Password'}
type={'password'}
/>
</div>
</div>
<div className={b('row')}>
<div className={b('row-item')}>
<Field
name="accepted_terms_of_service"
component={renderCheckboxInput}
item={'accepted_terms_of_service'}
label={<GDPRMessage />}
value={false}
/>
</div>
</div>
<button
className={b
.builder()('sign-up-button')
.mix('avant-garde-button-black')()}
type="submit"
>
{isLoading ? <div className="loading-spinner-white" /> : 'Submit'}
</button>
{error && <div className={b('error')}>{error}</div>}
</form>
</div>
)
}
const mapStateToProps = state => {
return {
error: state.submissionFlow.error,
isLoading: state.submissionFlow.isLoading,
}
}
const mapDispatchToProps = {
signUpAction: signUp,
updateAuthFormStateAndClearErrorAction: updateAuthFormStateAndClearError,
}
SignUp.propTypes = {
error: PropTypes.string,
handleSubmit: PropTypes.func.isRequired,
isLoading: PropTypes.bool.isRequired,
signUpAction: PropTypes.func.isRequired,
updateAuthFormStateAndClearErrorAction: PropTypes.func.isRequired,
}
export default compose(
reduxForm({
form: 'signUp', // a unique identifier for this form
validate,
}),
connect(mapStateToProps, mapDispatchToProps)
)(SignUp)<|fim▁end|> | <div className={b('row-item')}> |
<|file_name|>router.rs<|end_file_name|><|fim▁begin|>// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use crate::fsm::{Fsm, FsmScheduler, FsmState};
use crate::mailbox::{BasicMailbox, Mailbox};
use crate::metrics::CHANNEL_FULL_COUNTER_VEC;
use collections::HashMap;
use crossbeam::channel::{SendError, TrySendError};
use std::cell::Cell;
use std::mem;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use tikv_util::lru::LruCache;
use tikv_util::Either;
use tikv_util::{debug, info};
/// A struct that traces the approximate memory usage of router.
#[derive(Default)]
pub struct RouterTrace {
pub alive: usize,
pub leak: usize,
}
struct NormalMailMap<N: Fsm> {
map: HashMap<u64, BasicMailbox<N>>,
// Count of Mailboxes that is stored in `map`.
alive_cnt: Arc<AtomicUsize>,
}
enum CheckDoResult<T> {
NotExist,
Invalid,
Valid(T),
}
/// Router route messages to its target mailbox.
///
/// Every fsm has a mailbox, hence it's necessary to have an address book
/// that can deliver messages to specified fsm, which is exact router.
///
/// In our abstract model, every batch system has two different kind of
/// fsms. First is normal fsm, which does the common work like peers in a
/// raftstore model or apply delegate in apply model. Second is control fsm,
/// which does some work that requires a global view of resources or creates
/// missing fsm for specified address. Normal fsm and control fsm can have
/// different scheduler, but this is not required.
pub struct Router<N: Fsm, C: Fsm, Ns, Cs> {
normals: Arc<Mutex<NormalMailMap<N>>>,
caches: Cell<LruCache<u64, BasicMailbox<N>>>,
pub(super) control_box: BasicMailbox<C>,
// TODO: These two schedulers should be unified as single one. However
// it's not possible to write FsmScheduler<Fsm=C> + FsmScheduler<Fsm=N>
// for now.
pub(crate) normal_scheduler: Ns,
control_scheduler: Cs,
// Count of Mailboxes that is not destroyed.
// Added when a Mailbox created, and subtracted it when a Mailbox destroyed.
state_cnt: Arc<AtomicUsize>,
// Indicates the router is shutdown down or not.
shutdown: Arc<AtomicBool>,
}
impl<N, C, Ns, Cs> Router<N, C, Ns, Cs>
where
N: Fsm,
C: Fsm,
Ns: FsmScheduler<Fsm = N> + Clone,
Cs: FsmScheduler<Fsm = C> + Clone,
{
pub(super) fn new(
control_box: BasicMailbox<C>,
normal_scheduler: Ns,
control_scheduler: Cs,
state_cnt: Arc<AtomicUsize>,
) -> Router<N, C, Ns, Cs> {
Router {
normals: Arc::new(Mutex::new(NormalMailMap {
map: HashMap::default(),
alive_cnt: Arc::default(),
})),
caches: Cell::new(LruCache::with_capacity_and_sample(1024, 7)),
control_box,
normal_scheduler,
control_scheduler,
state_cnt,
shutdown: Arc::new(AtomicBool::new(false)),
}
}
/// The `Router` has been already shutdown or not.
pub fn is_shutdown(&self) -> bool {
self.shutdown.load(Ordering::SeqCst)
}
/// A helper function that tries to unify a common access pattern to
/// mailbox.
///
/// Generally, when sending a message to a mailbox, cache should be
/// check first, if not found, lock should be acquired.
///
/// Returns None means there is no mailbox inside the normal registry.
/// Some(None) means there is expected mailbox inside the normal registry
/// but it returns None after apply the given function. Some(Some) means
/// the given function returns Some and cache is updated if it's invalid.
#[inline]
fn check_do<F, R>(&self, addr: u64, mut f: F) -> CheckDoResult<R>
where
F: FnMut(&BasicMailbox<N>) -> Option<R>,
{
let caches = unsafe { &mut *self.caches.as_ptr() };
let mut connected = true;
if let Some(mailbox) = caches.get(&addr) {
match f(mailbox) {
Some(r) => return CheckDoResult::Valid(r),
None => {<|fim▁hole|>
let (cnt, mailbox) = {
let mut boxes = self.normals.lock().unwrap();
let cnt = boxes.map.len();
let b = match boxes.map.get_mut(&addr) {
Some(mailbox) => mailbox.clone(),
None => {
drop(boxes);
if !connected {
caches.remove(&addr);
}
return CheckDoResult::NotExist;
}
};
(cnt, b)
};
if cnt > caches.capacity() || cnt < caches.capacity() / 2 {
caches.resize(cnt);
}
let res = f(&mailbox);
match res {
Some(r) => {
caches.insert(addr, mailbox);
CheckDoResult::Valid(r)
}
None => {
if !connected {
caches.remove(&addr);
}
CheckDoResult::Invalid
}
}
}
/// Register a mailbox with given address.
pub fn register(&self, addr: u64, mailbox: BasicMailbox<N>) {
let mut normals = self.normals.lock().unwrap();
if let Some(mailbox) = normals.map.insert(addr, mailbox) {
mailbox.close();
}
normals
.alive_cnt
.store(normals.map.len(), Ordering::Relaxed);
}
pub fn register_all(&self, mailboxes: Vec<(u64, BasicMailbox<N>)>) {
let mut normals = self.normals.lock().unwrap();
normals.map.reserve(mailboxes.len());
for (addr, mailbox) in mailboxes {
if let Some(m) = normals.map.insert(addr, mailbox) {
m.close();
}
}
normals
.alive_cnt
.store(normals.map.len(), Ordering::Relaxed);
}
/// Get the mailbox of specified address.
pub fn mailbox(&self, addr: u64) -> Option<Mailbox<N, Ns>> {
let res = self.check_do(addr, |mailbox| {
if mailbox.is_connected() {
Some(Mailbox::new(mailbox.clone(), self.normal_scheduler.clone()))
} else {
None
}
});
match res {
CheckDoResult::Valid(r) => Some(r),
_ => None,
}
}
/// Get the mailbox of control fsm.
pub fn control_mailbox(&self) -> Mailbox<C, Cs> {
Mailbox::new(self.control_box.clone(), self.control_scheduler.clone())
}
/// Try to send a message to specified address.
///
/// If Either::Left is returned, then the message is sent. Otherwise,
/// it indicates mailbox is not found.
#[inline]
pub fn try_send(
&self,
addr: u64,
msg: N::Message,
) -> Either<Result<(), TrySendError<N::Message>>, N::Message> {
let mut msg = Some(msg);
let res = self.check_do(addr, |mailbox| {
let m = msg.take().unwrap();
match mailbox.try_send(m, &self.normal_scheduler) {
Ok(()) => Some(Ok(())),
r @ Err(TrySendError::Full(_)) => {
CHANNEL_FULL_COUNTER_VEC
.with_label_values(&["normal"])
.inc();
Some(r)
}
Err(TrySendError::Disconnected(m)) => {
msg = Some(m);
None
}
}
});
match res {
CheckDoResult::Valid(r) => Either::Left(r),
CheckDoResult::Invalid => Either::Left(Err(TrySendError::Disconnected(msg.unwrap()))),
CheckDoResult::NotExist => Either::Right(msg.unwrap()),
}
}
/// Send the message to specified address.
#[inline]
pub fn send(&self, addr: u64, msg: N::Message) -> Result<(), TrySendError<N::Message>> {
match self.try_send(addr, msg) {
Either::Left(res) => res,
Either::Right(m) => Err(TrySendError::Disconnected(m)),
}
}
/// Force sending message to specified address despite the capacity
/// limit of mailbox.
#[inline]
pub fn force_send(&self, addr: u64, msg: N::Message) -> Result<(), SendError<N::Message>> {
match self.send(addr, msg) {
Ok(()) => Ok(()),
Err(TrySendError::Full(m)) => {
let caches = unsafe { &mut *self.caches.as_ptr() };
caches
.get(&addr)
.unwrap()
.force_send(m, &self.normal_scheduler)
}
Err(TrySendError::Disconnected(m)) => {
if self.is_shutdown() {
Ok(())
} else {
Err(SendError(m))
}
}
}
}
/// Force sending message to control fsm.
#[inline]
pub fn send_control(&self, msg: C::Message) -> Result<(), TrySendError<C::Message>> {
match self.control_box.try_send(msg, &self.control_scheduler) {
Ok(()) => Ok(()),
r @ Err(TrySendError::Full(_)) => {
CHANNEL_FULL_COUNTER_VEC
.with_label_values(&["control"])
.inc();
r
}
r => r,
}
}
/// Try to notify all normal fsm a message.
pub fn broadcast_normal(&self, mut msg_gen: impl FnMut() -> N::Message) {
let mailboxes = self.normals.lock().unwrap();
for mailbox in mailboxes.map.values() {
let _ = mailbox.force_send(msg_gen(), &self.normal_scheduler);
}
}
/// Try to notify all fsm that the cluster is being shutdown.
pub fn broadcast_shutdown(&self) {
info!("broadcasting shutdown");
self.shutdown.store(true, Ordering::SeqCst);
unsafe { &mut *self.caches.as_ptr() }.clear();
let mut mailboxes = self.normals.lock().unwrap();
for (addr, mailbox) in mailboxes.map.drain() {
debug!("[region {}] shutdown mailbox", addr);
mailbox.close();
}
self.control_box.close();
self.normal_scheduler.shutdown();
self.control_scheduler.shutdown();
}
/// Close the mailbox of address.
pub fn close(&self, addr: u64) {
info!("[region {}] shutdown mailbox", addr);
unsafe { &mut *self.caches.as_ptr() }.remove(&addr);
let mut mailboxes = self.normals.lock().unwrap();
if let Some(mb) = mailboxes.map.remove(&addr) {
mb.close();
}
mailboxes
.alive_cnt
.store(mailboxes.map.len(), Ordering::Relaxed);
}
pub fn clear_cache(&self) {
unsafe { &mut *self.caches.as_ptr() }.clear();
}
pub fn state_cnt(&self) -> &Arc<AtomicUsize> {
&self.state_cnt
}
pub fn alive_cnt(&self) -> Arc<AtomicUsize> {
self.normals.lock().unwrap().alive_cnt.clone()
}
pub fn trace(&self) -> RouterTrace {
let alive = self.normals.lock().unwrap().alive_cnt.clone();
let total = self.state_cnt.load(Ordering::Relaxed);
let alive = alive.load(Ordering::Relaxed);
// 1 represents the control fsm.
let leak = if total > alive + 1 {
total - alive - 1
} else {
0
};
let mailbox_unit = mem::size_of::<(u64, BasicMailbox<N>)>();
let state_unit = mem::size_of::<FsmState<N>>();
// Every message in crossbeam sender needs 8 bytes to store state.
let message_unit = mem::size_of::<N::Message>() + 8;
// crossbeam unbounded channel sender has a list of blocks. Every block has 31 unit
// and every sender has at least one sender.
let sender_block_unit = 31;
RouterTrace {
alive: (mailbox_unit * 8 / 7 // hashmap uses 7/8 of allocated memory.
+ state_unit + message_unit * sender_block_unit)
* alive,
leak: (state_unit + message_unit * sender_block_unit) * leak,
}
}
}
impl<N: Fsm, C: Fsm, Ns: Clone, Cs: Clone> Clone for Router<N, C, Ns, Cs> {
fn clone(&self) -> Router<N, C, Ns, Cs> {
Router {
normals: self.normals.clone(),
caches: Cell::new(LruCache::with_capacity_and_sample(1024, 7)),
control_box: self.control_box.clone(),
// These two schedulers should be unified as single one. However
// it's not possible to write FsmScheduler<Fsm=C> + FsmScheduler<Fsm=N>
// for now.
normal_scheduler: self.normal_scheduler.clone(),
control_scheduler: self.control_scheduler.clone(),
shutdown: self.shutdown.clone(),
state_cnt: self.state_cnt.clone(),
}
}
}<|fim▁end|> | connected = false;
}
}
} |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|>__contact__ = "[email protected]"
__homepage__ = "http://packages.python.org/flatty"
__docformat__ = "restructuredtext"
from flatty import *
try:
import mongo
except ImportError:
pass
try:
import couch
except ImportError:
pass<|fim▁end|> | """flatty - marshaller/unmarshaller for light-schema python objects"""
VERSION = (0, 1, 2)
__version__ = ".".join(map(str, VERSION))
__author__ = "Christian Haintz" |
<|file_name|>tornadoviews.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import
from django.utils.translation import ugettext as _
from django.http import HttpRequest, HttpResponse
from six import text_type
from zerver.models import get_client, UserProfile, Client
from zerver.decorator import asynchronous, \
authenticated_json_post_view, internal_notify_view, RespondAsynchronously, \
has_request_variables, REQ, _RespondAsynchronously
from zerver.lib.response import json_success, json_error
from zerver.lib.validator import check_bool, check_list, check_string
from zerver.lib.event_queue import get_client_descriptor, \
process_notification, fetch_events
from django.core.handlers.base import BaseHandler
from typing import Union, Optional, Iterable, Sequence, List
import time<|fim▁hole|>@internal_notify_view
def notify(request):
# type: (HttpRequest) -> HttpResponse
process_notification(ujson.loads(request.POST['data']))
return json_success()
@has_request_variables
def cleanup_event_queue(request, user_profile, queue_id=REQ()):
# type: (HttpRequest, UserProfile, text_type) -> HttpResponse
client = get_client_descriptor(str(queue_id))
if client is None:
return json_error(_("Bad event queue id: %s") % (queue_id,))
if user_profile.id != client.user_profile_id:
return json_error(_("You are not authorized to access this queue"))
request._log_data['extra'] = "[%s]" % (queue_id,)
client.cleanup()
return json_success()
@authenticated_json_post_view
def json_get_events(request, user_profile):
# type: (HttpRequest, UserProfile) -> Union[HttpResponse, _RespondAsynchronously]
return get_events_backend(request, user_profile, apply_markdown=True)
@asynchronous
@has_request_variables
def get_events_backend(request, user_profile, handler,
user_client = REQ(converter=get_client, default=None),
last_event_id = REQ(converter=int, default=None),
queue_id = REQ(default=None),
apply_markdown = REQ(default=False, validator=check_bool),
all_public_streams = REQ(default=False, validator=check_bool),
event_types = REQ(default=None, validator=check_list(check_string)),
dont_block = REQ(default=False, validator=check_bool),
narrow = REQ(default=[], validator=check_list(None)),
lifespan_secs = REQ(default=0, converter=int)):
# type: (HttpRequest, UserProfile, BaseHandler, Optional[Client], Optional[int], Optional[List[text_type]], bool, bool, Optional[text_type], bool, Iterable[Sequence[text_type]], int) -> Union[HttpResponse, _RespondAsynchronously]
if user_client is None:
user_client = request.client
events_query = dict(
user_profile_id = user_profile.id,
user_profile_email = user_profile.email,
queue_id = queue_id,
last_event_id = last_event_id,
event_types = event_types,
client_type_name = user_client.name,
all_public_streams = all_public_streams,
lifespan_secs = lifespan_secs,
narrow = narrow,
dont_block = dont_block,
handler_id = handler.handler_id)
if queue_id is None:
events_query['new_queue_data'] = dict(
user_profile_id = user_profile.id,
realm_id = user_profile.realm.id,
user_profile_email = user_profile.email,
event_types = event_types,
client_type_name = user_client.name,
apply_markdown = apply_markdown,
all_public_streams = all_public_streams,
queue_timeout = lifespan_secs,
last_connection_time = time.time(),
narrow = narrow)
result = fetch_events(events_query)
if "extra_log_data" in result:
request._log_data['extra'] = result["extra_log_data"]
if result["type"] == "async":
handler._request = request
return RespondAsynchronously
if result["type"] == "error":
return json_error(result["message"])
return json_success(result["response"])<|fim▁end|> | import ujson
|
<|file_name|>AccuracyMeasure.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import csv, sys
mapping = {}
totalTruth, totalTesting, hit, miss, errors = (0, 0, 0, 0, 0)
with open(sys.argv[1], 'rb') as groundtruth:
reader = csv.reader(groundtruth)
for row in reader:
totalTruth += 1
mapping[(row[1], row[2])] = row[0]
<|fim▁hole|>with open(sys.argv[2], 'rb') as testing:
reader = csv.reader(testing)
for row in reader:
totalTesting += 1
try:
if (mapping[(row[1], row[2])] == row[0]):
hit += 1
else:
miss += 1
except KeyError:
errors += 1
print "Total size: ", totalTruth, " and testing size: ", totalTesting
print "Correct assignments: ", hit, " and failed assigments: ", miss
print "Errors: ", errors
print "Accuracy: ", float(hit) / float(totalTruth)<|fim▁end|> | |
<|file_name|>classification.py<|end_file_name|><|fim▁begin|>#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import operator
from pyspark import since, keyword_only
from pyspark.ml import Estimator, Model
from pyspark.ml.param.shared import *
from pyspark.ml.regression import DecisionTreeModel, DecisionTreeRegressionModel, \
RandomForestParams, TreeEnsembleModel, TreeEnsembleParams
from pyspark.ml.util import *
from pyspark.ml.wrapper import JavaEstimator, JavaModel, JavaParams
from pyspark.ml.wrapper import JavaWrapper
from pyspark.ml.common import inherit_doc
from pyspark.sql import DataFrame
from pyspark.sql.functions import udf, when
from pyspark.sql.types import ArrayType, DoubleType
from pyspark.storagelevel import StorageLevel
__all__ = ['LinearSVC', 'LinearSVCModel',
'LogisticRegression', 'LogisticRegressionModel',
'LogisticRegressionSummary', 'LogisticRegressionTrainingSummary',
'BinaryLogisticRegressionSummary', 'BinaryLogisticRegressionTrainingSummary',
'DecisionTreeClassifier', 'DecisionTreeClassificationModel',
'GBTClassifier', 'GBTClassificationModel',
'RandomForestClassifier', 'RandomForestClassificationModel',
'NaiveBayes', 'NaiveBayesModel',
'MultilayerPerceptronClassifier', 'MultilayerPerceptronClassificationModel',
'OneVsRest', 'OneVsRestModel']
@inherit_doc
class JavaClassificationModel(JavaPredictionModel):
"""
(Private) Java Model produced by a ``Classifier``.
Classes are indexed {0, 1, ..., numClasses - 1}.
To be mixed in with class:`pyspark.ml.JavaModel`
"""
@property
@since("2.1.0")
def numClasses(self):
"""
Number of classes (values which the label can take).
"""
return self._call_java("numClasses")
@inherit_doc
class LinearSVC(JavaEstimator, HasFeaturesCol, HasLabelCol, HasPredictionCol, HasMaxIter,
HasRegParam, HasTol, HasRawPredictionCol, HasFitIntercept, HasStandardization,
HasWeightCol, HasAggregationDepth, JavaMLWritable, JavaMLReadable):
"""
.. note:: Experimental
`Linear SVM Classifier <https://en.wikipedia.org/wiki/Support_vector_machine#Linear_SVM>`_
This binary classifier optimizes the Hinge Loss using the OWLQN optimizer.
Only supports L2 regularization currently.
>>> from pyspark.sql import Row
>>> from pyspark.ml.linalg import Vectors
>>> df = sc.parallelize([
... Row(label=1.0, features=Vectors.dense(1.0, 1.0, 1.0)),
... Row(label=0.0, features=Vectors.dense(1.0, 2.0, 3.0))]).toDF()
>>> svm = LinearSVC(maxIter=5, regParam=0.01)
>>> model = svm.fit(df)
>>> model.coefficients
DenseVector([0.0, -0.2792, -0.1833])
>>> model.intercept
1.0206118982229047
>>> model.numClasses
2
>>> model.numFeatures
3
>>> test0 = sc.parallelize([Row(features=Vectors.dense(-1.0, -1.0, -1.0))]).toDF()
>>> result = model.transform(test0).head()
>>> result.prediction
1.0
>>> result.rawPrediction
DenseVector([-1.4831, 1.4831])
>>> svm_path = temp_path + "/svm"
>>> svm.save(svm_path)
>>> svm2 = LinearSVC.load(svm_path)
>>> svm2.getMaxIter()
5
>>> model_path = temp_path + "/svm_model"
>>> model.save(model_path)
>>> model2 = LinearSVCModel.load(model_path)
>>> model.coefficients[0] == model2.coefficients[0]
True
>>> model.intercept == model2.intercept
True
.. versionadded:: 2.2.0
"""
threshold = Param(Params._dummy(), "threshold",
"The threshold in binary classification applied to the linear model"
" prediction. This threshold can be any real number, where Inf will make"
" all predictions 0.0 and -Inf will make all predictions 1.0.",
typeConverter=TypeConverters.toFloat)
@keyword_only
def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction",
maxIter=100, regParam=0.0, tol=1e-6, rawPredictionCol="rawPrediction",
fitIntercept=True, standardization=True, threshold=0.0, weightCol=None,
aggregationDepth=2):
"""
__init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
maxIter=100, regParam=0.0, tol=1e-6, rawPredictionCol="rawPrediction", \
fitIntercept=True, standardization=True, threshold=0.0, weightCol=None, \
aggregationDepth=2):
"""
super(LinearSVC, self).__init__()
self._java_obj = self._new_java_obj(
"org.apache.spark.ml.classification.LinearSVC", self.uid)
self._setDefault(maxIter=100, regParam=0.0, tol=1e-6, fitIntercept=True,
standardization=True, threshold=0.0, aggregationDepth=2)
kwargs = self._input_kwargs
self.setParams(**kwargs)
@keyword_only
@since("2.2.0")
def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction",
maxIter=100, regParam=0.0, tol=1e-6, rawPredictionCol="rawPrediction",
fitIntercept=True, standardization=True, threshold=0.0, weightCol=None,
aggregationDepth=2):
"""
setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
maxIter=100, regParam=0.0, tol=1e-6, rawPredictionCol="rawPrediction", \
fitIntercept=True, standardization=True, threshold=0.0, weightCol=None, \
aggregationDepth=2):
Sets params for Linear SVM Classifier.
"""
kwargs = self._input_kwargs
return self._set(**kwargs)
def _create_model(self, java_model):
return LinearSVCModel(java_model)
def setThreshold(self, value):
"""
Sets the value of :py:attr:`threshold`.
"""
return self._set(threshold=value)
def getThreshold(self):
"""
Gets the value of threshold or its default value.
"""
return self.getOrDefault(self.threshold)
class LinearSVCModel(JavaModel, JavaClassificationModel, JavaMLWritable, JavaMLReadable):
"""
.. note:: Experimental
Model fitted by LinearSVC.
.. versionadded:: 2.2.0
"""
@property
@since("2.2.0")
def coefficients(self):
"""
Model coefficients of Linear SVM Classifier.
"""
return self._call_java("coefficients")
@property
@since("2.2.0")
def intercept(self):
"""
Model intercept of Linear SVM Classifier.
"""
return self._call_java("intercept")
@inherit_doc
class LogisticRegression(JavaEstimator, HasFeaturesCol, HasLabelCol, HasPredictionCol, HasMaxIter,
HasRegParam, HasTol, HasProbabilityCol, HasRawPredictionCol,
HasElasticNetParam, HasFitIntercept, HasStandardization, HasThresholds,
HasWeightCol, HasAggregationDepth, JavaMLWritable, JavaMLReadable):
"""
Logistic regression.
This class supports multinomial logistic (softmax) and binomial logistic regression.
>>> from pyspark.sql import Row
>>> from pyspark.ml.linalg import Vectors
>>> bdf = sc.parallelize([
... Row(label=1.0, weight=1.0, features=Vectors.dense(0.0, 5.0)),
... Row(label=0.0, weight=2.0, features=Vectors.dense(1.0, 2.0)),
... Row(label=1.0, weight=3.0, features=Vectors.dense(2.0, 1.0)),
... Row(label=0.0, weight=4.0, features=Vectors.dense(3.0, 3.0))]).toDF()
>>> blor = LogisticRegression(regParam=0.01, weightCol="weight")
>>> blorModel = blor.fit(bdf)
>>> blorModel.coefficients
DenseVector([-1.080..., -0.646...])
>>> blorModel.intercept
3.112...
>>> data_path = "data/mllib/sample_multiclass_classification_data.txt"
>>> mdf = spark.read.format("libsvm").load(data_path)
>>> mlor = LogisticRegression(regParam=0.1, elasticNetParam=1.0, family="multinomial")
>>> mlorModel = mlor.fit(mdf)
>>> mlorModel.coefficientMatrix
SparseMatrix(3, 4, [0, 1, 2, 3], [3, 2, 1], [1.87..., -2.75..., -0.50...], 1)
>>> mlorModel.interceptVector
DenseVector([0.04..., -0.42..., 0.37...])
>>> test0 = sc.parallelize([Row(features=Vectors.dense(-1.0, 1.0))]).toDF()
>>> result = blorModel.transform(test0).head()
>>> result.prediction
1.0
>>> result.probability
DenseVector([0.02..., 0.97...])
>>> result.rawPrediction
DenseVector([-3.54..., 3.54...])
>>> test1 = sc.parallelize([Row(features=Vectors.sparse(2, [0], [1.0]))]).toDF()
>>> blorModel.transform(test1).head().prediction
1.0
>>> blor.setParams("vector")
Traceback (most recent call last):
...
TypeError: Method setParams forces keyword arguments.
>>> lr_path = temp_path + "/lr"
>>> blor.save(lr_path)
>>> lr2 = LogisticRegression.load(lr_path)
>>> lr2.getRegParam()
0.01
>>> model_path = temp_path + "/lr_model"
>>> blorModel.save(model_path)
>>> model2 = LogisticRegressionModel.load(model_path)
>>> blorModel.coefficients[0] == model2.coefficients[0]
True
>>> blorModel.intercept == model2.intercept
True
.. versionadded:: 1.3.0
"""
threshold = Param(Params._dummy(), "threshold",
"Threshold in binary classification prediction, in range [0, 1]." +
" If threshold and thresholds are both set, they must match." +
"e.g. if threshold is p, then thresholds must be equal to [1-p, p].",
typeConverter=TypeConverters.toFloat)
family = Param(Params._dummy(), "family",
"The name of family which is a description of the label distribution to " +
"be used in the model. Supported options: auto, binomial, multinomial",
typeConverter=TypeConverters.toString)
@keyword_only
def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction",
maxIter=100, regParam=0.0, elasticNetParam=0.0, tol=1e-6, fitIntercept=True,
threshold=0.5, thresholds=None, probabilityCol="probability",
rawPredictionCol="rawPrediction", standardization=True, weightCol=None,
aggregationDepth=2, family="auto"):
"""
__init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
maxIter=100, regParam=0.0, elasticNetParam=0.0, tol=1e-6, fitIntercept=True, \
threshold=0.5, thresholds=None, probabilityCol="probability", \
rawPredictionCol="rawPrediction", standardization=True, weightCol=None, \
aggregationDepth=2, family="auto")
If the threshold and thresholds Params are both set, they must be equivalent.
"""
super(LogisticRegression, self).__init__()
self._java_obj = self._new_java_obj(
"org.apache.spark.ml.classification.LogisticRegression", self.uid)
self._setDefault(maxIter=100, regParam=0.0, tol=1E-6, threshold=0.5, family="auto")
kwargs = self._input_kwargs
self.setParams(**kwargs)
self._checkThresholdConsistency()
@keyword_only
@since("1.3.0")
def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction",
maxIter=100, regParam=0.0, elasticNetParam=0.0, tol=1e-6, fitIntercept=True,
threshold=0.5, thresholds=None, probabilityCol="probability",
rawPredictionCol="rawPrediction", standardization=True, weightCol=None,
aggregationDepth=2, family="auto"):
"""
setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
maxIter=100, regParam=0.0, elasticNetParam=0.0, tol=1e-6, fitIntercept=True, \
threshold=0.5, thresholds=None, probabilityCol="probability", \
rawPredictionCol="rawPrediction", standardization=True, weightCol=None, \
aggregationDepth=2, family="auto")
Sets params for logistic regression.
If the threshold and thresholds Params are both set, they must be equivalent.
"""
kwargs = self._input_kwargs
self._set(**kwargs)
self._checkThresholdConsistency()
return self
def _create_model(self, java_model):
return LogisticRegressionModel(java_model)
@since("1.4.0")
def setThreshold(self, value):
"""
Sets the value of :py:attr:`threshold`.
Clears value of :py:attr:`thresholds` if it has been set.
"""
self._set(threshold=value)
self._clear(self.thresholds)
return self
@since("1.4.0")
def getThreshold(self):
"""
Get threshold for binary classification.
If :py:attr:`thresholds` is set with length 2 (i.e., binary classification),
this returns the equivalent threshold:
:math:`\\frac{1}{1 + \\frac{thresholds(0)}{thresholds(1)}}`.
Otherwise, returns :py:attr:`threshold` if set or its default value if unset.
"""
self._checkThresholdConsistency()
if self.isSet(self.thresholds):
ts = self.getOrDefault(self.thresholds)
if len(ts) != 2:
raise ValueError("Logistic Regression getThreshold only applies to" +
" binary classification, but thresholds has length != 2." +
" thresholds: " + ",".join(ts))
return 1.0/(1.0 + ts[0]/ts[1])
else:
return self.getOrDefault(self.threshold)
@since("1.5.0")
def setThresholds(self, value):
"""
Sets the value of :py:attr:`thresholds`.
Clears value of :py:attr:`threshold` if it has been set.
"""
self._set(thresholds=value)
self._clear(self.threshold)
return self
@since("1.5.0")
def getThresholds(self):
"""
If :py:attr:`thresholds` is set, return its value.
Otherwise, if :py:attr:`threshold` is set, return the equivalent thresholds for binary
classification: (1-threshold, threshold).
If neither are set, throw an error.
"""
self._checkThresholdConsistency()
if not self.isSet(self.thresholds) and self.isSet(self.threshold):
t = self.getOrDefault(self.threshold)
return [1.0-t, t]
else:
return self.getOrDefault(self.thresholds)
def _checkThresholdConsistency(self):
if self.isSet(self.threshold) and self.isSet(self.thresholds):
ts = self.getOrDefault(self.thresholds)
if len(ts) != 2:
raise ValueError("Logistic Regression getThreshold only applies to" +
" binary classification, but thresholds has length != 2." +
" thresholds: {0}".format(str(ts)))
t = 1.0/(1.0 + ts[0]/ts[1])
t2 = self.getOrDefault(self.threshold)
if abs(t2 - t) >= 1E-5:
raise ValueError("Logistic Regression getThreshold found inconsistent values for" +
" threshold (%g) and thresholds (equivalent to %g)" % (t2, t))
@since("2.1.0")
def setFamily(self, value):
"""
Sets the value of :py:attr:`family`.<|fim▁hole|> """
return self._set(family=value)
@since("2.1.0")
def getFamily(self):
"""
Gets the value of :py:attr:`family` or its default value.
"""
return self.getOrDefault(self.family)
class LogisticRegressionModel(JavaModel, JavaClassificationModel, JavaMLWritable, JavaMLReadable):
"""
Model fitted by LogisticRegression.
.. versionadded:: 1.3.0
"""
@property
@since("2.0.0")
def coefficients(self):
"""
Model coefficients of binomial logistic regression.
An exception is thrown in the case of multinomial logistic regression.
"""
return self._call_java("coefficients")
@property
@since("1.4.0")
def intercept(self):
"""
Model intercept of binomial logistic regression.
An exception is thrown in the case of multinomial logistic regression.
"""
return self._call_java("intercept")
@property
@since("2.1.0")
def coefficientMatrix(self):
"""
Model coefficients.
"""
return self._call_java("coefficientMatrix")
@property
@since("2.1.0")
def interceptVector(self):
"""
Model intercept.
"""
return self._call_java("interceptVector")
@property
@since("2.0.0")
def summary(self):
"""
Gets summary (e.g. accuracy/precision/recall, objective history, total iterations) of model
trained on the training set. An exception is thrown if `trainingSummary is None`.
"""
if self.hasSummary:
java_blrt_summary = self._call_java("summary")
# Note: Once multiclass is added, update this to return correct summary
return BinaryLogisticRegressionTrainingSummary(java_blrt_summary)
else:
raise RuntimeError("No training summary available for this %s" %
self.__class__.__name__)
@property
@since("2.0.0")
def hasSummary(self):
"""
Indicates whether a training summary exists for this model
instance.
"""
return self._call_java("hasSummary")
@since("2.0.0")
def evaluate(self, dataset):
"""
Evaluates the model on a test dataset.
:param dataset:
Test dataset to evaluate model on, where dataset is an
instance of :py:class:`pyspark.sql.DataFrame`
"""
if not isinstance(dataset, DataFrame):
raise ValueError("dataset must be a DataFrame but got %s." % type(dataset))
java_blr_summary = self._call_java("evaluate", dataset)
return BinaryLogisticRegressionSummary(java_blr_summary)
class LogisticRegressionSummary(JavaWrapper):
"""
.. note:: Experimental
Abstraction for Logistic Regression Results for a given model.
.. versionadded:: 2.0.0
"""
@property
@since("2.0.0")
def predictions(self):
"""
Dataframe outputted by the model's `transform` method.
"""
return self._call_java("predictions")
@property
@since("2.0.0")
def probabilityCol(self):
"""
Field in "predictions" which gives the probability
of each class as a vector.
"""
return self._call_java("probabilityCol")
@property
@since("2.0.0")
def labelCol(self):
"""
Field in "predictions" which gives the true label of each
instance.
"""
return self._call_java("labelCol")
@property
@since("2.0.0")
def featuresCol(self):
"""
Field in "predictions" which gives the features of each instance
as a vector.
"""
return self._call_java("featuresCol")
@inherit_doc
class LogisticRegressionTrainingSummary(LogisticRegressionSummary):
"""
.. note:: Experimental
Abstraction for multinomial Logistic Regression Training results.
Currently, the training summary ignores the training weights except
for the objective trace.
.. versionadded:: 2.0.0
"""
@property
@since("2.0.0")
def objectiveHistory(self):
"""
Objective function (scaled loss + regularization) at each
iteration.
"""
return self._call_java("objectiveHistory")
@property
@since("2.0.0")
def totalIterations(self):
"""
Number of training iterations until termination.
"""
return self._call_java("totalIterations")
@inherit_doc
class BinaryLogisticRegressionSummary(LogisticRegressionSummary):
"""
.. note:: Experimental
Binary Logistic regression results for a given model.
.. versionadded:: 2.0.0
"""
@property
@since("2.0.0")
def roc(self):
"""
Returns the receiver operating characteristic (ROC) curve,
which is a Dataframe having two fields (FPR, TPR) with
(0.0, 0.0) prepended and (1.0, 1.0) appended to it.
.. seealso:: `Wikipedia reference \
<http://en.wikipedia.org/wiki/Receiver_operating_characteristic>`_
.. note:: This ignores instance weights (setting all to 1.0) from
`LogisticRegression.weightCol`. This will change in later Spark
versions.
"""
return self._call_java("roc")
@property
@since("2.0.0")
def areaUnderROC(self):
"""
Computes the area under the receiver operating characteristic
(ROC) curve.
.. note:: This ignores instance weights (setting all to 1.0) from
`LogisticRegression.weightCol`. This will change in later Spark
versions.
"""
return self._call_java("areaUnderROC")
@property
@since("2.0.0")
def pr(self):
"""
Returns the precision-recall curve, which is a Dataframe
containing two fields recall, precision with (0.0, 1.0) prepended
to it.
.. note:: This ignores instance weights (setting all to 1.0) from
`LogisticRegression.weightCol`. This will change in later Spark
versions.
"""
return self._call_java("pr")
@property
@since("2.0.0")
def fMeasureByThreshold(self):
"""
Returns a dataframe with two fields (threshold, F-Measure) curve
with beta = 1.0.
.. note:: This ignores instance weights (setting all to 1.0) from
`LogisticRegression.weightCol`. This will change in later Spark
versions.
"""
return self._call_java("fMeasureByThreshold")
@property
@since("2.0.0")
def precisionByThreshold(self):
"""
Returns a dataframe with two fields (threshold, precision) curve.
Every possible probability obtained in transforming the dataset
are used as thresholds used in calculating the precision.
.. note:: This ignores instance weights (setting all to 1.0) from
`LogisticRegression.weightCol`. This will change in later Spark
versions.
"""
return self._call_java("precisionByThreshold")
@property
@since("2.0.0")
def recallByThreshold(self):
"""
Returns a dataframe with two fields (threshold, recall) curve.
Every possible probability obtained in transforming the dataset
are used as thresholds used in calculating the recall.
.. note:: This ignores instance weights (setting all to 1.0) from
`LogisticRegression.weightCol`. This will change in later Spark
versions.
"""
return self._call_java("recallByThreshold")
@inherit_doc
class BinaryLogisticRegressionTrainingSummary(BinaryLogisticRegressionSummary,
LogisticRegressionTrainingSummary):
"""
.. note:: Experimental
Binary Logistic regression training results for a given model.
.. versionadded:: 2.0.0
"""
pass
class TreeClassifierParams(object):
"""
Private class to track supported impurity measures.
.. versionadded:: 1.4.0
"""
supportedImpurities = ["entropy", "gini"]
impurity = Param(Params._dummy(), "impurity",
"Criterion used for information gain calculation (case-insensitive). " +
"Supported options: " +
", ".join(supportedImpurities), typeConverter=TypeConverters.toString)
def __init__(self):
super(TreeClassifierParams, self).__init__()
@since("1.6.0")
def setImpurity(self, value):
"""
Sets the value of :py:attr:`impurity`.
"""
return self._set(impurity=value)
@since("1.6.0")
def getImpurity(self):
"""
Gets the value of impurity or its default value.
"""
return self.getOrDefault(self.impurity)
class GBTParams(TreeEnsembleParams):
"""
Private class to track supported GBT params.
.. versionadded:: 1.4.0
"""
supportedLossTypes = ["logistic"]
@inherit_doc
class DecisionTreeClassifier(JavaEstimator, HasFeaturesCol, HasLabelCol, HasPredictionCol,
HasProbabilityCol, HasRawPredictionCol, DecisionTreeParams,
TreeClassifierParams, HasCheckpointInterval, HasSeed, JavaMLWritable,
JavaMLReadable):
"""
`Decision tree <http://en.wikipedia.org/wiki/Decision_tree_learning>`_
learning algorithm for classification.
It supports both binary and multiclass labels, as well as both continuous and categorical
features.
>>> from pyspark.ml.linalg import Vectors
>>> from pyspark.ml.feature import StringIndexer
>>> df = spark.createDataFrame([
... (1.0, Vectors.dense(1.0)),
... (0.0, Vectors.sparse(1, [], []))], ["label", "features"])
>>> stringIndexer = StringIndexer(inputCol="label", outputCol="indexed")
>>> si_model = stringIndexer.fit(df)
>>> td = si_model.transform(df)
>>> dt = DecisionTreeClassifier(maxDepth=2, labelCol="indexed")
>>> model = dt.fit(td)
>>> model.numNodes
3
>>> model.depth
1
>>> model.featureImportances
SparseVector(1, {0: 1.0})
>>> model.numFeatures
1
>>> model.numClasses
2
>>> print(model.toDebugString)
DecisionTreeClassificationModel (uid=...) of depth 1 with 3 nodes...
>>> test0 = spark.createDataFrame([(Vectors.dense(-1.0),)], ["features"])
>>> result = model.transform(test0).head()
>>> result.prediction
0.0
>>> result.probability
DenseVector([1.0, 0.0])
>>> result.rawPrediction
DenseVector([1.0, 0.0])
>>> test1 = spark.createDataFrame([(Vectors.sparse(1, [0], [1.0]),)], ["features"])
>>> model.transform(test1).head().prediction
1.0
>>> dtc_path = temp_path + "/dtc"
>>> dt.save(dtc_path)
>>> dt2 = DecisionTreeClassifier.load(dtc_path)
>>> dt2.getMaxDepth()
2
>>> model_path = temp_path + "/dtc_model"
>>> model.save(model_path)
>>> model2 = DecisionTreeClassificationModel.load(model_path)
>>> model.featureImportances == model2.featureImportances
True
.. versionadded:: 1.4.0
"""
@keyword_only
def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction",
probabilityCol="probability", rawPredictionCol="rawPrediction",
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, impurity="gini",
seed=None):
"""
__init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
probabilityCol="probability", rawPredictionCol="rawPrediction", \
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, \
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, impurity="gini", \
seed=None)
"""
super(DecisionTreeClassifier, self).__init__()
self._java_obj = self._new_java_obj(
"org.apache.spark.ml.classification.DecisionTreeClassifier", self.uid)
self._setDefault(maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10,
impurity="gini")
kwargs = self._input_kwargs
self.setParams(**kwargs)
@keyword_only
@since("1.4.0")
def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction",
probabilityCol="probability", rawPredictionCol="rawPrediction",
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10,
impurity="gini", seed=None):
"""
setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
probabilityCol="probability", rawPredictionCol="rawPrediction", \
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, \
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, impurity="gini", \
seed=None)
Sets params for the DecisionTreeClassifier.
"""
kwargs = self._input_kwargs
return self._set(**kwargs)
def _create_model(self, java_model):
return DecisionTreeClassificationModel(java_model)
@inherit_doc
class DecisionTreeClassificationModel(DecisionTreeModel, JavaClassificationModel, JavaMLWritable,
JavaMLReadable):
"""
Model fitted by DecisionTreeClassifier.
.. versionadded:: 1.4.0
"""
@property
@since("2.0.0")
def featureImportances(self):
"""
Estimate of the importance of each feature.
This generalizes the idea of "Gini" importance to other losses,
following the explanation of Gini importance from "Random Forests" documentation
by Leo Breiman and Adele Cutler, and following the implementation from scikit-learn.
This feature importance is calculated as follows:
- importance(feature j) = sum (over nodes which split on feature j) of the gain,
where gain is scaled by the number of instances passing through node
- Normalize importances for tree to sum to 1.
.. note:: Feature importance for single decision trees can have high variance due to
correlated predictor variables. Consider using a :py:class:`RandomForestClassifier`
to determine feature importance instead.
"""
return self._call_java("featureImportances")
@inherit_doc
class RandomForestClassifier(JavaEstimator, HasFeaturesCol, HasLabelCol, HasPredictionCol, HasSeed,
HasRawPredictionCol, HasProbabilityCol,
RandomForestParams, TreeClassifierParams, HasCheckpointInterval,
JavaMLWritable, JavaMLReadable):
"""
`Random Forest <http://en.wikipedia.org/wiki/Random_forest>`_
learning algorithm for classification.
It supports both binary and multiclass labels, as well as both continuous and categorical
features.
>>> import numpy
>>> from numpy import allclose
>>> from pyspark.ml.linalg import Vectors
>>> from pyspark.ml.feature import StringIndexer
>>> df = spark.createDataFrame([
... (1.0, Vectors.dense(1.0)),
... (0.0, Vectors.sparse(1, [], []))], ["label", "features"])
>>> stringIndexer = StringIndexer(inputCol="label", outputCol="indexed")
>>> si_model = stringIndexer.fit(df)
>>> td = si_model.transform(df)
>>> rf = RandomForestClassifier(numTrees=3, maxDepth=2, labelCol="indexed", seed=42)
>>> model = rf.fit(td)
>>> model.featureImportances
SparseVector(1, {0: 1.0})
>>> allclose(model.treeWeights, [1.0, 1.0, 1.0])
True
>>> test0 = spark.createDataFrame([(Vectors.dense(-1.0),)], ["features"])
>>> result = model.transform(test0).head()
>>> result.prediction
0.0
>>> numpy.argmax(result.probability)
0
>>> numpy.argmax(result.rawPrediction)
0
>>> test1 = spark.createDataFrame([(Vectors.sparse(1, [0], [1.0]),)], ["features"])
>>> model.transform(test1).head().prediction
1.0
>>> model.trees
[DecisionTreeClassificationModel (uid=...) of depth..., DecisionTreeClassificationModel...]
>>> rfc_path = temp_path + "/rfc"
>>> rf.save(rfc_path)
>>> rf2 = RandomForestClassifier.load(rfc_path)
>>> rf2.getNumTrees()
3
>>> model_path = temp_path + "/rfc_model"
>>> model.save(model_path)
>>> model2 = RandomForestClassificationModel.load(model_path)
>>> model.featureImportances == model2.featureImportances
True
.. versionadded:: 1.4.0
"""
@keyword_only
def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction",
probabilityCol="probability", rawPredictionCol="rawPrediction",
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, impurity="gini",
numTrees=20, featureSubsetStrategy="auto", seed=None, subsamplingRate=1.0):
"""
__init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
probabilityCol="probability", rawPredictionCol="rawPrediction", \
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, \
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, impurity="gini", \
numTrees=20, featureSubsetStrategy="auto", seed=None, subsamplingRate=1.0)
"""
super(RandomForestClassifier, self).__init__()
self._java_obj = self._new_java_obj(
"org.apache.spark.ml.classification.RandomForestClassifier", self.uid)
self._setDefault(maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10,
impurity="gini", numTrees=20, featureSubsetStrategy="auto",
subsamplingRate=1.0)
kwargs = self._input_kwargs
self.setParams(**kwargs)
@keyword_only
@since("1.4.0")
def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction",
probabilityCol="probability", rawPredictionCol="rawPrediction",
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, seed=None,
impurity="gini", numTrees=20, featureSubsetStrategy="auto", subsamplingRate=1.0):
"""
setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
probabilityCol="probability", rawPredictionCol="rawPrediction", \
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, \
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, seed=None, \
impurity="gini", numTrees=20, featureSubsetStrategy="auto", subsamplingRate=1.0)
Sets params for linear classification.
"""
kwargs = self._input_kwargs
return self._set(**kwargs)
def _create_model(self, java_model):
return RandomForestClassificationModel(java_model)
class RandomForestClassificationModel(TreeEnsembleModel, JavaClassificationModel, JavaMLWritable,
JavaMLReadable):
"""
Model fitted by RandomForestClassifier.
.. versionadded:: 1.4.0
"""
@property
@since("2.0.0")
def featureImportances(self):
"""
Estimate of the importance of each feature.
Each feature's importance is the average of its importance across all trees in the ensemble
The importance vector is normalized to sum to 1. This method is suggested by Hastie et al.
(Hastie, Tibshirani, Friedman. "The Elements of Statistical Learning, 2nd Edition." 2001.)
and follows the implementation from scikit-learn.
.. seealso:: :py:attr:`DecisionTreeClassificationModel.featureImportances`
"""
return self._call_java("featureImportances")
@property
@since("2.0.0")
def trees(self):
"""Trees in this ensemble. Warning: These have null parent Estimators."""
return [DecisionTreeClassificationModel(m) for m in list(self._call_java("trees"))]
@inherit_doc
class GBTClassifier(JavaEstimator, HasFeaturesCol, HasLabelCol, HasPredictionCol, HasMaxIter,
GBTParams, HasCheckpointInterval, HasStepSize, HasSeed, JavaMLWritable,
JavaMLReadable):
"""
`Gradient-Boosted Trees (GBTs) <http://en.wikipedia.org/wiki/Gradient_boosting>`_
learning algorithm for classification.
It supports binary labels, as well as both continuous and categorical features.
The implementation is based upon: J.H. Friedman. "Stochastic Gradient Boosting." 1999.
Notes on Gradient Boosting vs. TreeBoost:
- This implementation is for Stochastic Gradient Boosting, not for TreeBoost.
- Both algorithms learn tree ensembles by minimizing loss functions.
- TreeBoost (Friedman, 1999) additionally modifies the outputs at tree leaf nodes
based on the loss function, whereas the original gradient boosting method does not.
- We expect to implement TreeBoost in the future:
`SPARK-4240 <https://issues.apache.org/jira/browse/SPARK-4240>`_
.. note:: Multiclass labels are not currently supported.
>>> from numpy import allclose
>>> from pyspark.ml.linalg import Vectors
>>> from pyspark.ml.feature import StringIndexer
>>> df = spark.createDataFrame([
... (1.0, Vectors.dense(1.0)),
... (0.0, Vectors.sparse(1, [], []))], ["label", "features"])
>>> stringIndexer = StringIndexer(inputCol="label", outputCol="indexed")
>>> si_model = stringIndexer.fit(df)
>>> td = si_model.transform(df)
>>> gbt = GBTClassifier(maxIter=5, maxDepth=2, labelCol="indexed", seed=42)
>>> model = gbt.fit(td)
>>> model.featureImportances
SparseVector(1, {0: 1.0})
>>> allclose(model.treeWeights, [1.0, 0.1, 0.1, 0.1, 0.1])
True
>>> test0 = spark.createDataFrame([(Vectors.dense(-1.0),)], ["features"])
>>> model.transform(test0).head().prediction
0.0
>>> test1 = spark.createDataFrame([(Vectors.sparse(1, [0], [1.0]),)], ["features"])
>>> model.transform(test1).head().prediction
1.0
>>> model.totalNumNodes
15
>>> print(model.toDebugString)
GBTClassificationModel (uid=...)...with 5 trees...
>>> gbtc_path = temp_path + "gbtc"
>>> gbt.save(gbtc_path)
>>> gbt2 = GBTClassifier.load(gbtc_path)
>>> gbt2.getMaxDepth()
2
>>> model_path = temp_path + "gbtc_model"
>>> model.save(model_path)
>>> model2 = GBTClassificationModel.load(model_path)
>>> model.featureImportances == model2.featureImportances
True
>>> model.treeWeights == model2.treeWeights
True
>>> model.trees
[DecisionTreeRegressionModel (uid=...) of depth..., DecisionTreeRegressionModel...]
.. versionadded:: 1.4.0
"""
lossType = Param(Params._dummy(), "lossType",
"Loss function which GBT tries to minimize (case-insensitive). " +
"Supported options: " + ", ".join(GBTParams.supportedLossTypes),
typeConverter=TypeConverters.toString)
@keyword_only
def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction",
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, lossType="logistic",
maxIter=20, stepSize=0.1, seed=None, subsamplingRate=1.0):
"""
__init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, \
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, \
lossType="logistic", maxIter=20, stepSize=0.1, seed=None, subsamplingRate=1.0)
"""
super(GBTClassifier, self).__init__()
self._java_obj = self._new_java_obj(
"org.apache.spark.ml.classification.GBTClassifier", self.uid)
self._setDefault(maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10,
lossType="logistic", maxIter=20, stepSize=0.1, subsamplingRate=1.0)
kwargs = self._input_kwargs
self.setParams(**kwargs)
@keyword_only
@since("1.4.0")
def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction",
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0,
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10,
lossType="logistic", maxIter=20, stepSize=0.1, seed=None, subsamplingRate=1.0):
"""
setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
maxDepth=5, maxBins=32, minInstancesPerNode=1, minInfoGain=0.0, \
maxMemoryInMB=256, cacheNodeIds=False, checkpointInterval=10, \
lossType="logistic", maxIter=20, stepSize=0.1, seed=None, subsamplingRate=1.0)
Sets params for Gradient Boosted Tree Classification.
"""
kwargs = self._input_kwargs
return self._set(**kwargs)
def _create_model(self, java_model):
return GBTClassificationModel(java_model)
@since("1.4.0")
def setLossType(self, value):
"""
Sets the value of :py:attr:`lossType`.
"""
return self._set(lossType=value)
@since("1.4.0")
def getLossType(self):
"""
Gets the value of lossType or its default value.
"""
return self.getOrDefault(self.lossType)
class GBTClassificationModel(TreeEnsembleModel, JavaPredictionModel, JavaMLWritable,
JavaMLReadable):
"""
Model fitted by GBTClassifier.
.. versionadded:: 1.4.0
"""
@property
@since("2.0.0")
def featureImportances(self):
"""
Estimate of the importance of each feature.
Each feature's importance is the average of its importance across all trees in the ensemble
The importance vector is normalized to sum to 1. This method is suggested by Hastie et al.
(Hastie, Tibshirani, Friedman. "The Elements of Statistical Learning, 2nd Edition." 2001.)
and follows the implementation from scikit-learn.
.. seealso:: :py:attr:`DecisionTreeClassificationModel.featureImportances`
"""
return self._call_java("featureImportances")
@property
@since("2.0.0")
def trees(self):
"""Trees in this ensemble. Warning: These have null parent Estimators."""
return [DecisionTreeRegressionModel(m) for m in list(self._call_java("trees"))]
@inherit_doc
class NaiveBayes(JavaEstimator, HasFeaturesCol, HasLabelCol, HasPredictionCol, HasProbabilityCol,
HasRawPredictionCol, HasThresholds, HasWeightCol, JavaMLWritable, JavaMLReadable):
"""
Naive Bayes Classifiers.
It supports both Multinomial and Bernoulli NB. `Multinomial NB
<http://nlp.stanford.edu/IR-book/html/htmledition/naive-bayes-text-classification-1.html>`_
can handle finitely supported discrete data. For example, by converting documents into
TF-IDF vectors, it can be used for document classification. By making every vector a
binary (0/1) data, it can also be used as `Bernoulli NB
<http://nlp.stanford.edu/IR-book/html/htmledition/the-bernoulli-model-1.html>`_.
The input feature values must be nonnegative.
>>> from pyspark.sql import Row
>>> from pyspark.ml.linalg import Vectors
>>> df = spark.createDataFrame([
... Row(label=0.0, weight=0.1, features=Vectors.dense([0.0, 0.0])),
... Row(label=0.0, weight=0.5, features=Vectors.dense([0.0, 1.0])),
... Row(label=1.0, weight=1.0, features=Vectors.dense([1.0, 0.0]))])
>>> nb = NaiveBayes(smoothing=1.0, modelType="multinomial", weightCol="weight")
>>> model = nb.fit(df)
>>> model.pi
DenseVector([-0.81..., -0.58...])
>>> model.theta
DenseMatrix(2, 2, [-0.91..., -0.51..., -0.40..., -1.09...], 1)
>>> test0 = sc.parallelize([Row(features=Vectors.dense([1.0, 0.0]))]).toDF()
>>> result = model.transform(test0).head()
>>> result.prediction
1.0
>>> result.probability
DenseVector([0.32..., 0.67...])
>>> result.rawPrediction
DenseVector([-1.72..., -0.99...])
>>> test1 = sc.parallelize([Row(features=Vectors.sparse(2, [0], [1.0]))]).toDF()
>>> model.transform(test1).head().prediction
1.0
>>> nb_path = temp_path + "/nb"
>>> nb.save(nb_path)
>>> nb2 = NaiveBayes.load(nb_path)
>>> nb2.getSmoothing()
1.0
>>> model_path = temp_path + "/nb_model"
>>> model.save(model_path)
>>> model2 = NaiveBayesModel.load(model_path)
>>> model.pi == model2.pi
True
>>> model.theta == model2.theta
True
>>> nb = nb.setThresholds([0.01, 10.00])
>>> model3 = nb.fit(df)
>>> result = model3.transform(test0).head()
>>> result.prediction
0.0
.. versionadded:: 1.5.0
"""
smoothing = Param(Params._dummy(), "smoothing", "The smoothing parameter, should be >= 0, " +
"default is 1.0", typeConverter=TypeConverters.toFloat)
modelType = Param(Params._dummy(), "modelType", "The model type which is a string " +
"(case-sensitive). Supported options: multinomial (default) and bernoulli.",
typeConverter=TypeConverters.toString)
@keyword_only
def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction",
probabilityCol="probability", rawPredictionCol="rawPrediction", smoothing=1.0,
modelType="multinomial", thresholds=None, weightCol=None):
"""
__init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
probabilityCol="probability", rawPredictionCol="rawPrediction", smoothing=1.0, \
modelType="multinomial", thresholds=None, weightCol=None)
"""
super(NaiveBayes, self).__init__()
self._java_obj = self._new_java_obj(
"org.apache.spark.ml.classification.NaiveBayes", self.uid)
self._setDefault(smoothing=1.0, modelType="multinomial")
kwargs = self._input_kwargs
self.setParams(**kwargs)
@keyword_only
@since("1.5.0")
def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction",
probabilityCol="probability", rawPredictionCol="rawPrediction", smoothing=1.0,
modelType="multinomial", thresholds=None, weightCol=None):
"""
setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
probabilityCol="probability", rawPredictionCol="rawPrediction", smoothing=1.0, \
modelType="multinomial", thresholds=None, weightCol=None)
Sets params for Naive Bayes.
"""
kwargs = self._input_kwargs
return self._set(**kwargs)
def _create_model(self, java_model):
return NaiveBayesModel(java_model)
@since("1.5.0")
def setSmoothing(self, value):
"""
Sets the value of :py:attr:`smoothing`.
"""
return self._set(smoothing=value)
@since("1.5.0")
def getSmoothing(self):
"""
Gets the value of smoothing or its default value.
"""
return self.getOrDefault(self.smoothing)
@since("1.5.0")
def setModelType(self, value):
"""
Sets the value of :py:attr:`modelType`.
"""
return self._set(modelType=value)
@since("1.5.0")
def getModelType(self):
"""
Gets the value of modelType or its default value.
"""
return self.getOrDefault(self.modelType)
class NaiveBayesModel(JavaModel, JavaClassificationModel, JavaMLWritable, JavaMLReadable):
"""
Model fitted by NaiveBayes.
.. versionadded:: 1.5.0
"""
@property
@since("2.0.0")
def pi(self):
"""
log of class priors.
"""
return self._call_java("pi")
@property
@since("2.0.0")
def theta(self):
"""
log of class conditional probabilities.
"""
return self._call_java("theta")
@inherit_doc
class MultilayerPerceptronClassifier(JavaEstimator, HasFeaturesCol, HasLabelCol, HasPredictionCol,
HasMaxIter, HasTol, HasSeed, HasStepSize, JavaMLWritable,
JavaMLReadable):
"""
Classifier trainer based on the Multilayer Perceptron.
Each layer has sigmoid activation function, output layer has softmax.
Number of inputs has to be equal to the size of feature vectors.
Number of outputs has to be equal to the total number of labels.
>>> from pyspark.ml.linalg import Vectors
>>> df = spark.createDataFrame([
... (0.0, Vectors.dense([0.0, 0.0])),
... (1.0, Vectors.dense([0.0, 1.0])),
... (1.0, Vectors.dense([1.0, 0.0])),
... (0.0, Vectors.dense([1.0, 1.0]))], ["label", "features"])
>>> mlp = MultilayerPerceptronClassifier(maxIter=100, layers=[2, 2, 2], blockSize=1, seed=123)
>>> model = mlp.fit(df)
>>> model.layers
[2, 2, 2]
>>> model.weights.size
12
>>> testDF = spark.createDataFrame([
... (Vectors.dense([1.0, 0.0]),),
... (Vectors.dense([0.0, 0.0]),)], ["features"])
>>> model.transform(testDF).show()
+---------+----------+
| features|prediction|
+---------+----------+
|[1.0,0.0]| 1.0|
|[0.0,0.0]| 0.0|
+---------+----------+
...
>>> mlp_path = temp_path + "/mlp"
>>> mlp.save(mlp_path)
>>> mlp2 = MultilayerPerceptronClassifier.load(mlp_path)
>>> mlp2.getBlockSize()
1
>>> model_path = temp_path + "/mlp_model"
>>> model.save(model_path)
>>> model2 = MultilayerPerceptronClassificationModel.load(model_path)
>>> model.layers == model2.layers
True
>>> model.weights == model2.weights
True
>>> mlp2 = mlp2.setInitialWeights(list(range(0, 12)))
>>> model3 = mlp2.fit(df)
>>> model3.weights != model2.weights
True
>>> model3.layers == model.layers
True
.. versionadded:: 1.6.0
"""
layers = Param(Params._dummy(), "layers", "Sizes of layers from input layer to output layer " +
"E.g., Array(780, 100, 10) means 780 inputs, one hidden layer with 100 " +
"neurons and output layer of 10 neurons.",
typeConverter=TypeConverters.toListInt)
blockSize = Param(Params._dummy(), "blockSize", "Block size for stacking input data in " +
"matrices. Data is stacked within partitions. If block size is more than " +
"remaining data in a partition then it is adjusted to the size of this " +
"data. Recommended size is between 10 and 1000, default is 128.",
typeConverter=TypeConverters.toInt)
solver = Param(Params._dummy(), "solver", "The solver algorithm for optimization. Supported " +
"options: l-bfgs, gd.", typeConverter=TypeConverters.toString)
initialWeights = Param(Params._dummy(), "initialWeights", "The initial weights of the model.",
typeConverter=TypeConverters.toVector)
@keyword_only
def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction",
maxIter=100, tol=1e-6, seed=None, layers=None, blockSize=128, stepSize=0.03,
solver="l-bfgs", initialWeights=None):
"""
__init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
maxIter=100, tol=1e-6, seed=None, layers=None, blockSize=128, stepSize=0.03, \
solver="l-bfgs", initialWeights=None)
"""
super(MultilayerPerceptronClassifier, self).__init__()
self._java_obj = self._new_java_obj(
"org.apache.spark.ml.classification.MultilayerPerceptronClassifier", self.uid)
self._setDefault(maxIter=100, tol=1E-4, blockSize=128, stepSize=0.03, solver="l-bfgs")
kwargs = self._input_kwargs
self.setParams(**kwargs)
@keyword_only
@since("1.6.0")
def setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction",
maxIter=100, tol=1e-6, seed=None, layers=None, blockSize=128, stepSize=0.03,
solver="l-bfgs", initialWeights=None):
"""
setParams(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
maxIter=100, tol=1e-6, seed=None, layers=None, blockSize=128, stepSize=0.03, \
solver="l-bfgs", initialWeights=None)
Sets params for MultilayerPerceptronClassifier.
"""
kwargs = self._input_kwargs
return self._set(**kwargs)
def _create_model(self, java_model):
return MultilayerPerceptronClassificationModel(java_model)
@since("1.6.0")
def setLayers(self, value):
"""
Sets the value of :py:attr:`layers`.
"""
return self._set(layers=value)
@since("1.6.0")
def getLayers(self):
"""
Gets the value of layers or its default value.
"""
return self.getOrDefault(self.layers)
@since("1.6.0")
def setBlockSize(self, value):
"""
Sets the value of :py:attr:`blockSize`.
"""
return self._set(blockSize=value)
@since("1.6.0")
def getBlockSize(self):
"""
Gets the value of blockSize or its default value.
"""
return self.getOrDefault(self.blockSize)
@since("2.0.0")
def setStepSize(self, value):
"""
Sets the value of :py:attr:`stepSize`.
"""
return self._set(stepSize=value)
@since("2.0.0")
def getStepSize(self):
"""
Gets the value of stepSize or its default value.
"""
return self.getOrDefault(self.stepSize)
@since("2.0.0")
def setSolver(self, value):
"""
Sets the value of :py:attr:`solver`.
"""
return self._set(solver=value)
@since("2.0.0")
def getSolver(self):
"""
Gets the value of solver or its default value.
"""
return self.getOrDefault(self.solver)
@since("2.0.0")
def setInitialWeights(self, value):
"""
Sets the value of :py:attr:`initialWeights`.
"""
return self._set(initialWeights=value)
@since("2.0.0")
def getInitialWeights(self):
"""
Gets the value of initialWeights or its default value.
"""
return self.getOrDefault(self.initialWeights)
class MultilayerPerceptronClassificationModel(JavaModel, JavaPredictionModel, JavaMLWritable,
JavaMLReadable):
"""
Model fitted by MultilayerPerceptronClassifier.
.. versionadded:: 1.6.0
"""
@property
@since("1.6.0")
def layers(self):
"""
array of layer sizes including input and output layers.
"""
return self._call_java("javaLayers")
@property
@since("2.0.0")
def weights(self):
"""
the weights of layers.
"""
return self._call_java("weights")
class OneVsRestParams(HasFeaturesCol, HasLabelCol, HasWeightCol, HasPredictionCol):
"""
Parameters for OneVsRest and OneVsRestModel.
"""
classifier = Param(Params._dummy(), "classifier", "base binary classifier")
@since("2.0.0")
def setClassifier(self, value):
"""
Sets the value of :py:attr:`classifier`.
.. note:: Only LogisticRegression and NaiveBayes are supported now.
"""
return self._set(classifier=value)
@since("2.0.0")
def getClassifier(self):
"""
Gets the value of classifier or its default value.
"""
return self.getOrDefault(self.classifier)
@inherit_doc
class OneVsRest(Estimator, OneVsRestParams, MLReadable, MLWritable):
"""
.. note:: Experimental
Reduction of Multiclass Classification to Binary Classification.
Performs reduction using one against all strategy.
For a multiclass classification with k classes, train k models (one per class).
Each example is scored against all k models and the model with highest score
is picked to label the example.
>>> from pyspark.sql import Row
>>> from pyspark.ml.linalg import Vectors
>>> data_path = "data/mllib/sample_multiclass_classification_data.txt"
>>> df = spark.read.format("libsvm").load(data_path)
>>> lr = LogisticRegression(regParam=0.01)
>>> ovr = OneVsRest(classifier=lr)
>>> model = ovr.fit(df)
>>> model.models[0].coefficients
DenseVector([0.5..., -1.0..., 3.4..., 4.2...])
>>> model.models[1].coefficients
DenseVector([-2.1..., 3.1..., -2.6..., -2.3...])
>>> model.models[2].coefficients
DenseVector([0.3..., -3.4..., 1.0..., -1.1...])
>>> [x.intercept for x in model.models]
[-2.7..., -2.5..., -1.3...]
>>> test0 = sc.parallelize([Row(features=Vectors.dense(-1.0, 0.0, 1.0, 1.0))]).toDF()
>>> model.transform(test0).head().prediction
0.0
>>> test1 = sc.parallelize([Row(features=Vectors.sparse(4, [0], [1.0]))]).toDF()
>>> model.transform(test1).head().prediction
2.0
>>> test2 = sc.parallelize([Row(features=Vectors.dense(0.5, 0.4, 0.3, 0.2))]).toDF()
>>> model.transform(test2).head().prediction
0.0
>>> model_path = temp_path + "/ovr_model"
>>> model.save(model_path)
>>> model2 = OneVsRestModel.load(model_path)
>>> model2.transform(test0).head().prediction
0.0
.. versionadded:: 2.0.0
"""
@keyword_only
def __init__(self, featuresCol="features", labelCol="label", predictionCol="prediction",
classifier=None, weightCol=None):
"""
__init__(self, featuresCol="features", labelCol="label", predictionCol="prediction", \
classifier=None, weightCol=None)
"""
super(OneVsRest, self).__init__()
kwargs = self._input_kwargs
self._set(**kwargs)
@keyword_only
@since("2.0.0")
def setParams(self, featuresCol=None, labelCol=None, predictionCol=None,
classifier=None, weightCol=None):
"""
setParams(self, featuresCol=None, labelCol=None, predictionCol=None, \
classifier=None, weightCol=None):
Sets params for OneVsRest.
"""
kwargs = self._input_kwargs
return self._set(**kwargs)
def _fit(self, dataset):
labelCol = self.getLabelCol()
featuresCol = self.getFeaturesCol()
predictionCol = self.getPredictionCol()
classifier = self.getClassifier()
assert isinstance(classifier, HasRawPredictionCol),\
"Classifier %s doesn't extend from HasRawPredictionCol." % type(classifier)
numClasses = int(dataset.agg({labelCol: "max"}).head()["max("+labelCol+")"]) + 1
weightCol = None
if (self.isDefined(self.weightCol) and self.getWeightCol()):
if isinstance(classifier, HasWeightCol):
weightCol = self.getWeightCol()
else:
warnings.warn("weightCol is ignored, "
"as it is not supported by {} now.".format(classifier))
if weightCol:
multiclassLabeled = dataset.select(labelCol, featuresCol, weightCol)
else:
multiclassLabeled = dataset.select(labelCol, featuresCol)
# persist if underlying dataset is not persistent.
handlePersistence = \
dataset.rdd.getStorageLevel() == StorageLevel(False, False, False, False)
if handlePersistence:
multiclassLabeled.persist(StorageLevel.MEMORY_AND_DISK)
def trainSingleClass(index):
binaryLabelCol = "mc2b$" + str(index)
trainingDataset = multiclassLabeled.withColumn(
binaryLabelCol,
when(multiclassLabeled[labelCol] == float(index), 1.0).otherwise(0.0))
paramMap = dict([(classifier.labelCol, binaryLabelCol),
(classifier.featuresCol, featuresCol),
(classifier.predictionCol, predictionCol)])
if weightCol:
paramMap[classifier.weightCol] = weightCol
return classifier.fit(trainingDataset, paramMap)
# TODO: Parallel training for all classes.
models = [trainSingleClass(i) for i in range(numClasses)]
if handlePersistence:
multiclassLabeled.unpersist()
return self._copyValues(OneVsRestModel(models=models))
@since("2.0.0")
def copy(self, extra=None):
"""
Creates a copy of this instance with a randomly generated uid
and some extra params. This creates a deep copy of the embedded paramMap,
and copies the embedded and extra parameters over.
:param extra: Extra parameters to copy to the new instance
:return: Copy of this instance
"""
if extra is None:
extra = dict()
newOvr = Params.copy(self, extra)
if self.isSet(self.classifier):
newOvr.setClassifier(self.getClassifier().copy(extra))
return newOvr
@since("2.0.0")
def write(self):
"""Returns an MLWriter instance for this ML instance."""
return JavaMLWriter(self)
@since("2.0.0")
def save(self, path):
"""Save this ML instance to the given path, a shortcut of `write().save(path)`."""
self.write().save(path)
@classmethod
@since("2.0.0")
def read(cls):
"""Returns an MLReader instance for this class."""
return JavaMLReader(cls)
@classmethod
def _from_java(cls, java_stage):
"""
Given a Java OneVsRest, create and return a Python wrapper of it.
Used for ML persistence.
"""
featuresCol = java_stage.getFeaturesCol()
labelCol = java_stage.getLabelCol()
predictionCol = java_stage.getPredictionCol()
classifier = JavaParams._from_java(java_stage.getClassifier())
py_stage = cls(featuresCol=featuresCol, labelCol=labelCol, predictionCol=predictionCol,
classifier=classifier)
py_stage._resetUid(java_stage.uid())
return py_stage
def _to_java(self):
"""
Transfer this instance to a Java OneVsRest. Used for ML persistence.
:return: Java object equivalent to this instance.
"""
_java_obj = JavaParams._new_java_obj("org.apache.spark.ml.classification.OneVsRest",
self.uid)
_java_obj.setClassifier(self.getClassifier()._to_java())
_java_obj.setFeaturesCol(self.getFeaturesCol())
_java_obj.setLabelCol(self.getLabelCol())
_java_obj.setPredictionCol(self.getPredictionCol())
return _java_obj
class OneVsRestModel(Model, OneVsRestParams, MLReadable, MLWritable):
"""
.. note:: Experimental
Model fitted by OneVsRest.
This stores the models resulting from training k binary classifiers: one for each class.
Each example is scored against all k models, and the model with the highest score
is picked to label the example.
.. versionadded:: 2.0.0
"""
def __init__(self, models):
super(OneVsRestModel, self).__init__()
self.models = models
def _transform(self, dataset):
# determine the input columns: these need to be passed through
origCols = dataset.columns
# add an accumulator column to store predictions of all the models
accColName = "mbc$acc" + str(uuid.uuid4())
initUDF = udf(lambda _: [], ArrayType(DoubleType()))
newDataset = dataset.withColumn(accColName, initUDF(dataset[origCols[0]]))
# persist if underlying dataset is not persistent.
handlePersistence = \
dataset.rdd.getStorageLevel() == StorageLevel(False, False, False, False)
if handlePersistence:
newDataset.persist(StorageLevel.MEMORY_AND_DISK)
# update the accumulator column with the result of prediction of models
aggregatedDataset = newDataset
for index, model in enumerate(self.models):
rawPredictionCol = model._call_java("getRawPredictionCol")
columns = origCols + [rawPredictionCol, accColName]
# add temporary column to store intermediate scores and update
tmpColName = "mbc$tmp" + str(uuid.uuid4())
updateUDF = udf(
lambda predictions, prediction: predictions + [prediction.tolist()[1]],
ArrayType(DoubleType()))
transformedDataset = model.transform(aggregatedDataset).select(*columns)
updatedDataset = transformedDataset.withColumn(
tmpColName,
updateUDF(transformedDataset[accColName], transformedDataset[rawPredictionCol]))
newColumns = origCols + [tmpColName]
# switch out the intermediate column with the accumulator column
aggregatedDataset = updatedDataset\
.select(*newColumns).withColumnRenamed(tmpColName, accColName)
if handlePersistence:
newDataset.unpersist()
# output the index of the classifier with highest confidence as prediction
labelUDF = udf(
lambda predictions: float(max(enumerate(predictions), key=operator.itemgetter(1))[0]),
DoubleType())
# output label and label metadata as prediction
return aggregatedDataset.withColumn(
self.getPredictionCol(), labelUDF(aggregatedDataset[accColName])).drop(accColName)
@since("2.0.0")
def copy(self, extra=None):
"""
Creates a copy of this instance with a randomly generated uid
and some extra params. This creates a deep copy of the embedded paramMap,
and copies the embedded and extra parameters over.
:param extra: Extra parameters to copy to the new instance
:return: Copy of this instance
"""
if extra is None:
extra = dict()
newModel = Params.copy(self, extra)
newModel.models = [model.copy(extra) for model in self.models]
return newModel
@since("2.0.0")
def write(self):
"""Returns an MLWriter instance for this ML instance."""
return JavaMLWriter(self)
@since("2.0.0")
def save(self, path):
"""Save this ML instance to the given path, a shortcut of `write().save(path)`."""
self.write().save(path)
@classmethod
@since("2.0.0")
def read(cls):
"""Returns an MLReader instance for this class."""
return JavaMLReader(cls)
@classmethod
def _from_java(cls, java_stage):
"""
Given a Java OneVsRestModel, create and return a Python wrapper of it.
Used for ML persistence.
"""
featuresCol = java_stage.getFeaturesCol()
labelCol = java_stage.getLabelCol()
predictionCol = java_stage.getPredictionCol()
classifier = JavaParams._from_java(java_stage.getClassifier())
models = [JavaParams._from_java(model) for model in java_stage.models()]
py_stage = cls(models=models).setPredictionCol(predictionCol).setLabelCol(labelCol)\
.setFeaturesCol(featuresCol).setClassifier(classifier)
py_stage._resetUid(java_stage.uid())
return py_stage
def _to_java(self):
"""
Transfer this instance to a Java OneVsRestModel. Used for ML persistence.
:return: Java object equivalent to this instance.
"""
sc = SparkContext._active_spark_context
java_models = [model._to_java() for model in self.models]
java_models_array = JavaWrapper._new_java_array(
java_models, sc._gateway.jvm.org.apache.spark.ml.classification.ClassificationModel)
metadata = JavaParams._new_java_obj("org.apache.spark.sql.types.Metadata")
_java_obj = JavaParams._new_java_obj("org.apache.spark.ml.classification.OneVsRestModel",
self.uid, metadata.empty(), java_models_array)
_java_obj.set("classifier", self.getClassifier()._to_java())
_java_obj.set("featuresCol", self.getFeaturesCol())
_java_obj.set("labelCol", self.getLabelCol())
_java_obj.set("predictionCol", self.getPredictionCol())
return _java_obj
if __name__ == "__main__":
import doctest
import pyspark.ml.classification
from pyspark.sql import SparkSession
globs = pyspark.ml.classification.__dict__.copy()
# The small batch size here ensures that we see multiple batches,
# even in these small test examples:
spark = SparkSession.builder\
.master("local[2]")\
.appName("ml.classification tests")\
.getOrCreate()
sc = spark.sparkContext
globs['sc'] = sc
globs['spark'] = spark
import tempfile
temp_path = tempfile.mkdtemp()
globs['temp_path'] = temp_path
try:
(failure_count, test_count) = doctest.testmod(globs=globs, optionflags=doctest.ELLIPSIS)
spark.stop()
finally:
from shutil import rmtree
try:
rmtree(temp_path)
except OSError:
pass
if failure_count:
exit(-1)<|fim▁end|> | |
<|file_name|>test_namedict.py<|end_file_name|><|fim▁begin|># Copyright (C) 2003-2007, 2009-2011 Nominum, Inc.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose with or without fee is hereby granted,
# provided that the above copyright notice and this permission notice
# appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
try:
import unittest2 as unittest
except ImportError:
import unittest
import dns.name
import dns.namedict
class NameTestCase(unittest.TestCase):
def setUp(self):
self.ndict = dns.namedict.NameDict()
n1 = dns.name.from_text('foo.bar.')
n2 = dns.name.from_text('bar.')
self.ndict[n1] = 1
self.ndict[n2] = 2
self.rndict = dns.namedict.NameDict()
n1 = dns.name.from_text('foo.bar', None)
n2 = dns.name.from_text('bar', None)
self.rndict[n1] = 1
self.rndict[n2] = 2
def testDepth(self):
self.failUnless(self.ndict.max_depth == 3)
def testLookup1(self):
k = dns.name.from_text('foo.bar.')
self.failUnless(self.ndict[k] == 1)
def testLookup2(self):
k = dns.name.from_text('foo.bar.')
self.failUnless(self.ndict.get_deepest_match(k)[1] == 1)
def testLookup3(self):
k = dns.name.from_text('a.b.c.foo.bar.')
self.failUnless(self.ndict.get_deepest_match(k)[1] == 1)
def testLookup4(self):
k = dns.name.from_text('a.b.c.bar.')
self.failUnless(self.ndict.get_deepest_match(k)[1] == 2)
def testLookup5(self):
def bad():
n = dns.name.from_text('a.b.c.')
(k, v) = self.ndict.get_deepest_match(n)
self.failUnlessRaises(KeyError, bad)
def testLookup6(self):
def bad():
(k, v) = self.ndict.get_deepest_match(dns.name.empty)
self.failUnlessRaises(KeyError, bad)<|fim▁hole|> self.ndict[dns.name.empty] = 100
n = dns.name.from_text('a.b.c.')
(k, v) = self.ndict.get_deepest_match(n)
self.failUnless(v == 100)
def testLookup8(self):
def bad():
self.ndict['foo'] = 100
self.failUnlessRaises(ValueError, bad)
def testRelDepth(self):
self.failUnless(self.rndict.max_depth == 2)
def testRelLookup1(self):
k = dns.name.from_text('foo.bar', None)
self.failUnless(self.rndict[k] == 1)
def testRelLookup2(self):
k = dns.name.from_text('foo.bar', None)
self.failUnless(self.rndict.get_deepest_match(k)[1] == 1)
def testRelLookup3(self):
k = dns.name.from_text('a.b.c.foo.bar', None)
self.failUnless(self.rndict.get_deepest_match(k)[1] == 1)
def testRelLookup4(self):
k = dns.name.from_text('a.b.c.bar', None)
self.failUnless(self.rndict.get_deepest_match(k)[1] == 2)
def testRelLookup7(self):
self.rndict[dns.name.empty] = 100
n = dns.name.from_text('a.b.c', None)
(k, v) = self.rndict.get_deepest_match(n)
self.failUnless(v == 100)
if __name__ == '__main__':
unittest.main()<|fim▁end|> |
def testLookup7(self): |
<|file_name|>celery_run.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: UTF-8 -*-<|fim▁hole|>app = create_app()<|fim▁end|> | from app import create_app, celery
|
<|file_name|>fixtures.py<|end_file_name|><|fim▁begin|>from datetime import date, time, timedelta
from decimal import Decimal
import itertools
from django.utils import timezone
from six.moves import xrange
from .models import Person
def get_fixtures(n=None):
"""
Returns `n` dictionaries of `Person` objects.
If `n` is not specified it defaults to 6.
"""
_now = timezone.now().replace(microsecond=0) # mysql doesn't do microseconds. # NOQA
_date = date(2015, 3, 28)
_time = time(13, 0)
fixtures = [
{
'big_age': 59999999999999999, 'comma_separated_age': '1,2,3',
'age': -99, 'positive_age': 9999, 'positive_small_age': 299,
'small_age': -299, 'certified': False, 'null_certified': None,
'name': 'Mike', 'email': '[email protected]',
'file_path': '/Users/user/fixtures.json', 'slug': 'mike',
'text': 'here is a dummy text',
'url': 'https://docs.djangoproject.com',
'height': Decimal('1.81'), 'date_time': _now,
'date': _date, 'time': _time, 'float_height': 0.3,
'remote_addr': '192.0.2.30', 'my_file': 'dummy.txt',
'image': 'kitten.jpg', 'data': {'name': 'Mike', 'age': -99},
},
{
'big_age': 245999992349999, 'comma_separated_age': '6,2,9',
'age': 25, 'positive_age': 49999, 'positive_small_age': 315,
'small_age': 5409, 'certified': False, 'null_certified': True,
'name': 'Pete', 'email': '[email protected]',
'file_path': 'users.json', 'slug': 'pete', 'text': 'dummy',
'url': 'https://google.com', 'height': Decimal('1.93'),
'date_time': _now, 'date': _date, 'time': _time,
'float_height': 0.5, 'remote_addr': '127.0.0.1',
'my_file': 'fixtures.json',
'data': [{'name': 'Pete'}, {'name': 'Mike'}],
},
{
'big_age': 9929992349999, 'comma_separated_age': '6,2,9,10,5',
'age': 29, 'positive_age': 412399, 'positive_small_age': 23315,
'small_age': -5409, 'certified': False, 'null_certified': True,
'name': 'Ash', 'email': '[email protected]',
'file_path': '/Downloads/kitten.jpg', 'slug': 'ash',
'text': 'bla bla bla', 'url': 'news.ycombinator.com',
'height': Decimal('1.78'), 'date_time': _now,
'date': _date, 'time': _time,
'float_height': 0.8, 'my_file': 'dummy.png',
'data': {'text': 'bla bla bla', 'names': ['Mike', 'Pete']},
},
{
'big_age': 9992349234, 'comma_separated_age': '12,29,10,5',
'age': -29, 'positive_age': 4199, 'positive_small_age': 115,
'small_age': 909, 'certified': True, 'null_certified': False,
'name': 'Mary', 'email': '[email protected]',
'file_path': 'dummy.png', 'slug': 'mary',
'text': 'bla bla bla bla bla', 'url': 'news.ycombinator.com',
'height': Decimal('1.65'), 'date_time': _now,
'date': _date, 'time': _time, 'float_height': 0,
'remote_addr': '2a02:42fe::4',
'data': {'names': {'name': 'Mary'}},
},
{<|fim▁hole|> 'file_path': '/home/dummy.png', 'slug': 'sandra',
'text': 'this is a dummy text', 'url': 'google.com',
'height': Decimal('1.59'), 'date_time': _now,
'date': _date, 'time': _time, 'float_height': 2 ** 2,
'image': 'dummy.jpeg', 'data': {},
},
{
'big_age': 9999999999, 'comma_separated_age': '1,100,3,5',
'age': 35, 'positive_age': 1111, 'positive_small_age': 500,
'small_age': 110, 'certified': True, 'null_certified': None,
'name': 'Crystal', 'email': '[email protected]',
'file_path': '/home/dummy.txt', 'slug': 'crystal',
'text': 'dummy text', 'url': 'docs.djangoproject.com',
'height': Decimal('1.71'), 'date_time': _now,
'date': _date, 'time': _time, 'float_height': 2 ** 10,
'image': 'dummy.png', 'data': [],
},
]
n = n or len(fixtures)
fixtures = itertools.cycle(fixtures)
for _ in xrange(n):
yield next(fixtures)
def create_fixtures(n=None):
"""
Wrapper for Person.bulk_create which creates `n` fixtures
"""
Person.objects.bulk_create(Person(**person)
for person in get_fixtures(n))<|fim▁end|> | 'big_age': 999234, 'comma_separated_age': '12,1,30,50',
'age': 1, 'positive_age': 99199, 'positive_small_age': 5,
'small_age': -909, 'certified': False, 'null_certified': False,
'name': 'Sandra', 'email': '[email protected]', |
<|file_name|>webpack.config.js<|end_file_name|><|fim▁begin|>module.exports = {
entry: ["react", "react-dom", "lodash"]<|fim▁hole|><|fim▁end|> | } |
<|file_name|>tcp_posix_test.cc<|end_file_name|><|fim▁begin|>/*
*
* Copyright 2015 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "src/core/lib/iomgr/port.h"
// This test won't work except with posix sockets enabled
#ifdef GRPC_POSIX_SOCKET_TCP
#include "src/core/lib/iomgr/tcp_posix.h"
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/time.h>
#include "src/core/lib/gpr/useful.h"
#include "src/core/lib/iomgr/buffer_list.h"
#include "src/core/lib/iomgr/ev_posix.h"
#include "src/core/lib/iomgr/sockaddr_posix.h"
#include "src/core/lib/slice/slice_internal.h"
#include "test/core/iomgr/endpoint_tests.h"
#include "test/core/util/test_config.h"
static gpr_mu* g_mu;
static grpc_pollset* g_pollset;
/*
General test notes:
All tests which write data into a socket write i%256 into byte i, which is
verified by readers.
In general there are a few interesting things to vary which may lead to
exercising different codepaths in an implementation:
1. Total amount of data written to the socket
2. Size of slice allocations
3. Amount of data we read from or write to the socket at once
The tests here tend to parameterize these where applicable.
*/
static void create_sockets(int sv[2]) {
int flags;
GPR_ASSERT(socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == 0);
flags = fcntl(sv[0], F_GETFL, 0);
GPR_ASSERT(fcntl(sv[0], F_SETFL, flags | O_NONBLOCK) == 0);
flags = fcntl(sv[1], F_GETFL, 0);
GPR_ASSERT(fcntl(sv[1], F_SETFL, flags | O_NONBLOCK) == 0);
}
static void create_inet_sockets(int sv[2]) {
/* Prepare listening socket */
struct sockaddr_in addr;
memset(&addr, 0, sizeof(struct sockaddr_in));
addr.sin_family = AF_INET;
int sock = socket(AF_INET, SOCK_STREAM, 0);
GPR_ASSERT(sock);
GPR_ASSERT(bind(sock, (sockaddr*)&addr, sizeof(sockaddr_in)) == 0);
listen(sock, 1);
/* Prepare client socket and connect to server */
socklen_t len = sizeof(sockaddr_in);
GPR_ASSERT(getsockname(sock, (sockaddr*)&addr, &len) == 0);
int client = socket(AF_INET, SOCK_STREAM, 0);
GPR_ASSERT(client);
int ret;
do {
ret = connect(client, reinterpret_cast<sockaddr*>(&addr),
sizeof(sockaddr_in));
} while (ret == -1 && errno == EINTR);
/* Accept client connection */
len = sizeof(socklen_t);
int server;
do {
server = accept(sock, reinterpret_cast<sockaddr*>(&addr), &len);
} while (server == -1 && errno == EINTR);
GPR_ASSERT(server != -1);
sv[0] = server;
sv[1] = client;
int flags = fcntl(sv[0], F_GETFL, 0);
GPR_ASSERT(fcntl(sv[0], F_SETFL, flags | O_NONBLOCK) == 0);
flags = fcntl(sv[1], F_GETFL, 0);
GPR_ASSERT(fcntl(sv[1], F_SETFL, flags | O_NONBLOCK) == 0);
}
static ssize_t fill_socket(int fd) {
ssize_t write_bytes;
ssize_t total_bytes = 0;
int i;
unsigned char buf[256];
for (i = 0; i < 256; ++i) {
buf[i] = static_cast<uint8_t>(i);
}
do {
write_bytes = write(fd, buf, 256);
if (write_bytes > 0) {
total_bytes += write_bytes;
}
} while (write_bytes >= 0 || errno == EINTR);<|fim▁hole|> GPR_ASSERT(errno == EAGAIN);
return total_bytes;
}
static size_t fill_socket_partial(int fd, size_t bytes) {
ssize_t write_bytes;
size_t total_bytes = 0;
unsigned char* buf = static_cast<unsigned char*>(gpr_malloc(bytes));
unsigned i;
for (i = 0; i < bytes; ++i) {
buf[i] = static_cast<uint8_t>(i % 256);
}
do {
write_bytes = write(fd, buf, bytes - total_bytes);
if (write_bytes > 0) {
total_bytes += static_cast<size_t>(write_bytes);
}
} while ((write_bytes >= 0 || errno == EINTR) && bytes > total_bytes);
gpr_free(buf);
return total_bytes;
}
struct read_socket_state {
grpc_endpoint* ep;
size_t read_bytes;
size_t target_read_bytes;
grpc_slice_buffer incoming;
grpc_closure read_cb;
};
static size_t count_slices(grpc_slice* slices, size_t nslices,
int* current_data) {
size_t num_bytes = 0;
unsigned i, j;
unsigned char* buf;
for (i = 0; i < nslices; ++i) {
buf = GRPC_SLICE_START_PTR(slices[i]);
for (j = 0; j < GRPC_SLICE_LENGTH(slices[i]); ++j) {
GPR_ASSERT(buf[j] == *current_data);
*current_data = (*current_data + 1) % 256;
}
num_bytes += GRPC_SLICE_LENGTH(slices[i]);
}
return num_bytes;
}
static void read_cb(void* user_data, grpc_error_handle error) {
struct read_socket_state* state =
static_cast<struct read_socket_state*>(user_data);
size_t read_bytes;
int current_data;
GPR_ASSERT(error == GRPC_ERROR_NONE);
gpr_mu_lock(g_mu);
current_data = state->read_bytes % 256;
read_bytes = count_slices(state->incoming.slices, state->incoming.count,
¤t_data);
state->read_bytes += read_bytes;
gpr_log(GPR_INFO, "Read %" PRIuPTR " bytes of %" PRIuPTR, read_bytes,
state->target_read_bytes);
if (state->read_bytes >= state->target_read_bytes) {
GPR_ASSERT(
GRPC_LOG_IF_ERROR("kick", grpc_pollset_kick(g_pollset, nullptr)));
gpr_mu_unlock(g_mu);
} else {
gpr_mu_unlock(g_mu);
grpc_endpoint_read(state->ep, &state->incoming, &state->read_cb,
/*urgent=*/false);
}
}
/* Write to a socket, then read from it using the grpc_tcp API. */
static void read_test(size_t num_bytes, size_t slice_size) {
int sv[2];
grpc_endpoint* ep;
struct read_socket_state state;
size_t written_bytes;
grpc_millis deadline =
grpc_timespec_to_millis_round_up(grpc_timeout_seconds_to_deadline(20));
grpc_core::ExecCtx exec_ctx;
gpr_log(GPR_INFO, "Read test of size %" PRIuPTR ", slice size %" PRIuPTR,
num_bytes, slice_size);
create_sockets(sv);
grpc_arg a[1];
a[0].key = const_cast<char*>(GRPC_ARG_TCP_READ_CHUNK_SIZE);
a[0].type = GRPC_ARG_INTEGER,
a[0].value.integer = static_cast<int>(slice_size);
grpc_channel_args args = {GPR_ARRAY_SIZE(a), a};
ep =
grpc_tcp_create(grpc_fd_create(sv[1], "read_test", false), &args, "test");
grpc_endpoint_add_to_pollset(ep, g_pollset);
written_bytes = fill_socket_partial(sv[0], num_bytes);
gpr_log(GPR_INFO, "Wrote %" PRIuPTR " bytes", written_bytes);
state.ep = ep;
state.read_bytes = 0;
state.target_read_bytes = written_bytes;
grpc_slice_buffer_init(&state.incoming);
GRPC_CLOSURE_INIT(&state.read_cb, read_cb, &state, grpc_schedule_on_exec_ctx);
grpc_endpoint_read(ep, &state.incoming, &state.read_cb, /*urgent=*/false);
gpr_mu_lock(g_mu);
while (state.read_bytes < state.target_read_bytes) {
grpc_pollset_worker* worker = nullptr;
GPR_ASSERT(GRPC_LOG_IF_ERROR(
"pollset_work", grpc_pollset_work(g_pollset, &worker, deadline)));
gpr_mu_unlock(g_mu);
gpr_mu_lock(g_mu);
}
GPR_ASSERT(state.read_bytes == state.target_read_bytes);
gpr_mu_unlock(g_mu);
grpc_slice_buffer_destroy_internal(&state.incoming);
grpc_endpoint_destroy(ep);
}
/* Write to a socket until it fills up, then read from it using the grpc_tcp
API. */
static void large_read_test(size_t slice_size) {
int sv[2];
grpc_endpoint* ep;
struct read_socket_state state;
ssize_t written_bytes;
grpc_millis deadline =
grpc_timespec_to_millis_round_up(grpc_timeout_seconds_to_deadline(20));
grpc_core::ExecCtx exec_ctx;
gpr_log(GPR_INFO, "Start large read test, slice size %" PRIuPTR, slice_size);
create_sockets(sv);
grpc_arg a[1];
a[0].key = const_cast<char*>(GRPC_ARG_TCP_READ_CHUNK_SIZE);
a[0].type = GRPC_ARG_INTEGER;
a[0].value.integer = static_cast<int>(slice_size);
grpc_channel_args args = {GPR_ARRAY_SIZE(a), a};
ep = grpc_tcp_create(grpc_fd_create(sv[1], "large_read_test", false), &args,
"test");
grpc_endpoint_add_to_pollset(ep, g_pollset);
written_bytes = fill_socket(sv[0]);
gpr_log(GPR_INFO, "Wrote %" PRIuPTR " bytes", written_bytes);
state.ep = ep;
state.read_bytes = 0;
state.target_read_bytes = static_cast<size_t>(written_bytes);
grpc_slice_buffer_init(&state.incoming);
GRPC_CLOSURE_INIT(&state.read_cb, read_cb, &state, grpc_schedule_on_exec_ctx);
grpc_endpoint_read(ep, &state.incoming, &state.read_cb, /*urgent=*/false);
gpr_mu_lock(g_mu);
while (state.read_bytes < state.target_read_bytes) {
grpc_pollset_worker* worker = nullptr;
GPR_ASSERT(GRPC_LOG_IF_ERROR(
"pollset_work", grpc_pollset_work(g_pollset, &worker, deadline)));
gpr_mu_unlock(g_mu);
gpr_mu_lock(g_mu);
}
GPR_ASSERT(state.read_bytes == state.target_read_bytes);
gpr_mu_unlock(g_mu);
grpc_slice_buffer_destroy_internal(&state.incoming);
grpc_endpoint_destroy(ep);
}
struct write_socket_state {
grpc_endpoint* ep;
int write_done;
};
static grpc_slice* allocate_blocks(size_t num_bytes, size_t slice_size,
size_t* num_blocks, uint8_t* current_data) {
size_t nslices = num_bytes / slice_size + (num_bytes % slice_size ? 1u : 0u);
grpc_slice* slices =
static_cast<grpc_slice*>(gpr_malloc(sizeof(grpc_slice) * nslices));
size_t num_bytes_left = num_bytes;
unsigned i, j;
unsigned char* buf;
*num_blocks = nslices;
for (i = 0; i < nslices; ++i) {
slices[i] = grpc_slice_malloc(slice_size > num_bytes_left ? num_bytes_left
: slice_size);
num_bytes_left -= GRPC_SLICE_LENGTH(slices[i]);
buf = GRPC_SLICE_START_PTR(slices[i]);
for (j = 0; j < GRPC_SLICE_LENGTH(slices[i]); ++j) {
buf[j] = *current_data;
(*current_data)++;
}
}
GPR_ASSERT(num_bytes_left == 0);
return slices;
}
static void write_done(void* user_data /* write_socket_state */,
grpc_error_handle error) {
GPR_ASSERT(error == GRPC_ERROR_NONE);
struct write_socket_state* state =
static_cast<struct write_socket_state*>(user_data);
gpr_mu_lock(g_mu);
state->write_done = 1;
GPR_ASSERT(
GRPC_LOG_IF_ERROR("pollset_kick", grpc_pollset_kick(g_pollset, nullptr)));
gpr_mu_unlock(g_mu);
}
void drain_socket_blocking(int fd, size_t num_bytes, size_t read_size) {
unsigned char* buf = static_cast<unsigned char*>(gpr_malloc(read_size));
ssize_t bytes_read;
size_t bytes_left = num_bytes;
int flags;
int current = 0;
int i;
grpc_core::ExecCtx exec_ctx;
flags = fcntl(fd, F_GETFL, 0);
GPR_ASSERT(fcntl(fd, F_SETFL, flags & ~O_NONBLOCK) == 0);
for (;;) {
grpc_pollset_worker* worker = nullptr;
gpr_mu_lock(g_mu);
GPR_ASSERT(GRPC_LOG_IF_ERROR(
"pollset_work",
grpc_pollset_work(g_pollset, &worker,
grpc_timespec_to_millis_round_up(
grpc_timeout_milliseconds_to_deadline(10)))));
gpr_mu_unlock(g_mu);
do {
bytes_read =
read(fd, buf, bytes_left > read_size ? read_size : bytes_left);
} while (bytes_read < 0 && errno == EINTR);
GPR_ASSERT(bytes_read >= 0);
for (i = 0; i < bytes_read; ++i) {
GPR_ASSERT(buf[i] == current);
current = (current + 1) % 256;
}
bytes_left -= static_cast<size_t>(bytes_read);
if (bytes_left == 0) break;
}
flags = fcntl(fd, F_GETFL, 0);
GPR_ASSERT(fcntl(fd, F_SETFL, flags | O_NONBLOCK) == 0);
gpr_free(buf);
}
/* Verifier for timestamps callback for write_test */
void timestamps_verifier(void* arg, grpc_core::Timestamps* ts,
grpc_error_handle error) {
GPR_ASSERT(error == GRPC_ERROR_NONE);
GPR_ASSERT(arg != nullptr);
GPR_ASSERT(ts->sendmsg_time.time.clock_type == GPR_CLOCK_REALTIME);
GPR_ASSERT(ts->scheduled_time.time.clock_type == GPR_CLOCK_REALTIME);
GPR_ASSERT(ts->acked_time.time.clock_type == GPR_CLOCK_REALTIME);
gpr_atm* done_timestamps = static_cast<gpr_atm*>(arg);
gpr_atm_rel_store(done_timestamps, static_cast<gpr_atm>(1));
}
/* Write to a socket using the grpc_tcp API, then drain it directly.
Note that if the write does not complete immediately we need to drain the
socket in parallel with the read. If collect_timestamps is true, it will
try to get timestamps for the write. */
static void write_test(size_t num_bytes, size_t slice_size,
bool collect_timestamps) {
int sv[2];
grpc_endpoint* ep;
struct write_socket_state state;
size_t num_blocks;
grpc_slice* slices;
uint8_t current_data = 0;
grpc_slice_buffer outgoing;
grpc_closure write_done_closure;
grpc_millis deadline =
grpc_timespec_to_millis_round_up(grpc_timeout_seconds_to_deadline(20));
grpc_core::ExecCtx exec_ctx;
if (collect_timestamps && !grpc_event_engine_can_track_errors()) {
return;
}
gpr_log(GPR_INFO,
"Start write test with %" PRIuPTR " bytes, slice size %" PRIuPTR,
num_bytes, slice_size);
if (collect_timestamps) {
create_inet_sockets(sv);
} else {
create_sockets(sv);
}
grpc_arg a[1];
a[0].key = const_cast<char*>(GRPC_ARG_TCP_READ_CHUNK_SIZE);
a[0].type = GRPC_ARG_INTEGER,
a[0].value.integer = static_cast<int>(slice_size);
grpc_channel_args args = {GPR_ARRAY_SIZE(a), a};
ep = grpc_tcp_create(grpc_fd_create(sv[1], "write_test", collect_timestamps),
&args, "test");
grpc_endpoint_add_to_pollset(ep, g_pollset);
state.ep = ep;
state.write_done = 0;
slices = allocate_blocks(num_bytes, slice_size, &num_blocks, ¤t_data);
grpc_slice_buffer_init(&outgoing);
grpc_slice_buffer_addn(&outgoing, slices, num_blocks);
GRPC_CLOSURE_INIT(&write_done_closure, write_done, &state,
grpc_schedule_on_exec_ctx);
gpr_atm done_timestamps;
gpr_atm_rel_store(&done_timestamps, static_cast<gpr_atm>(0));
grpc_endpoint_write(ep, &outgoing, &write_done_closure,
grpc_event_engine_can_track_errors() && collect_timestamps
? &done_timestamps
: nullptr);
drain_socket_blocking(sv[0], num_bytes, num_bytes);
exec_ctx.Flush();
gpr_mu_lock(g_mu);
for (;;) {
grpc_pollset_worker* worker = nullptr;
if (state.write_done &&
(!(grpc_event_engine_can_track_errors() && collect_timestamps) ||
gpr_atm_acq_load(&done_timestamps) == static_cast<gpr_atm>(1))) {
break;
}
GPR_ASSERT(GRPC_LOG_IF_ERROR(
"pollset_work", grpc_pollset_work(g_pollset, &worker, deadline)));
gpr_mu_unlock(g_mu);
exec_ctx.Flush();
gpr_mu_lock(g_mu);
}
gpr_mu_unlock(g_mu);
grpc_slice_buffer_destroy_internal(&outgoing);
grpc_endpoint_destroy(ep);
gpr_free(slices);
}
void on_fd_released(void* arg, grpc_error_handle /*errors*/) {
int* done = static_cast<int*>(arg);
*done = 1;
GPR_ASSERT(
GRPC_LOG_IF_ERROR("pollset_kick", grpc_pollset_kick(g_pollset, nullptr)));
}
/* Do a read_test, then release fd and try to read/write again. Verify that
grpc_tcp_fd() is available before the fd is released. */
static void release_fd_test(size_t num_bytes, size_t slice_size) {
int sv[2];
grpc_endpoint* ep;
struct read_socket_state state;
size_t written_bytes;
int fd;
grpc_millis deadline =
grpc_timespec_to_millis_round_up(grpc_timeout_seconds_to_deadline(20));
grpc_core::ExecCtx exec_ctx;
grpc_closure fd_released_cb;
int fd_released_done = 0;
GRPC_CLOSURE_INIT(&fd_released_cb, &on_fd_released, &fd_released_done,
grpc_schedule_on_exec_ctx);
gpr_log(GPR_INFO,
"Release fd read_test of size %" PRIuPTR ", slice size %" PRIuPTR,
num_bytes, slice_size);
create_sockets(sv);
grpc_arg a[1];
a[0].key = const_cast<char*>(GRPC_ARG_TCP_READ_CHUNK_SIZE);
a[0].type = GRPC_ARG_INTEGER;
a[0].value.integer = static_cast<int>(slice_size);
grpc_channel_args args = {GPR_ARRAY_SIZE(a), a};
ep =
grpc_tcp_create(grpc_fd_create(sv[1], "read_test", false), &args, "test");
GPR_ASSERT(grpc_tcp_fd(ep) == sv[1] && sv[1] >= 0);
grpc_endpoint_add_to_pollset(ep, g_pollset);
written_bytes = fill_socket_partial(sv[0], num_bytes);
gpr_log(GPR_INFO, "Wrote %" PRIuPTR " bytes", written_bytes);
state.ep = ep;
state.read_bytes = 0;
state.target_read_bytes = written_bytes;
grpc_slice_buffer_init(&state.incoming);
GRPC_CLOSURE_INIT(&state.read_cb, read_cb, &state, grpc_schedule_on_exec_ctx);
grpc_endpoint_read(ep, &state.incoming, &state.read_cb, /*urgent=*/false);
gpr_mu_lock(g_mu);
while (state.read_bytes < state.target_read_bytes) {
grpc_pollset_worker* worker = nullptr;
GPR_ASSERT(GRPC_LOG_IF_ERROR(
"pollset_work", grpc_pollset_work(g_pollset, &worker, deadline)));
gpr_log(GPR_DEBUG, "wakeup: read=%" PRIdPTR " target=%" PRIdPTR,
state.read_bytes, state.target_read_bytes);
gpr_mu_unlock(g_mu);
grpc_core::ExecCtx::Get()->Flush();
gpr_mu_lock(g_mu);
}
GPR_ASSERT(state.read_bytes == state.target_read_bytes);
gpr_mu_unlock(g_mu);
grpc_slice_buffer_destroy_internal(&state.incoming);
grpc_tcp_destroy_and_release_fd(ep, &fd, &fd_released_cb);
grpc_core::ExecCtx::Get()->Flush();
gpr_mu_lock(g_mu);
while (!fd_released_done) {
grpc_pollset_worker* worker = nullptr;
GPR_ASSERT(GRPC_LOG_IF_ERROR(
"pollset_work", grpc_pollset_work(g_pollset, &worker, deadline)));
gpr_log(GPR_DEBUG, "wakeup: fd_released_done=%d", fd_released_done);
}
gpr_mu_unlock(g_mu);
GPR_ASSERT(fd_released_done == 1);
GPR_ASSERT(fd == sv[1]);
written_bytes = fill_socket_partial(sv[0], num_bytes);
drain_socket_blocking(fd, written_bytes, written_bytes);
written_bytes = fill_socket_partial(fd, num_bytes);
drain_socket_blocking(sv[0], written_bytes, written_bytes);
close(fd);
}
void run_tests(void) {
size_t i = 0;
read_test(100, 8192);
read_test(10000, 8192);
read_test(10000, 137);
read_test(10000, 1);
large_read_test(8192);
large_read_test(1);
write_test(100, 8192, false);
write_test(100, 1, false);
write_test(100000, 8192, false);
write_test(100000, 1, false);
write_test(100000, 137, false);
write_test(100, 8192, true);
write_test(100, 1, true);
write_test(100000, 8192, true);
write_test(100000, 1, true);
write_test(100, 137, true);
for (i = 1; i < 1000; i = GPR_MAX(i + 1, i * 5 / 4)) {
write_test(40320, i, false);
write_test(40320, i, true);
}
release_fd_test(100, 8192);
}
static void clean_up(void) {}
static grpc_endpoint_test_fixture create_fixture_tcp_socketpair(
size_t slice_size) {
int sv[2];
grpc_endpoint_test_fixture f;
grpc_core::ExecCtx exec_ctx;
create_sockets(sv);
grpc_resource_quota* resource_quota =
grpc_resource_quota_create("tcp_posix_test_socketpair");
grpc_arg a[1];
a[0].key = const_cast<char*>(GRPC_ARG_TCP_READ_CHUNK_SIZE);
a[0].type = GRPC_ARG_INTEGER;
a[0].value.integer = static_cast<int>(slice_size);
grpc_channel_args args = {GPR_ARRAY_SIZE(a), a};
f.client_ep = grpc_tcp_create(grpc_fd_create(sv[0], "fixture:client", false),
&args, "test");
f.server_ep = grpc_tcp_create(grpc_fd_create(sv[1], "fixture:server", false),
&args, "test");
grpc_resource_quota_unref_internal(resource_quota);
grpc_endpoint_add_to_pollset(f.client_ep, g_pollset);
grpc_endpoint_add_to_pollset(f.server_ep, g_pollset);
return f;
}
static grpc_endpoint_test_config configs[] = {
{"tcp/tcp_socketpair", create_fixture_tcp_socketpair, clean_up},
};
static void destroy_pollset(void* p, grpc_error_handle /*error*/) {
grpc_pollset_destroy(static_cast<grpc_pollset*>(p));
}
int main(int argc, char** argv) {
grpc_closure destroyed;
grpc::testing::TestEnvironment env(argc, argv);
grpc_init();
grpc_core::grpc_tcp_set_write_timestamps_callback(timestamps_verifier);
{
grpc_core::ExecCtx exec_ctx;
g_pollset = static_cast<grpc_pollset*>(gpr_zalloc(grpc_pollset_size()));
grpc_pollset_init(g_pollset, &g_mu);
grpc_endpoint_tests(configs[0], g_pollset, g_mu);
run_tests();
GRPC_CLOSURE_INIT(&destroyed, destroy_pollset, g_pollset,
grpc_schedule_on_exec_ctx);
grpc_pollset_shutdown(g_pollset, &destroyed);
grpc_core::ExecCtx::Get()->Flush();
}
grpc_shutdown();
gpr_free(g_pollset);
return 0;
}
#else /* GRPC_POSIX_SOCKET_TCP */
int main(int argc, char** argv) { return 1; }
#endif /* GRPC_POSIX_SOCKET_TCP */<|fim▁end|> | |
<|file_name|>radchat.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python2
import os,sys,socket,select
from time import strftime
variables = ['name','tripcode']
servercommands = ["/pm", "/peoplecount"]
def date():
return strftime(".%Y-%m-%d")
def chat_client(inputsocket,data,location):
#initialize radchat client files
if not os.path.exists(location+'/resources/programparts/radchat'): os.makedirs(location+'/resources/programparts/radchat')
if not os.path.exists(location+'/resources/programparts/radchat/logs'): os.makedirs(location+'/resources/programparts/radchat/logs')
if not os.path.exists(location+'/resources/programparts/radchat/settings.txt'):
with open(location+'/resources/programparts/radchat/settings.txt', "a") as settingsfile:
settingsfile.write("")
#introduce variables
name = data[0]
tripcode = data[1]
#if there is a settings file, read it
if os.path.isfile(location + '/resources/programparts/radchat/settings.txt'):<|fim▁hole|> if line.split()[0] == "name":
name = line[5:].replace("\n","")
if line.split()[0] == "tripcode":
tripcode = line[9:].replace("\n", "")
if line.split()[0] == "host":
host = line[5:].replace("\n","")
if line.split()[0] == "port":
port = int(line[5:].replace("\n",""))
s = inputsocket
sys.stdout.write("\n[{}] ".format(name)); sys.stdout.flush()
while 1:
socket_list = [sys.stdin, s]
# Get the list sockets which are readable
ready_to_read,ready_to_write,in_error = select.select(socket_list , [], [])
for sock in ready_to_read:
if sock == s:
# incoming message from remote server, s
data = sock.recv(4096)
if not data :
print '\nDisconnected from chat server'
return
else :
with open(location+'/resources/programparts/radchat/logs/client'+date(), "a") as log:
log.write(data + "\n")
os.system('cls' if os.name == 'nt' else 'tput reset') #cross platform screen clearing. this just in, clears the ENTIRE SHELL
with open(location+'/resources/programparts/radchat/logs/client'+date(), "r") as log:
sys.stdout.write(log.read()) #prints the entire log. alll of it.
sys.stdout.write('\n\n[{}] '.format(name)) # skips to new first line, rewrites name.
sys.stdout.flush()
else :
# user entered a message
message = sys.stdin.readline().replace("\n", "")
if message:
if message[0] == "/" and message.split()[0] not in servercommands:
#that message was a command
if message.split()[0] == "/changename":
name = message[len(message.split()[0])+1:].replace("\n","")
if not name:
name = "Anonymous"
elif message.split()[0] == "/changetripcode":
tripcode = message[len(message.split()[0])+1:].replace("\n","")
elif message.split()[0] == "/exit" or message.split()[0] == "/quit" or message.split()[0] == "/leave":
print "Leaving chat server."
return
elif message.split()[0] == "/help" or message.split()[0] == "/?":
sys.stdout.write("\nThanks for using the radchat client. Here are the commands you currently have available:\n/changename + new name: changes your name\n/changetripcode + new tripcode: changes your trip code.\n/quit OR /leave: exits gracefully\n/help OR /?: Displays this menu.\n")
else:
print "Invalid command"
else:
#format all the data and send it
s.send("{}\n{}\n{}".format(message, name, tripcode))
sys.stdout.write('[{}] '.format(name))
sys.stdout.flush()<|fim▁end|> | with open(location + '/resources/programparts/radchat/settings.txt') as settingsfile:
for line in settingsfile: |
<|file_name|>slider-test.js<|end_file_name|><|fim▁begin|>import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';<|fim▁hole|>
module('Unit | Service | slider', function(hooks) {
setupTest(hooks);
// Replace this with your real tests.
test('it exists', function(assert) {
let service = this.owner.lookup('service:slider');
assert.ok(service);
});
});<|fim▁end|> | |
<|file_name|>res_partner_address.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2013 - TODAY Denero Team. (<http://www.deneroteam.com>)
# All Rights Reserved
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import orm, fields
from openerp import addons
from openerp.tools.translate import _
class res_partner_title(orm.Model):
_inherit = "res.partner.title"
_order = "sequence"
_columns = {
'sequence': fields.integer('Sequence'),
}
_defaults = {
'sequence': 1,
}
class res_contact_function(orm.Model):
_name = "res.contact.function"
_description = "Contact Function"
_order = "name"
_columns = {
'name': fields.char('Name', size=32),
}
class res_partner_address_contact(orm.Model):
_name = "res.partner.address.contact"
_description = "Address Contact"
def name_get(self, cr, uid, ids, context=None):
res = []
for rec in self.browse(cr, uid, ids, context=context):
if rec.title:
res.append((rec.id, rec.title.name + ' ' + rec.last_name + ' ' + (rec.first_name or '')))
else:
res.append((rec.id, rec.last_name + ' ' + (rec.first_name or '')))
return res
def _name_get_full(self, cr, uid, ids, prop, unknow_none, context=None):
result = {}
for rec in self.browse(cr, uid, ids, context=context):
if rec.title:
result[rec.id] = rec.title.name + ' ' + rec.last_name + ' ' + (rec.first_name or '')
else:
result[rec.id] = rec.last_name + ' ' + (rec.first_name or '')
return result
_columns = {
'complete_name': fields.function(_name_get_full, string='Name', size=64, type="char", store=False, select=True),
'name': fields.char('Name', size=64, ),
'last_name': fields.char('Last Name', size=64, required=True),
'first_name': fields.char('First Name', size=64),
'mobile': fields.char('Mobile', size=64),
'fisso': fields.char('Phone', size=64),
'title': fields.many2one('res.partner.title', 'Title', domain=[('domain', '=', 'contact')]),
'website': fields.char('Website', size=120),
'address_id': fields.many2one('res.partner.address', 'Address'),
'partner_id': fields.related(
'address_id', 'partner_id', type='many2one', relation='res.partner', string='Main Employer'),
'lang_id': fields.many2one('res.lang', 'Language'),
'country_id': fields.many2one('res.country', 'Nationality'),
'birthdate': fields.char('Birthdate', size=64),
'active': fields.boolean('Active', help="If the active field is set to False,\
it will allow you to hide the partner contact without removing it."),
'email': fields.char('E-Mail', size=240),
'comment': fields.text('Notes', translate=True),
'photo': fields.binary('Photo'),
'function': fields.char("Function", size=64),
'function_id': fields.many2one('res.contact.function', 'Function'),
}
def _get_photo(self, cr, uid, context=None):
photo_path = addons.get_module_resource('base_address_contacts', 'images', 'photo.png')
return open(photo_path, 'rb').read().encode('base64')
_defaults = {
'name': '/',
'photo': _get_photo,
'active': True,
'address_id': lambda self, cr, uid, context: context.get('address_id', False),
}
_order = "last_name"
def name_search(self, cr, uid, name='', args=None, operator='ilike', context=None, limit=None):
if not args:
args = []
if context is None:
context = {}
if name:
ids = self.search(
cr, uid, ['|', ('last_name', operator, name), ('first_name', operator, name)] + args, limit=limit,
context=context)
else:
ids = self.search(cr, uid, args, limit=limit, context=context)
return self.name_get(cr, uid, ids, context=context)
def create(self, cr, uid, vals, context=None):
if context is None:
context = {}
name = ''
update = False
if vals.get('last_name', False):
name += vals['last_name']
update = True
if vals.get('first_name', False):
name += ' ' + vals['first_name']
update = True
if update:
vals['name'] = name
return super(res_partner_address_contact, self).create(cr, uid, vals, context=context)
def write(self, cr, uid, ids, vals, context=None):
if context is None:
context = {}
name = ''
update = False
if vals.get('last_name', False):
name += vals['last_name']
update = True
if vals.get('first_name', False):
name += ' ' + vals['first_name']
update = True
if update:
vals['name'] = name
return super(res_partner_address_contact, self).write(cr, uid, ids, vals, context)
class res_partner_address(orm.Model):
_inherit = 'res.partner.address'
def get_full_name(self, cr, uid, ids, field_name, arg, context=None):
res = {}
for re in self.browse(cr, uid, ids, context=context):
addr = ''
if re.partner_id:
if re.partner_id.name != re.name:
addr = re.name or ''
if re.name and (re.city or re.country_id):
addr += ', '
addr += (re.city or '') + ', ' + (re.street or '')
if re.partner_id and context.get('contact_display', False) == 'partner_address':
addr = "%s: %s" % (re.partner_id.name, addr.strip())
else:
addr = addr.strip()
res[re.id] = addr or ''
return res
def name_get(self, cr, uid, ids, context=None):
if not len(ids):
return []
res = []
length = context.get('name_lenght', False) or 45
for record in self.browse(cr, uid, ids, context=context):
name = record.complete_name or record.name or ''
if len(name) > length:
name = name[:length] + '...'
res.append((record.id, name))
return res
def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=100):
if not args:
args = []
if context is None:
context = {}
ids = []
name_array = name.split()
search_domain = []
for n in name_array:
search_domain.append('|')
search_domain.append(('name', operator, n))
search_domain.append(('complete_name', operator, n))
ids = self.search(cr, user, search_domain + args, limit=limit, context=context)
return self.name_get(cr, user, ids, context=context)
_columns = {
'partner_id': fields.many2one('res.partner', 'Partner Name', ondelete='set null', select=True, help="Keep empty for a private address, not related to partner.", required=True),
'contact_ids': fields.one2many('res.partner.address.contact', 'address_id', 'Functions and Contacts'),
'mobile': fields.char('Mobile', size=64),
'pec': fields.char('PEC', size=64),
'complete_name': fields.function(get_full_name, method=True, type='char', size=1024, readonly=True, store=False),
}
class res_partner(orm.Model):
_inherit = 'res.partner'
def _get_contacts(self, cr, uid, ids, field_name, arg, context=None):
result = {}
for partner in self.browse(cr, uid, ids, context):
result[partner.id] = []
for address in partner.address:
result[partner.id] += [contact.id for contact in address.contact_ids]
return result
def create(self, cr, uid, vals, context):
if context is None:
context = {}
if context.get('import', False):
return super(res_partner, self).create(cr, uid, vals, context)
if not vals.get('address', False) and context.get('default_type', '') != 'lead':
raise orm.except_orm(_('Error!'),
_('At least one address of type "Default" is needed!'))
is_default = False
if context.get('default_type', '') == 'lead':
return super(res_partner, self).create(cr, uid, vals, context)
for address in vals['address']:
if address[2].get('type') == 'default':
is_default = True
if not is_default:
raise orm.except_orm(_('Error!'),
_('At least one address of type "Default" is needed!'))
return super(res_partner, self).create(cr, uid, vals, context)
def write(self, cr, uid, ids, vals, context=None):
if context is None:
context = {}
if vals.get('address', False):
for address in vals['address']:
if address[0] == 2: # 2 means 'delete'
if self.pool['res.partner.address'].browse(cr, uid, address[1], context).type == 'default':
raise orm.except_orm(_('Error!'),
_('At least one address of type "Default" is needed!'))
return super(res_partner, self).write(cr, uid, ids, vals, context)
def unlink(self, cr, uid, ids, context):<|fim▁hole|> if context is None:
context = {}
for partner in self.browse(cr, uid, ids, context):
if partner.address:
raise orm.except_orm(_('Error!'),
_('Before Delete the Partner, you need to delete the Address from menù'))
return super(res_partner, self).unlink(cr, uid, ids, context)
_columns = {
'contact_ids': fields.function(_get_contacts, string=_("Functions and Contacts"), type='one2many', method=True, obj='res.partner.address.contact')
}<|fim▁end|> | |
<|file_name|>new.rs<|end_file_name|><|fim▁begin|>#![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::atomic::AtomicIsize;
use core::atomic::Ordering::Relaxed;
// pub struct AtomicIsize {
// v: UnsafeCell<isize>,
// }
// impl Default for AtomicIsize {
// fn default() -> Self {
// Self::new(Default::default())
// }
// }
// unsafe impl Sync for AtomicIsize {}
// #[derive(Copy, Clone)]
// pub enum Ordering {
// /// No ordering constraints, only atomic operations.
// #[stable(feature = "rust1", since = "1.0.0")]
// Relaxed,
// /// When coupled with a store, all previous writes become visible
// /// to another thread that performs a load with `Acquire` ordering
// /// on the same value.
// #[stable(feature = "rust1", since = "1.0.0")]
// Release,
// /// When coupled with a load, all subsequent loads will see data
// /// written before a store with `Release` ordering on the same value
// /// in another thread.
// #[stable(feature = "rust1", since = "1.0.0")]
// Acquire,
// /// When coupled with a load, uses `Acquire` ordering, and with a store
// /// `Release` ordering.
// #[stable(feature = "rust1", since = "1.0.0")]
// AcqRel,
// /// Like `AcqRel` with the additional guarantee that all threads see all
// /// sequentially consistent operations in the same order.
// #[stable(feature = "rust1", since = "1.0.0")]<|fim▁hole|> // }
// impl AtomicIsize {
// /// Creates a new `AtomicIsize`.
// ///
// /// # Examples
// ///
// /// ```
// /// use std::sync::atomic::AtomicIsize;
// ///
// /// let atomic_forty_two = AtomicIsize::new(42);
// /// ```
// #[inline]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub const fn new(v: isize) -> AtomicIsize {
// AtomicIsize {v: UnsafeCell::new(v)}
// }
//
// /// Loads a value from the isize.
// ///
// /// `load` takes an `Ordering` argument which describes the memory ordering of this operation.
// ///
// /// # Panics
// ///
// /// Panics if `order` is `Release` or `AcqRel`.
// ///
// /// # Examples
// ///
// /// ```
// /// use std::sync::atomic::{AtomicIsize, Ordering};
// ///
// /// let some_isize = AtomicIsize::new(5);
// ///
// /// assert_eq!(some_isize.load(Ordering::Relaxed), 5);
// /// ```
// #[inline]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub fn load(&self, order: Ordering) -> isize {
// unsafe { atomic_load(self.v.get(), order) }
// }
//
// /// Stores a value into the isize.
// ///
// /// `store` takes an `Ordering` argument which describes the memory ordering of this operation.
// ///
// /// # Examples
// ///
// /// ```
// /// use std::sync::atomic::{AtomicIsize, Ordering};
// ///
// /// let some_isize = AtomicIsize::new(5);
// ///
// /// some_isize.store(10, Ordering::Relaxed);
// /// assert_eq!(some_isize.load(Ordering::Relaxed), 10);
// /// ```
// ///
// /// # Panics
// ///
// /// Panics if `order` is `Acquire` or `AcqRel`.
// #[inline]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub fn store(&self, val: isize, order: Ordering) {
// unsafe { atomic_store(self.v.get(), val, order); }
// }
//
// /// Stores a value into the isize, returning the old value.
// ///
// /// `swap` takes an `Ordering` argument which describes the memory ordering of this operation.
// ///
// /// # Examples
// ///
// /// ```
// /// use std::sync::atomic::{AtomicIsize, Ordering};
// ///
// /// let some_isize = AtomicIsize::new(5);
// ///
// /// assert_eq!(some_isize.swap(10, Ordering::Relaxed), 5);
// /// ```
// #[inline]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub fn swap(&self, val: isize, order: Ordering) -> isize {
// unsafe { atomic_swap(self.v.get(), val, order) }
// }
//
// /// Stores a value into the `isize` if the current value is the same as the `current` value.
// ///
// /// The return value is always the previous value. If it is equal to `current`, then the value
// /// was updated.
// ///
// /// `compare_and_swap` also takes an `Ordering` argument which describes the memory ordering of
// /// this operation.
// ///
// /// # Examples
// ///
// /// ```
// /// use std::sync::atomic::{AtomicIsize, Ordering};
// ///
// /// let some_isize = AtomicIsize::new(5);
// ///
// /// assert_eq!(some_isize.compare_and_swap(5, 10, Ordering::Relaxed), 5);
// /// assert_eq!(some_isize.load(Ordering::Relaxed), 10);
// ///
// /// assert_eq!(some_isize.compare_and_swap(6, 12, Ordering::Relaxed), 10);
// /// assert_eq!(some_isize.load(Ordering::Relaxed), 10);
// /// ```
// #[inline]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub fn compare_and_swap(&self, current: isize, new: isize, order: Ordering) -> isize {
// unsafe { atomic_compare_and_swap(self.v.get(), current, new, order) }
// }
//
// /// Add an isize to the current value, returning the previous value.
// ///
// /// # Examples
// ///
// /// ```
// /// use std::sync::atomic::{AtomicIsize, Ordering};
// ///
// /// let foo = AtomicIsize::new(0);
// /// assert_eq!(foo.fetch_add(10, Ordering::SeqCst), 0);
// /// assert_eq!(foo.load(Ordering::SeqCst), 10);
// /// ```
// #[inline]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub fn fetch_add(&self, val: isize, order: Ordering) -> isize {
// unsafe { atomic_add(self.v.get(), val, order) }
// }
//
// /// Subtract an isize from the current value, returning the previous value.
// ///
// /// # Examples
// ///
// /// ```
// /// use std::sync::atomic::{AtomicIsize, Ordering};
// ///
// /// let foo = AtomicIsize::new(0);
// /// assert_eq!(foo.fetch_sub(10, Ordering::SeqCst), 0);
// /// assert_eq!(foo.load(Ordering::SeqCst), -10);
// /// ```
// #[inline]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub fn fetch_sub(&self, val: isize, order: Ordering) -> isize {
// unsafe { atomic_sub(self.v.get(), val, order) }
// }
//
// /// Bitwise and with the current isize, returning the previous value.
// ///
// /// # Examples
// ///
// /// ```
// /// use std::sync::atomic::{AtomicIsize, Ordering};
// ///
// /// let foo = AtomicIsize::new(0b101101);
// /// assert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101);
// /// assert_eq!(foo.load(Ordering::SeqCst), 0b100001);
// #[inline]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub fn fetch_and(&self, val: isize, order: Ordering) -> isize {
// unsafe { atomic_and(self.v.get(), val, order) }
// }
//
// /// Bitwise or with the current isize, returning the previous value.
// ///
// /// # Examples
// ///
// /// ```
// /// use std::sync::atomic::{AtomicIsize, Ordering};
// ///
// /// let foo = AtomicIsize::new(0b101101);
// /// assert_eq!(foo.fetch_or(0b110011, Ordering::SeqCst), 0b101101);
// /// assert_eq!(foo.load(Ordering::SeqCst), 0b111111);
// #[inline]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub fn fetch_or(&self, val: isize, order: Ordering) -> isize {
// unsafe { atomic_or(self.v.get(), val, order) }
// }
//
// /// Bitwise xor with the current isize, returning the previous value.
// ///
// /// # Examples
// ///
// /// ```
// /// use std::sync::atomic::{AtomicIsize, Ordering};
// ///
// /// let foo = AtomicIsize::new(0b101101);
// /// assert_eq!(foo.fetch_xor(0b110011, Ordering::SeqCst), 0b101101);
// /// assert_eq!(foo.load(Ordering::SeqCst), 0b011110);
// #[inline]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub fn fetch_xor(&self, val: isize, order: Ordering) -> isize {
// unsafe { atomic_xor(self.v.get(), val, order) }
// }
// }
// pub const ATOMIC_ISIZE_INIT: AtomicIsize = AtomicIsize::new(0);
#[test]
fn new_test1() {
let atomicisize: AtomicIsize = AtomicIsize::new(0);
let result: isize = atomicisize.load(Relaxed);
assert_eq!(result, 0);
}
#[test]
fn new_test2() {
let atomicisize: AtomicIsize = AtomicIsize::new(68);
let result: isize = atomicisize.load(Relaxed);
assert_eq!(result, 68);
}
#[test]
fn new_test3() {
let atomicisize: AtomicIsize = AtomicIsize::new(-68);
let result: isize = atomicisize.load(Relaxed);
assert_eq!(result, -68);
}
}<|fim▁end|> | // SeqCst, |
<|file_name|>next_in_inclusive_range.rs<|end_file_name|><|fim▁begin|>use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base::num::random::variable_range_generator;
use malachite_base::random::EXAMPLE_SEED;
use std::panic::catch_unwind;
fn next_in_inclusive_range_helper<T: PrimitiveUnsigned>(a: T, b: T, expected_values: &[T]) {
let mut range_generator = variable_range_generator(EXAMPLE_SEED);
let mut xs = Vec::with_capacity(20);
for _ in 0..20 {
xs.push(range_generator.next_in_inclusive_range(a, b))
}
assert_eq!(xs, expected_values);
}
#[test]
fn test_next_in_inclusive_range() {
next_in_inclusive_range_helper::<u8>(5, 5, &[5; 20]);
next_in_inclusive_range_helper::<u16>(
1,<|fim▁hole|> &[2, 6, 4, 2, 3, 5, 6, 2, 3, 6, 5, 1, 6, 1, 3, 6, 3, 1, 5, 1],
);
next_in_inclusive_range_helper::<u32>(
10,
19,
&[11, 17, 15, 14, 16, 14, 12, 18, 11, 17, 15, 10, 12, 16, 13, 15, 12, 12, 19, 15],
);
next_in_inclusive_range_helper::<u8>(
0,
u8::MAX,
&[
113, 239, 69, 108, 228, 210, 168, 161, 87, 32, 110, 83, 188, 34, 89, 238, 93, 200, 149,
115,
],
);
}
fn next_in_inclusive_range_fail_helper<T: PrimitiveUnsigned>() {
assert_panic!({
let mut range_generator = variable_range_generator(EXAMPLE_SEED);
range_generator.next_in_inclusive_range(T::TWO, T::ONE);
});
}
#[test]
fn next_in_inclusive_range_fail() {
apply_fn_to_unsigneds!(next_in_inclusive_range_fail_helper);
}<|fim▁end|> | 6, |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | from growler_guys import scrape_growler_guys |
<|file_name|>update_api.py<|end_file_name|><|fim▁begin|>import logging
from django.core.management.base import BaseCommand
from readthedocs.projects import tasks
from readthedocs.api.client import api
log = logging.getLogger(__name__)
class Command(BaseCommand):
"""
Build documentation using the API and not hitting a database.
Usage::
./manage.py update_api <slug>
"""
def add_arguments(self, parser):
parser.add_argument('--docker', action='store_true', default=False)
parser.add_argument('projects', nargs='+', type=str)<|fim▁hole|> project_data = api.project(slug).get()
p = tasks.make_api_project(project_data)
log.info("Building %s" % p)
tasks.update_docs.run(pk=p.pk, docker=docker)<|fim▁end|> |
def handle(self, *args, **options):
docker = options.get('docker', False)
for slug in options['projects']: |
<|file_name|>rustplugin.rs<|end_file_name|><|fim▁begin|>// compile with
// rustc --crate-type dylib rustplugin.rs
// on windows:
// rustc --crate-type cdylib -C opt-level=3 -C link-args=-s -C prefer-dynamic rustplugin.rs
use std::os::raw::{c_void,c_char,c_uchar,c_int,c_uint,c_double,c_float};
use std::ffi::CString;
const VOO_PLUGIN_API_VERSION: i32 = 6;
// display pixel data type
#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[repr(C)]
pub struct voo_target_space_t
{
b: c_uchar,
g: c_uchar,<|fim▁hole|> r: c_uchar,
x: c_uchar,
}
#[allow(dead_code)]
#[allow(non_camel_case_types)]
pub enum voo_colorSpace_t {
vooColorSpace_Unknown = -1,
vooCS_YUV,
vooCS_XYZ,
vooCS_YIQ,
vooCS_RGB,
vooCS_Gray,
vooCS_HSV,
vooCS_YCgCo,
vooCS_ICtCp
}
#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
pub enum voo_dataArrangement_t {
vooDataArrangement_Unknown = -1,
vooDA_planar_420,
vooDA_planar_422,
vooDA_planar_444,
vooDA_planar_410,
vooDA_planar_411,
vooDA_uyvy,
vooDA_yuyv,
vooDA_yuy2,
vooDA_nv12,
vooDA_v210,
vooDA_interleaved_410,
vooDA_interleaved_411,
vooDA_reserved0,
vooDA_interleaved_422,
vooDA_interleaved_444,
vooDA_single,
vooDA_singleDouble,
vooDA_singleFloat,
vooDA_planar_420double,
vooDA_planar_422double,
vooDA_planar_444double,
vooDA_planar_410double,
vooDA_planar_411double,
vooDA_planar_420float,
vooDA_planar_422float,
vooDA_planar_444float,
vooDA_planar_410float,
vooDA_planar_411float,
vooDA_rgb565,
vooDA_rgb555,
vooDA_r210,
vooDA_v410,
vooDA_yuv10,
vooDA_p010,
vooDA_p016,
vooDA_interleaved_444float,
vooDA_interleaved_444double,
vooNumDataArrangements
}
#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
pub enum voo_channelOrder_t
{
vooChannelOrder_Unknown = -1,
vooCO_c123,
vooCO_c231,
vooCO_c312,
vooCO_c213,
vooCO_c321,
vooCO_c132,
vooCO_c123x,
vooCO_c231x,
vooCO_c312x,
vooCO_c213x,
vooCO_c321x,
vooCO_c132x,
vooNumChannelOrders
}
#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
#[repr(C)]
pub struct voo_sequence_t {
pub filename: *const c_char,
// video resolution
pub width: c_int,
pub height: c_int,
// frames per seconds
pub fps: c_double,
// Color space, such as YUV, RGB etc.
pub colorSpace: voo_colorSpace_t,
// How the channels are packed or interleaved
arrangement: voo_dataArrangement_t,
// The order in which color channels are written
channel_order: voo_channelOrder_t,
// size in bytes of a single video frame in native format
framesize: c_uint,
// Bits per channel is normally 8 or 10-16 (valid bit depths are 1-16) (if integer)
bitsPerChannel: c_int,
// Whether the video shall be played upside down
b_flipped: c_int,
// Whether 16bit words shall be byte-swapped
b_toggle_endian: c_int,
// Whether the values (if integer) shall be treated as signed integers
b_signed: c_int,
// number of frames in sequences
frame_count: c_uint,
// Chroma subsampling. Set, but never read by vooya.
chroma_subsampling_hor: c_int,
chroma_subsampling_ver: c_int,
reserved: [c_char; 20],
}
// structure vooya gives you in on_load_video( ... ).
#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
#[repr(C)]
pub struct voo_app_info_t {
// a handle to vooya's current window (what it is, is platform dependent)
p_handle: *const c_void,
// to trigger vooya to a reload a frame, use these like:
// p_app_info.pf_trigger_reload( app_info.p_reload_cargo )
// note that this should happen not too often.
p_reload_cargo: *const c_void,
pf_trigger_reload: extern fn(p_reload_cargo: *const c_void) -> c_int,
// send a message to the console window in vooya
p_message_cargo: *const c_void,
pf_console_message: extern fn(p_message_cargo: *const c_void, message: *const c_char ) -> c_void,
reserved: [c_char; 32],
}
// Structure you get in per-frame callback functions.
#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
#[repr(C)]
pub struct voo_video_frame_metadata_t {
// user data you might have provided in voo_describe( ... ) as voo_plugin_t::p_user
p_user: *const c_void,
// per-sequence user data you might have provided in voo_plugin_t::on_load_video( ... )
p_user_video: *const c_void,
// per-frame user data you might have provided in input_plugin_t::load( ... )
p_user_frame: *const c_void,
p_info: *const voo_sequence_t, // info about the current sequence
// frame number, beginning at zero
frame_idx: c_uint,
// Tells vooya to display text for the given frame at the given position x,y relative to the video resolution.
// This function can be called from within an on_frame_done callback (and only from there)
// For "flags" see vooPluginTextFlag... below.
pfun_add_text: extern fn( p_cargo: *const c_void, text: *const c_char, flags: c_int, x: c_int, y: c_int ) -> c_void,
// Tells vooya to clear all text for the given frame.
// This function can be called from within an on_frame_done callback (and only from there)
pfun_clear_all: extern fn( p_cargo: *const c_void ) -> c_void,
p_textfun_cargo: *const c_void,
flags: c_int,
reserved: [c_char; 32],
}
#[allow(dead_code)]
#[allow(non_upper_case_globals)]
const vooPluginTextFlag_AlignRight: i32 = 0x01;
#[allow(dead_code)]
#[allow(non_upper_case_globals)]
const vooPluginTextFlag_AlignCenter: i32 = 0x02;
#[allow(dead_code)]
#[allow(non_upper_case_globals)]
const VOOPerFrameFlag_YouAlreadyProcessed: i32 = 0x01; // this frame has already been processed by you
#[allow(dead_code)]
#[allow(non_upper_case_globals)]
const VOOPerFrameFlag_IsFromCache: i32 = 0x02; // this one comes from RGB-display cache
#[allow(dead_code)]
#[allow(non_upper_case_globals)]
const VOOPerFrameFlag_IsDifference: i32 = 0x04; // this frame is a difference frame
// structure that is passed to pixel-wise difference callbacks.
// represents one pixel in the respective frame.
#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
#[repr(C)]
pub struct voo_diff_t_float
{
// Pixel buffer a and b from sequence A and B, component 1,2,3
// and data type (inferred from voo_sequence_t::p_info)
c1_a: *mut c_float,
c2_a: *mut c_float,
c3_a: *mut c_float,
c1_b: *mut c_float,
c2_b: *mut c_float,
c3_b: *mut c_float,
stride: c_int,
p_metadata: *const voo_video_frame_metadata_t
}
// PLUGIN CALLBACK FUNCTION STRUCT
//
// This struct shall contain user-defined callback functions along with some metadata.
// First the callback types:
#[allow(dead_code)]
#[allow(non_camel_case_types)]
enum vooya_callback_type_t {
vooCallback_Native,
vooCallback_RGBOut,
vooCallback_EOTF,
vooCallback_Histogram,
vooCallback_Diff,
}
#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[repr(C)]
pub struct vooya_callback_t
{
// The following strings must be set and be persistent throughout plugin's linkage.
// uid must not be empty or NULL.
uid: *const c_char, // a unique string, e.g. "myplugin.rgb_invert.1",
// at most 63 chars in length, ANSI without any whitespace
name: *const c_char, // a user-friendly, descriptive name
description: *const c_char, // a more in-depth description
// Functions vooya will call upon user's (de)selection of this callback (optional)
on_select: unsafe extern fn( p_info: *const voo_sequence_t, p_app_info: *const voo_app_info_t, p_user: *const c_void, pp_user_video: *const *mut c_void ) -> (),
on_deselect: unsafe extern fn( p_user: *const c_void, p_user_video: *const c_void ) -> (),
// this function will be called when a frame has completed processing and is about to be displayed.
// May be called multiple times for the same frame.
on_frame_done: extern fn( p_metadata: *const voo_video_frame_metadata_t ) -> c_void,
// Flags to signal something to vooya (for future use)
flags: i32,
// type determines which callback signature will be called
e_type: vooya_callback_type_t,
// actual callback function (required, see below)
method: *const c_void,
// For type == vooCallback_RGBOut:
// Called by vooya for each video frame with rgb data ready to be rendered,
// i.e. color-converted, range-shifted to 8bit and with EOTF and image
// adjustments applied. Can be used to feed the data outside of vooya as
// well as to alter the data right before display.
// Stride in bytes is equal to width*sizeof(voo_target_space_t).
// method shall be:
// unsafe extern fn( p_data: *mut voo_target_space_t, p_metadata: *const voo_video_frame_metadata_t ) -> (),
// For type == vooCallback_Native:
// Called by vooya for each video frame with native data before color
// conversion to RGB 8bit, and without image adjustments. Can be used to
// feed the data outside of vooya. Properties like resolution
// and data format are given beforehand in on_load_video( ... ); you can
// save them in p_metadata->p_user_video. "p_data" is the image data.
// method shall be
// unsafe extern fn( ch1: *mut c_float, ch2: *mut c_float, ch3: *mut c_float, stride: mut c_int, p_metadata: *const voo_video_frame_metadata_t ) -> (),
// For type == vooCallback_EOTF:
// Called by vooya when a lookup-table for the transfer function is being made.
// "value" is in the range of 0-1, representing an RGB channel value of input bit
// depth ("bits"). "p_user" might be provided by you from within voo_describe(...)
// and can be NULL or any custom data. The call of this function happens before
// application of brightness, contrast, gamma and exposure user settings.
// method shall be:
// unsafe extern fn( value: c_double, bits: c_int, p_user: *const c_void ) -> c_double,
// For type == vooCallback_Histogram:
// Called by vooya for each frame if histogram calculation (and display) is enabled.
// The three pointers contain the histograms for each channel respectively. Their
// length is (1<<bit_depth)-1 (floating point data is put into 12bits).
// method shall be:
// unsafe extern fn( p_h1: *const c_uint, p_h2: *const c_uint, p_h3: *const c_uint,
// p_metadata: *const voo_video_frame_metadata_t ) -> (),
// For type == vooCallback_Diff:
// Called by vooya when two sequences are being compared.
// This method is called pixel-wise and thus not the fastest. Note that multiple threads
// (all for the same frame) might call this function concurrently.
// see also voo_diff_t_...
// method shall be:
// unsafe extern fn( p_diff_pixel : *const voo_diff_t ) -> ()
}
// INPUT DESCRIPTION STRUCT
//
// Container to provide custom input to vooya from file or from "nowhere".
#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
#[repr(C)]
struct input_plugin_t {
uid: *const c_char, // a unique string, e.g. "myplugin.text.input",
// at most 63 chars in length, ANSI without any whitespace
name: *const c_char, // a user-friendly, descriptive name (mandatory)
description: *const c_char, // a more in-depth description
// If b_fileBased is TRUE, vooya will ask for file suffixes supported by this input,
// call file_suffixes( ... ), responsible( ... ) and open( ... ), and will include
// this input in the file open dialog. If b_fileBased is FALSE, an entry for this input
// will be displayed in the plugins-menu that the user can select as current input.
// In that case, vooya will call open_nowhere( ... ).
b_fileBased: i32,
// Flags to signal something to vooya (for future use)
flags: i32,
reserved1: [c_char; 8],
// If the input is file-based, responsible will be called with the file name and the
// first sixteen bytes of data, which e.g. might contain magic data. p_user is
// voo_plugin_t::p_user. If responsible returns TRUE, open will be called.
// Only if input comes from stdin and "--container [your input UID]" is specified,
// responsible will not be called, but open( ... ) directly.
// For stdin, the filename is simply "-".
// FIXME: filename not a c_char in Windows
responsible: unsafe extern fn( filename: *const c_char, sixteen_bytes: *const c_char, p_user: *const c_void ) -> c_int,
// The global p_user pointer you may have set in voo_describe( ... )
// is given here as *pp_user_seq, but you can alter it. In that case, subsequent
// calls to methods of this struct will have the new, per-sequence value. This is
// important on macOS, where multiple instances of this input may exist.
open: unsafe extern fn( filename: *const c_char, p_app_info: *const voo_app_info_t, pp_user_seq: *const *mut c_void ) -> c_int,
// If the input is not based on file input (b_fileBased is FALSE),
// open_nowhere will be called. The global p_user pointer you may have set in
// voo_describe( ... ) is given here as *pp_user_seq, but you can alter it.
// In that case, subsequent calls to methods of this struct will have the new,
// per-sequence value. This is important on macOS, where multiple instances
// of this input may exist.
open_nowhere: unsafe extern fn( p_app_info: *const voo_app_info_t, pp_user_seq: *const *mut c_void ) -> c_int,
// Called by vooya to get information about the video you provide.
// You should fill p_info with correct information to make vooya play.
get_properties: unsafe extern fn( p_info: *const voo_sequence_t, p_user_seq: *const c_void ) -> c_int,
// Client shall return the number of frames available, or ~0U if no
// framecount can be given (e.g. stdin).
framecount: unsafe extern fn( p_user_seq: *const c_void ) -> c_uint,
// Shall issue a seek by the client plugin to frame number "frame"
seek: unsafe extern fn( frame: c_uint, p_user_seq: *const c_void ) -> c_int,
// Load contents of frame number "frame" into p_buffer. p_buffer has a size
// appropriate to the format given by the client in get_properties( ... ).
// "pb_skipped" shall be set by the client to FALSE if the p_buffer has been filled
// with data, or to TRUE if client decided to no reload the frame if e.g. "frame" is
// repeated. "pp_user_frame" can hold custom data and is later available
// in voo_video_frame_metadata_t::p_user_frame.
load: unsafe extern fn( frame: c_uint, p_buffer: *const c_char, pb_skipped: *const c_int, pp_user_frame: *const *mut c_void, p_user_seq: *const c_void ) -> c_int,
eof: unsafe extern fn( p_user_seq: *const c_void ) -> c_uint,
good: unsafe extern fn( p_user_seq: *const c_void ) -> c_uint,
reload: unsafe extern fn( p_user_seq: *const c_void ) -> c_uint,
close: unsafe extern fn( p_user_seq: *const c_void ) -> (),
// After open( ... ) or open_nowhere( ... ), this is called.
// Set pp_err to an appropriate, persistent error message or to NULL.
error_msg: unsafe extern fn( pp_err: *const *mut c_char, p_user_seq: *const c_void ) -> (),
// Called by vooya to get supported file extensions. Those are then displayed in
// the "Open file" dialog. vooya will start with idx=0, then increment idx and
// call this again as long as you return TRUE. (only called when b_fileBased is true)
file_suffixes: unsafe extern fn( idx: c_int, pp_suffix: *const *mut c_char, p_user_seq: *const c_void ) -> c_int,
// Called by vooya to enumerate meta information tags about the video you provide.
// idx is counting up for each call as long as TRUE is return. Return FALSE to finish the
// enumeration. "buffer_k" char[64] and shall take a key, "buffer_v" char[1024] and
// shall take a corresponding value.
get_meta: unsafe extern fn( idx: c_int, buffer_k: *const c_char, buffer_v: *const c_char, p_user_seq: *const c_void ) -> c_int,
// vooya gives you a callback that you might call whenever the sequence's number of frames
// will change. Note that p_vooya_ctx must not be altered and is valid only as long as this input is bound.
cb_seq_len_changed: unsafe extern fn( seq_len_callback: unsafe extern fn( p_vooya_ctx: *const c_void, new_len: c_uint ) -> (), p_vooya_ctx: *const c_void ) -> (),
reserved2: [c_char; 32],
}
// Most important structure, this describes the plugin
#[allow(dead_code)]
#[allow(non_camel_case_types)]
#[repr(C)]
pub struct voo_plugin_t
{
voo_version: c_int, // set this always to VOO_PLUGIN_API_VERSION
// plugin's main name, user friendly description, copyright notice and version info
name: *const c_char,
description: *const c_char,
copyright: *const c_char,
version: *const c_char,
// Flags to signal something to vooya (for future use)
flags: c_int,
// any user data that shall be forwarded by vooya into other callback
// functions ("void *p_user" argument)
p_user: *const c_void,
// called by vooya before the plugin is unloaded
on_unload_plugin: extern fn( p_user: *const c_void ) -> (),
reserved: [c_char; 48],
// the plugin's callback functions
callbacks: [vooya_callback_t; 10],
// plugin's input capabilities. See input_plugin_t above.
input: input_plugin_t
}
/*
------- actual plugin below -------
*/
const NAME: &'static [u8] = b"vooya Plugin Written in Rust\0";
const DESCR: &'static [u8] = b"Adds funny RGB callback to show Rust binding, hehe.\0";
const COPYRIGHT: &'static [u8] = b"(C) Arion Neddens 2016.\0";
const VERSION: &'static [u8] = b"ver 1.0\0";
const CB_UID: &'static [u8] = b"rust.callback.0\0";
const CB_NAME: &'static [u8] = b"Convert to gray (Rust)\0";
const CB_DESCR: &'static [u8] = b"Fun Function to show Rust bindings.\0";
// Main entry function that every plugin must implement to describe itself on startup.
// The "p_plugin"-structure is provided by vooya and to be filled in the implementation.
// This is the first function to be called and must be implemented.
#[no_mangle]
pub unsafe extern fn voo_describe( p_plugin: *mut voo_plugin_t )
{
let ref mut p = *p_plugin;
p.voo_version = VOO_PLUGIN_API_VERSION;
p.name = NAME.as_ptr() as *const c_char;
p.description = DESCR.as_ptr() as *const c_char;
p.copyright = COPYRIGHT.as_ptr() as *const c_char;
p.version = VERSION.as_ptr() as *const c_char;
p.callbacks[0].uid = CB_UID.as_ptr() as *const c_char;
p.callbacks[0].name = CB_NAME.as_ptr() as *const c_char;
p.callbacks[0].description = CB_DESCR.as_ptr() as *const c_char;
p.callbacks[0].e_type = vooya_callback_type_t::vooCallback_RGBOut;
p.callbacks[0].method = twizzle as *const c_void;
}
// our function which does "something" with an rgb buffer.
#[no_mangle]
pub unsafe extern fn twizzle( p_data: *mut voo_target_space_t, p_metadata: *const voo_video_frame_metadata_t )
{
let ref p_meta = *p_metadata;
let ref p_seq_info = *(p_meta.p_info);
if 0 != (p_meta.flags & VOOPerFrameFlag_IsFromCache) {
return;
}
for y in 0..p_seq_info.height {
for x in 0..p_seq_info.width {
let ref mut p: voo_target_space_t = *p_data.offset( (x + p_seq_info.width * y) as isize );
let luma : i32 = (130 * p.r as i32 + 256 * p.g as i32 + 50 * p.b as i32) >> 8;
p.r = std::cmp::min( 255, luma ) as u8;
p.g = std::cmp::min( 255, luma ) as u8;
p.b = std::cmp::min( 255, luma ) as u8;
}
}
let formatted_number = format!("Rust did frame {:03},\nça nous amuse.", p_meta.frame_idx );
let plugin_message_c = CString::new(formatted_number).unwrap();
(p_meta.pfun_add_text)( p_meta.p_textfun_cargo,
plugin_message_c.as_ptr(),
vooPluginTextFlag_AlignCenter,
p_seq_info.width/2, p_seq_info.height-40 );
}<|fim▁end|> | |
<|file_name|>item_allocator.py<|end_file_name|><|fim▁begin|># Copyright 2015 IBM Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
from oslo_log import log as logging
from neutron._i18n import _
LOG = logging.getLogger(__name__)
class ItemAllocator(object):
"""Manages allocation of items from a pool
Some of the allocations such as link local addresses used for routing
inside the fip namespaces need to persist across agent restarts to maintain
consistency. Persisting such allocations in the neutron database is
unnecessary and would degrade performance. ItemAllocator utilizes local
file system to track allocations made for objects of a given class.
The persistent datastore is a file. The records are one per line of
the format: key<delimiter>value. For example if the delimiter is a ','
(the default value) then the records will be: key,value (one per line)
"""
def __init__(self, state_file, ItemClass, item_pool, delimiter=','):
"""Read the file with previous allocations recorded.
See the note in the allocate method for more detail.
"""
self.ItemClass = ItemClass
self.state_file = state_file
self.allocations = {}
self.remembered = {}
self.pool = item_pool
read_error = False
for line in self._read():
try:
key, saved_value = line.strip().split(delimiter)
self.remembered[key] = self.ItemClass(saved_value)
except ValueError:
read_error = True
LOG.warning("Invalid line in %(file)s, "
"ignoring: %(line)s",
{'file': state_file, 'line': line})
self.pool.difference_update(self.remembered.values())
if read_error:
LOG.debug("Re-writing file %s due to read error", state_file)
self._write_allocations()
def lookup(self, key):
"""Try to lookup an item of ItemClass type.
See if there are any current or remembered allocations for the key.
"""
if key in self.allocations:
return self.allocations[key]
if key in self.remembered:
self.allocations[key] = self.remembered.pop(key)
return self.allocations[key]
def allocate(self, key):
"""Try to allocate an item of ItemClass type.
I expect this to work in all cases because I expect the pool size to be
large enough for any situation. Nonetheless, there is some defensive
programming in here.
Since the allocations are persisted, there is the chance to leak
allocations which should have been released but were not. This leak
could eventually exhaust the pool.
So, if a new allocation is needed, the code first checks to see if
there are any remembered allocations for the key. If not, it checks
the free pool. If the free pool is empty then it dumps the remembered
allocations to free the pool. This final desperate step will not
happen often in practice.
"""
entry = self.lookup(key)
if entry:
return entry
if not self.pool:
# Desperate times. Try to get more in the pool.
self.pool.update(self.remembered.values())
self.remembered.clear()
if not self.pool:
# The number of address pairs allocated from the
# pool depends upon the prefix length specified
# in DVR_FIP_LL_CIDR
raise RuntimeError(_("Cannot allocate item of type: "
"%(class)s from pool using file %(file)s")
% {'class': self.ItemClass,
'file': self.state_file})
self.allocations[key] = self.pool.pop()
self._write_allocations()
return self.allocations[key]
def release(self, key):
if self.lookup(key):
self.pool.add(self.allocations.pop(key))
self._write_allocations()
def _write_allocations(self):
current = ["%s,%s\n" % (k, v) for k, v in self.allocations.items()]
remembered = ["%s,%s\n" % (k, v) for k, v in self.remembered.items()]
current.extend(remembered)
self._write(current)
def _write(self, lines):
with open(self.state_file, "w") as f:
f.writelines(lines)
<|fim▁hole|> if not os.path.exists(self.state_file):
return []
with open(self.state_file) as f:
return f.readlines()<|fim▁end|> | def _read(self): |
<|file_name|>AddKeywordEpgrecOperater.ts<|end_file_name|><|fim▁begin|>"use strict";
import EpgrecOperater from './EpgrecOperater';
class AddKeywordEpgrecOperater extends EpgrecOperater {
public execute(option: { [key: string]: any }, callback: (value: string) => void, errCallback: (value: { [key: string]: any }) => void): void {
this.log.system.info('AddKeywordEpgrecOperater was called');
let url = `${this.hostUrl}/keywordTable.php`;
<|fim▁hole|>export default AddKeywordEpgrecOperater;<|fim▁end|> | this.httpPost(url, option, `AddKeywordEpgrecOperater`, callback, errCallback);
}
}
|
<|file_name|>package.py<|end_file_name|><|fim▁begin|>##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, [email protected], All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program 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) version 2.1, February 1999.
#
# This program 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 terms and
# conditions of the GNU Lesser General Public License for more details.<|fim▁hole|># Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class PySphinxcontribProgramoutput(PythonPackage):
"""A Sphinx extension to literally insert the output of arbitrary commands
into documents, helping you to keep your command examples up to date."""
homepage = "https://sphinxcontrib-programoutput.readthedocs.org/"
url = "https://pypi.io/packages/source/s/sphinxcontrib-programoutput/sphinxcontrib-programoutput-0.10.tar.gz"
# FIXME: These import tests don't work for some reason
# import_modules = ['sphinxcontrib', 'sphinxcontrib.programoutput']
version('0.10', '8e511e476c67696c7ae2c08b15644eb4')
depends_on('py-setuptools', type='build')
depends_on('[email protected]:', type=('build', 'run'))<|fim▁end|> | #
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software |
<|file_name|>file.py<|end_file_name|><|fim▁begin|>f = open('test_content.txt', 'r')
print(f.read())
f.close()<|fim▁hole|># using context manager
with open('test_content.txt', 'r') as f:
print(f.read())<|fim▁end|> | |
<|file_name|>index.js<|end_file_name|><|fim▁begin|>var fs = require('fs');
var path = require('path');
var createSourceMapLocatorPreprocessor = function(args, logger, helper) {
var log = logger.create('preprocessor.sourcemap');
return function(content, file, done) {
function sourceMapData(data){
file.sourceMap = JSON.parse(data);
done(content);
}
function inlineMap(inlineData){
var data;
var b64Match = inlineData.match(/^data:.+\/(.+);base64,(.*)$/);
if (b64Match !== null && b64Match.length == 3) {
// base64-encoded JSON string
log.debug('base64-encoded source map for', file.originalPath);
var buffer = new Buffer(b64Match[2], 'base64');
sourceMapData(buffer.toString());
} else {
// straight-up URL-encoded JSON string
log.debug('raw inline source map for', file.originalPath);
sourceMapData(decodeURIComponent(inlineData.slice('data:application/json'.length)));
}
}
function fileMap(mapPath){
fs.exists(mapPath, function(exists) {
if (!exists) {<|fim▁hole|> fs.readFile(mapPath, function(err, data) {
if (err){ throw err; }
log.debug('external source map exists for', file.originalPath);
sourceMapData(data);
});
});
}
var lastLine = content.split(new RegExp(require('os').EOL)).pop();
var match = lastLine.match(/^\/\/#\s*sourceMappingURL=(.+)$/);
var mapUrl = match && match[1];
if (!mapUrl) {
fileMap(file.path + ".map");
} else if (/^data:application\/json/.test(mapUrl)) {
inlineMap(mapUrl);
} else {
fileMap(path.resolve(path.dirname(file.path), mapUrl));
}
};
};
createSourceMapLocatorPreprocessor.$inject = ['args', 'logger', 'helper'];
// PUBLISH DI MODULE
module.exports = {
'preprocessor:sourcemap': ['factory', createSourceMapLocatorPreprocessor]
};<|fim▁end|> | done(content);
return;
} |
<|file_name|>server.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
from livereload import Server, shell
server = Server()<|fim▁hole|>
style = ("style.scss", "style.css")
script = ("typing-test.js", "typing-test-compiled.js")
server.watch(style[0], shell(["sass", style[0]], output=style[1]))
server.watch(script[0], shell(["babel", script[0]], output=script[1]))
server.watch("index.html")
server.serve(port=8080, host="localhost", open_url=True)<|fim▁end|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.