The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
The dataset generation failed
Error code: DatasetGenerationError
Exception: TypeError
Message: Couldn't cast array of type
struct<content_hash: string, timestamp: string, source: string, line_count: int64, max_line_length: int64, avg_line_length: double, alnum_prop: double, repo_name: string, id: string, size: string, binary: bool, copies: string, ref: string, path: string, mode: string, license: string, language: list<item: struct<name: string, bytes: string>>, symlink_target: string>
to
{'content_hash': Value(dtype='string', id=None), 'timestamp': Value(dtype='string', id=None), 'source': Value(dtype='string', id=None), 'line_count': Value(dtype='int64', id=None), 'max_line_length': Value(dtype='int64', id=None), 'avg_line_length': Value(dtype='float64', id=None), 'alnum_prop': Value(dtype='float64', id=None), 'repo_name': Value(dtype='string', id=None), 'id': Value(dtype='string', id=None), 'size': Value(dtype='string', id=None), 'binary': Value(dtype='bool', id=None), 'copies': Value(dtype='string', id=None), 'ref': Value(dtype='string', id=None), 'path': Value(dtype='string', id=None), 'mode': Value(dtype='string', id=None), 'license': Value(dtype='string', id=None), 'language': [{'name': Value(dtype='string', id=None), 'bytes': Value(dtype='string', id=None)}]}
Traceback: Traceback (most recent call last):
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 2011, in _prepare_split_single
writer.write_table(table)
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/arrow_writer.py", line 585, in write_table
pa_table = table_cast(pa_table, self._schema)
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2302, in table_cast
return cast_table_to_schema(table, schema)
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2261, in cast_table_to_schema
arrays = [cast_array_to_feature(table[name], feature) for name, feature in features.items()]
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2261, in <listcomp>
arrays = [cast_array_to_feature(table[name], feature) for name, feature in features.items()]
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 1802, in wrapper
return pa.chunked_array([func(chunk, *args, **kwargs) for chunk in array.chunks])
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 1802, in <listcomp>
return pa.chunked_array([func(chunk, *args, **kwargs) for chunk in array.chunks])
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2122, in cast_array_to_feature
raise TypeError(f"Couldn't cast array of type\n{_short_str(array.type)}\nto\n{_short_str(feature)}")
TypeError: Couldn't cast array of type
struct<content_hash: string, timestamp: string, source: string, line_count: int64, max_line_length: int64, avg_line_length: double, alnum_prop: double, repo_name: string, id: string, size: string, binary: bool, copies: string, ref: string, path: string, mode: string, license: string, language: list<item: struct<name: string, bytes: string>>, symlink_target: string>
to
{'content_hash': Value(dtype='string', id=None), 'timestamp': Value(dtype='string', id=None), 'source': Value(dtype='string', id=None), 'line_count': Value(dtype='int64', id=None), 'max_line_length': Value(dtype='int64', id=None), 'avg_line_length': Value(dtype='float64', id=None), 'alnum_prop': Value(dtype='float64', id=None), 'repo_name': Value(dtype='string', id=None), 'id': Value(dtype='string', id=None), 'size': Value(dtype='string', id=None), 'binary': Value(dtype='bool', id=None), 'copies': Value(dtype='string', id=None), 'ref': Value(dtype='string', id=None), 'path': Value(dtype='string', id=None), 'mode': Value(dtype='string', id=None), 'license': Value(dtype='string', id=None), 'language': [{'name': Value(dtype='string', id=None), 'bytes': Value(dtype='string', id=None)}]}
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1529, in compute_config_parquet_and_info_response
parquet_operations = convert_to_parquet(builder)
File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1154, in convert_to_parquet
builder.download_and_prepare(
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1027, in download_and_prepare
self._download_and_prepare(
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1122, in _download_and_prepare
self._prepare_split(split_generator, **prepare_split_kwargs)
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1882, in _prepare_split
for job_id, done, content in self._prepare_split_single(
File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 2038, in _prepare_split_single
raise DatasetGenerationError("An error occurred while generating the dataset") from e
datasets.exceptions.DatasetGenerationError: An error occurred while generating the datasetNeed help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.
text
string | meta
dict |
|---|---|
namespace MassTransit.Courier.Contracts
{
using System;
/// <summary>
/// Capture the exception information thrown by an activity
/// </summary>
public interface ActivityException
{
/// <summary>
/// The tracking number of the activity that threw the exception
/// </summary>
Guid ExecutionId { get; }
/// <summary>
/// The point in time when the exception occurred
/// </summary>
DateTime Timestamp { get; }
/// <summary>
/// The time from when the routing slip was created until the exception occurred
/// </summary>
TimeSpan Elapsed { get; }
/// <summary>
/// The name of the activity that caused the exception
/// </summary>
string Name { get; }
/// <summary>
/// The host where the exception was thrown
/// </summary>
HostInfo Host { get; }
/// <summary>
/// The exception details
/// </summary>
ExceptionInfo ExceptionInfo { get; }
}
}
|
{
"content_hash": "1fe9a3d0b253a3c6b7f7dffcd5a9dc62",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 88,
"avg_line_length": 26.097560975609756,
"alnum_prop": 0.5467289719626168,
"repo_name": "MassTransit/MassTransit",
"id": "14e15ab52cccd765de002a402ed83ea04d6d7387",
"size": "1072",
"binary": false,
"copies": "3",
"ref": "refs/heads/develop",
"path": "src/MassTransit.Abstractions/Courier/Courier/Contracts/ActivityException.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "12668130"
},
{
"name": "Dockerfile",
"bytes": "781"
},
{
"name": "PowerShell",
"bytes": "3303"
},
{
"name": "Shell",
"bytes": "907"
},
{
"name": "Smalltalk",
"bytes": "4"
}
]
}
|
.oo-ui-icon-bright {
background-image: url('themes/wikimediaui/images/icons/bright.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bright.svg');
}
.oo-ui-icon-halfBright {
background-image: url('themes/wikimediaui/images/icons/halfBright-ltr.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/halfBright-ltr.svg');
}
.oo-ui-icon-notBright {
background-image: url('themes/wikimediaui/images/icons/notBright.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/notBright.svg');
}
.oo-ui-icon-eye {
background-image: url('themes/wikimediaui/images/icons/eye.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/eye.svg');
}
.oo-ui-icon-eyeClosed {
background-image: url('themes/wikimediaui/images/icons/eyeClosed.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/eyeClosed.svg');
}
.oo-ui-icon-moon {
background-image: url('themes/wikimediaui/images/icons/moon.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/moon.svg');
}
.oo-ui-icon-largerText {
background-image: url('themes/wikimediaui/images/icons/largerText.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/largerText.svg');
}
.oo-ui-icon-smallerText {
background-image: url('themes/wikimediaui/images/icons/smallerText.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/smallerText.svg');
}
.oo-ui-icon-visionSimulator {
background-image: url('themes/wikimediaui/images/icons/visionSimulator.png');
background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/visionSimulator.svg');
}
|
{
"content_hash": "806eb3f6b59736e79935895d5b47f1c7",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 135,
"avg_line_length": 55.86486486486486,
"alnum_prop": 0.7547169811320755,
"repo_name": "extend1994/cdnjs",
"id": "977b95f4185a27a63ed6268c4fc864122c0a97f0",
"size": "2289",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "ajax/libs/oojs-ui/0.33.4/oojs-ui-apex-icons-accessibility.css",
"mode": "33188",
"license": "mit",
"language": []
}
|
from __future__ import print_function
import argparse
import json
import os
_FILE_URL = 'https://repo.maven.apache.org/maven2/com/google/code/findbugs/jsr305/3.0.2/jsr305-3.0.2.jar'
_FILE_NAME = 'jsr305-3.0.2.jar'
_FILE_VERSION = '3.0.2'
def do_latest():
print(_FILE_VERSION)
def get_download_url(version):
if _FILE_URL.endswith('.jar'):
ext = '.jar'
elif _FILE_URL.endswith('.aar'):
ext = '.aar'
else:
raise Exception('Unsupported extension for %s' % _FILE_URL)
partial_manifest = {
'url': [_FILE_URL],
'name': [_FILE_NAME],
'ext': ext,
}
print(json.dumps(partial_manifest))
def main():
ap = argparse.ArgumentParser()
sub = ap.add_subparsers()
latest = sub.add_parser("latest")
latest.set_defaults(func=lambda _opts: do_latest())
download = sub.add_parser("get_url")
download.set_defaults(
func=lambda _opts: get_download_url(os.environ['_3PP_VERSION']))
opts = ap.parse_args()
opts.func(opts)
if __name__ == '__main__':
main()
|
{
"content_hash": "9cf9f232722d077db1500df8804f9ae2",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 105,
"avg_line_length": 22.145833333333332,
"alnum_prop": 0.605832549388523,
"repo_name": "ric2b/Vivaldi-browser",
"id": "e078a0872d54c15b375c522c09dace8e42b287dd",
"size": "1351",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chromium/third_party/android_deps/libs/com_google_code_findbugs_jsr305/3pp/fetch.py",
"mode": "33261",
"license": "bsd-3-clause",
"language": []
}
|
@class GADBannerView;
@class GADInterstitial;
#pragma mark AdMob Plugin
// This version of the AdMob plugin has been tested with Cordova version 2.5.0.
@interface CDVAdMob : CDVPlugin <GADBannerViewDelegate, GADInterstitialDelegate> {
}
@property(nonatomic, retain) GADBannerView *bannerView;
@property(nonatomic, retain) GADInterstitial *interstitialView;
@property (assign) BOOL bannerAtTop;
- (void)createBannerView:(CDVInvokedUrlCommand *)command;
- (void)destroyBannerView:(CDVInvokedUrlCommand *)command;
- (void)requestAd:(CDVInvokedUrlCommand *)command;
- (void)showAd:(CDVInvokedUrlCommand *)command;
- (void)createInterstitialView:(CDVInvokedUrlCommand *)command;
- (void)requestInterstitialAd:(CDVInvokedUrlCommand *)command;
@end
|
{
"content_hash": "0085acd44080f63caf966aa0eb935a28",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 82,
"avg_line_length": 34,
"alnum_prop": 0.8008021390374331,
"repo_name": "Icenium/cordova-plugin-admob",
"id": "8831381537ffa2a5c6c823b7e63f3a5d93508008",
"size": "1153",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/ios/CDVAdMob.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "4253"
},
{
"name": "C++",
"bytes": "40025"
},
{
"name": "Java",
"bytes": "17430"
},
{
"name": "JavaScript",
"bytes": "7785"
},
{
"name": "Objective-C",
"bytes": "30633"
}
]
}
|
@interface CTFrameParser : NSObject
+ (NSMutableDictionary *)attributesWithConfig:(CTFrameParserConfig *)config;
+ (CoreTextData *)parseContent:(NSString *)content config:(CTFrameParserConfig*)config;
+ (CoreTextData *)parseAttributedContent:(NSAttributedString *)content config:(CTFrameParserConfig*)config;
+ (CoreTextData *)parseTemplateFile:(NSString *)path config:(CTFrameParserConfig*)config;
+ (CoreTextData *)parseString:(NSString *)string config:(CTFrameParserConfig *)config;
@end
|
{
"content_hash": "6bd22e4fd1032663cf325dbac5f8aa55",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 107,
"avg_line_length": 41.333333333333336,
"alnum_prop": 0.8004032258064516,
"repo_name": "NoryCao/zhuishushenqi",
"id": "609046ce3b986070ebea8dd0b19549d86f004dbc",
"size": "722",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "zhuishushenqi/Vendor/CTDisplayText/Source/CTFrameParser.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1078"
},
{
"name": "HTML",
"bytes": "1200"
},
{
"name": "Objective-C",
"bytes": "373701"
},
{
"name": "Ruby",
"bytes": "47649"
},
{
"name": "Shell",
"bytes": "1054"
},
{
"name": "Swift",
"bytes": "1853479"
}
]
}
|
from .app import Flask, Request, Response
from .config import Config
from .helpers import url_for, flash, send_file, send_from_directory, \
get_flashed_messages, get_template_attribute, make_response, safe_join, \
stream_with_context
from .sessions import SecureCookieSession as Session
|
{
"content_hash": "a7115eb880c9956fd1d602e813d4a5b6",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 77,
"avg_line_length": 49.166666666666664,
"alnum_prop": 0.7762711864406779,
"repo_name": "sourcegraph/python-deps",
"id": "6612f88276a8ca465d13e4c67149cf43d5f42b70",
"size": "303",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "testdata/reexporter/reexporter/__init__.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Python",
"bytes": "20260"
}
]
}
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>VO808X: /home/bhargavi/Documents/SDR/Copy_Exam_808X/docs/html/classtesting_1_1gmock__matchers__test_1_1_new_even_matcher_impl.js File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
$(window).load(resizeHeight);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">VO808X
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.11 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li><a href="globals.html"><span>File Members</span></a></li>
</ul>
</div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('classtesting__1__1gmock____matchers____test__1__1__new__even__matcher__impl_8js.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="summary">
<a href="#var-members">Variables</a> </div>
<div class="headertitle">
<div class="title">classtesting_1_1gmock__matchers__test_1_1_new_even_matcher_impl.js File Reference</div> </div>
</div><!--header-->
<div class="contents">
<p><a href="classtesting__1__1gmock____matchers____test__1__1__new__even__matcher__impl_8js_source.html">Go to the source code of this file.</a></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="var-members"></a>
Variables</h2></td></tr>
<tr class="memitem:ab08a5368dde563f915585ebe0678bf29"><td class="memItemLeft" align="right" valign="top">var </td><td class="memItemRight" valign="bottom"><a class="el" href="classtesting__1__1gmock____matchers____test__1__1__new__even__matcher__impl_8js.html#ab08a5368dde563f915585ebe0678bf29">classtesting_1_1gmock__matchers__test_1_1_new_even_matcher_impl</a></td></tr>
<tr class="separator:ab08a5368dde563f915585ebe0678bf29"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<h2 class="groupheader">Variable Documentation</h2>
<a class="anchor" id="ab08a5368dde563f915585ebe0678bf29"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">var classtesting_1_1gmock__matchers__test_1_1_new_even_matcher_impl</td>
</tr>
</table>
</div><div class="memdoc">
<b>Initial value:</b><div class="fragment"><div class="line">=</div><div class="line">[</div><div class="line"> [ <span class="stringliteral">"DescribeTo"</span>, <span class="stringliteral">"classtesting_1_1gmock__matchers__test_1_1_new_even_matcher_impl.html#a28f634d1b39d1d7a9008b29068e98ce2"</span>, null ],</div><div class="line"> [ <span class="stringliteral">"MatchAndExplain"</span>, <span class="stringliteral">"classtesting_1_1gmock__matchers__test_1_1_new_even_matcher_impl.html#ae09c1c6d46be8b229f271571cd4df53f"</span>, null ]</div><div class="line">]</div></div><!-- fragment -->
<p>Definition at line <a class="el" href="classtesting__1__1gmock____matchers____test__1__1__new__even__matcher__impl_8js_source.html#l00001">1</a> of file <a class="el" href="classtesting__1__1gmock____matchers____test__1__1__new__even__matcher__impl_8js_source.html">classtesting_1_1gmock__matchers__test_1_1_new_even_matcher_impl.js</a>.</p>
</div>
</div>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="dir_9daeb764126746bd421670cd05145a44.html">Copy_Exam_808X</a></li><li class="navelem"><a class="el" href="dir_3513b8ce3485e7bb0e9d6f6c5b58913f.html">docs</a></li><li class="navelem"><a class="el" href="dir_f5fa7e70618c0bcb7f530ff60feeacb7.html">html</a></li><li class="navelem"><a class="el" href="classtesting__1__1gmock____matchers____test__1__1__new__even__matcher__impl_8js.html">classtesting_1_1gmock__matchers__test_1_1_new_even_matcher_impl.js</a></li>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.11 </li>
</ul>
</div>
</body>
</html>
|
{
"content_hash": "b58c106e2f5df0ba1f2b0395f4d21007",
"timestamp": "",
"source": "github",
"line_count": 148,
"max_line_length": 639,
"avg_line_length": 51.28378378378378,
"alnum_prop": 0.6650856389986824,
"repo_name": "bhargavipatel/808X_VO",
"id": "59d7ed6802fa9b99391c93c0a36a9b327846ac87",
"size": "7590",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/html/classtesting__1__1gmock____matchers____test__1__1__new__even__matcher__impl_8js.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "18150"
},
{
"name": "CMake",
"bytes": "9404"
},
{
"name": "Matlab",
"bytes": "10128"
},
{
"name": "Python",
"bytes": "5095"
}
]
}
|
module Conratesecurity
class User < ActiveRecord::Base
TEMP_EMAIL_PREFIX = 'change@me'
TEMP_EMAIL_REGEX = /\Achange@me/
rolify :role_cname => 'Conratesecurity::Role'
#rolify role_cname: 'Conratesecurity::Role', role_join_table_name: 'conrate_security_users_conrate_security_roles'
has_many :orders, class_name: Pamer::Order
has_many :addresses, class_name: Conrateaddressable::Address
accepts_nested_attributes_for :addresses, reject_if: :all_blank, allow_destroy: true
# attr_accessor :login
# validates :username,
# :presence => true,
# :uniqueness => {
# :case_sensitive => false
# }
# validate :validate_username, on: :create
validates :username, uniqueness: true
validates_format_of :username, with: /\A[a-zA-Z0-9_\.]*\z/
validates_format_of :email, :without => TEMP_EMAIL_REGEX, on: :update
validates_presence_of [:email, :username]
# def validate_username
# if User.where(username: username).exists?
# errors.add(:username, :taken)
# end
# end
# def login=(login)
# @login = login
# end
# def login
# @login || self.username || self.email
# end
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable, :lockable, :timeoutable, :omniauthable, :async
def default_role(role)
roles << Conratesecurity::Role.find_or_create_by(name: :conratesecurity_user, role_type: 'SYSTEM')
end
def pretty_name
if username.blank?
email.split('@').first
else
username
end
end
# Login with username or e-mail
# def self.find_for_database_authentication(warden_conditions)
# conditions = warden_conditions.dup
# if login = conditions.delete(:login)
# where(conditions.to_hash).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
# else
# conditions[:email].downcase! if conditions[:email]
# if conditions[:username].nil?
# where(conditions).first
# else
# where(username: conditions[:username]).first
# end
# end
# end
def self.find_for_oauth(auth, signed_in_resource = nil)
# Get the identity and user if they exist
identity = Identity.find_for_oauth(auth)
# If a signed_in_resource is provided it always overrides the existing user
# to prevent the identity being locked with accidentally created accounts.
# Note that this may leave zombie accounts (with no associated identity) which
# can be cleaned up at a later date.
user = signed_in_resource ? signed_in_resource : identity.user
# Create the user if needed
if user.nil?
# Get the existing user by email if the provider gives us a verified email.
# If no verified email was provided we assign a temporary email and ask the
# user to verify it on the next step via UsersController.finish_signup
email_is_verified = auth.info.email && (auth.info.verified || auth.info.verified_email)
email = auth.info.email if email_is_verified
user = User.where(:email => email).first if email
# Create the user if it's a new registration
if user.nil?
user = Conratesecurity::User.new(
#username: auth.info.nickname || auth.uid,
email: email ? email : "#{TEMP_EMAIL_PREFIX}-#{auth.uid}-#{auth.provider}.com",
password: Devise.friendly_token[0,20]
)
user.skip_confirmation!
user.save!
end
end
# Associate the identity with the user if needed
if identity.user != user
identity.user = user
identity.save!
end
user
end
def email_verified?
self.email && self.email !~ TEMP_EMAIL_REGEX
end
def billing_address
address = Conrateaddressable::Address.find_by(addresstype: Conrateaddressable::Address.addresstype.billing, user_id: id)
if address.nil?
address = Conrateaddressable::Address.new(addresstype: Conrateaddressable::Address.addresstype.billing)
end
return address
end
def delivery_address
address = Conrateaddressable::Address.find_by(addresstype: Conrateaddressable::Address.addresstype.delivery, user_id: id)
if address.nil?
address = Conrateaddressable::Address.new(addresstype: Conrateaddressable::Address.addresstype.delivery)
end
return address
end
end
end
|
{
"content_hash": "6810c9606f1e1dbcda9cfc46b532ae8e",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 132,
"avg_line_length": 34.87022900763359,
"alnum_prop": 0.6477670753064798,
"repo_name": "muskovicsnet/conrate",
"id": "b991aa27dae3c1743bcc661cebe46ed20585ace0",
"size": "4568",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/engines/security/app/models/conratesecurity/user.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3283"
},
{
"name": "CoffeeScript",
"bytes": "211"
},
{
"name": "HTML",
"bytes": "7481"
},
{
"name": "JavaScript",
"bytes": "1355"
},
{
"name": "Ruby",
"bytes": "105903"
},
{
"name": "Shell",
"bytes": "786"
}
]
}
|
package com.example.android.sunshine;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.android.sunshine", appContext.getPackageName());
}
}
|
{
"content_hash": "f32a334d97b31c0262b34f39b5de3039",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 82,
"avg_line_length": 29.23076923076923,
"alnum_prop": 0.75,
"repo_name": "Gr8manish/GoUbiquitous",
"id": "3d44761d074353b5a8de648e66fa7375322b202e",
"size": "760",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sunshine/src/androidTest/java/com/example/android/sunshine/ExampleInstrumentedTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "260942"
}
]
}
|
<?php
namespace oboe\test\output\head;
use \oboe\head\FavIcon;
use \PHPUnit_Framework_TestCase as TestCase;
require_once __DIR__ . '/../../test-common.php';
/**
* This class tests the output of the Oboe_Head_FavIcon element.
*
* @author Philip Graham <philip@lightbox.org>
*/
class FavIconTest extends TestCase {
public function testOutput() {
$favIcon = new FavIcon('favicon.ico');
$output = $favIcon->__toString();
$expected = '<link rel="shortcut icon" href="favicon.ico"/>';
$this->assertEquals($expected, $output,
'Invalid output for favicon element');
}
}
|
{
"content_hash": "c2893dac81f64e5917118a6dd65fade1",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 65,
"avg_line_length": 23.92,
"alnum_prop": 0.6705685618729097,
"repo_name": "pgraham/oobo",
"id": "96c0fb6f7976e8d7e6f630627565dbfb7492ca4f",
"size": "1148",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/output/head/FavIconTest.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "PHP",
"bytes": "235455"
},
{
"name": "Shell",
"bytes": "247"
}
]
}
|
This sample template demonstrates how to create a NAT rule in loadbalancer to allow RDP to a vm.
You can connect to the vm using:
* mstsc.exe /v:<publicDnsName>.<location>.cloudapp.azure.com:<rdpPort>
This template deploys the following resources:
<ul><li>storage account</li><li>vnet</li><li>public ip</li><li>load balancer with a NAT rule for RDP</li><li>a virtual machine</li></ul>
<a href="https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2FAzure%2Fazure-quickstart-templates%2Fmaster%2F101-vm-with-rdp-port%2Fazuredeploy.json" target="_blank">
<img src="http://azuredeploy.net/deploybutton.png"/>
</a>
Template parameters:
| Name | Description |
|:--- |:---|
| location | Location where to deploy the resources |
| publicDnsName | The DNS prefix for the public IP address |
| storageAccountName | Name of the storage account to create |
| vmName | The name of the VM |
| imagePublisher | The name of the pulisher of the OS Image |
| imageOffer | The Image Offer |
| imageSKU | The Image SKU |
| adminUsername | Admin username |
| adminPassword | Admin password |
| rdpPort | Public port number for RDP |
|
{
"content_hash": "8a700d1d2a73fd554dff8caf1c625565",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 210,
"avg_line_length": 37.375,
"alnum_prop": 0.7290969899665551,
"repo_name": "jrowies/azure-quickstart-templates",
"id": "ce788d48040f94420aa3ee512afdd7ba50168cf8",
"size": "1229",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "101-vm-with-rdp-port/Readme.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Groovy",
"bytes": "393"
},
{
"name": "PHP",
"bytes": "645"
},
{
"name": "PowerShell",
"bytes": "74784"
},
{
"name": "Python",
"bytes": "130341"
},
{
"name": "Shell",
"bytes": "215201"
}
]
}
|
package com.yext.serialization.xml;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Takes all the child elements of the field and embeds them into the parent
* element.
*
* For example:
*
* <pre>
* class Parent {
* @EmbedChildren
* List<Child> children = ...;
* }
*
* class Child {
* String value = "text";
* }
* </pre>
*
* will result in
*
* <pre>
* <parent>
* <value>text<value>
* <value>text<value>
* <value>text<value>
* </parent>
* </pre>
*
* which does not contain any <code>children</code> elements
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface EmbedChildren {
}
|
{
"content_hash": "7c9698d810cbdf586e85224855316e1b",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 76,
"avg_line_length": 21.428571428571427,
"alnum_prop": 0.6644444444444444,
"repo_name": "yext/serialization",
"id": "3fb4007368f7c1cb4198782754876228b37424c4",
"size": "900",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/yext/serialization/xml/EmbedChildren.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "302905"
}
]
}
|
You can use a variable to assign a value to it and return the value:
function() {
var a = 42;
return a;
}
One solution to solve this riddle is to write a loop:
function() {
for (var i = 1; i < n; i++) {
...
}
}
But Carly is really good at math. You may need a better solution.
**And never forget:**
Hit `Ctrl-Enter` to run your code!
|
{
"content_hash": "45bd1cd41ce253c38a582c80c202a232",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 68,
"avg_line_length": 19.095238095238095,
"alnum_prop": 0.5610972568578554,
"repo_name": "furti/evalquiz",
"id": "80e170c9ec24dde8942087e739131d4375b36190",
"size": "401",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/riddles/gauss/hints.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "7926"
},
{
"name": "HTML",
"bytes": "14669"
},
{
"name": "JavaScript",
"bytes": "11732"
},
{
"name": "TypeScript",
"bytes": "154387"
}
]
}
|
# pagePiling.js


Pile your sections one over another and access them scrolling or by URL!
- [Live demo](http://alvarotrigo.com/pagePiling/)
- [Who is using it](https://github.com/alvarotrigo/pagePiling.js#who-is-using-pagepilingjs)
Invite me to a coffee
[](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=BEK5JQCQMED4J&lc=GB&item_name=pagePiling%2ejs¤cy_code=USD&bn=PP%2dDonationsBF%3abtn_donate_LG%2egif%3aNonHosted)
Customizations of the plugin available upon request for some reasonable price. <a href="http://alvarotrigo.com/#contact-page">Contact me</a>.
Would you like to have a website using pilePage.js functionality but you don't know how to use it? I can do it for you for a reasonable price. <a href="http://alvarotrigo.com/#contact-page">Contact me</a>.
## Introduction
Suggestion are more than welcome, not only for feature requests but also for coding style improvements.
Let's make this a great plugin to make people's lives easier!
## Compatibility
pagePiling.js is fully functional on all modern browsers, as well as some old ones such as Internet Explorer 8, 9, Opera 12, etc.
It works with browsers with CSS3 support and with the ones which don't have it, making it ideal for old browsers compatibility.
It is also designed to work on touch devices such as mobile phones or tablets.
## Usage
As you can see in the example files, you will need to include the JavaScript file `jquery.pagepiling.js` (or the minified version `jquery.pagepiling.min.js`) and the css file `jquery.pagepiling.css` of the plugin, as well as [jQuery](http://jquery.com/). Optionally, you can add the [jQuery UI library](http://jqueryui.com/) in case you want to use other easing effects apart from the ones included in the jQuery library which are the `linear` or `swing` effects.
### Install using bower:
Optionally, you can install pagePiling.js with bower:
Terminal:
```shell
bower install pagepiling.js
```
###Including files:
```html
<link rel="stylesheet" type="text/css" href="jquery.pagepiling.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.pagepiling.js"></script>
```
###Required HTML structure
Each section will be defined with a `div` containing the `section` class.
The active section by default will be the first section, which is taken as the home page.
```html
<div id="pagepiling">
<div class="section">Some section</div>
<div class="section">Some section</div>
<div class="section">Some section</div>
<div class="section">Some section</div>
</div>
```
###Initialization
All you need to do is call the plugin inside a `$(document).ready` function:
```javascript
$(document).ready(function() {
$('#pagepiling').pagepiling();
});
```
A more complex initialization with all options set could look like this:
```javascript
$(document).ready(function() {
$('#pagepiling').pagepiling({
menu: null,
direction: 'vertical',
verticalCentered: true,
sectionsColor: [],
anchors: [],
scrollingSpeed: 700,
easing: 'swing',
loopBottom: false,
loopTop: false,
css3: true,
navigation: {
'textColor': '#000',
'bulletsColor': '#000',
'position': 'right',
'tooltips': ['section1', 'section2', 'section3', 'section4']
},
normalScrollElements: null,
normalScrollElementTouchThreshold: 5,
touchSensitivity: 5,
keyboardScrolling: true,
sectionSelector: '.section',
animateAnchor: false,
//events
onLeave: function(index, nextIndex, direction){},
afterLoad: function(anchorLink, index){},
afterRender: function(){},
});
});
```
### Accesing sections
In order to create links to a certain section, you can use a normal URL link if you are using pagePiling.js with anchor links (using the `anchors` option), then you will be able to use anchor links also to navigate directly to a certain section.
For example: http://alvarotrigo.com/pagePiling/#page2
**Be careful!** `data-anchor` tags can not have the same value as any ID element on the site (or NAME element for IE).
### Using a menu
To link the menu with the active section you will have to use the `menu` option and make use of anchor links (#) as explained below in the options section.
### Creating a scrollable section
In case you want to have a section with large content and therefore create an scroll bar for that section, you can do it by adding the class `pp-scrollable` to that section:
```html
<div class="section pp-scrollable"></div>
```
## Options
- `verticalCentered`: (default `true`) Vertically centering of the content within sections.
- `scrollingSpeed`: (default `700`) Speed in milliseconds for the scrolling transitions.
- `sectionsColor`:(default `none`) Define the CSS `background-color` property for each section:
Example:
```javascript
$('#pagepiling').pagepiling({
sectionsColor: ['#f2f2f2', '#4BBFC3', '#7BAABE', 'whitesmoke', '#000'],
});
```
- `anchors`: (default `[]`) Defines the anchor links (#example) to be shown on the URL for each section. Using anchors forward and backward navigation will also be possible through the browser. This option also allows users to bookmark a specific section. **Be careful!** if you use anchors, they can not have the same value as any ID element on the site (or NAME element for IE).
**Important** It is helpful to understand that the values in the `anchors` option array correlate directly to the element with the class of `.section` by it's position in the markup.
- `easing`: (default `swing`) Defines the transition effect to use for the vertical scrolling.
It requires [jQuery UI](http://jqueryui.com/) in order to use any other transition other than `swing` and `linear`. Other libraries could be used instead.
- `loopTop`: (default `false`) Defines whether scrolling up in the first section should scroll to the last one or not.
- `loopBottom`: (default `false`) Defines whether scrolling down in the last section should scroll to the first one or not.
- `css3`: (default `true`). Defines wheter to use JavaScript or CSS3 transforms to scroll within sections. Useful to speed up the movement in tablet and mobile devices with browsers supporting CSS3. If this option is set to `true` and the browser doesn't support CSS3, a jQuery fallback will be used instead.
- `normalScrollElements`: (default `null`) If you want to avoid the auto scroll when scrolling over some elements, this is the option you need to use. (useful for maps, scrolling divs etc.) It requires a string with the jQuery selectors for those elements. (For example: `normalScrollElements: '#element1, .element2'`)
- `normalScrollElementTouchThreshold` : (default `5`) Defines the threshold for the number of hops up the html node tree pagePiling will test to see if `normalScrollElements` is a match to allow scrolling functionality on divs on a touch device. (For example: `normalScrollElementTouchThreshold: 3`)
- `keyboardScrolling`: (default `true`) Defines if the content can be navigated using the keyboard
- `touchSensitivity`: (default `5`) Defines a percentage of the browsers window width/height, and how far a swipe must measure for navigating to the next section.
- `animateAnchor`: (default `true`) Defines whether the load of the site when given an anchor (#) will scroll with animation to its destination or will directly load on the given section.
- `direction`: (default `vertical`) Defines if the scroll is vertical or horizontal.
- `menu`: (default `false`) A selector can be used to specify the menu to link with the sections. This way the scrolling of the sections will activate the corresponding element in the menu using the class `active`.
This won't generate a menu but will just add the `active` class to the element in the given menu with the corresponding anchor links.
In order to link the elements of the menu with the sections, an HTML 5 data-tag (`data-menuanchor`) will be needed to use with the same anchor links as used within the sections. Example:
```html
<ul id="myMenu">
<li data-menuanchor="firstPage" class="active"><a href="#firstPage">First section</a></li>
<li data-menuanchor="secondPage"><a href="#secondPage">Second section</a></li>
<li data-menuanchor="thirdPage"><a href="#thirdPage">Third section</a></li>
<li data-menuanchor="fourthPage"><a href="#fourthPage">Fourth section</a></li>
</ul>
```
```javascript
$('#pagepiling').pagepiling({
anchors: ['firstPage', 'secondPage', 'thirdPage', 'fourthPage', 'lastPage'],
menu: '#myMenu'
});
```
**Note:** the menu element should be placed outside the pagePiling wrapper in order to avoid problem when using `css3:true`. Otherwise it will be appended to the `body` by the plugin itself.
- `navigation`: (default `false`) If set to `true`, it will show a navigation bar made up of small circles.
- `sectionSelector`: (default `.section`) Defines the jQuery selector used for the plugin sections. It might need to be changed sometimes to avoid problem with other plugins using the same selectors as pagePiling.js..
## Methods
### moveSectionUp()
Scrolls one section up:
```javascript
$.fn.pagepiling.moveSectionUp();
```
### moveSectionDown()
Scrolls one section down:
```javascript
$.fn.pagepiling.moveSectionDown();
```
### moveTo(section)
Scrolls the page to the given section.
```javascript
/*Scrolling to the section with the anchor link `firstSection` */
$.fn.pagepiling.moveTo('firstSection');
```
```javascript
//Scrolling to the 3rd section in the site
$.fn.pagepiling.moveTo(3);
//Which is the same as
$.fn.pagepiling.moveTo(3);
```
### setAllowScrolling(boolean)
Adds or remove the possibility of scrolling through sections by using the mouse wheel/trackpad or touch gestures (which is active by default).
```javascript
$.fn.pagepiling.setAllowScrolling(false);
```
### setKeyboardScrolling(boolean)
Adds or remove the possibility of scrolling through sections by using the keyboard arrow keys (which is active by default).
```javascript
$.fn.pagepiling.setKeyboardScrolling(false);
```
### setScrollingSpeed(milliseconds)
Defines the scrolling speed in milliseconds.
```javascript
$.fn.pagepiling.setScrollingSpeed(700);
```
## Callbacks
###afterLoad (`anchorLink`, `index`)
Callback fired once the sections have been loaded, after the scrolling has ended.
Parameters:
- `anchorLink`: anchorLink corresponding to the section.
- `index`: index of the section. Starting from 1.
In case of not having anchorLinks defined in the plugin the `index` parameter would be the only one to use.
Example:
```javascript
$('#pagepiling').pagepiling({
anchors: ['firstPage', 'secondPage', 'thirdPage', 'fourthPage', 'lastPage'],
afterLoad: function(anchorLink, index){
//using index
if(index == 3){
alert("Section 3 ended loading");
}
//using anchorLink
if(anchorLink == 'secondPage'){
alert("Section 2 ended loading");
}
}
});
```
###onLeave (`index`, `nextIndex`, `direction`)
This callback is fired once the user leaves a section, in the transition to the new section.
Parameters:
- `index`: index of the leaving section. Starting from 1.
- `nextIndex`: index of the destination section. Starting from 1.
- `direction`: it will take the values `up` or `down` depending on the scrolling direction.
Example:
```javascript
$('#pagepiling').pagepiling({
onLeave: function(index, nextIndex, direction){
//after leaving section 2
if(index == 2 && direction =='down'){
alert("Going to section 3!");
}
else if(index == 2 && direction == 'up'){
alert("Going to section 1!");
}
}
});
```
###afterRender()
This callback is fired just after the structure of the page is generated. This is the callback you want to use to initialize other plugins or fire any code which requires the document to be ready (as this plugin modifies the DOM to create the resulting structure).
Example:
```javascript
$('#pagepiling').pagepiling({
afterRender: function(){
alert("The resulting DOM structure is ready");
}
});
```
## Resources
[CSS Easing Animation Tool - Matthew Lein](http://matthewlein.com/ceaser/)
## Who is using pagePiling.js
If you want your page to be listed here. Please <a href="mailto:alvaro@alvarotrigo.com">contact me</a> with the URL.
[](http://www.facebookgroups.com/)
- http://www.facebookgroups.com/
- https://number26.de/
- http://fngeats.com/
- http://ednahouse.org/statistics/
- http://sushi.steadfastlight.com/
- http://netstorage.com.br/nucs/nucs.html
- http://aungthurhahein.me/
- http://mannydesigns.co
## Donations
Donations would be more than welcome :)
[](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=BEK5JQCQMED4J&lc=GB&item_name=pagePiling%2ejs¤cy_code=USD&bn=PP%2dDonationsBF%3abtn_donate_LG%2egif%3aNonHosted)
## License
(The MIT License)
Copyright (c) 2014 Alvaro Trigo <alvaro@alvarotrigo.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
{
"content_hash": "7ae9ceefffad73793353ee613b212599",
"timestamp": "",
"source": "github",
"line_count": 351,
"max_line_length": 463,
"avg_line_length": 41.26495726495727,
"alnum_prop": 0.7352250759458713,
"repo_name": "taaesan/kradarnpraweb",
"id": "62d9c6c3377be72187ca2ce23d9b9306cdd2a105",
"size": "14484",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bower_components/pagePiling.js/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "19300"
},
{
"name": "CSS",
"bytes": "22544"
},
{
"name": "HTML",
"bytes": "5492968"
},
{
"name": "JavaScript",
"bytes": "125870"
},
{
"name": "PHP",
"bytes": "1921921"
}
]
}
|
namespace {
// Mark as volatile to defensively make sure usage is thread-safe.
// Note that at the time of this writing, access is only on the UI thread.
static volatile bool g_non_browser_ui_displayed = false;
const base::Time* MainEntryPointTimeInternal() {
static base::Time main_start_time = base::Time::Now();
return &main_start_time;
}
static bool g_main_entry_time_was_recorded = false;
} // namespace
namespace startup_metric_utils {
bool WasNonBrowserUIDisplayed() {
return g_non_browser_ui_displayed;
}
void SetNonBrowserUIDisplayed() {
g_non_browser_ui_displayed = true;
}
void RecordMainEntryPointTime() {
DCHECK(!g_main_entry_time_was_recorded);
g_main_entry_time_was_recorded = true;
MainEntryPointTimeInternal();
}
const base::Time MainEntryStartTime() {
DCHECK(g_main_entry_time_was_recorded);
return *MainEntryPointTimeInternal();
}
} // namespace startup_metric_utils
|
{
"content_hash": "95f2e9b7a9c1f897fa8f50e00a4eafe4",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 74,
"avg_line_length": 25.416666666666668,
"alnum_prop": 0.740983606557377,
"repo_name": "junmin-zhu/chromium-rivertrail",
"id": "2292fffe77da3a7991b9e62ddff2aac2bfd4150b",
"size": "1184",
"binary": false,
"copies": "4",
"ref": "refs/heads/v8-binding",
"path": "chrome/common/startup_metric_utils.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "853"
},
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "1172794"
},
{
"name": "Awk",
"bytes": "9519"
},
{
"name": "C",
"bytes": "75806807"
},
{
"name": "C#",
"bytes": "1132"
},
{
"name": "C++",
"bytes": "145161929"
},
{
"name": "DOT",
"bytes": "1559"
},
{
"name": "F#",
"bytes": "381"
},
{
"name": "Java",
"bytes": "1546515"
},
{
"name": "JavaScript",
"bytes": "18675242"
},
{
"name": "Logos",
"bytes": "4517"
},
{
"name": "Matlab",
"bytes": "5234"
},
{
"name": "Objective-C",
"bytes": "6981387"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "Perl",
"bytes": "926245"
},
{
"name": "Python",
"bytes": "8088373"
},
{
"name": "R",
"bytes": "262"
},
{
"name": "Ragel in Ruby Host",
"bytes": "3239"
},
{
"name": "Shell",
"bytes": "1513486"
},
{
"name": "Tcl",
"bytes": "277077"
},
{
"name": "XML",
"bytes": "13493"
}
]
}
|
from __future__ import print_function
import os
import fnmatch
import re
import sys
import urllib.parse
import argparse
HOSTNAME = 'https://azure-sdk-impressions.azurewebsites.net'
README_PATTERNS = ['*/readme.md', '*/readme.rst']
MARKDOWN_REGEX = r'!\[Impressions\]\([^\)]+\)'
RST_REGEX = r'\.\. image:: ' + HOSTNAME + r'/api/impressions/[^\s]+'
TRACKING_PIXEL_MD_FORMAT_STRING = ''
TRACKING_PIXEL_RST_FORMAT_STRING = '.. image:: ' + HOSTNAME + '/api/impressions/{0}{1}'
# walks a target directory with support for multiple glob patterns
def walk_directory_for_pattern(target_directory, target_patterns):
expected_locations = []
target_directory = os.path.normpath(target_directory)
normalized_target_patterns = [os.path.normpath(pattern) for pattern in target_patterns]
# walk the folders, filter to the patterns established
for folder, subfolders, files in os.walk(target_directory):
for file in files:
file_path = os.path.join(folder, file)
if check_match(file_path, normalized_target_patterns):
expected_locations.append(file_path)
return expected_locations
# a set of glob patterns against a single file path
def check_match(file_path, normalized_target_patterns):
return any([fnmatch.fnmatch(file_path, normalized_target_pattern)
for normalized_target_pattern in normalized_target_patterns])
# returns all readmes that match either of the readme patterns.
def get_all_readme_files(folder_location):
return walk_directory_for_pattern(folder_location, README_PATTERNS)
# runs across provided set of readmes, inserts or updates pixels in all
def update_readmes_with_tracking(readme_files, target_directory, repo_id):
for file_path in readme_files:
with open(file_path, 'r') as f:
data = f.read()
md_regex = re.compile(MARKDOWN_REGEX, re.IGNORECASE | re.MULTILINE)
rs_regex = re.compile(RST_REGEX, re.IGNORECASE | re.MULTILINE)
try:
extension = os.path.splitext(file_path)[1]
except e:
print('No file extension present.')
print(e)
exit(1)
if (extension == '.rst'):
updated_content = replace_tracking_pixel_rst(file_path, data, rs_regex, target_directory, repo_id)
if (extension == '.md'):
updated_content = replace_tracking_pixel_md(file_path, data, md_regex, target_directory, repo_id)
if updated_content != data:
with open(file_path, 'w') as f:
f.write(updated_content)
# insert/update tracking pixel, rst specific
def replace_tracking_pixel_rst(file_path, file_content, compiled_regex, target_directory, repo_id):
existing_matches = compiled_regex.search(file_content)
if existing_matches:
return compiled_regex.sub(get_tracking_pixel(TRACKING_PIXEL_RST_FORMAT_STRING, file_path, target_directory, repo_id), file_content)
else:
return file_content + '\n\n' + get_tracking_pixel(TRACKING_PIXEL_RST_FORMAT_STRING, file_path, target_directory, repo_id) + '\n'
# insert/update tracking pixel, markdown specific
def replace_tracking_pixel_md(file_path, file_content, compiled_regex, target_directory, repo_id):
existing_matches = compiled_regex.search(file_content)
if existing_matches:
return compiled_regex.sub(get_tracking_pixel(TRACKING_PIXEL_MD_FORMAT_STRING, file_path, target_directory, repo_id), file_content)
else:
return file_content + '\n\n' + get_tracking_pixel(TRACKING_PIXEL_MD_FORMAT_STRING, file_path, target_directory, repo_id) + '\n'
# creates the pixel tag
def get_tracking_pixel(fmt_string, file_path, target_directory, repo_id):
# remove leading folders
relative_path = file_path.replace(os.path.normpath(target_directory), '')
# rename to an image
relative_path = os.path.splitext(relative_path)[0] + '.png'
# ensure that windows doesn't mess up anything
slash_path = relative_path.replace('\\', '/')
# uri encode
url_encoded_path = urllib.parse.quote_plus(slash_path)
return fmt_string.format(repo_id, url_encoded_path)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description ='Script that will take any repository + identifier as input, and add or update a tracking pixel image in all readme files contained within the input directory.')
parser.add_argument(
'-d',
'--scan-directory',
dest = 'scan_directory',
help = 'The repo directory that this tool should be scanning.',
required = True)
parser.add_argument(
'-i',
'--id',
dest = 'repo_id',
help = 'The repository identifier. Will be prefixed onto the readme path.',
required = True)
args = parser.parse_args()
args.scan_directory = os.path.abspath(args.scan_directory)
target_readme_files = get_all_readme_files(args.scan_directory)
update_readmes_with_tracking(target_readme_files, args.scan_directory, args.repo_id)
|
{
"content_hash": "207feeb783ec1a316aaced384b4ee73a",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 211,
"avg_line_length": 42.25833333333333,
"alnum_prop": 0.6811279826464208,
"repo_name": "tg-msft/azure-sdk-tools",
"id": "30d9e08a5b9102efc419f423fb6c798592036ea5",
"size": "5071",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scripts/python/readme_tracking/update_readmes_for_tracking.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "816"
},
{
"name": "C#",
"bytes": "1358017"
},
{
"name": "CSS",
"bytes": "6089"
},
{
"name": "Dockerfile",
"bytes": "868"
},
{
"name": "Go",
"bytes": "35301"
},
{
"name": "HTML",
"bytes": "59599"
},
{
"name": "Java",
"bytes": "187077"
},
{
"name": "JavaScript",
"bytes": "9361"
},
{
"name": "PowerShell",
"bytes": "312580"
},
{
"name": "Python",
"bytes": "187175"
},
{
"name": "SCSS",
"bytes": "9152"
},
{
"name": "Shell",
"bytes": "8139"
},
{
"name": "TypeScript",
"bytes": "21823"
}
]
}
|
<?php
declare(strict_types=1);
namespace Helper;
use Zend\Diactoros\UploadedFile;
trait UploadFileTrait
{
protected $tmpFile;
/** @var UploadedFile */
protected $uploadedFile;
public function setupUploadFile()
{
$uploadDir = __DIR__ . '/../../_data/upload/';
$imageFile = $uploadDir . 'phpjBhmXi';
$this->tmpFile = $uploadDir . 'tmp/phpjBhmXi';
if (! file_exists($uploadDir . 'tmp/')) {
mkdir($uploadDir . 'tmp/', 0777, true);
}
copy($imageFile, $this->tmpFile);
$this->uploadedFile = new UploadedFile(
$this->tmpFile,
786572,
0,
'earth.tiff',
'image/tiff'
);
}
}
|
{
"content_hash": "b8f5681ed0fe9742b0694fca52b8116a",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 54,
"avg_line_length": 22.78125,
"alnum_prop": 0.5308641975308642,
"repo_name": "pacphp/graphql-package",
"id": "5cc7914ab061baae95c3f26fd3afac6970b1baea",
"size": "729",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/_support/Helper/UploadFileTrait.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "36911"
}
]
}
|
/***********************************************************************
created: 21/2/2004
author: Paul D Turner
purpose: Implements the Window base class
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS 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.
***************************************************************************/
#include "CEGUI/Window.h"
#include "CEGUI/Exceptions.h"
#include "CEGUI/WindowManager.h"
#include "CEGUI/System.h"
#include "CEGUI/FontManager.h"
#include "CEGUI/ImageManager.h"
#include "CEGUI/Cursor.h"
#include "CEGUI/CoordConverter.h"
#include "CEGUI/WindowRendererManager.h"
#include "CEGUI/WindowFactoryManager.h"
#include "CEGUI/widgets/Tooltip.h"
#include "CEGUI/falagard/WidgetLookManager.h"
#include "CEGUI/falagard/WidgetLookFeel.h"
#include "CEGUI/falagard/WidgetComponent.h"
#include "CEGUI/GeometryBuffer.h"
#include "CEGUI/GUIContext.h"
#include "CEGUI/RenderingContext.h"
#include "CEGUI/RenderingWindow.h"
#include "CEGUI/GlobalEventSet.h"
#include <algorithm>
#include <iterator>
#include <cmath>
#include <stdio.h>
#include <queue>
#if defined (CEGUI_USE_FRIBIDI)
#include "CEGUI/FribidiVisualMapping.h"
#elif defined (CEGUI_USE_MINIBIDI)
#include "CEGUI/MinibidiVisualMapping.h"
#else
#include "CEGUI/BidiVisualMapping.h"
#endif
#if defined(_MSC_VER)
# pragma warning(push)
# pragma warning(disable : 4355)
#endif
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
const String Window::EventNamespace("Window");
const String Window::EventUpdated ("Updated");
const String Window::EventTextChanged("TextChanged");
const String Window::EventFontChanged("FontChanged");
const String Window::EventAlphaChanged("AlphaChanged");
const String Window::EventIDChanged("IDChanged");
const String Window::EventActivated("Activated");
const String Window::EventDeactivated("Deactivated");
const String Window::EventShown("Shown");
const String Window::EventHidden("Hidden");
const String Window::EventEnabled("Enabled");
const String Window::EventDisabled("Disabled");
const String Window::EventClippedByParentChanged( "ClippedByParentChanged" );
const String Window::EventDestroyedByParentChanged("DestroyedByParentChanged");
const String Window::EventInheritsAlphaChanged( "InheritsAlphaChanged" );
const String Window::EventAlwaysOnTopChanged("AlwaysOnTopChanged");
const String Window::EventInputCaptureGained( "InputCaptureGained" );
const String Window::EventInputCaptureLost( "InputCaptureLost" );
const String Window::EventInvalidated( "Invalidated" );
const String Window::EventRenderingStarted( "RenderingStarted" );
const String Window::EventRenderingEnded( "RenderingEnded" );
const String Window::EventDestructionStarted( "DestructionStarted" );
const String Window::EventDragDropItemEnters("DragDropItemEnters");
const String Window::EventDragDropItemLeaves("DragDropItemLeaves");
const String Window::EventDragDropItemDropped("DragDropItemDropped");
const String Window::EventWindowRendererAttached("WindowRendererAttached");
const String Window::EventWindowRendererDetached("WindowRendererDetached");
const String Window::EventTextParsingChanged("TextParsingChanged");
const String Window::EventMarginChanged("MarginChanged");
const String Window::EventCursorEntersArea("CursorEntersArea");
const String Window::EventCursorLeavesArea("CursorLeavesArea");
const String Window::EventCursorEntersSurface("CursorEntersSurface");
const String Window::EventCursorLeavesSurface("CursorLeavesSurface");
const String Window::EventCursorMove("CursorMove");
const String Window::EventCursorPressHold("CursorPressHold");
const String Window::EventCursorActivate("CursorActivate");
const String Window::EventCharacterKey("CharacterKey");
const String Window::EventScroll("Scroll");
const String Window::EventSemanticEvent("SemanticEvent");
//----------------------------------------------------------------------------//
// XML element and attribute names that relate to Window.
const String Window::WindowXMLElementName("Window");
const String Window::AutoWindowXMLElementName("AutoWindow");
const String Window::UserStringXMLElementName("UserString");
const String Window::WindowTypeXMLAttributeName("type");
const String Window::WindowNameXMLAttributeName("name");
const String Window::AutoWindowNamePathXMLAttributeName("namePath");
const String Window::UserStringNameXMLAttributeName("name");
const String Window::UserStringValueXMLAttributeName("value");
//----------------------------------------------------------------------------//
const String Window::TooltipNameSuffix("__auto_tooltip__");
//----------------------------------------------------------------------------//
BasicRenderedStringParser Window::d_basicStringParser;
DefaultRenderedStringParser Window::d_defaultStringParser;
//----------------------------------------------------------------------------//
Window::WindowRendererProperty Window::d_windowRendererProperty;
Window::LookNFeelProperty Window::d_lookNFeelProperty;
//----------------------------------------------------------------------------//
Window::WindowRendererProperty::WindowRendererProperty() : TplWindowProperty<Window,String>(
"WindowRenderer",
"Property to get/set the assigned WindowRenderer object type. For "
"advanced use only. See the api reference for Window::setWindowRenderer "
"for more information. "
"Value is a string.",
"Window", &Window::setWindowRenderer,&Window::getWindowRendererName, "")
{}
//----------------------------------------------------------------------------//
void Window::WindowRendererProperty::writeXMLToStream(const PropertyReceiver* receiver,
XMLSerializer& xml_stream) const
{
const Window* wnd = static_cast<const Window*>(receiver);
if (!WindowFactoryManager::getSingleton().isFalagardMappedType(wnd->getType()))
Property::writeXMLToStream(receiver, xml_stream);
}
//----------------------------------------------------------------------------//
Window::LookNFeelProperty::LookNFeelProperty() : TplWindowProperty<Window,String>(
"LookNFeel",
"Property to get/set the assigned look'n'feel. For advanced use only. See "
"the api reference for Window::setLookNFeel for more informaton. "
"Value is a string.",
"Window", &Window::setLookNFeel,&Window::getLookNFeel, "")
{}
//----------------------------------------------------------------------------//
void Window::LookNFeelProperty::writeXMLToStream(const PropertyReceiver* receiver,
XMLSerializer& xml_stream) const
{
const Window* wnd = static_cast<const Window*>(receiver);
if (!WindowFactoryManager::getSingleton().isFalagardMappedType(wnd->getType()))
Property::writeXMLToStream(receiver, xml_stream);
}
//----------------------------------------------------------------------------//
Window::Window(const String& type, const String& name):
NamedElement(name),
// basic types and initial window name
d_type(type),
d_autoWindow(false),
// basic state
d_initialising(false),
d_destructionStarted(false),
d_enabled(true),
d_visible(true),
d_active(false),
// parent related fields
d_destroyedByParent(true),
// clipping options
d_clippedByParent(true),
// rendering components and options
d_windowRenderer(0),
d_surface(0),
d_needsRedraw(true),
d_autoRenderingWindow(false),
d_cursor(0),
// alpha transparency set up
d_alpha(1.0f),
d_inheritsAlpha(true),
// cursor input capture set up
d_oldCapture(0),
d_restoreOldCapture(false),
d_distCapturedInputs(false),
// text system set up
d_font(0),
#ifndef CEGUI_BIDI_SUPPORT
d_bidiVisualMapping(0),
#elif defined (CEGUI_USE_FRIBIDI)
d_bidiVisualMapping(new FribidiVisualMapping),
#elif defined (CEGUI_USE_MINIBIDI)
d_bidiVisualMapping(new MinibidiVisualMapping),
#else
#error "BIDI Configuration is inconsistant, check your config!"
#endif
d_bidiDataValid(false),
d_renderedStringValid(false),
d_customStringParser(0),
d_textParsingEnabled(true),
// margin
d_margin(UBox(UDim(0, 0))),
// user specific data
d_ID(0),
d_userData(0),
// z-order related options
d_alwaysOnTop(false),
d_riseOnPointerActivation(true),
d_zOrderingEnabled(true),
d_cursorPassThroughEnabled(false),
d_autoRepeat(false),
d_repeatDelay(0.3f),
d_repeatRate(0.06f),
d_repeatPointerSource(CIS_None),
d_repeating(false),
d_repeatElapsed(0.0f),
// drag and drop
d_dragDropTarget(true),
// tool tip related
d_customTip(0),
d_weOwnTip(false),
d_inheritsTipText(true),
// XML writing options
d_allowWriteXML(true),
// initialise area cache rects
d_outerRectClipper(0, 0, 0, 0),
d_innerRectClipper(0, 0, 0, 0),
d_hitTestRect(0, 0, 0, 0),
// cached pixel rect validity flags
d_outerRectClipperValid(false),
d_innerRectClipperValid(false),
d_hitTestRectValid(false),
// Initial update mode
d_updateMode(WUM_VISIBLE),
// Don't propagate cursor inputs by default.
d_propagatePointerInputs(false),
d_guiContext(0),
d_containsPointer(false),
d_isFocused(false),
d_fontRenderSizeChangeConnection(
GlobalEventSet::getSingleton().subscribeEvent(
"Font/RenderSizeChanged",
Event::Subscriber(&Window::handleFontRenderSizeChange, this)))
{
// add properties
addWindowProperties();
}
//----------------------------------------------------------------------------//
Window::~Window(void)
{
// most cleanup actually happened earlier in Window::destroy.
destroyGeometryBuffers();
delete d_bidiVisualMapping;
}
//----------------------------------------------------------------------------//
const String& Window::getType(void) const
{
return d_falagardType.empty() ? d_type : d_falagardType;
}
//----------------------------------------------------------------------------//
bool Window::isDisabled() const
{
return !d_enabled;
}
//----------------------------------------------------------------------------//
bool Window::isEffectiveDisabled() const
{
const bool parent_disabled = !d_parent ? false : getParent()->isEffectiveDisabled();
return !d_enabled || parent_disabled;
}
//----------------------------------------------------------------------------//
bool Window::isVisible() const
{
return d_visible;
}
//----------------------------------------------------------------------------//
bool Window::isEffectiveVisible() const
{
const bool parent_visible = !d_parent ? true : getParent()->isEffectiveVisible();
return d_visible && parent_visible;
}
//----------------------------------------------------------------------------//
bool Window::isActive(void) const
{
const bool parent_active = !d_parent ? true : getParent()->isActive();
return d_active && parent_active;
}
//----------------------------------------------------------------------------//
bool Window::isChild(uint ID) const
{
const size_t child_count = getChildCount();
for (size_t i = 0; i < child_count; ++i)
if (getChildAtIdx(i)->getID() == ID)
return true;
return false;
}
//----------------------------------------------------------------------------//
bool Window::isChildRecursive(uint ID) const
{
const size_t child_count = getChildCount();
for (size_t i = 0; i < child_count; ++i)
if (getChildAtIdx(i)->getID() == ID || getChildAtIdx(i)->isChildRecursive(ID))
return true;
return false;
}
//----------------------------------------------------------------------------//
Window* Window::getChild(uint ID) const
{
const size_t child_count = getChildCount();
for (size_t i = 0; i < child_count; ++i)
if (getChildAtIdx(i)->getID() == ID)
return getChildAtIdx(i);
char strbuf[16];
sprintf(strbuf, "%X", ID);
CEGUI_THROW(UnknownObjectException("A Window with ID: '" +
String(strbuf) + "' is not attached to Window '" + d_name + "'."));
}
//----------------------------------------------------------------------------//
Window* Window::getChildRecursive(uint ID) const
{
const size_t child_count = getChildCount();
std::queue<Element*> ElementsToSearch;
for (size_t i = 0; i < child_count; ++i) // load all children into the queue
{
Element* child = getChildElementAtIdx(i);
ElementsToSearch.push(child);
}
while (!ElementsToSearch.empty()) // breadth-first search for the child to find
{
Element* child = ElementsToSearch.front();
ElementsToSearch.pop();
Window* window = dynamic_cast<Window*>(child);
if (window)
{
if (window->getID() == ID)
{
return window;
}
}
const size_t element_child_count = child->getChildCount();
for(size_t i = 0; i < element_child_count; ++i)
{
ElementsToSearch.push(child->getChildElementAtIdx(i));
}
}
return 0;
}
//----------------------------------------------------------------------------//
Window* Window::getActiveChild(void)
{
return const_cast<Window*>(
static_cast<const Window*>(this)->getActiveChild());
}
//----------------------------------------------------------------------------//
const Window* Window::getActiveChild(void) const
{
// are children can't be active if we are not
if (!isActive())
return 0;
for (ChildDrawList::const_reverse_iterator it = d_drawList.rbegin(); it != d_drawList.rend(); ++it)
{
// don't need full backward scan for activeness as we already know
// 'this' is active. NB: This uses the draw-ordered child list, as that
// should be quicker in most cases.
const Window* wnd = *it;
if (wnd->d_active)
return wnd->getActiveChild();
}
// no child was active, therefore we are the topmost active window
return this;
}
//----------------------------------------------------------------------------//
bool Window::isAncestor(uint ID) const
{
// return false if we have no ancestor
if (!d_parent)
return false;
// check our immediate parent
if (getParent()->getID() == ID)
return true;
// not our parent, check back up the family line
return getParent()->isAncestor(ID);
}
//----------------------------------------------------------------------------//
const Font* Window::getFont(bool useDefault) const
{
if (!d_font)
return useDefault ? getGUIContext().getDefaultFont() : 0;
return d_font;
}
//----------------------------------------------------------------------------//
float Window::getEffectiveAlpha(void) const
{
if (!d_parent || !inheritsAlpha())
return d_alpha;
return d_alpha * getParent()->getEffectiveAlpha();
}
//----------------------------------------------------------------------------//
const Rectf& Window::getOuterRectClipper() const
{
if (!d_outerRectClipperValid)
{
d_outerRectClipper = getOuterRectClipper_impl();
d_outerRectClipperValid = true;
}
return d_outerRectClipper;
}
//----------------------------------------------------------------------------//
const Rectf& Window::getInnerRectClipper() const
{
if (!d_innerRectClipperValid)
{
d_innerRectClipper = getInnerRectClipper_impl();
d_innerRectClipperValid = true;
}
return d_innerRectClipper;
}
//----------------------------------------------------------------------------//
const Rectf& Window::getClipRect(const bool non_client) const
{
return non_client ? getOuterRectClipper() : getInnerRectClipper();
}
//----------------------------------------------------------------------------//
const Rectf& Window::getHitTestRect() const
{
if (!d_hitTestRectValid)
{
d_hitTestRect = getHitTestRect_impl();
d_hitTestRectValid = true;
}
return d_hitTestRect;
}
//----------------------------------------------------------------------------//
Rectf Window::getParentElementClipIntersection(const Rectf& unclipped_area) const
{
return unclipped_area.getIntersection(
(d_parent && d_clippedByParent) ?
getParent()->getClipRect(isNonClient()) :
Rectf(glm::vec2(0, 0), getRootContainerSize()));
}
//----------------------------------------------------------------------------//
Rectf Window::getUnclippedInnerRect_impl(bool skipAllPixelAlignment) const
{
// TODO: skip all pixel alignment!
return d_windowRenderer ? d_windowRenderer->getUnclippedInnerRect() :
(skipAllPixelAlignment ? getUnclippedOuterRect().getFresh(true) : getUnclippedOuterRect().get());
}
//----------------------------------------------------------------------------//
Rectf Window::getOuterRectClipper_impl() const
{
return (d_surface && d_surface->isRenderingWindow()) ?
getUnclippedOuterRect().get() :
getParentElementClipIntersection(getUnclippedOuterRect().get());
}
//----------------------------------------------------------------------------//
Rectf Window::getInnerRectClipper_impl() const
{
return (d_surface && d_surface->isRenderingWindow()) ?
getUnclippedInnerRect().get() :
getParentElementClipIntersection(getUnclippedInnerRect().get());
}
//----------------------------------------------------------------------------//
Rectf Window::getHitTestRect_impl() const
{
// if clipped by parent wnd, hit test area is the intersection of our
// outer rect with the parent's hit test area intersected with the
// parent's clipper.
if (d_parent && d_clippedByParent)
{
return getUnclippedOuterRect().get().getIntersection(
getParent()->getHitTestRect().getIntersection(
getParent()->getClipRect(isNonClient())));
}
// not clipped to parent wnd, so get intersection with screen area.
else
{
return getUnclippedOuterRect().get().getIntersection(
Rectf(glm::vec2(0, 0), getRootContainerSize()));
}
}
//----------------------------------------------------------------------------//
bool Window::isHit(const glm::vec2& position, const bool allow_disabled) const
{
// cannot be hit if we are disabled.
if (!allow_disabled && isEffectiveDisabled())
return false;
const Rectf test_area(getHitTestRect());
if ((test_area.getWidth() == 0.0f) || (test_area.getHeight() == 0.0f))
return false;
return test_area.isPointInRect(position);
}
//----------------------------------------------------------------------------//
Window* Window::getChildAtPosition(const glm::vec2& position) const
{
return getChildAtPosition(position, &Window::isHit);
}
//----------------------------------------------------------------------------//
Window* Window::getChildAtPosition(const glm::vec2& position,
bool (Window::*hittestfunc)(const glm::vec2&, bool) const,
bool allow_disabled) const
{
glm::vec2 p;
// if the window has RenderingWindow backing
if (d_surface && d_surface->isRenderingWindow())
static_cast<RenderingWindow*>(d_surface)->unprojectPoint(position, p);
else
p = position;
const ChildDrawList::const_reverse_iterator end = d_drawList.rend();
ChildDrawList::const_reverse_iterator child;
for (child = d_drawList.rbegin(); child != end; ++child)
{
if ((*child)->isEffectiveVisible())
{
// recursively scan for hit on children of this child window...
if (Window* const wnd = (*child)->getChildAtPosition(p, hittestfunc, allow_disabled))
return wnd;
// see if this child is hit and return it's cursor if it is
else if (((*child)->*hittestfunc)(p, allow_disabled))
return *child;
}
}
// nothing hit
return 0;
}
//----------------------------------------------------------------------------//
Window* Window::getTargetChildAtPosition(const glm::vec2& position,
const bool allow_disabled) const
{
return getChildAtPosition(position, &Window::isHitTargetWindow, allow_disabled);
}
//----------------------------------------------------------------------------//
bool Window::isHitTargetWindow(const glm::vec2& position, bool allow_disabled) const
{
return !isCursorPassThroughEnabled() && isHit(position, allow_disabled);
}
//----------------------------------------------------------------------------//
void Window::setAlwaysOnTop(bool setting)
{
// only react to an actual change
if (isAlwaysOnTop() == setting)
return;
d_alwaysOnTop = setting;
// move us in front of sibling windows with the same 'always-on-top'
// setting as we have.
if (d_parent)
{
Window* const org_parent = getParent();
org_parent->removeChild_impl(this);
org_parent->addChild_impl(this);
onZChange_impl();
}
WindowEventArgs args(this);
onAlwaysOnTopChanged(args);
}
//----------------------------------------------------------------------------//
void Window::setEnabled(bool setting)
{
// only react if setting has changed
if (d_enabled == setting)
return;
d_enabled = setting;
WindowEventArgs args(this);
if (d_enabled)
{
// check to see if the window is actually enabled (which depends
// upon all ancestor windows being enabled) we do this so that
// events we fire give an accurate indication of the state of a
// window.
if ((d_parent && !getParent()->isDisabled()) || !d_parent)
onEnabled(args);
}
else
{
onDisabled(args);
}
getGUIContext().updateWindowContainingCursor();
}
//----------------------------------------------------------------------------//
void Window::setDisabled(bool setting)
{
setEnabled(!setting);
}
//----------------------------------------------------------------------------//
void Window::setVisible(bool setting)
{
// only react if setting has changed
if (d_visible == setting)
return;
d_visible = setting;
WindowEventArgs args(this);
d_visible ? onShown(args) : onHidden(args);
getGUIContext().updateWindowContainingCursor();
}
//----------------------------------------------------------------------------//
void Window::activate(void)
{
// exit if the window is not visible, since a hidden window may not be the
// active window.
if (!isEffectiveVisible())
return;
// force complete release of input capture.
// NB: This is not done via releaseCapture() because that has
// different behaviour depending on the restoreOldCapture setting.
if (getCaptureWindow() && getCaptureWindow() != this)
{
Window* const tmpCapture = getCaptureWindow();
getGUIContext().setInputCaptureWindow(0);
WindowEventArgs args(0);
tmpCapture->onCaptureLost(args);
}
moveToFront();
}
//----------------------------------------------------------------------------//
void Window::deactivate(void)
{
ActivationEventArgs args(this);
args.otherWindow = 0;
onDeactivated(args);
}
//----------------------------------------------------------------------------//
void Window::setClippedByParent(bool setting)
{
// only react if setting has changed
if (d_clippedByParent == setting)
return;
d_clippedByParent = setting;
WindowEventArgs args(this);
onClippingChanged(args);
}
//----------------------------------------------------------------------------//
void Window::setText(const String& text)
{
d_textLogical = text;
d_renderedStringValid = false;
d_bidiDataValid = false;
WindowEventArgs args(this);
onTextChanged(args);
}
//----------------------------------------------------------------------------//
void Window::setFont(const Font* font)
{
d_font = font;
d_renderedStringValid = false;
WindowEventArgs args(this);
onFontChanged(args);
}
//----------------------------------------------------------------------------//
void Window::setFont(const String& name)
{
setFont(!name.empty() ? &FontManager::getSingleton().get(name) : 0);
}
//----------------------------------------------------------------------------//
void Window::removeChild(uint ID)
{
const size_t child_count = getChildCount();
for (size_t i = 0; i < child_count; ++i)
{
if (getChildAtIdx(i)->getID() == ID)
{
removeChild(d_children[i]);
return;
}
}
}
//----------------------------------------------------------------------------//
Window* Window::createChild(const String& type, const String& name)
{
Window* ret = WindowManager::getSingleton().createWindow(type, name);
addChild(ret);
return ret;
}
//----------------------------------------------------------------------------//
void Window::destroyChild(Window* wnd)
{
assert(isChild(wnd) && "Window you are attempting to destroy is not a child!");
WindowManager::getSingleton().destroyWindow(wnd);
}
//----------------------------------------------------------------------------//
void Window::destroyChild(const String& name_path)
{
destroyChild(getChild(name_path));
}
//----------------------------------------------------------------------------//
void Window::moveToFront()
{
moveToFront_impl(false);
}
//----------------------------------------------------------------------------//
bool Window::moveToFront_impl(bool wasClicked)
{
bool took_action = false;
// if the window has no parent then we can have no siblings
if (!d_parent)
{
// perform initial activation if required.
if (!isActive())
{
took_action = true;
ActivationEventArgs args(this);
args.otherWindow = 0;
onActivated(args);
}
return took_action;
}
// bring parent window to front of it's siblings
took_action = getParent()->moveToFront_impl(wasClicked);
// get immediate child of parent that is currently active (if any)
Window* const activeWnd = getActiveSibling();
// if a change in active window has occurred
if (activeWnd != this)
{
took_action = true;
// notify ourselves that we have become active
ActivationEventArgs args(this);
args.otherWindow = activeWnd;
onActivated(args);
// notify any previously active window that it is no longer active
if (activeWnd)
{
args.window = activeWnd;
args.otherWindow = this;
args.handled = 0;
activeWnd->onDeactivated(args);
}
}
// bring us to the front of our siblings
if (d_zOrderingEnabled &&
(!wasClicked || d_riseOnPointerActivation) &&
!isTopOfZOrder())
{
took_action = true;
// remove us from our parent's draw list
getParent()->removeWindowFromDrawList(*this);
// re-attach ourselves to our parent's draw list which will move us in
// front of sibling windows with the same 'always-on-top' setting as we
// have.
getParent()->addWindowToDrawList(*this);
// notify relevant windows about the z-order change.
onZChange_impl();
}
return took_action;
}
//----------------------------------------------------------------------------//
void Window::moveToBack()
{
// if the window is active, de-activate it.
if (isActive())
{
ActivationEventArgs args(this);
args.otherWindow = 0;
onDeactivated(args);
}
// we only proceed if we have a parent (otherwise we can have no siblings)
if (d_parent)
{
if (d_zOrderingEnabled)
{
// remove us from our parent's draw list
getParent()->removeWindowFromDrawList(*this);
// re-attach ourselves to our parent's draw list which will move us
// in behind sibling windows with the same 'always-on-top' setting
// as we have.
getParent()->addWindowToDrawList(*this, true);
// notify relevant windows about the z-order change.
onZChange_impl();
}
getParent()->moveToBack();
}
}
//----------------------------------------------------------------------------//
bool Window::captureInput(void)
{
// we can only capture if we are the active window (LEAVE THIS ALONE!)
if (!isActive())
return false;
if (!isCapturedByThis())
{
Window* const current_capture = getCaptureWindow();
getGUIContext().setInputCaptureWindow(this);
WindowEventArgs args(this);
// inform window which previously had capture that it doesn't anymore.
if (current_capture && current_capture != this && !d_restoreOldCapture)
current_capture->onCaptureLost(args);
if (d_restoreOldCapture)
d_oldCapture = current_capture;
onCaptureGained(args);
}
return true;
}
//----------------------------------------------------------------------------//
void Window::releaseInput(void)
{
// if we are not the window that has capture, do nothing
if (!isCapturedByThis())
return;
// restore old captured window if that mode is set
if (d_restoreOldCapture)
{
getGUIContext().setInputCaptureWindow(d_oldCapture);
// check for case when there was no previously captured window
if (d_oldCapture)
{
d_oldCapture = 0;
getCaptureWindow()->moveToFront();
}
}
else
getGUIContext().setInputCaptureWindow(0);
WindowEventArgs args(this);
onCaptureLost(args);
}
//----------------------------------------------------------------------------//
void Window::setRestoreOldCapture(bool setting)
{
d_restoreOldCapture = setting;
const size_t child_count = getChildCount();
for (size_t i = 0; i < child_count; ++i)
getChildAtIdx(i)->setRestoreOldCapture(setting);
}
//----------------------------------------------------------------------------//
void Window::setAlpha(const float alpha)
{
// clamp this to the valid range [0.0, 1.0]
float clampedAlpha = ceguimax(ceguimin(alpha, 1.0f), 0.0f);
// Ensure that the new alpha value is actually different from the currently set one
// to avoid unnecessary invalidating and re-caching of textures and children
if (d_alpha == clampedAlpha)
return;
d_alpha = clampedAlpha;
WindowEventArgs args(this);
onAlphaChanged(args);
}
//----------------------------------------------------------------------------//
void Window::setInheritsAlpha(bool setting)
{
if (d_inheritsAlpha != setting)
{
// store old effective alpha so we can test if alpha value changes due
// to new setting.
const float oldAlpha = getEffectiveAlpha();
// notify about the setting change.
d_inheritsAlpha = setting;
WindowEventArgs args(this);
onInheritsAlphaChanged(args);
// if effective alpha has changed fire notification about that too
if (oldAlpha != getEffectiveAlpha())
{
args.handled = 0;
onAlphaChanged(args);
}
}
}
//----------------------------------------------------------------------------//
void Window::invalidate(const bool recursive)
{
invalidate_impl(recursive);
getGUIContext().markAsDirty();
}
//----------------------------------------------------------------------------//
void Window::invalidate_impl(const bool recursive)
{
d_needsRedraw = true;
invalidateRenderingSurface();
WindowEventArgs args(this);
onInvalidated(args);
if (recursive)
{
const size_t child_count = getChildCount();
for (size_t i = 0; i < child_count; ++i)
getChildAtIdx(i)->invalidate_impl(true);
}
}
//----------------------------------------------------------------------------//
void Window::render()
{
// don't do anything if window is not visible
if (!isEffectiveVisible())
return;
// get rendering context
RenderingContext ctx;
getRenderingContext(ctx);
// clear geometry from surface if it's ours
if (ctx.owner == this)
ctx.surface->clearGeometry();
// redraw if no surface set, or if surface is invalidated
if (!d_surface || d_surface->isInvalidated())
{
// perform drawing for 'this' Window
drawSelf(ctx);
// render any child windows
for (ChildDrawList::iterator it = d_drawList.begin(); it != d_drawList.end(); ++it)
{
(*it)->render();
}
}
// do final rendering for surface if it's ours
if (ctx.owner == this)
ctx.surface->draw();
}
//----------------------------------------------------------------------------//
void Window::drawSelf(const RenderingContext& ctx)
{
bufferGeometry(ctx);
queueGeometry(ctx);
}
//----------------------------------------------------------------------------//
void Window::bufferGeometry(const RenderingContext&)
{
if (d_needsRedraw)
{
// dispose of already cached geometry.
destroyGeometryBuffers();
// signal rendering started
WindowEventArgs args(this);
onRenderingStarted(args);
// HACK: ensure our rendered string content is up to date
getRenderedString();
// get derived class or WindowRenderer to re-populate geometry buffer.
if (d_windowRenderer)
d_windowRenderer->render();
else
populateGeometryBuffer();
updateGeometryBuffersTranslationAndClipping();
updateGeometryBuffersAlpha();
// signal rendering ended
args.handled = 0;
onRenderingEnded(args);
// mark ourselves as no longer needed a redraw.
d_needsRedraw = false;
}
}
//----------------------------------------------------------------------------//
void Window::queueGeometry(const RenderingContext& ctx)
{
// add geometry so that it gets drawn to the target surface.
ctx.surface->addGeometryBuffers(ctx.queue, d_geometryBuffers);
}
//----------------------------------------------------------------------------//
void Window::setParent(Element* parent)
{
Element::setParent(parent);
syncTargetSurface();
}
//----------------------------------------------------------------------------//
void Window::syncTargetSurface()
{
// if we do not have a surface, xfer any surfaces from our children to
// whatever our target surface now is.
if (!d_surface)
transferChildSurfaces();
// else, since we have a surface, child surfaces stay with us. Though we
// must now ensure /our/ surface is xferred if it is a RenderingWindow.
else if (d_surface->isRenderingWindow())
{
// target surface is eihter the parent's target, or the gui context.
RenderingSurface& tgt = d_parent ?
getParent()->getTargetRenderingSurface() : getGUIContext();
tgt.transferRenderingWindow(static_cast<RenderingWindow&>(*d_surface));
}
}
//----------------------------------------------------------------------------//
void Window::cleanupChildren(void)
{
while(getChildCount() != 0)
{
Window* wnd = static_cast<Window*>(d_children[0]);
// always remove child
removeChild(wnd);
// destroy child if that is required
if (wnd->isDestroyedByParent())
WindowManager::getSingleton().destroyWindow(wnd);
}
}
//----------------------------------------------------------------------------//
void Window::addChild_impl(Element* element)
{
Window* wnd = dynamic_cast<Window*>(element);
if (!wnd)
CEGUI_THROW(InvalidRequestException(
"Window can only have Elements of type Window added as children "
"(Window path: " + getNamePath() + ")."));
// if the element is already a child of this Window, this is a NOOP
if (isChild(element))
return;
NamedElement::addChild_impl(wnd);
addWindowToDrawList(*wnd);
wnd->invalidate(true);
wnd->onZChange_impl();
}
//----------------------------------------------------------------------------//
void Window::removeChild_impl(Element* element)
{
Window* wnd = static_cast<Window*>(element);
Window* const capture_wnd = getCaptureWindow();
if ((capture_wnd && wnd) &&
(capture_wnd == wnd || capture_wnd->isAncestor(wnd)))
getCaptureWindow()->releaseInput();
// remove from draw list
removeWindowFromDrawList(*wnd);
Element::removeChild_impl(wnd);
// find this window in the child list
const ChildList::iterator position =
std::find(d_children.begin(), d_children.end(), wnd);
// if the window was found in the child list
if (position != d_children.end())
{
// unban properties window could write as a root window
wnd->unbanPropertyFromXML("RestoreOldCapture");
}
wnd->onZChange_impl();
}
//----------------------------------------------------------------------------//
void Window::onZChange_impl(void)
{
if (!d_parent)
{
WindowEventArgs args(this);
onZChanged(args);
}
else
{
const size_t child_count = d_parent->getChildCount();
for (size_t i = 0; i < child_count; ++i)
{
WindowEventArgs args(getParent()->getChildAtIdx(i));
getParent()->getChildAtIdx(i)->onZChanged(args);
}
}
getGUIContext().updateWindowContainingCursor();
}
//----------------------------------------------------------------------------//
const Image* Window::getCursor(bool useDefault) const
{
if (d_cursor)
return d_cursor;
else
return useDefault ? getGUIContext().getCursor().getDefaultImage() : 0;
}
//----------------------------------------------------------------------------//
void Window::setCursor(const String& name)
{
setCursor(
&ImageManager::getSingleton().get(name));
}
//----------------------------------------------------------------------------//
void Window::setCursor(const Image* image)
{
d_cursor = image;
if (getGUIContext().getWindowContainingCursor() == this)
getGUIContext().getCursor().setImage(image);
}
//----------------------------------------------------------------------------//
void Window::setID(uint ID)
{
if (d_ID == ID)
return;
d_ID = ID;
WindowEventArgs args(this);
onIDChanged(args);
}
//----------------------------------------------------------------------------//
void Window::setDestroyedByParent(bool setting)
{
if (d_destroyedByParent == setting)
return;
d_destroyedByParent = setting;
WindowEventArgs args(this);
onParentDestroyChanged(args);
}
//----------------------------------------------------------------------------//
void Window::generateAutoRepeatEvent(CursorInputSource source)
{
CursorInputEventArgs ciea(this);
ciea.position = getUnprojectedPosition(
getGUIContext().getCursor().getPosition());
ciea.moveDelta = glm::vec2(0, 0);
ciea.source = source;
ciea.scroll = 0;
onCursorPressHold(ciea);
}
//----------------------------------------------------------------------------//
void Window::addWindowProperties(void)
{
const String propertyOrigin("Window");
CEGUI_DEFINE_PROPERTY(Window, float,
"Alpha", "Property to get/set the alpha value of the Window. Value is floating point number.",
&Window::setAlpha, &Window::getAlpha, 1.0f
);
CEGUI_DEFINE_PROPERTY(Window, bool,
"AlwaysOnTop", "Property to get/set the 'always on top' setting for the Window. Value is either \"true\" or \"false\".",
&Window::setAlwaysOnTop, &Window::isAlwaysOnTop, false
);
CEGUI_DEFINE_PROPERTY(Window, bool,
"ClippedByParent", "Property to get/set the 'clipped by parent' setting for the Window. Value is either \"true\" or \"false\".",
&Window::setClippedByParent, &Window::isClippedByParent, true
);
CEGUI_DEFINE_PROPERTY(Window, bool,
"DestroyedByParent", "Property to get/set the 'destroyed by parent' setting for the Window. Value is either \"true\" or \"false\".",
&Window::setDestroyedByParent, &Window::isDestroyedByParent, true
);
CEGUI_DEFINE_PROPERTY(Window, bool,
"Disabled", "Property to get/set the 'disabled state' setting for the Window. Value is either \"true\" or \"false\".",
&Window::setDisabled, &Window::isDisabled, false
);
CEGUI_DEFINE_PROPERTY(Window, Font*,
"Font","Property to get/set the font for the Window. Value is the name of the font to use (must be loaded already).",
&Window::setFont, &Window::property_getFont, 0
);
CEGUI_DEFINE_PROPERTY(Window, uint,
"ID", "Property to get/set the ID value of the Window. Value is an unsigned integer number.",
&Window::setID, &Window::getID, 0
);
CEGUI_DEFINE_PROPERTY(Window, bool,
"InheritsAlpha", "Property to get/set the 'inherits alpha' setting for the Window. Value is either \"true\" or \"false\".",
&Window::setInheritsAlpha, &Window::inheritsAlpha, true
);
CEGUI_DEFINE_PROPERTY(Window, Image*,
"CursorImage","Property to get/set the cursor image for the Window. Value should be \"<image name>\".",
&Window::setCursor, &Window::property_getCursor, 0
);
CEGUI_DEFINE_PROPERTY(Window, bool,
"Visible", "Property to get/set the 'visible state' setting for the Window. Value is either \"true\" or \"false\".",
&Window::setVisible, &Window::isVisible, true
);
CEGUI_DEFINE_PROPERTY(Window, bool,
"RestoreOldCapture", "Property to get/set the 'restore old capture' setting for the Window. Value is either \"true\" or \"false\".",
&Window::setRestoreOldCapture, &Window::restoresOldCapture, false
);
CEGUI_DEFINE_PROPERTY(Window, String,
"Text", "Property to get/set the text / caption for the Window. Value is the text string to use. Meaning of this property heavily depends on the type of the Window.",
&Window::setText, &Window::getText, ""
);
CEGUI_DEFINE_PROPERTY(Window, bool,
"ZOrderingEnabled", "Property to get/set the 'z-order changing enabled' setting for the Window. Value is either \"true\" or \"false\".",
&Window::setZOrderingEnabled, &Window::isZOrderingEnabled, true
);
CEGUI_DEFINE_PROPERTY(Window, bool,
"CursorAutoRepeatEnabled", "Property to get/set whether the window will receive autorepeat cursor press events. Value is either \"true\" or \"false\".",
&Window::setCursorAutoRepeatEnabled, &Window::isCursorAutoRepeatEnabled, false
);
CEGUI_DEFINE_PROPERTY(Window, float,
"AutoRepeatDelay", "Property to get/set the autorepeat delay. Value is a floating point number indicating the delay required in seconds.",
&Window::setAutoRepeatDelay, &Window::getAutoRepeatDelay, 0.3f
);
CEGUI_DEFINE_PROPERTY(Window, float,
"AutoRepeatRate", "Property to get/set the autorepeat rate. Value is a floating point number indicating the rate required in seconds.",
&Window::setAutoRepeatRate, &Window::getAutoRepeatRate, 0.06f
);
CEGUI_DEFINE_PROPERTY(Window, bool,
"DistributeCapturedInputs", "Property to get/set whether captured inputs are passed to child windows. Value is either \"true\" or \"false\".",
&Window::setDistributesCapturedInputs, &Window::distributesCapturedInputs, false
);
CEGUI_DEFINE_PROPERTY(Window, String,
"TooltipType", "Property to get/set the custom tooltip for the window. Value is the type name of the custom tooltip. If \"\", the default System tooltip is used.",
&Window::setTooltipType, &Window::getTooltipType, ""
);
CEGUI_DEFINE_PROPERTY(Window, String,
"TooltipText", "Property to get/set the tooltip text for the window. Value is the tooltip text for the window.",
&Window::setTooltipText, &Window::getTooltipText, ""
);
CEGUI_DEFINE_PROPERTY(Window, bool,
"InheritsTooltipText", "Property to get/set whether the window inherits its parents tooltip text when it has none of its own. Value is either \"true\" or \"false\".",
&Window::setInheritsTooltipText, &Window::inheritsTooltipText, true
);
CEGUI_DEFINE_PROPERTY(Window, bool,
"RiseOnClickEnabled", "Property to get/set whether the window will come to the top of the Z-order when clicked. Value is either \"true\" or \"false\".",
&Window::setRiseOnClickEnabled, &Window::isRiseOnPointerActivationEnabled, true
);
CEGUI_DEFINE_PROPERTY(Window, bool,
"CursorPassThroughEnabled", "Property to get/set whether the window ignores cursor events and pass them through to any windows behind it. Value is either \"true\" or \"false\".",
&Window::setCursorPassThroughEnabled, &Window::isCursorPassThroughEnabled, false
);
addProperty(&d_windowRendererProperty);
addProperty(&d_lookNFeelProperty);
CEGUI_DEFINE_PROPERTY(Window, bool,
"DragDropTarget", "Property to get/set whether the Window will receive drag and drop related notifications. Value is either \"true\" or \"false\".",
&Window::setDragDropTarget, &Window::isDragDropTarget, true
);
CEGUI_DEFINE_PROPERTY(Window, bool,
"AutoRenderingSurface", "Property to get/set whether the Window will automatically attempt to "
"use a full imagery caching RenderingSurface (if supported by the "
"renderer). Here, full imagery caching usually will mean caching a "
"window's representation onto a texture (although no such "
"implementation requirement is specified.)"
" Value is either \"true\" or \"false\".",
&Window::setUsingAutoRenderingSurface, &Window::isUsingAutoRenderingSurface, false /* TODO: Inconsistency*/
);
CEGUI_DEFINE_PROPERTY(Window, bool,
"TextParsingEnabled", "Property to get/set the text parsing setting for the Window. "
"Value is either \"true\" or \"false\".",
&Window::setTextParsingEnabled, &Window::isTextParsingEnabled, true
);
CEGUI_DEFINE_PROPERTY(Window, UBox,
"Margin", "Property to get/set margin for the Window. Value format:"
"{top:{[tops],[topo]},left:{[lefts],[lefto]},bottom:{[bottoms],[bottomo]},right:{[rights],[righto]}}.",
&Window::setMargin, &Window::getMargin, UBox(UDim(0, 0))
);
CEGUI_DEFINE_PROPERTY(Window, WindowUpdateMode,
"UpdateMode", "Property to get/set the window update mode setting. "
"Value is one of \"Always\", \"Never\" or \"Visible\".",
&Window::setUpdateMode,&Window::getUpdateMode, WUM_VISIBLE
);
CEGUI_DEFINE_PROPERTY(Window, bool,
"CursorInputPropagationEnabled", "Property to get/set whether unhandled cursor inputs should be "
"propagated back to the Window's parent. "
"Value is either \"true\" or \"false\".",
&Window::setCursorInputPropagationEnabled, &Window::isCursorInputPropagationEnabled, false
);
CEGUI_DEFINE_PROPERTY(Window, bool,
"AutoWindow",
"Property to access whether the system considers this window to be an "
"automatically created sub-component window."
"Value is either \"true\" or \"false\".",
&Window::setAutoWindow, &Window::isAutoWindow, false
);
}
//----------------------------------------------------------------------------//
bool Window::isZOrderingEnabled(void) const
{
return d_zOrderingEnabled;
}
//----------------------------------------------------------------------------//
void Window::setZOrderingEnabled(bool setting)
{
d_zOrderingEnabled = setting;
}
//----------------------------------------------------------------------------//
bool Window::isCursorAutoRepeatEnabled(void) const
{
return d_autoRepeat;
}
//----------------------------------------------------------------------------//
float Window::getAutoRepeatDelay(void) const
{
return d_repeatDelay;
}
//----------------------------------------------------------------------------//
float Window::getAutoRepeatRate(void) const
{
return d_repeatRate;
}
//----------------------------------------------------------------------------//
void Window::setCursorAutoRepeatEnabled(bool setting)
{
if (d_autoRepeat == setting)
return;
d_autoRepeat = setting;
d_repeatPointerSource = CIS_None;
// FIXME: There is a potential issue here if this setting is
// FIXME: changed _while_ the cursor is auto-repeating, and
// FIXME: the 'captured' state of input could get messed up.
// FIXME: The alternative is to always release here, but that
// FIXME: has a load of side effects too - so for now nothing
// FIXME: is done. This whole aspect of the system needs a
// FIXME: review an reworking - though such a change was
// FIXME: beyond the scope of the bug-fix that originated this
// FIXME: comment block. PDT - 30/10/06
}
//----------------------------------------------------------------------------//
void Window::setAutoRepeatDelay(float delay)
{
d_repeatDelay = delay;
}
//----------------------------------------------------------------------------//
void Window::setAutoRepeatRate(float rate)
{
d_repeatRate = rate;
}
//----------------------------------------------------------------------------//
void Window::update(float elapsed)
{
// perform update for 'this' Window
updateSelf(elapsed);
// update underlying RenderingWinodw if needed
if (d_surface && d_surface->isRenderingWindow())
static_cast<RenderingWindow*>(d_surface)->update(elapsed);
UpdateEventArgs e(this,elapsed);
fireEvent(EventUpdated,e,EventNamespace);
// update child windows
for (size_t i = 0; i < getChildCount(); ++i)
{
// update children based on their WindowUpdateMode setting.
if (getChildAtIdx(i)->d_updateMode == WUM_ALWAYS ||
(getChildAtIdx(i)->d_updateMode == WUM_VISIBLE &&
getChildAtIdx(i)->isVisible()))
{
getChildAtIdx(i)->update(elapsed);
}
}
}
//----------------------------------------------------------------------------//
void Window::updateSelf(float elapsed)
{
// cursor autorepeat processing.
if (d_autoRepeat && d_repeatPointerSource != CIS_None)
{
d_repeatElapsed += elapsed;
if (d_repeating)
{
if (d_repeatElapsed > d_repeatRate)
{
d_repeatElapsed -= d_repeatRate;
// trigger the repeated event
generateAutoRepeatEvent(d_repeatPointerSource);
}
}
else
{
if (d_repeatElapsed > d_repeatDelay)
{
d_repeatElapsed = 0;
d_repeating = true;
// trigger the repeated event
generateAutoRepeatEvent(d_repeatPointerSource);
}
}
}
// allow for updates within an assigned WindowRenderer
if (d_windowRenderer)
d_windowRenderer->update(elapsed);
}
//----------------------------------------------------------------------------//
bool Window::performCopy(Clipboard& /*clipboard*/)
{
// deny copying by default
return false;
}
//----------------------------------------------------------------------------//
bool Window::performCut(Clipboard& /*clipboard*/)
{
// deny cutting by default
return false;
}
//----------------------------------------------------------------------------//
bool Window::performPaste(Clipboard& /*clipboard*/)
{
// deny pasting by default
return false;
}
//----------------------------------------------------------------------------//
bool Window::performUndo()
{
// deny undo by default
return false;
}
//----------------------------------------------------------------------------//
bool Window::performRedo()
{
// deny redo by default
return false;
}
//----------------------------------------------------------------------------//
bool Window::distributesCapturedInputs(void) const
{
return d_distCapturedInputs;
}
//----------------------------------------------------------------------------//
void Window::setDistributesCapturedInputs(bool setting)
{
d_distCapturedInputs = setting;
}
//----------------------------------------------------------------------------//
void Window::notifyDragDropItemEnters(DragContainer* item)
{
if (!item)
return;
DragDropEventArgs args(this);
args.dragDropItem = item;
onDragDropItemEnters(args);
}
//----------------------------------------------------------------------------//
void Window::notifyDragDropItemLeaves(DragContainer* item)
{
if (!item)
return;
DragDropEventArgs args(this);
args.dragDropItem = item;
onDragDropItemLeaves(args);
}
//----------------------------------------------------------------------------//
void Window::notifyDragDropItemDropped(DragContainer* item)
{
if (!item)
return;
DragDropEventArgs args(this);
args.dragDropItem = item;
onDragDropItemDropped(args);
}
//----------------------------------------------------------------------------//
void Window::destroy(void)
{
// because we know that people do not read the API ref properly,
// here is some protection to ensure that WindowManager does the
// destruction and not anyone else.
WindowManager& wmgr = WindowManager::getSingleton();
if (wmgr.isAlive(this))
{
wmgr.destroyWindow(this);
// now return, the rest of what we need to do will happen
// once WindowManager re-calls this method.
return;
}
// signal our imminent destruction
WindowEventArgs args(this);
onDestructionStarted(args);
releaseInput();
// let go of the tooltip if we have it
Tooltip* const tip = getTooltip();
if (tip && tip->getTargetWindow()==this)
tip->setTargetWindow(0);
// ensure custom tooltip is cleaned up
setTooltip(static_cast<Tooltip*>(0));
// clean up looknfeel related things
if (!d_lookName.empty())
{
d_windowRenderer->onLookNFeelUnassigned();
WidgetLookManager::getSingleton().getWidgetLook(d_lookName).
cleanUpWidget(*this);
}
// free any assigned WindowRenderer
if (d_windowRenderer != 0)
{
d_windowRenderer->onDetach();
WindowRendererManager::getSingleton().
destroyWindowRenderer(d_windowRenderer);
d_windowRenderer = 0;
}
// double check we are detached from parent
if (d_parent)
d_parent->removeChild(this);
cleanupChildren();
releaseRenderingWindow();
invalidate();
}
//----------------------------------------------------------------------------//
bool Window::isUsingDefaultTooltip(void) const
{
return d_customTip == 0;
}
//----------------------------------------------------------------------------//
Tooltip* Window::getTooltip(void) const
{
return isUsingDefaultTooltip() ?
getGUIContext().getDefaultTooltipObject(): d_customTip;
}
//----------------------------------------------------------------------------//
void Window::setTooltip(Tooltip* tooltip)
{
// destroy current custom tooltip if one exists and we created it
if (d_customTip && d_weOwnTip)
WindowManager::getSingleton().destroyWindow(d_customTip);
// set new custom tooltip
d_weOwnTip = false;
d_customTip = tooltip;
}
//----------------------------------------------------------------------------//
void Window::setTooltipType(const String& tooltipType)
{
// destroy current custom tooltip if one exists and we created it
if (d_customTip && d_weOwnTip)
WindowManager::getSingleton().destroyWindow(d_customTip);
if (tooltipType.empty())
{
d_customTip = 0;
d_weOwnTip = false;
}
else
{
CEGUI_TRY
{
d_customTip = static_cast<Tooltip*>(
WindowManager::getSingleton().createWindow(
tooltipType, getName() + TooltipNameSuffix));
d_customTip->setAutoWindow(true);
d_weOwnTip = true;
}
CEGUI_CATCH (UnknownObjectException&)
{
d_customTip = 0;
d_weOwnTip = false;
}
}
}
//----------------------------------------------------------------------------//
String Window::getTooltipType(void) const
{
return isUsingDefaultTooltip() ? String("") : d_customTip->getType();
}
//----------------------------------------------------------------------------//
void Window::setTooltipText(const String& tip)
{
d_tooltipText = tip;
Tooltip* const tooltip = getTooltip();
if (tooltip && tooltip->getTargetWindow() == this)
tooltip->setText(tip);
}
//----------------------------------------------------------------------------//
const String& Window::getTooltipText(void) const
{
if (d_inheritsTipText && d_parent && d_tooltipText.empty())
return getParent()->getTooltipText();
else
return d_tooltipText;
}
//----------------------------------------------------------------------------//
bool Window::inheritsTooltipText(void) const
{
return d_inheritsTipText;
}
//----------------------------------------------------------------------------//
void Window::setInheritsTooltipText(bool setting)
{
d_inheritsTipText = setting;
}
//----------------------------------------------------------------------------//
void Window::setArea_impl(const UVector2& pos, const USize& size,
bool topLeftSizing, bool fireEvents)
{
markCachedWindowRectsInvalid();
Element::setArea_impl(pos, size, topLeftSizing, fireEvents);
//if (moved || sized)
// FIXME: This is potentially wasteful
getGUIContext().updateWindowContainingCursor();
// update geometry position and clipping if nothing from above appears to
// have done so already (NB: may be occasionally wasteful, but fixes bugs!)
if (!d_unclippedOuterRect.isCacheValid())
updateGeometryRenderSettings();
}
//----------------------------------------------------------------------------//
void Window::markCachedWindowRectsInvalid()
{
d_outerRectClipperValid = false;
d_innerRectClipperValid = false;
d_hitTestRectValid = false;
}
//----------------------------------------------------------------------------//
const String& Window::getLookNFeel() const
{
return d_lookName;
}
//----------------------------------------------------------------------------//
void Window::setLookNFeel(const String& look)
{
if (d_lookName == look)
return;
if (!d_windowRenderer)
CEGUI_THROW(NullObjectException("There must be a "
"window renderer assigned to the window '" + d_name +
"' to set its look'n'feel"));
WidgetLookManager& wlMgr = WidgetLookManager::getSingleton();
if (!d_lookName.empty())
{
d_windowRenderer->onLookNFeelUnassigned();
const WidgetLookFeel& wlf = wlMgr.getWidgetLook(d_lookName);
wlf.cleanUpWidget(*this);
}
d_lookName = look;
Logger::getSingleton().logEvent("Assigning LookNFeel '" + look +
"' to window '" + d_name + "'.", Informative);
// Work to initialise the look and feel...
const WidgetLookFeel& wlf = wlMgr.getWidgetLook(look);
// Get look and feel to initialise the widget as it needs.
wlf.initialiseWidget(*this);
// do the necessary binding to the stuff added by the look and feel
initialiseComponents();
// let the window renderer know about this
d_windowRenderer->onLookNFeelAssigned();
invalidate();
performChildWindowLayout();
}
//----------------------------------------------------------------------------//
void Window::setModalState(bool state)
{
// do nothing if state isn't changing
if (getModalState() == state)
return;
// if going modal
if (state)
{
activate();
getGUIContext().setModalWindow(this);
}
// clear the modal target
else
getGUIContext().setModalWindow(0);
}
//----------------------------------------------------------------------------//
void Window::performChildWindowLayout(const bool nonclient_sized_hint,
const bool client_sized_hint)
{
const Sizef old_size(d_pixelSize);
d_pixelSize = calculatePixelSize();
layoutLookNFeelChildWidgets();
const bool outer_changed = nonclient_sized_hint || d_pixelSize != old_size;
const bool inner_changed = client_sized_hint || isInnerRectSizeChanged();
d_outerRectClipperValid &= !outer_changed;
d_innerRectClipperValid &= !inner_changed;
if (d_windowRenderer)
d_windowRenderer->performChildWindowLayout();
notifyChildrenOfSizeChange(outer_changed, inner_changed);
}
//----------------------------------------------------------------------------//
void Window::layoutLookNFeelChildWidgets()
{
if (d_lookName.empty())
return;
CEGUI_TRY
{
WidgetLookManager::getSingleton().
getWidgetLook(d_lookName).layoutChildWidgets(*this);
}
CEGUI_CATCH (UnknownObjectException&)
{
Logger::getSingleton().logEvent(
"Window::layoutLookNFeelChildWidgets: "
"WidgetLook '" + d_lookName + "' was not found.", Errors);
}
}
//----------------------------------------------------------------------------//
const String& Window::getUserString(const String& name) const
{
UserStringMap::const_iterator iter = d_userStrings.find(name);
if (iter == d_userStrings.end())
CEGUI_THROW(UnknownObjectException(
"a user string named '" + name + "' is not defined for Window '" +
d_name + "'."));
return (*iter).second;
}
//----------------------------------------------------------------------------//
bool Window::isUserStringDefined(const String& name) const
{
return d_userStrings.find(name) != d_userStrings.end();
}
//----------------------------------------------------------------------------//
void Window::setUserString(const String& name, const String& value)
{
d_userStrings[name] = value;
}
//----------------------------------------------------------------------------//
void Window::writeXMLToStream(XMLSerializer& xml_stream) const
{
// just stop now if we are'nt allowed to write XML
if (!d_allowWriteXML)
return;
// output opening Window tag
xml_stream.openTag(WindowXMLElementName)
.attribute(WindowTypeXMLAttributeName, getType());
// write name if not auto-generated
if (getName().compare(0, WindowManager::GeneratedWindowNameBase.length(),
WindowManager::GeneratedWindowNameBase) != 0)
{
xml_stream.attribute(WindowNameXMLAttributeName, getName());
}
// write out properties.
writePropertiesXML(xml_stream);
// write out attached child windows.
writeChildWindowsXML(xml_stream);
// now ouput closing Window tag
xml_stream.closeTag();
}
//----------------------------------------------------------------------------//
int Window::writePropertiesXML(XMLSerializer& xml_stream) const
{
int propertiesWritten = 0;
PropertySet::PropertyIterator iter = getPropertyIterator();
while(!iter.isAtEnd())
{
// first we check to make sure the property is'nt banned from XML
if (!isPropertyBannedFromXML(iter.getCurrentValue()))
{
CEGUI_TRY
{
// only write property if it's not at the default state
if (!isPropertyAtDefault(iter.getCurrentValue()))
{
iter.getCurrentValue()->writeXMLToStream(this, xml_stream);
++propertiesWritten;
}
}
CEGUI_CATCH (InvalidRequestException&)
{
// This catches errors from the MultiLineColumnList for example
Logger::getSingleton().logEvent(
"Window::writePropertiesXML: property receiving failed. "
"Continuing...", Errors);
}
}
++iter;
}
return propertiesWritten;
}
//----------------------------------------------------------------------------//
int Window::writeChildWindowsXML(XMLSerializer& xml_stream) const
{
int windowsWritten = 0;
for (uint i = 0; i < getChildCount(); ++i)
{
const Window* const child = getChildAtIdx(i);
// conditional to ensure that auto created windows are handled
// seperately.
if (!child->isAutoWindow())
{
child->writeXMLToStream(xml_stream);
++windowsWritten;
}
// this is one of those auto created windows so we do some special
// handling
else if (child->writeAutoChildWindowXML(xml_stream))
{
++windowsWritten;
}
}
return windowsWritten;
}
//----------------------------------------------------------------------------//
bool Window::writeAutoChildWindowXML(XMLSerializer& xml_stream) const
{
// just stop now if we are'nt allowed to write XML
if (!d_allowWriteXML)
return false;
// we temporarily output to this string stream to see if have to do the tag
// at all. Make sure this stream does UTF-8
std::ostringstream ss;
XMLSerializer xml(ss);
xml.openTag(AutoWindowXMLElementName);
// Create the XML Child Tree
// write out properties.
writePropertiesXML(xml);
// write out attached child windows.
writeChildWindowsXML(xml);
xml.closeTag();
if (xml.getTagCount() <= 1)
return false;
// output opening AutoWindow tag
xml_stream.openTag(AutoWindowXMLElementName);
// write name suffix attribute
xml_stream.attribute(AutoWindowNamePathXMLAttributeName, getName());
// Inefficient : do the XML serialization again
// write out properties.
writePropertiesXML(xml_stream);
// write out attached child windows.
writeChildWindowsXML(xml_stream);
xml_stream.closeTag();
return true;
}
//----------------------------------------------------------------------------//
void Window::addWindowToDrawList(Window& wnd, bool at_back)
{
// add behind other windows in same group
if (at_back)
{
// calculate position where window should be added for drawing
ChildDrawList::iterator pos = d_drawList.begin();
if (wnd.isAlwaysOnTop())
{
// find first topmost window
while ((pos != d_drawList.end()) && (!(*pos)->isAlwaysOnTop()))
++pos;
}
// add window to draw list
d_drawList.insert(pos, &wnd);
}
// add in front of other windows in group
else
{
// calculate position where window should be added for drawing
ChildDrawList::reverse_iterator position = d_drawList.rbegin();
if (!wnd.isAlwaysOnTop())
{
// find last non-topmost window
while ((position != d_drawList.rend()) && ((*position)->isAlwaysOnTop()))
++position;
}
// add window to draw list
d_drawList.insert(position.base(), &wnd);
}
}
//----------------------------------------------------------------------------//
void Window::removeWindowFromDrawList(const Window& wnd)
{
// if draw list is not empty
if (!d_drawList.empty())
{
// attempt to find the window in the draw list
const ChildDrawList::iterator position =
std::find(d_drawList.begin(), d_drawList.end(), &wnd);
// remove the window if it was found in the draw list
if (position != d_drawList.end())
d_drawList.erase(position);
}
}
//----------------------------------------------------------------------------//
Window* Window::getActiveSibling()
{
// initialise with this if we are active, else 0
Window* activeWnd = isActive() ? this : 0;
// if active window not already known, and we have a parent window
if (!activeWnd && d_parent)
{
// scan backwards through the draw list, as this will
// usually result in the fastest result.
for (ChildDrawList::reverse_iterator it = getParent()->d_drawList.rbegin(); it != getParent()->d_drawList.rend(); ++it)
{
Window* wnd = *it;
// if this child is active
if (wnd->isActive())
{
// set the return value
activeWnd = wnd;
// exit loop early, as we have found what we needed
break;
}
}
}
// return whatever we discovered
return activeWnd;
}
//----------------------------------------------------------------------------//
void Window::onSized(ElementEventArgs& e)
{
/*
* Why are we not calling Element::onSized? It's because that function
* always calls the onParentSized notification for all children - we really
* want that to be done via performChildWindowLayout instead and we
* definitely don't want it done twice.
*
* (The other option was to add an Element::performChildLayout function -
* maybe we should consider that).
*/
// resize the underlying RenderingWindow if we're using such a thing
if (d_surface && d_surface->isRenderingWindow())
static_cast<RenderingWindow*>(d_surface)->setSize(getPixelSize());
// screen area changes when we're resized.
// NB: Called non-recursive since the performChildWindowLayout call should
// have dealt more selectively with child Window cases.
notifyScreenAreaChanged(false);
performChildWindowLayout(true, true);
invalidate();
fireEvent(EventSized, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onMoved(ElementEventArgs& e)
{
Element::onMoved(e);
// handle invalidation of surfaces and trigger needed redraws
if (d_parent)
{
getParent()->invalidateRenderingSurface();
// need to redraw some geometry if parent uses a caching surface
if (getParent()->getTargetRenderingSurface().isRenderingWindow())
getGUIContext().markAsDirty();
}
}
//----------------------------------------------------------------------------//
void Window::onTextChanged(WindowEventArgs& e)
{
invalidate();
fireEvent(EventTextChanged, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onFontChanged(WindowEventArgs& e)
{
// This was added to enable the Falagard FontDim to work
// properly. A better, more selective, solution would
// probably be to do something funky with events ;)
performChildWindowLayout();
invalidate();
fireEvent(EventFontChanged, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onAlphaChanged(WindowEventArgs& e)
{
// scan child list and call this method for all children that inherit alpha
const size_t child_count = getChildCount();
for (size_t i = 0; i < child_count; ++i)
{
if (getChildAtIdx(i)->inheritsAlpha())
{
WindowEventArgs args(getChildAtIdx(i));
getChildAtIdx(i)->onAlphaChanged(args);
}
}
updateGeometryBuffersAlpha();
invalidateRenderingSurface();
getGUIContext().markAsDirty();
fireEvent(EventAlphaChanged, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onIDChanged(WindowEventArgs& e)
{
fireEvent(EventIDChanged, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onShown(WindowEventArgs& e)
{
invalidate();
fireEvent(EventShown, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onHidden(WindowEventArgs& e)
{
// first deactivate window if it is the active window.
if (isActive())
deactivate();
invalidate();
fireEvent(EventHidden, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onEnabled(WindowEventArgs& e)
{
// signal all non-disabled children that they are now enabled
// (via inherited state)
const size_t child_count = getChildCount();
for (size_t i = 0; i < child_count; ++i)
{
if (getChildAtIdx(i)->d_enabled)
{
WindowEventArgs args(getChildAtIdx(i));
getChildAtIdx(i)->onEnabled(args);
}
}
invalidate();
fireEvent(EventEnabled, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onDisabled(WindowEventArgs& e)
{
// signal all non-disabled children that they are now disabled
// (via inherited state)
const size_t child_count = getChildCount();
for (size_t i = 0; i < child_count; ++i)
{
if (getChildAtIdx(i)->d_enabled)
{
WindowEventArgs args(getChildAtIdx(i));
getChildAtIdx(i)->onDisabled(args);
}
}
invalidate();
fireEvent(EventDisabled, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onClippingChanged(WindowEventArgs& e)
{
invalidate();
notifyClippingChanged();
fireEvent(EventClippedByParentChanged, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onParentDestroyChanged(WindowEventArgs& e)
{
fireEvent(EventDestroyedByParentChanged, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onInheritsAlphaChanged(WindowEventArgs& e)
{
invalidate();
fireEvent(EventInheritsAlphaChanged, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onAlwaysOnTopChanged(WindowEventArgs& e)
{
// we no longer want a total redraw here, instead we just get each window
// to resubmit it's imagery to the Renderer.
getGUIContext().markAsDirty();
fireEvent(EventAlwaysOnTopChanged, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onCaptureGained(WindowEventArgs& e)
{
fireEvent(EventInputCaptureGained, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onCaptureLost(WindowEventArgs& e)
{
// reset auto-repeat state
d_repeatPointerSource = CIS_None;
// handle restore of previous capture window as required.
if (d_restoreOldCapture && (d_oldCapture != 0)) {
d_oldCapture->onCaptureLost(e);
d_oldCapture = 0;
}
// handle case where cursor is now in a different window
// (this is a bit of a hack that uses the injection of a semantic event to handle
// this for us).
SemanticInputEvent moveEvent(SV_CursorMove);
const glm::vec2 cursorPosition = getGUIContext().getCursor().getPosition();
moveEvent.d_payload.array[0] = cursorPosition.x;
moveEvent.d_payload.array[1] = cursorPosition.y;
getGUIContext().injectInputEvent(moveEvent);
fireEvent(EventInputCaptureLost, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onInvalidated(WindowEventArgs& e)
{
fireEvent(EventInvalidated, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onRenderingStarted(WindowEventArgs& e)
{
fireEvent(EventRenderingStarted, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onRenderingEnded(WindowEventArgs& e)
{
fireEvent(EventRenderingEnded, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onZChanged(WindowEventArgs& e)
{
// we no longer want a total redraw here, instead we just get each window
// to resubmit it's imagery to the Renderer.
getGUIContext().markAsDirty();
fireEvent(EventZOrderChanged, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onDestructionStarted(WindowEventArgs& e)
{
d_destructionStarted = true;
fireEvent(EventDestructionStarted, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onActivated(ActivationEventArgs& e)
{
d_active = true;
invalidate();
fireEvent(EventActivated, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onDeactivated(ActivationEventArgs& e)
{
// first de-activate all children
const size_t child_count = getChildCount();
for (size_t i = 0; i < child_count; ++i)
{
if (getChildAtIdx(i)->isActive())
{
// make sure the child gets itself as the .window member
ActivationEventArgs child_e(getChildAtIdx(i));
child_e.otherWindow = e.otherWindow;
getChildAtIdx(i)->onDeactivated(child_e);
}
}
d_active = false;
invalidate();
fireEvent(EventDeactivated, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onParentSized(ElementEventArgs& e)
{
Element::onParentSized(e);
// if we were not moved or sized, do child layout anyway!
// URGENT FIXME
//if (!(moved || sized))
performChildWindowLayout();
}
//----------------------------------------------------------------------------//
void Window::onChildAdded(ElementEventArgs& e)
{
// we no longer want a total redraw here, instead we just get each window
// to resubmit it's imagery to the Renderer.
getGUIContext().markAsDirty();
Element::onChildAdded(e);
}
//----------------------------------------------------------------------------//
void Window::onChildRemoved(ElementEventArgs& e)
{
// we no longer want a total redraw here, instead we just get each window
// to resubmit it's imagery to the Renderer.
getGUIContext().markAsDirty();
// Though we do need to invalidate the rendering surface!
getTargetRenderingSurface().invalidate();
Element::onChildRemoved(e);
}
//----------------------------------------------------------------------------//
void Window::onCursorEntersArea(CursorInputEventArgs& e)
{
d_containsPointer = true;
fireEvent(EventCursorEntersArea, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onCursorLeavesArea(CursorInputEventArgs& e)
{
d_containsPointer = false;
fireEvent(EventCursorLeavesArea, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onCursorEnters(CursorInputEventArgs& e)
{
// set the cursor
getGUIContext().getCursor().setImage(getCursor());
// perform tooltip control
Tooltip* const tip = getTooltip();
if (tip && !isAncestor(tip))
tip->setTargetWindow(this);
fireEvent(EventCursorEntersSurface, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onCursorLeaves(CursorInputEventArgs& e)
{
// perform tooltip control
const Window* const mw = getGUIContext().getWindowContainingCursor();
Tooltip* const tip = getTooltip();
if (tip && mw != tip && !(mw && mw->isAncestor(tip)))
tip->setTargetWindow(0);
fireEvent(EventCursorLeavesSurface, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onCursorMove(CursorInputEventArgs& e)
{
// perform tooltip control
Tooltip* const tip = getTooltip();
if (tip)
tip->resetTimer();
fireEvent(EventCursorMove, e, EventNamespace);
// optionally propagate to parent
if (!e.handled && d_propagatePointerInputs &&
d_parent && this != getGUIContext().getModalWindow())
{
e.window = getParent();
getParent()->onCursorMove(e);
return;
}
// by default we now mark cursor events as handled
// (derived classes may override, of course!)
++e.handled;
}
//----------------------------------------------------------------------------//
void Window::onScroll(CursorInputEventArgs& e)
{
fireEvent(EventScroll, e, EventNamespace);
// optionally propagate to parent
if (!e.handled && d_propagatePointerInputs &&
d_parent && this != getGUIContext().getModalWindow())
{
e.window = getParent();
getParent()->onScroll(e);
return;
}
// by default we now mark cursor events as handled
// (derived classes may override, of course!)
++e.handled;
}
//----------------------------------------------------------------------------//
void Window::onCursorPressHold(CursorInputEventArgs& e)
{
// perform tooltip control
Tooltip* const tip = getTooltip();
if (tip)
tip->setTargetWindow(0);
if ((e.source == CIS_Left) && moveToFront_impl(true))
++e.handled;
// if auto repeat is enabled and we are not currently tracking
// the source that was just pushed (need this source check because
// it could be us that generated this event via auto-repeat).
if (d_autoRepeat)
{
if (d_repeatPointerSource == CIS_None)
captureInput();
if ((d_repeatPointerSource != e.source) && isCapturedByThis())
{
d_repeatPointerSource = e.source;
d_repeatElapsed = 0;
d_repeating = false;
}
}
fireEvent(EventCursorPressHold, e, EventNamespace);
// optionally propagate to parent
if (!e.handled && d_propagatePointerInputs &&
d_parent && this != getGUIContext().getModalWindow())
{
e.window = getParent();
getParent()->onCursorPressHold(e);
return;
}
// by default we now mark cursor events as handled
// (derived classes may override, of course!)
++e.handled;
}
//----------------------------------------------------------------------------//
void Window::onCursorActivate(CursorInputEventArgs& e)
{
// reset auto-repeat state
if (d_autoRepeat && d_repeatPointerSource != CIS_None)
{
releaseInput();
d_repeatPointerSource = CIS_None;
}
fireEvent(EventCursorActivate, e, EventNamespace);
// optionally propagate to parent
if (!e.handled && d_propagatePointerInputs &&
d_parent && this != getGUIContext().getModalWindow())
{
e.window = getParent();
getParent()->onCursorActivate(e);
return;
}
++e.handled;
}
//----------------------------------------------------------------------------//
void Window::onCharacter(TextEventArgs& e)
{
fireEvent(EventCharacterKey, e, EventNamespace);
// As of 0.7.0 CEGUI::System no longer does input event propogation, so by
// default we now do that here. Generally speaking key handling widgets
// may need to override this behaviour to halt further propagation.
if (!e.handled && d_parent &&
this != getGUIContext().getModalWindow())
{
e.window = getParent();
getParent()->onCharacter(e);
}
}
//----------------------------------------------------------------------------//
void Window::onSemanticInputEvent(SemanticEventArgs& e)
{
fireEvent(EventSemanticEvent, e, EventNamespace);
// optionally propagate to parent
if (!e.handled && d_parent && this != getGUIContext().getModalWindow())
{
e.window = getParent();
getParent()->onSemanticInputEvent(e);
return;
}
}
//----------------------------------------------------------------------------//
void Window::onDragDropItemEnters(DragDropEventArgs& e)
{
fireEvent(EventDragDropItemEnters, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onDragDropItemLeaves(DragDropEventArgs& e)
{
fireEvent(EventDragDropItemLeaves, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onDragDropItemDropped(DragDropEventArgs& e)
{
fireEvent(EventDragDropItemDropped, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::setWindowRenderer(const String& name)
{
if (d_windowRenderer && d_windowRenderer->getName() == name)
return;
WindowRendererManager& wrm = WindowRendererManager::getSingleton();
if (d_windowRenderer != 0)
{
// Allow reset of renderer
if (d_windowRenderer->getName() == name)
return;
WindowEventArgs e(this);
onWindowRendererDetached(e);
wrm.destroyWindowRenderer(d_windowRenderer);
}
if (!name.empty())
{
Logger::getSingleton().logEvent("Assigning the window renderer '" +
name + "' to the window '" + d_name + "'", Informative);
d_windowRenderer = wrm.createWindowRenderer(name);
WindowEventArgs e(this);
onWindowRendererAttached(e);
}
else
CEGUI_THROW(InvalidRequestException(
"Attempt to assign a 'null' window renderer to window '" +
d_name + "'."));
}
//----------------------------------------------------------------------------//
WindowRenderer* Window::getWindowRenderer(void) const
{
return d_windowRenderer;
}
//----------------------------------------------------------------------------//
void Window::onWindowRendererAttached(WindowEventArgs& e)
{
if (!validateWindowRenderer(d_windowRenderer))
CEGUI_THROW(InvalidRequestException(
"The window renderer '" + d_windowRenderer->getName() + "' is not "
"compatible with this widget type (" + getType() + ")"));
d_windowRenderer->d_window = this;
d_windowRenderer->onAttach();
fireEvent(EventWindowRendererAttached, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onWindowRendererDetached(WindowEventArgs& e)
{
d_windowRenderer->onDetach();
d_windowRenderer->d_window = 0;
fireEvent(EventWindowRendererDetached, e, EventNamespace);
}
//----------------------------------------------------------------------------//
bool Window::validateWindowRenderer(const WindowRenderer*) const
{
return true;
}
//----------------------------------------------------------------------------//
const String& Window::getWindowRendererName() const
{
if (d_windowRenderer)
return d_windowRenderer->getName();
static String empty("");
return empty;
}
//----------------------------------------------------------------------------//
void Window::banPropertyFromXML(const String& property_name)
{
Property* instance = getPropertyInstance(property_name);
if (!instance->isWritable())
{
Logger::getSingleton().logEvent("Property '" + property_name + "' "
"is not writable so it's implicitly banned from XML. No need "
"to ban it manually", Warnings);
return;
}
// check if the insertion failed
if (!d_bannedXMLProperties.insert(property_name).second)
// just log the incidence
CEGUI_LOGINSANE("Window::banPropertyFromXML: The property '" +
property_name + "' is already banned in window '" + d_name + "'");
}
//----------------------------------------------------------------------------//
void Window::unbanPropertyFromXML(const String& property_name)
{
d_bannedXMLProperties.erase(property_name);
}
//----------------------------------------------------------------------------//
bool Window::isPropertyBannedFromXML(const String& property_name) const
{
const BannedXMLPropertySet::const_iterator i =
d_bannedXMLProperties.find(property_name);
// generally, there will always less banned properties than all properties,
// so it makes sense to check that first before querying the property instance
if (i != d_bannedXMLProperties.end())
{
return true;
}
// properties that don't write any XML code are implicitly banned
// read-only properties are implicitly banned
// (such stored information wouldn't be of any value in the XML anyways,
// no way to apply it to the widget)
Property* instance = getPropertyInstance(property_name);
return (!instance->doesWriteXML() || !instance->isWritable());
}
//----------------------------------------------------------------------------//
void Window::banPropertyFromXML(const Property* property)
{
if (property)
banPropertyFromXML(property->getName());
}
//----------------------------------------------------------------------------//
void Window::unbanPropertyFromXML(const Property* property)
{
if (property)
unbanPropertyFromXML(property->getName());
}
//----------------------------------------------------------------------------//
bool Window::isPropertyBannedFromXML(const Property* property) const
{
if (property)
return isPropertyBannedFromXML(property->getName());
else
return false;
}
//----------------------------------------------------------------------------//
bool Window::isPropertyAtDefault(const Property* property) const
{
// if we have a looknfeel we examine it for defaults
if (!d_lookName.empty())
{
if (d_parent && !getParent()->getLookNFeel().empty())
{
const WidgetLookFeel& wlf =
WidgetLookManager::getSingleton().
getWidgetLook(getParent()->getLookNFeel());
// If this property is a target of a PropertyLink, we always report it as being at default.
WidgetLookFeel::StringSet propDefNames = wlf.getPropertyDefinitionNames(true);
if(propDefNames.find(property->getName()) != propDefNames.end())
return true;
// for an auto-window see if the property is is set via a Property
// tag within the WidgetComponent that defines it.
if (d_autoWindow)
{
// Check if a widget component with the name was added to the look
if(wlf.isWidgetComponentPresent(getName()))
{
const WidgetComponent& widgetComp = wlf.getWidgetComponent(getName());
const PropertyInitialiser* const propInitialiser = widgetComp.findPropertyInitialiser(property->getName());
if (propInitialiser)
return (getProperty(property->getName()) == propInitialiser->getInitialiserValue());
}
}
}
// if the looknfeel has a new default for this property we compare
// against that
const WidgetLookFeel& wlf =
WidgetLookManager::getSingleton().getWidgetLook(d_lookName);
const PropertyInitialiser* const propinit =
wlf.findPropertyInitialiser(property->getName());
if (propinit)
return (getProperty(property->getName()) ==
propinit->getInitialiserValue());
}
// we don't have a looknfeel with a new value for this property so we rely
// on the hardcoded default
return property->isDefault(this);
}
//----------------------------------------------------------------------------//
void Window::notifyClippingChanged(void)
{
markCachedWindowRectsInvalid();
// inform children that their clipped screen areas must be updated
const size_t num = d_children.size();
for (size_t i=0; i<num; ++i)
if (getChildAtIdx(i)->isClippedByParent())
getChildAtIdx(i)->notifyClippingChanged();
}
//----------------------------------------------------------------------------//
void Window::notifyScreenAreaChanged(bool recursive /* = true */)
{
markCachedWindowRectsInvalid();
Element::notifyScreenAreaChanged(recursive);
updateGeometryRenderSettings();
}
//----------------------------------------------------------------------------//
void Window::updateGeometryRenderSettings()
{
RenderingContext ctx;
getRenderingContext(ctx);
// move the underlying RenderingWindow if we're using such a thing
if (ctx.owner == this && ctx.surface->isRenderingWindow())
{
static_cast<RenderingWindow*>(ctx.surface)->
setPosition(getUnclippedOuterRect().get().getPositionGLM());
static_cast<RenderingWindow*>(d_surface)->setPivot(
glm::vec3(
d_pixelSize.d_width / 2.0f,
d_pixelSize.d_height / 2.0f,
0.0f
)
);
d_translation = glm::vec3(0, 0, 0);
}
// if we're not texture backed, update geometry position.
else
{
// position is the offset of the window on the dest surface.
const Rectf ucrect(getUnclippedOuterRect().get());
d_translation = glm::vec3(ucrect.d_min.d_x - ctx.offset.x,
ucrect.d_min.d_y - ctx.offset.y,
0.0f);
}
initialiseClippers(ctx);
updateGeometryBuffersTranslationAndClipping();
}
//----------------------------------------------------------------------------//
bool Window::isDragDropTarget() const
{
return d_dragDropTarget;
}
//----------------------------------------------------------------------------//
void Window::setDragDropTarget(bool setting)
{
d_dragDropTarget = setting;
}
//-----------------------------------------------------------------------
void Window::setFalagardType(const String& type, const String& rendererType)
{
// Retrieve the new widget look
const String separator("/");
String::size_type pos = type.find(separator);
const String newLook(type, 0, pos);
// Check if old one is the same. If so, ignore since we don't need to do
// anything (type is already assigned)
pos = d_falagardType.find(separator);
String oldLook(d_falagardType, 0, pos);
if(oldLook == newLook)
return;
// Obtain widget kind
String widget(d_falagardType, pos + 1);
// Build new type (look/widget)
d_falagardType = newLook + separator + widget;
// Set new renderer
if(rendererType.length() > 0)
setWindowRenderer(rendererType);
// Apply the new look to the widget
setLookNFeel(type);
}
//----------------------------------------------------------------------------//
bool Window::isTopOfZOrder() const
{
// if not attached, then always on top!
if (!d_parent)
return true;
// get position of window at top of z-order in same group as this window
ChildDrawList::reverse_iterator pos = getParent()->d_drawList.rbegin();
if (!d_alwaysOnTop)
{
// find last non-topmost window
while ((pos != getParent()->d_drawList.rend()) && (*pos)->isAlwaysOnTop())
++pos;
}
// return whether the window at the top of the z order is us
return *pos == this;
}
//----------------------------------------------------------------------------//
void Window::insertText(const String& text, const String::size_type position)
{
d_textLogical.insert(position, text);
d_renderedStringValid = false;
d_bidiDataValid = false;
WindowEventArgs args(this);
onTextChanged(args);
}
//----------------------------------------------------------------------------//
void Window::appendText(const String& text)
{
d_textLogical.append(text);
d_renderedStringValid = false;
d_bidiDataValid = false;
WindowEventArgs args(this);
onTextChanged(args);
}
//----------------------------------------------------------------------------//
std::vector<GeometryBuffer*>& Window::getGeometryBuffers()
{
return d_geometryBuffers;
}
//----------------------------------------------------------------------------//
void Window::getRenderingContext(RenderingContext& ctx) const
{
if (d_windowRenderer)
d_windowRenderer->getRenderingContext(ctx);
else
getRenderingContext_impl(ctx);
}
//----------------------------------------------------------------------------//
void Window::getRenderingContext_impl(RenderingContext& ctx) const
{
if (d_surface)
{
ctx.surface = d_surface;
ctx.owner = this;
ctx.offset = getUnclippedOuterRect().get().getPositionGLM();
ctx.queue = RQ_BASE;
}
else if (d_parent)
{
getParent()->getRenderingContext(ctx);
}
else
{
ctx.surface = &getGUIContext();
ctx.owner = 0;
ctx.offset = glm::vec2(0, 0);
ctx.queue = RQ_BASE;
}
}
//----------------------------------------------------------------------------//
RenderingSurface* Window::getRenderingSurface() const
{
return d_surface;
}
//----------------------------------------------------------------------------//
RenderingSurface& Window::getTargetRenderingSurface() const
{
if (d_surface)
return *d_surface;
else if (d_parent)
return getParent()->getTargetRenderingSurface();
else
return getGUIContext();
}
//----------------------------------------------------------------------------//
void Window::setRenderingSurface(RenderingSurface* surface)
{
if (d_surface == surface)
return;
if (d_autoRenderingWindow)
setUsingAutoRenderingSurface(false);
d_surface = surface;
// transfer child surfaces to this new surface
if (d_surface)
{
transferChildSurfaces();
notifyScreenAreaChanged();
}
}
//----------------------------------------------------------------------------//
void Window::invalidateRenderingSurface()
{
// invalidate our surface chain if we have one
if (d_surface)
d_surface->invalidate();
// else look through the hierarchy for a surface chain to invalidate.
else if (d_parent)
getParent()->invalidateRenderingSurface();
}
//----------------------------------------------------------------------------//
const Window* Window::getRootWindow() const
{
return d_parent ? getParent()->getRootWindow() : this;
}
//----------------------------------------------------------------------------//
Window* Window::getRootWindow()
{
return const_cast<Window*>(
static_cast<const Window*>(this)->getRootWindow());
}
//----------------------------------------------------------------------------//
bool Window::isUsingAutoRenderingSurface() const
{
return d_autoRenderingWindow;
}
//----------------------------------------------------------------------------//
void Window::setUsingAutoRenderingSurface(bool setting)
{
if (setting)
{
allocateRenderingWindow();
}
else
{
releaseRenderingWindow();
// make sure we set this because releaseRenderingWindow won't do it
// unless the surface was already initialised
d_autoRenderingWindow = setting;
}
// while the actal area on screen may not have changed, the arrangement of
// surfaces and geometry did...
notifyScreenAreaChanged();
}
//----------------------------------------------------------------------------//
void Window::allocateRenderingWindow()
{
if (!d_autoRenderingWindow)
{
d_autoRenderingWindow = true;
TextureTarget* const t =
System::getSingleton().getRenderer()->createTextureTarget();
// TextureTargets may not be available, so check that first.
if (!t)
{
Logger::getSingleton().logEvent("Window::allocateRenderingWindow - "
"Failed to create a suitable TextureTarget for use by Window '"
+ d_name + "'", Errors);
d_surface = 0;
return;
}
d_surface = &getTargetRenderingSurface().createRenderingWindow(*t);
transferChildSurfaces();
// set size and position of RenderingWindow
static_cast<RenderingWindow*>(d_surface)->setSize(getPixelSize());
static_cast<RenderingWindow*>(d_surface)->
setPosition(getUnclippedOuterRect().get().getPositionGLM());
getGUIContext().markAsDirty();
}
}
//----------------------------------------------------------------------------//
void Window::releaseRenderingWindow()
{
if (d_autoRenderingWindow && d_surface)
{
RenderingWindow* const old_surface =
static_cast<RenderingWindow*>(d_surface);
d_autoRenderingWindow = false;
d_surface = 0;
// detach child surfaces prior to destroying the owning surface
transferChildSurfaces();
// destroy surface and texture target it used
TextureTarget* tt = &old_surface->getTextureTarget();
old_surface->getOwner().destroyRenderingWindow(*old_surface);
System::getSingleton().getRenderer()->destroyTextureTarget(tt);
getGUIContext().markAsDirty();
}
}
//----------------------------------------------------------------------------//
void Window::transferChildSurfaces()
{
RenderingSurface& s = getTargetRenderingSurface();
const size_t child_count = getChildCount();
for (size_t i = 0; i < child_count; ++i)
{
Window* const c = getChildAtIdx(i);
if (c->d_surface && c->d_surface->isRenderingWindow())
s.transferRenderingWindow(
*static_cast<RenderingWindow*>(c->d_surface));
else
c->transferChildSurfaces();
}
}
//----------------------------------------------------------------------------//
void Window::initialiseClippers(const RenderingContext& ctx)
{
if (ctx.surface->isRenderingWindow() && ctx.owner == this)
{
RenderingWindow* const rendering_window =
static_cast<RenderingWindow*>(ctx.surface);
if (d_clippedByParent && d_parent)
rendering_window->setClippingRegion(
getParent()->getClipRect(d_nonClient));
else
rendering_window->setClippingRegion(
Rectf(glm::vec2(0, 0), getRootContainerSize()));
d_clippingRegion = Rectf(glm::vec2(0, 0), d_pixelSize);
}
else
{
Rectf geo_clip(getOuterRectClipper());
if (geo_clip.getWidth() != 0.0f && geo_clip.getHeight() != 0.0f)
geo_clip.offset(-ctx.offset);
d_clippingRegion = Rectf(geo_clip);
}
}
//----------------------------------------------------------------------------//
void Window::onRotated(ElementEventArgs& e)
{
Element::onRotated(e);
// if we have no surface set, enable the auto surface
if (!d_surface)
{
Logger::getSingleton().logEvent("Window::setRotation - "
"Activating AutoRenderingSurface on Window '" + d_name +
"' to enable rotation support.");
setUsingAutoRenderingSurface(true);
// still no surface? Renderer or HW must not support what we need :(
if (!d_surface)
{
Logger::getSingleton().logEvent("Window::setRotation - "
"Failed to obtain a suitable ReneringWindow surface for "
"Window '" + d_name + "'. Rotation will not be available.",
Errors);
return;
}
}
// ensure surface we have is the right type
if (!d_surface->isRenderingWindow())
{
Logger::getSingleton().logEvent("Window::setRotation - "
"Window '" + d_name + "' has a manual RenderingSurface that is not "
"a RenderingWindow. Rotation will not be available.", Errors);
return;
}
// Checks / setup complete! Now we can finally set the rotation.
static_cast<RenderingWindow*>(d_surface)->setRotation(d_rotation);
static_cast<RenderingWindow*>(d_surface)->setPivot(
glm::vec3(d_pixelSize.d_width / 2.0f, d_pixelSize.d_height / 2.0f, 0.0f));
}
//----------------------------------------------------------------------------//
const RenderedString& Window::getRenderedString() const
{
if (!d_renderedStringValid)
{
d_renderedString = getRenderedStringParser().parse(
getTextVisual(), getFont(), 0);
d_renderedStringValid = true;
}
return d_renderedString;
}
//----------------------------------------------------------------------------//
RenderedStringParser* Window::getCustomRenderedStringParser() const
{
return d_customStringParser;
}
//----------------------------------------------------------------------------//
void Window::setCustomRenderedStringParser(RenderedStringParser* parser)
{
d_customStringParser = parser;
d_renderedStringValid = false;
}
//----------------------------------------------------------------------------//
RenderedStringParser& Window::getRenderedStringParser() const
{
// if parsing is disabled, we use a DefaultRenderedStringParser that creates
// a RenderedString to renderi the input text verbatim (i.e. no parsing).
if (!d_textParsingEnabled)
return d_defaultStringParser;
// Next prefer a custom RenderedStringParser assigned to this Window.
if (d_customStringParser)
return *d_customStringParser;
// Next prefer any globally set RenderedStringParser.
RenderedStringParser* const global_parser =
CEGUI::System::getSingleton().getDefaultCustomRenderedStringParser();
if (global_parser)
return *global_parser;
// if parsing is enabled and no custom RenderedStringParser is set anywhere,
// use the system's BasicRenderedStringParser to do the parsing.
return d_basicStringParser;
}
//----------------------------------------------------------------------------//
glm::vec2 Window::getUnprojectedPosition(const glm::vec2& pos) const
{
RenderingSurface* rs = &getTargetRenderingSurface();
// if window is not backed by RenderingWindow, return same pos.
if (!rs->isRenderingWindow())
return pos;
// get first target RenderingWindow
RenderingWindow* rw = static_cast<RenderingWindow*>(rs);
// setup for loop
glm::vec2 out_pos(pos);
// while there are rendering windows
while (rw)
{
// unproject the point for the current rw
const glm::vec2 in_pos(out_pos);
rw->unprojectPoint(in_pos, out_pos);
// get next rendering window, if any
rw = (rs = &rw->getOwner())->isRenderingWindow() ?
static_cast<RenderingWindow*>(rs) : 0;
}
return out_pos;
}
//----------------------------------------------------------------------------//
const String& Window::getTextVisual() const
{
// no bidi support
if (!d_bidiVisualMapping)
return d_textLogical;
if (!d_bidiDataValid)
{
d_bidiVisualMapping->updateVisual(d_textLogical);
d_bidiDataValid = true;
}
return d_bidiVisualMapping->getTextVisual();
}
//----------------------------------------------------------------------------//
bool Window::isTextParsingEnabled() const
{
return d_textParsingEnabled;
}
//----------------------------------------------------------------------------//
void Window::setTextParsingEnabled(const bool setting)
{
d_textParsingEnabled = setting;
d_renderedStringValid = false;
WindowEventArgs args(this);
onTextParsingChanged(args);
}
//----------------------------------------------------------------------------//
void Window::setMargin(const UBox& margin)
{
d_margin = margin;
WindowEventArgs args(this);
onMarginChanged(args);
}
//----------------------------------------------------------------------------//
const UBox& Window::getMargin() const
{
return d_margin;
}
//----------------------------------------------------------------------------//
void Window::onTextParsingChanged(WindowEventArgs& e)
{
fireEvent(EventTextParsingChanged, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::onMarginChanged(WindowEventArgs& e)
{
fireEvent(EventMarginChanged, e, EventNamespace);
}
//----------------------------------------------------------------------------//
void Window::moveInFront(const Window* const window)
{
if (!window || !window->d_parent || window->d_parent != d_parent ||
window == this || window->d_alwaysOnTop != d_alwaysOnTop ||
!d_zOrderingEnabled)
return;
// find our position in the parent child draw list
const ChildDrawList::iterator p(std::find(getParent()->d_drawList.begin(),
getParent()->d_drawList.end(),
this));
// sanity checK that we were attached to our parent.
assert(p != getParent()->d_drawList.end());
// erase us from our current position
getParent()->d_drawList.erase(p);
// find window we're to be moved in front of in parent's draw list
ChildDrawList::iterator i(std::find(getParent()->d_drawList.begin(),
getParent()->d_drawList.end(),
window));
// sanity check that target window was also attached to correct parent.
assert(i != getParent()->d_drawList.end());
// reinsert ourselves at the right location
getParent()->d_drawList.insert(++i, this);
// handle event notifications for affected windows.
onZChange_impl();
}
//----------------------------------------------------------------------------//
void Window::moveBehind(const Window* const window)
{
if (!window || !window->d_parent || window->d_parent != d_parent ||
window == this || window->d_alwaysOnTop != d_alwaysOnTop ||
!d_zOrderingEnabled)
return;
// find our position in the parent child draw list
const ChildDrawList::iterator p(std::find(getParent()->d_drawList.begin(),
getParent()->d_drawList.end(),
this));
// sanity checK that we were attached to our parent.
assert(p != getParent()->d_drawList.end());
// erase us from our current position
getParent()->d_drawList.erase(p);
// find window we're to be moved in front of in parent's draw list
const ChildDrawList::iterator i(std::find(getParent()->d_drawList.begin(),
getParent()->d_drawList.end(),
window));
// sanity check that target window was also attached to correct parent.
assert(i != getParent()->d_drawList.end());
// reinsert ourselves at the right location
getParent()->d_drawList.insert(i, this);
// handle event notifications for affected windows.
onZChange_impl();
}
//----------------------------------------------------------------------------//
void Window::setUpdateMode(const WindowUpdateMode mode)
{
d_updateMode = mode;
}
//----------------------------------------------------------------------------//
WindowUpdateMode Window::getUpdateMode() const
{
return d_updateMode;
}
//----------------------------------------------------------------------------//
void Window::setCursorInputPropagationEnabled(const bool enabled)
{
d_propagatePointerInputs = enabled;
}
//----------------------------------------------------------------------------//
bool Window::isCursorInputPropagationEnabled() const
{
return d_propagatePointerInputs;
}
//----------------------------------------------------------------------------//
Window* Window::clone(const bool deepCopy) const
{
Window* ret =
WindowManager::getSingleton().createWindow(getType(), getName());
// always copy properties
clonePropertiesTo(*ret);
// if user requested deep copy, we should copy children as well
if (deepCopy)
cloneChildWidgetsTo(*ret);
return ret;
}
//----------------------------------------------------------------------------//
void Window::clonePropertiesTo(Window& target) const
{
for (PropertySet::PropertyIterator propertyIt = getPropertyIterator();
!propertyIt.isAtEnd();
++propertyIt)
{
const String& propertyName = propertyIt.getCurrentKey();
const String propertyValue = getProperty(propertyName);
// we never copy stuff that doesn't get written into XML
if (isPropertyBannedFromXML(propertyName))
continue;
// some cases when propertyValue is "" could lead to exception throws
if (propertyValue.empty())
{
// special case, this causes exception throw when no window renderer
// is assigned to the window
if (propertyName == "LookNFeel")
continue;
// special case, this causes exception throw because we are setting
// 'null' window renderer
if (propertyName == "WindowRenderer")
continue;
}
target.setProperty(propertyName, propertyValue);
}
}
//----------------------------------------------------------------------------//
void Window::cloneChildWidgetsTo(Window& target) const
{
// todo: ChildWindowIterator?
for (size_t childI = 0; childI < getChildCount(); ++childI)
{
Window* child = getChildAtIdx(childI);
if (child->isAutoWindow())
{
// we skip auto windows, they are already created
// automatically
// note: some windows store non auto windows inside auto windows,
// standard solution is to copy these non-auto windows to
// the parent window
//
// If you need alternative behaviour, you have to override
// this method!
// so just copy it's child widgets
child->cloneChildWidgetsTo(target);
// and skip the auto widget
continue;
}
Window* newChild = child->clone(true);
target.addChild(newChild);
}
}
//----------------------------------------------------------------------------//
size_t Window::getZIndex() const
{
if (!d_parent)
return 0;
ChildDrawList::iterator i = std::find(
getParent()->d_drawList.begin(),
getParent()->d_drawList.end(),
this);
if (i == getParent()->d_drawList.end())
CEGUI_THROW(InvalidRequestException(
"Window is not in its parent's draw list."));
return std::distance(getParent()->d_drawList.begin(), i);
}
//----------------------------------------------------------------------------//
bool Window::isInFront(const Window& wnd) const
{
// children are always in front of their ancestors
if (isAncestor(&wnd))
return true;
// conversely, ancestors are always behind their children
if (wnd.isAncestor(this))
return false;
const Window* const w1 = getWindowAttachedToCommonAncestor(wnd);
// seems not to be in same window hierarchy
if (!w1)
return false;
const Window* const w2 = wnd.getWindowAttachedToCommonAncestor(*this);
// at this point, w1 and w2 share the same parent.
return w2->getZIndex() > w1->getZIndex();
}
//----------------------------------------------------------------------------//
const Window* Window::getWindowAttachedToCommonAncestor(const Window& wnd) const
{
const Window* w = &wnd;
const Window* tmp = w->getParent();
while (tmp)
{
if (isAncestor(tmp))
break;
w = tmp;
tmp = tmp->getParent();
}
return tmp ? w : 0;
}
//----------------------------------------------------------------------------//
bool Window::isBehind(const Window& wnd) const
{
return !isInFront(wnd);
}
//----------------------------------------------------------------------------//
const Font* Window::property_getFont() const
{
// This is changed behaviour when compared to 0.7, we return the Font set
// for this window but we don't return name of the default font when
// no font is set. This is IMO more practical. User can always use
// getFont() directly to get 0.7 behaviour.
return getFont(false);
}
//----------------------------------------------------------------------------//
const Image* Window::property_getCursor() const
{
return getCursor();
}
//----------------------------------------------------------------------------//
GUIContext& Window::getGUIContext() const
{
// GUIContext is always the one on the root window, we do not allow parts
// of a hierarchy to be drawn to seperate contexts (which is not much of
// a limitation).
//
// ISSUE: if root has no GUIContext set for it, should we return 0 or
// System::getDefaultGUIContext? Come to IRC and argue about it!
return getParent() ? getParent()->getGUIContext() :
d_guiContext ? *d_guiContext :
System::getSingleton().getDefaultGUIContext();
}
//----------------------------------------------------------------------------//
void Window::setGUIContext(GUIContext* context)
{
if (d_guiContext == context)
return;
d_guiContext = context;
syncTargetSurface();
}
//----------------------------------------------------------------------------//
const Sizef& Window::getRootContainerSize() const
{
return getGUIContext().getSurfaceSize();
}
//----------------------------------------------------------------------------//
void Window::setAutoWindow(bool is_auto)
{
d_autoWindow = is_auto;
if (d_autoWindow)
banPropertiesForAutoWindow();
}
//----------------------------------------------------------------------------//
void Window::banPropertiesForAutoWindow()
{
banPropertyFromXML("AutoWindow"); // :-D
banPropertyFromXML("DestroyedByParent");
banPropertyFromXML("VerticalAlignment");
banPropertyFromXML("HorizontalAlignment");
banPropertyFromXML("Area");
banPropertyFromXML("Position");
banPropertyFromXML("Size");
banPropertyFromXML("MinSize");
banPropertyFromXML("MaxSize");
banPropertyFromXML(&d_windowRendererProperty);
banPropertyFromXML(&d_lookNFeelProperty);
}
//----------------------------------------------------------------------------//
bool Window::handleFontRenderSizeChange(const EventArgs& args)
{
if (!d_windowRenderer)
return false;
return d_windowRenderer->handleFontRenderSizeChange(
static_cast<const FontEventArgs&>(args).font);
}
//----------------------------------------------------------------------------//
bool Window::isPointerContainedInArea() const
{
return d_containsPointer;
}
//----------------------------------------------------------------------------//
bool Window::isFocused() const
{
return d_isFocused;
}
//----------------------------------------------------------------------------//
void Window::focus()
{
if (isDisabled())
return;
d_isFocused = true;
ActivationEventArgs event_args(this);
onActivated(event_args);
}
//----------------------------------------------------------------------------//
void Window::unfocus()
{
d_isFocused = false;
if (d_active)
{
ActivationEventArgs event_args(this);
onDeactivated(event_args);
}
}
//----------------------------------------------------------------------------//
bool Window::canFocus()
{
// by default all widgets can be focused if they are not disabled
return !isDisabled();
}
//----------------------------------------------------------------------------//
void Window::destroyGeometryBuffers()
{
const size_t geom_buffer_count = d_geometryBuffers.size();
for (size_t i = 0; i < geom_buffer_count; ++i)
System::getSingleton().getRenderer()->destroyGeometryBuffer(*d_geometryBuffers.at(i));
d_geometryBuffers.clear();
}
//----------------------------------------------------------------------------//
void Window::updateGeometryBuffersTranslationAndClipping()
{
const size_t geom_buffer_count = d_geometryBuffers.size();
for (size_t i = 0; i < geom_buffer_count; ++i)
{
CEGUI::GeometryBuffer*& currentBuffer = d_geometryBuffers[i];
currentBuffer->setTranslation(d_translation);
currentBuffer->setClippingRegion(d_clippingRegion);
}
}
void Window::updateGeometryBuffersAlpha()
{
float final_alpha = getEffectiveAlpha();
const size_t geom_buffer_count = d_geometryBuffers.size();
for (size_t i = 0; i < geom_buffer_count; ++i)
{
CEGUI::GeometryBuffer*& currentBuffer = d_geometryBuffers[i];
currentBuffer->setAlpha(final_alpha);
}
}
//----------------------------------------------------------------------------//
#if defined(_MSC_VER)
# pragma warning(pop)
#endif
} // End of CEGUI namespace section
|
{
"content_hash": "4f169859c7445835dcd27b221e426be4",
"timestamp": "",
"source": "github",
"line_count": 3819,
"max_line_length": 186,
"avg_line_length": 32.22623723487824,
"alnum_prop": 0.545404316172647,
"repo_name": "OpenTechEngine/CEGUI",
"id": "aae8b2ff6778a5fac0c74cb61701bc7a7b792608",
"size": "123072",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "cegui/src/Window.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "394676"
},
{
"name": "C++",
"bytes": "20361770"
},
{
"name": "Lua",
"bytes": "131055"
},
{
"name": "Python",
"bytes": "92177"
},
{
"name": "Shell",
"bytes": "1001"
}
]
}
|
End of preview.