Merge latest green mozilla-central to services-central.

This commit is contained in:
Nick Alexander 2013-07-16 08:31:31 -07:00
Родитель 08693cb5b8 95cc3ca47e
Коммит a8f8b1b419
720 изменённых файлов: 100446 добавлений и 3181 удалений

Просмотреть файл

@ -17,4 +17,4 @@
#
# Modifying this file will now automatically clobber the buildbot machines \o/
#
Bug 870407 - move CMMSRCS to mozbuild
Bug 870180 - CPOWs

Просмотреть файл

@ -415,6 +415,31 @@ nsAccessiblePivot::MovePivotInternal(Accessible* aPosition,
return NotifyOfPivotChange(oldPosition, oldStart, oldEnd, aReason);
}
Accessible*
nsAccessiblePivot::AdjustStartPosition(Accessible* aAccessible,
RuleCache& aCache,
uint16_t* aFilterResult,
nsresult* aResult)
{
Accessible* matched = aAccessible;
*aResult = aCache.ApplyFilter(aAccessible, aFilterResult);
if (aAccessible != mRoot && aAccessible != mModalRoot) {
for (Accessible* temp = aAccessible->Parent();
temp && temp != mRoot && temp != mModalRoot; temp = temp->Parent()) {
uint16_t filtered = nsIAccessibleTraversalRule::FILTER_IGNORE;
*aResult = aCache.ApplyFilter(temp, &filtered);
NS_ENSURE_SUCCESS(*aResult, nullptr);
if (filtered & nsIAccessibleTraversalRule::FILTER_IGNORE_SUBTREE) {
*aFilterResult = filtered;
matched = temp;
}
}
}
return matched;
}
Accessible*
nsAccessiblePivot::SearchBackward(Accessible* aAccessible,
nsIAccessibleTraversalRule* aRule,
@ -428,15 +453,13 @@ nsAccessiblePivot::SearchBackward(Accessible* aAccessible,
return nullptr;
RuleCache cache(aRule);
Accessible* accessible = aAccessible;
uint16_t filtered = nsIAccessibleTraversalRule::FILTER_IGNORE;
Accessible* accessible = AdjustStartPosition(aAccessible, cache,
&filtered, aResult);
NS_ENSURE_SUCCESS(*aResult, nullptr);
if (aSearchCurrent) {
*aResult = cache.ApplyFilter(accessible, &filtered);
NS_ENSURE_SUCCESS(*aResult, nullptr);
if (filtered & nsIAccessibleTraversalRule::FILTER_MATCH)
return accessible;
if (aSearchCurrent && (filtered & nsIAccessibleTraversalRule::FILTER_MATCH)) {
return accessible;
}
Accessible* root = GetActiveRoot();
@ -492,7 +515,7 @@ nsAccessiblePivot::SearchForward(Accessible* aAccessible,
RuleCache cache(aRule);
uint16_t filtered = nsIAccessibleTraversalRule::FILTER_IGNORE;
*aResult = cache.ApplyFilter(accessible, &filtered);
accessible = AdjustStartPosition(accessible, cache, &filtered, aResult);
NS_ENSURE_SUCCESS(*aResult, nullptr);
if (aSearchCurrent && (filtered & nsIAccessibleTraversalRule::FILTER_MATCH))
return accessible;

Просмотреть файл

@ -16,6 +16,7 @@
#include "mozilla/Attributes.h"
class nsIAccessibleTraversalRule;
class RuleCache;
/**
* Class represents an accessible pivot.
@ -90,6 +91,18 @@ private:
*/
bool MovePivotInternal(Accessible* aPosition, PivotMoveReason aReason);
/*
* Get initial node we should start a search from with a given rule.
*
* When we do a move operation from one position to another,
* the initial position can be inside of a subtree that is ignored by
* the given rule. We need to step out of the ignored subtree and start
* the search from there.
*
*/
Accessible* AdjustStartPosition(Accessible* aAccessible, RuleCache& aCache,
uint16_t* aFilterResult, nsresult* aResult);
/*
* The root accessible.
*/

Просмотреть файл

@ -1130,7 +1130,9 @@ HyperTextAccessible::GetTextAtOffset(int32_t aOffset,
if (aOffset == nsIAccessibleText::TEXT_OFFSET_CARET)
offset = AdjustCaretOffset(offset);
// Home key, arrow down and if not on last line then home key.
// Start offset is begin of the current line (as the home key was
// pressed). End offset is begin of the next line if any (arrow down and
// home keys), otherwise end of the current line (arrow down only).
*aStartOffset = FindLineBoundary(offset, eDirPrevious, eSelectBeginLine);
*aEndOffset = FindLineBoundary(offset, eDirNext, eSelectLine);
int32_t tmpOffset = FindLineBoundary(*aEndOffset, eDirPrevious, eSelectBeginLine);
@ -1154,8 +1156,10 @@ HyperTextAccessible::GetTextAtOffset(int32_t aOffset,
if (aOffset == nsIAccessibleText::TEXT_OFFSET_CARET)
offset = AdjustCaretOffset(offset);
// In contrast to word end boundary we follow the spec here. End key,
// then up arrow and if not on first line then end key.
// In contrast to word end boundary we follow the spec here.
// End offset is end of the current line (as the end key was pressed).
// Start offset is end of the previous line if any (up arrow and end keys),
// otherwise 0 offset (up arrow only).
*aEndOffset = FindLineBoundary(offset, eDirNext, eSelectEndLine);
int32_t tmpOffset = FindLineBoundary(offset, eDirPrevious, eSelectLine);
*aStartOffset = FindLineBoundary(tmpOffset, eDirNext, eSelectEndLine);
@ -1216,7 +1220,41 @@ HyperTextAccessible::GetTextAfterOffset(int32_t aOffset,
return GetText(*aStartOffset, *aEndOffset, aText);
case BOUNDARY_LINE_START:
if (aOffset == nsIAccessibleText::TEXT_OFFSET_CARET)
offset = AdjustCaretOffset(offset);
// Down arrow, home key, down arrow, home key.
*aStartOffset = FindLineBoundary(offset, eDirNext, eSelectLine);
if (*aStartOffset != CharacterCount()) {
*aStartOffset = FindLineBoundary(*aStartOffset, eDirPrevious, eSelectBeginLine);
*aEndOffset = FindLineBoundary(*aStartOffset, eDirNext, eSelectLine);
if (*aEndOffset != CharacterCount())
*aEndOffset = FindLineBoundary(*aEndOffset, eDirPrevious, eSelectBeginLine);
} else {
*aEndOffset = CharacterCount();
}
return GetText(*aStartOffset, *aEndOffset, aText);
case BOUNDARY_LINE_END:
if (aOffset == nsIAccessibleText::TEXT_OFFSET_CARET)
offset = AdjustCaretOffset(offset);
// Empty last line doesn't have own frame (a previous line contains '\n'
// character instead) thus we can't operate on last line separately
// from the previous line.
if (IsEmptyLastLineOffset(offset)) {
*aStartOffset = *aEndOffset = offset;
return NS_OK;
}
// End key, down arrow, end key.
*aStartOffset = FindLineBoundary(offset, eDirNext, eSelectEndLine);
*aEndOffset = FindLineBoundary(*aStartOffset, eDirNext, eSelectLine);
if (*aEndOffset != CharacterCount())
*aEndOffset = FindLineBoundary(*aEndOffset, eDirNext, eSelectEndLine);
return GetText(*aStartOffset, *aEndOffset, aText);
case BOUNDARY_ATTRIBUTE_RANGE:
return GetTextHelper(eGetAfter, aBoundaryType, aOffset,
aStartOffset, aEndOffset, aText);

Просмотреть файл

@ -579,7 +579,7 @@ this.UtteranceGenerator = {
if (roleStr) {
desc.push(roleStr);
}
desc.push(this._getPluralFormString('listItemCount', aItemCount));
desc.push(this._getPluralFormString('listItemsCount', aItemCount));
let utterance = [desc.join(' ')];
this._addName(utterance, aAccessible, aFlags);

Просмотреть файл

@ -17,7 +17,6 @@ LIBXUL_LIBRARY = 1
# macros which conflicts with std::min/max. Suppress the macros:
OS_CXXFLAGS += -DNOMINMAX
include $(topsrcdir)/config/config.mk
include $(topsrcdir)/config/rules.mk
LOCAL_INCLUDES += \

Просмотреть файл

@ -16,7 +16,6 @@ LIBXUL_LIBRARY = 1
# macros which conflicts with std::min/max. Suppress the macros:
OS_CXXFLAGS += -DNOMINMAX
include $(topsrcdir)/config/config.mk
include $(topsrcdir)/config/rules.mk
LOCAL_INCLUDES += \

Просмотреть файл

@ -16,7 +16,6 @@ LIBXUL_LIBRARY = 1
# macros which conflicts with std::min/max. Suppress the macros:
OS_CXXFLAGS += -DNOMINMAX
include $(topsrcdir)/config/config.mk
include $(topsrcdir)/config/rules.mk
LOCAL_INCLUDES += \

Просмотреть файл

@ -76,6 +76,21 @@ function VCChangedChecker(aDocAcc, aIdOrNameOrAcc, aTextOffsets, aPivotMoveMetho
{
this.__proto__ = new invokerChecker(EVENT_VIRTUALCURSOR_CHANGED, aDocAcc);
this.match = function VCChangedChecker_check(aEvent)
{
var event = null;
try {
event = aEvent.QueryInterface(nsIAccessibleVirtualCursorChangeEvent);
} catch (e) {
return false;
}
var expectedReason = VCChangedChecker.methodReasonMap[aPivotMoveMethod] ||
nsIAccessiblePivot.REASON_NONE;
return event.reason == expectedReason;
};
this.check = function VCChangedChecker_check(aEvent)
{
SimpleTest.info("VCChangedChecker_check");
@ -87,11 +102,6 @@ function VCChangedChecker(aDocAcc, aIdOrNameOrAcc, aTextOffsets, aPivotMoveMetho
SimpleTest.ok(false, "Does not support correct interface: " + e);
}
SimpleTest.is(
event.reason,
VCChangedChecker.methodReasonMap[aPivotMoveMethod],
'wrong move reason');
var position = aDocAcc.virtualCursor.position;
var idMatches = position && position.DOMNode.id == aIdOrNameOrAcc;
var nameMatches = position && position.name == aIdOrNameOrAcc;
@ -196,9 +206,14 @@ function setVCPosInvoker(aDocAcc, aPivotMoveMethod, aRule, aIdOrNameOrAcc)
{
VCChangedChecker.
storePreviousPosAndOffset(aDocAcc.virtualCursor);
var moved = aDocAcc.virtualCursor[aPivotMoveMethod](aRule);
SimpleTest.ok((expectMove && moved) || (!expectMove && !moved),
"moved pivot");
if (aPivotMoveMethod && aRule) {
var moved = aDocAcc.virtualCursor[aPivotMoveMethod](aRule);
SimpleTest.is(!!moved, !!expectMove,
"moved pivot with " + aPivotMoveMethod +
" to " + aIdOrNameOrAcc);
} else {
aDocAcc.virtualCursor.position = getAccessible(aIdOrNameOrAcc);
}
};
this.getID = function setVCPosInvoker_getID()
@ -447,7 +462,7 @@ function removeVCRootInvoker(aRootNode)
*/
function dumpTraversalSequence(aPivot, aRule)
{
var sequence = []
var sequence = [];
if (aPivot.moveFirst(aRule)) {
do {
sequence.push("'" + prettyName(aPivot.position) + "'");

Просмотреть файл

@ -15,7 +15,7 @@
<p id="paragraph-2" aria-hidden="">
Sed accumsan luctus lacus, vitae mollis arcu tristique vulputate.</p>
<p id="paragraph-3" aria-hidden="true">
Maybe it was the other <i>George Michael</i>.
<a href="#" id="hidden-link">Maybe</a> it was the other <i>George Michael</i>.
You know, the <a href="#">singer-songwriter</a>.
</p>
<iframe

Просмотреть файл

@ -95,6 +95,12 @@
gQueue.push(new setModalRootInvoker(docAcc, docAcc.parent,
NS_ERROR_INVALID_ARG));
// Put cursor in an ignored subtree
gQueue.push(new setVCPosInvoker(docAcc, null, null,
getAccessible(doc.getElementById("hidden-link"))));
// Next item shoud be outside of that subtree
gQueue.push(new setVCPosInvoker(docAcc, "moveNext", ObjectTraversalRule, "An "));
gQueue.invoke();
}

Просмотреть файл

@ -44,7 +44,7 @@
["textarea"]);
testTextAfterOffset(kCaretOffset, BOUNDARY_LINE_END, "", 15, 15,
"textarea", kOk, kTodo, kTodo);
[ "textarea" ]);
testTextAtOffset(kCaretOffset, BOUNDARY_LINE_START, "words", 10, 15,
[ "textarea" ]);
@ -72,10 +72,10 @@
this.finalCheck = function moveToLastLineStart_finalCheck()
{
testTextAfterOffset(kCaretOffset, BOUNDARY_LINE_START, "", 15, 15,
"textarea", kTodo, kTodo, kOk);
[ "textarea" ]);
testTextAfterOffset(kCaretOffset, BOUNDARY_LINE_END, "", 15, 15,
"textarea", kTodo, kTodo, kOk);
[ "textarea" ]);
testTextAtOffset(kCaretOffset, BOUNDARY_LINE_START, "words", 10, 15,
[ "textarea" ]);
@ -104,10 +104,10 @@
this.finalCheck = function moveToMiddleLineStart_finalCheck()
{
testTextAfterOffset(kCaretOffset, BOUNDARY_LINE_START, "words", 10, 15,
"textarea", kTodo, kTodo, kTodo);
[ "textarea" ]);
testTextAfterOffset(kCaretOffset, BOUNDARY_LINE_END, "words", 10, 15,
"textarea", kTodo, kTodo, kTodo);
[ "textarea" ]);
testTextAtOffset(kCaretOffset, BOUNDARY_LINE_START, "two ", 6, 10,
[ "textarea" ]);
@ -135,10 +135,10 @@
this.finalCheck = function moveToMiddleLineEnd_finalCheck()
{
testTextAfterOffset(kCaretOffset, BOUNDARY_LINE_START, "words", 10, 15,
"textarea", kTodo, kTodo, kTodo);
[ "textarea" ]);
testTextAfterOffset(kCaretOffset, BOUNDARY_LINE_END, "words", 10, 15,
"textarea", kTodo, kTodo, kOk);
[ "textarea" ]);
testTextAtOffset(kCaretOffset, BOUNDARY_LINE_START, "two ", 6, 10,
[ "textarea" ]);
@ -166,10 +166,10 @@
this.finalCheck = function moveToFirstLineStart_finalCheck()
{
testTextAfterOffset(kCaretOffset, BOUNDARY_LINE_START, "two ", 6, 10,
"textarea", kTodo, kTodo, kTodo);
[ "textarea" ]);
testTextAfterOffset(kCaretOffset, BOUNDARY_LINE_END, "aword", 0, 5,
"textarea", kOk, kOk, kOk);
testTextAfterOffset(kCaretOffset, BOUNDARY_LINE_END, "\ntwo ", 5, 10,
[ "textarea" ]);
testTextAtOffset(kCaretOffset, BOUNDARY_LINE_START, "aword\n", 0, 6,
[ "textarea" ]);
@ -197,10 +197,10 @@
this.finalCheck = function moveToFirstLineStart_finalCheck()
{
testTextAfterOffset(kCaretOffset, BOUNDARY_LINE_START, "two ", 6, 10,
"textarea", kTodo, kTodo, kTodo);
[ "textarea" ]);
testTextAfterOffset(kCaretOffset, BOUNDARY_LINE_END, "\ntwo ", 5, 10,
"textarea", kTodo, kTodo, kTodo);
[ "textarea" ]);
testTextAtOffset(kCaretOffset, BOUNDARY_LINE_START, "aword\n", 0, 6,
[ "textarea" ]);
@ -224,8 +224,6 @@
var gQueue = null;
function doTest()
{
SimpleTest.expectAssertions(1);
gQueue = new eventQueue();
gQueue.push(new moveToLastLineEnd());
gQueue.push(new moveToLastLineStart());

Просмотреть файл

@ -16,8 +16,6 @@
function doTest()
{
SimpleTest.expectAssertions(5);
// __o__n__e__w__o__r__d__\n
// 0 1 2 3 4 5 6 7
// __\n
@ -34,74 +32,19 @@
// getTextAfterOffset
// BOUNDARY_LINE_START
testTextAfterOffset(0, BOUNDARY_LINE_START, "\n", 8, 9,
"div", kTodo, kTodo, kTodo,
"divbr", kTodo, kTodo, kTodo,
"editable", kTodo, kTodo, kTodo,
"editablebr", kTodo, kTodo, kTodo,
"textarea", kTodo, kTodo, kTodo);
testTextAfterOffset(7, BOUNDARY_LINE_START, "\n", 8, 9,
"div", kOk, kTodo, kTodo,
"divbr", kOk, kTodo, kTodo,
"editable", kOk, kTodo, kTodo,
"editablebr", kOk, kTodo, kTodo,
"textarea", kOk, kTodo, kTodo);
testTextAfterOffset(8, BOUNDARY_LINE_START, "two words\n", 9, 19,
"div", kTodo, kTodo, kTodo,
"divbr", kTodo, kTodo, kTodo,
"editable", kTodo, kTodo, kTodo,
"editablebr", kTodo, kTodo, kTodo,
"textarea", kTodo, kTodo, kTodo);
testTextAfterOffset(9, BOUNDARY_LINE_START, "", 19, 19,
"div", kTodo, kTodo, kTodo,
"divbr", kTodo, kTodo, kTodo,
"editable", kTodo, kTodo, kTodo,
"editablebr", kTodo, kTodo, kTodo,
"textarea", kTodo, kTodo, kTodo);
testTextAfterOffset(19, BOUNDARY_LINE_START, "", 19, 19,
"div", kOk, kOk, kTodo,
"divbr", kOk, kOk, kTodo,
"editable", kOk, kOk, kTodo,
"editablebr", kOk, kOk, kTodo,
"textarea", kOk, kOk, kTodo);
testTextAfterOffset(0, BOUNDARY_LINE_START, "\n", 8, 9, IDs);
testTextAfterOffset(7, BOUNDARY_LINE_START, "\n", 8, 9, IDs);
testTextAfterOffset(8, BOUNDARY_LINE_START, "two words\n", 9, 19, IDs);
testTextAfterOffset(9, BOUNDARY_LINE_START, "", 19, 19, IDs);
testTextAfterOffset(19, BOUNDARY_LINE_START, "", 19, 19, IDs);
// BOUNDARY_LINE_END
testTextAfterOffset(0, BOUNDARY_LINE_END, "\n", 7, 8,
"div", kTodo, kTodo, kTodo,
"divbr", kTodo, kTodo, kTodo,
"editable", kTodo, kTodo, kTodo,
"editablebr", kTodo, kTodo, kTodo,
"textarea", kTodo, kTodo, kTodo);
testTextAfterOffset(7, BOUNDARY_LINE_END, "\n", 7, 8,
"div", kOk, kOk, kOk,
"divbr", kOk, kOk, kOk,
"editable", kOk, kOk, kOk,
"editablebr", kOk, kOk, kOk,
"textarea", kOk, kOk, kOk);
testTextAfterOffset(8, BOUNDARY_LINE_END, "\ntwo words", 8, 18,
"div", kOk, kOk, kOk,
"divbr", kOk, kOk, kOk,
"editable", kOk, kOk, kOk,
"editablebr", kOk, kOk, kOk,
"textarea", kOk, kOk, kOk);
testTextAfterOffset(9, BOUNDARY_LINE_END, "\n", 18, 19,
"div", kTodo, kTodo, kTodo,
"divbr", kTodo, kTodo, kTodo,
"editable", kTodo, kTodo, kTodo,
"editablebr", kTodo, kTodo, kTodo,
"textarea", kTodo, kTodo, kTodo);
testTextAfterOffset(18, BOUNDARY_LINE_END, "\n", 18, 19,
"div", kOk, kOk, kOk,
"divbr", kOk, kOk, kOk,
"editable", kOk, kOk, kOk,
"editablebr", kOk, kOk, kOk,
"textarea", kOk, kOk, kOk);
testTextAfterOffset(19, BOUNDARY_LINE_END, "", 19, 19,
"div", kOk, kTodo, kTodo,
"divbr", kOk, kTodo, kTodo,
"editable", kOk, kTodo, kTodo,
"editablebr", kOk, kTodo, kTodo,
"textarea", kOk, kTodo, kTodo);
testTextAfterOffset(0, BOUNDARY_LINE_END, "\n", 7, 8, IDs);
testTextAfterOffset(7, BOUNDARY_LINE_END, "\n", 7, 8, IDs);
testTextAfterOffset(8, BOUNDARY_LINE_END, "\ntwo words", 8, 18, IDs);
testTextAfterOffset(9, BOUNDARY_LINE_END, "\n", 18, 19, IDs);
testTextAfterOffset(18, BOUNDARY_LINE_END, "\n", 18, 19, IDs);
testTextAfterOffset(19, BOUNDARY_LINE_END, "", 19, 19, IDs);
////////////////////////////////////////////////////////////////////////
// getTextBeforeOffset
@ -166,6 +109,11 @@
href="https://bugzilla.mozilla.org/show_bug.cgi?id=855732">
Bug 855732
</a>
<a target="_blank"
title=" getTextAfterOffset for line boundary on new rails"
href="https://bugzilla.mozilla.org/show_bug.cgi?id=882292">
Bug 882292
</a>
<p id="display"></p>
<div id="content" style="display: none"></div>
<pre id="test">

Просмотреть файл

@ -11,12 +11,6 @@
<script type="application/javascript"
src="../text.js"></script>
<script type="application/javascript">
if (navigator.platform.startsWith("Mac")) {
SimpleTest.expectAssertions(0, 4);
} else {
SimpleTest.expectAssertions(4);
}
function doTest()
{
// __h__e__l__l__o__ __m__y__ __f__r__i__e__n__d__
@ -29,48 +23,16 @@
var regularIDs = [ "input", "div", "editable" ];
// BOUNDARY_LINE_START
testTextAfterOffset(0, BOUNDARY_LINE_START, "", 15, 15,
"input", kTodo, kTodo, kOk,
"div", kTodo, kTodo, kOk,
"editable", kTodo, kTodo, kOk,
"textarea", kTodo, kTodo, kOk);
testTextAfterOffset(1, BOUNDARY_LINE_START, "", 15, 15,
"input", kTodo, kTodo, kOk,
"div", kTodo, kTodo, kOk,
"editable", kTodo, kTodo, kOk,
"textarea", kTodo, kTodo, kOk);
testTextAfterOffset(14, BOUNDARY_LINE_START, "", 15, 15,
"input", kTodo, kTodo, kOk,
"div", kTodo, kTodo, kOk,
"editable", kTodo, kTodo, kOk,
"textarea", kTodo, kTodo, kOk);
testTextAfterOffset(15, BOUNDARY_LINE_START, "", 15, 15,
"input", kOk, kOk, kOk,
"div", kOk, kOk, kOk,
"editable", kOk, kOk, kOk,
"textarea", kOk, kOk, kOk);
testTextAfterOffset(0, BOUNDARY_LINE_START, "", 15, 15, IDs);
testTextAfterOffset(1, BOUNDARY_LINE_START, "", 15, 15, IDs);
testTextAfterOffset(14, BOUNDARY_LINE_START, "", 15, 15, IDs);
testTextAfterOffset(15, BOUNDARY_LINE_START, "", 15, 15, IDs);
// BOUNDARY_LINE_END
testTextAfterOffset(0, BOUNDARY_LINE_END, "", 15, 15,
"input", kTodo, kTodo, kOk,
"div", kTodo, kTodo, kOk,
"editable", kTodo, kTodo, kOk,
"textarea", kTodo, kTodo, kOk);
testTextAfterOffset(1, BOUNDARY_LINE_END, "", 15, 15,
"input", kTodo, kTodo, kOk,
"div", kTodo, kTodo, kOk,
"editable", kTodo, kTodo, kOk,
"textarea", kTodo, kTodo, kOk);
testTextAfterOffset(14, BOUNDARY_LINE_END, "", 15, 15,
"input", kTodo, kTodo, kOk,
"div", kTodo, kTodo, kOk,
"editable", kTodo, kTodo, kOk,
"textarea", kTodo, kTodo, kOk);
testTextAfterOffset(15, BOUNDARY_LINE_END, "", 15, 15,
"input", kOk, kTodo, kTodo,
"div", kOk, kTodo, kTodo,
"editable", kOk, kTodo, kTodo,
"textarea", kOk, kTodo, kTodo);
testTextAfterOffset(0, BOUNDARY_LINE_END, "", 15, 15, IDs);
testTextAfterOffset(1, BOUNDARY_LINE_END, "", 15, 15, IDs);
testTextAfterOffset(14, BOUNDARY_LINE_END, "", 15, 15, IDs);
testTextAfterOffset(15, BOUNDARY_LINE_END, "", 15, 15, IDs);
////////////////////////////////////////////////////////////////////////
// getTextBeforeOffset
@ -131,6 +93,11 @@
href="https://bugzilla.mozilla.org/show_bug.cgi?id=855732">
Bug 855732
</a>
<a target="_blank"
title=" getTextAfterOffset for line boundary on new rails"
href="https://bugzilla.mozilla.org/show_bug.cgi?id=882292">
Bug 882292
</a>
<p id="display"></p>
<div id="content" style="display: none"></div>
<pre id="test">

Просмотреть файл

@ -559,10 +559,13 @@ pref("javascript.options.mem.log", false);
// Increase mark slice time from 10ms to 30ms
pref("javascript.options.mem.gc_incremental_slice_ms", 30);
pref("javascript.options.mem.gc_high_frequency_heap_growth_max", 150);
// Increase time to get more high frequency GC on benchmarks from 1000ms to 1500ms
pref("javascript.options.mem.gc_high_frequency_time_limit_ms", 1500);
pref("javascript.options.mem.gc_high_frequency_heap_growth_max", 300);
pref("javascript.options.mem.gc_high_frequency_heap_growth_min", 120);
pref("javascript.options.mem.gc_high_frequency_high_limit_mb", 40);
pref("javascript.options.mem.gc_high_frequency_low_limit_mb", 10);
pref("javascript.options.mem.gc_high_frequency_low_limit_mb", 0);
pref("javascript.options.mem.gc_low_frequency_heap_growth", 120);
pref("javascript.options.mem.high_water_mark", 6);
pref("javascript.options.mem.gc_allocation_threshold_mb", 1);

Просмотреть файл

@ -1,4 +1,4 @@
{
"revision": "d717e2e751a6bb1303499bde6be9dbd88b275e30",
"revision": "37d94f0bacee10e768aca70b2ea6acab378ebed5",
"repo_path": "/integration/gaia-central"
}

Просмотреть файл

@ -7,8 +7,6 @@ topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(topsrcdir)/config/config.mk
include $(topsrcdir)/config/rules.mk
ifdef MAKENSISU
@ -21,3 +19,6 @@ ifdef MOZ_MAINTENANCE_SERVICE
$(MAKE) -C installer/windows maintenanceservice_installer
endif
endif
check::
$(PYTHON) $(topsrcdir)/build/compare-mozconfig/compare-mozconfigs-wrapper.py

Просмотреть файл

@ -3668,10 +3668,8 @@ var XULBrowserWindow = {
init: function () {
this.throbberElement = document.getElementById("navigator-throbber");
// Initialize the security button's state and tooltip text. Remember to reset
// _hostChanged, otherwise onSecurityChange will short circuit.
// Initialize the security button's state and tooltip text.
var securityUI = gBrowser.securityUI;
this._hostChanged = true;
this.onSecurityChange(null, null, securityUI.state);
},
@ -3862,7 +3860,6 @@ var XULBrowserWindow = {
onLocationChange: function (aWebProgress, aRequest, aLocationURI, aFlags) {
var location = aLocationURI ? aLocationURI.spec : "";
this._hostChanged = true;
// Hide the form invalid popup.
if (gFormSubmitObserver.panel) {
@ -4004,37 +4001,18 @@ var XULBrowserWindow = {
// Properties used to cache security state used to update the UI
_state: null,
_hostChanged: false, // onLocationChange will flip this bit
_lastLocation: null,
onSecurityChange: function (aWebProgress, aRequest, aState) {
// Don't need to do anything if the data we use to update the UI hasn't
// changed
let uri = gBrowser.currentURI;
let spec = uri.spec;
if (this._state == aState &&
!this._hostChanged) {
#ifdef DEBUG
try {
var contentHost = gBrowser.contentWindow.location.host;
if (this._host !== undefined && this._host != contentHost) {
Components.utils.reportError(
"ASSERTION: browser.js host is inconsistent. Content window has " +
"<" + contentHost + "> but cached host is <" + this._host + ">.\n"
);
}
} catch (ex) {}
#endif
this._lastLocation == spec)
return;
}
this._state = aState;
#ifdef DEBUG
try {
this._host = gBrowser.contentWindow.location.host;
} catch(ex) {
this._host = null;
}
#endif
this._hostChanged = false;
this._lastLocation = spec;
// aState is defined as a bitmask that may be extended in the future.
// We filter out any unknown bits before testing for known values.
@ -4063,7 +4041,6 @@ var XULBrowserWindow = {
gURLBar.removeAttribute("level");
}
let uri = gBrowser.currentURI;
try {
uri = Services.uriFixup.createExposableURI(uri);
} catch (e) {}

Просмотреть файл

@ -87,7 +87,7 @@ function part7() {
ok(!objLoadingContent.activated, "plugin should not be activated");
EventUtils.synthesizeMouseAtCenter(plugin, {}, gNewWindow.gBrowser.selectedBrowser.contentWindow);
let condition = function() !PopupNotifications.getNotification("click-to-play-plugins", gNewWindow.gBrowser.selectedBrowser).dismissed;
let condition = function() !PopupNotifications.getNotification("click-to-play-plugins", gNewWindow.gBrowser.selectedBrowser).dismissed && gNewWindow.PopupNotifications.panel.firstChild;
waitForCondition(condition, part8, "waited too long for plugin to activate");
}

Просмотреть файл

@ -34,7 +34,6 @@ function test() {
function checkIdentityMode(win) {
let identityMode = win.document.getElementById("identity-box").className;
is(identityMode, "unknownIdentity", "Identity should be chromeUI but is currently " +
"shown as unknownIdentity for new windows.");
is(identityMode, "chromeUI", "Identity state should be chromeUI for about:home in a new window");
finish();
}

Просмотреть файл

@ -20,7 +20,8 @@ let manifest2 = { // used for testing install
origin: "https://test1.example.com",
sidebarURL: "https://test1.example.com/browser/browser/base/content/test/social/social_sidebar.html",
workerURL: "https://test1.example.com/browser/browser/base/content/test/social/social_worker.js",
iconURL: "https://test1.example.com/browser/browser/base/content/test/moz.png"
iconURL: "https://test1.example.com/browser/browser/base/content/test/moz.png",
version: 1
};
function test() {
@ -279,5 +280,49 @@ var tests = {
});
});
});
},
testUpgradeProviderFromWorker: function(next) {
// add the provider, change the pref, add it again. The provider at that
// point should be upgraded
let activationURL = manifest2.origin + "/browser/browser/base/content/test/social/social_activate.html"
addTab(activationURL, function(tab) {
let doc = tab.linkedBrowser.contentDocument;
let installFrom = doc.nodePrincipal.origin;
Services.prefs.setCharPref("social.whitelist", installFrom);
Social.installProvider(doc, manifest2, function(addonManifest) {
SocialService.addBuiltinProvider(addonManifest.origin, function(provider) {
Social.enabled = true;
checkSocialUI();
is(Social.provider.manifest.version, 1, "manifest version is 1")
// watch for the provider-update and tell the worker to update
SocialService.registerProviderListener(function providerListener(topic, data) {
if (topic != "provider-update")
return;
SocialService.unregisterProviderListener(providerListener);
observeProviderSet(function() {
Services.prefs.clearUserPref("social.whitelist");
executeSoon(function() {
is(Social.provider.manifest.version, 2, "manifest version is 2");
Social.uninstallProvider(addonManifest.origin);
gBrowser.removeTab(tab);
next();
})
});
});
let port = Social.provider.getWorkerPort();
port.postMessage({topic: "worker.update", data: true});
});
});
});
}
}
function observeProviderSet(cb) {
Services.obs.addObserver(function providerSet(subject, topic, data) {
Services.obs.removeObserver(providerSet, "social:provider-set");
info("social:provider-set observer was notified");
// executeSoon to let the browser UI observers run first
executeSoon(cb);
}, "social:provider-set", false);
}

Просмотреть файл

@ -20,7 +20,7 @@ var data = {
"author": "Shane Caraveo, Mozilla",
// optional
"version": "1.0"
"version": 1
}
function activate(node) {

Просмотреть файл

@ -137,6 +137,13 @@ onconnect = function(e) {
if (testPort)
testPort.postMessage({topic:"got-share-data-message", result: event.data.result});
break;
case "worker.update":
apiPort.postMessage({topic: 'social.manifest-get'});
break;
case "social.manifest":
event.data.data.version = 2;
apiPort.postMessage({topic: 'social.manifest-set', data: event.data.data});
break;
}
}
}

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 1.3 KiB

После

Ширина:  |  Высота:  |  Размер: 1.8 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 3.1 KiB

После

Ширина:  |  Высота:  |  Размер: 4.7 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 1.3 KiB

После

Ширина:  |  Высота:  |  Размер: 1.6 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 3.1 KiB

После

Ширина:  |  Высота:  |  Размер: 4.2 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 965 B

После

Ширина:  |  Высота:  |  Размер: 1.6 KiB

Двоичный файл не отображается.

До

Ширина:  |  Высота:  |  Размер: 2.1 KiB

После

Ширина:  |  Высота:  |  Размер: 4.2 KiB

Просмотреть файл

@ -118,15 +118,20 @@
SimpleTest.isnot(listItem, null, "Valid listItem found");
tagsSelector.ensureElementIsVisible(listItem);
let visibleIndex = tagsSelector.getIndexOfFirstVisibleRow();
let firstVisibleTag = tags[tagsSelector.getIndexOfFirstVisibleRow()];
SimpleTest.ok(listItem.checked, "Item is checked " + i);
let selectedTag = listItem.label;
// Uncheck the tag.
listItem.checked = false;
SimpleTest.is(tagsSelector.getIndexOfFirstVisibleRow(),
Math.max(visibleIndex -1, 0),
// Ensure the first visible tag is still visible in the list.
let firstVisibleIndex = tagsSelector.getIndexOfFirstVisibleRow();
let lastVisibleIndex = firstVisibleIndex + tagsSelector.getNumberOfVisibleRows() -1;
let expectedTagIndex = tags.indexOf(firstVisibleTag);
SimpleTest.ok(expectedTagIndex >= firstVisibleIndex &&
expectedTagIndex <= lastVisibleIndex,
"Scroll position is correct");
// The listbox is rebuilt, so we have to get the new element.

Просмотреть файл

@ -0,0 +1,90 @@
# 'nightly' contains things that are in nightly mozconfigs and allowed to be missing from release builds.
# Other keys in whitelist contain things are in that branches mozconfigs and allowed to be missing from nightly builds.
whitelist = {
'release': {},
'nightly': {},
}
all_platforms = ['win32', 'linux32', 'linux64', 'macosx-universal']
for platform in all_platforms:
whitelist['nightly'][platform] = [
'ac_add_options --enable-update-channel=nightly',
'ac_add_options --enable-profiling',
'mk_add_options CLIENT_PY_ARGS="--hg-options=\'--verbose --time\' --hgtool=../tools/buildfarm/utils/hgtool.py --skip-chatzilla --skip-comm --skip-inspector --skip-venkman --tinderbox-print"'
]
for platform in ['linux32', 'linux64', 'macosx-universal']:
whitelist['nightly'][platform] += [
'ac_add_options --enable-codesighs',
'mk_add_options MOZ_MAKE_FLAGS="-j4"',
]
for platform in ['linux32', 'linux64', 'macosx-universal', 'win32']:
whitelist['nightly'][platform] += ['ac_add_options --enable-signmar']
whitelist['nightly'][platform] += ['ac_add_options --enable-js-diagnostics']
whitelist['nightly']['linux32'] += [
'CXX=$REAL_CXX',
'CXX="ccache $REAL_CXX"',
'CC="ccache $REAL_CC"',
'mk_add_options PROFILE_GEN_SCRIPT=@TOPSRCDIR@/build/profile_pageloader.pl',
'ac_add_options --with-ccache=/usr/bin/ccache',
'export MOZILLA_OFFICIAL=1',
'export MOZ_TELEMETRY_REPORTING=1',
"mk_add_options PROFILE_GEN_SCRIPT='$(PYTHON) @MOZ_OBJDIR@/_profile/pgo/profileserver.py 10'",
'STRIP_FLAGS="--strip-debug"',
'ac_add_options --disable-elf-hack # --enable-elf-hack conflicts with --enable-profiling',
]
whitelist['nightly']['linux64'] += [
'export MOZILLA_OFFICIAL=1',
'export MOZ_TELEMETRY_REPORTING=1',
"mk_add_options PROFILE_GEN_SCRIPT='$(PYTHON) @MOZ_OBJDIR@/_profile/pgo/profileserver.py 10'",
'STRIP_FLAGS="--strip-debug"',
'ac_add_options --with-ccache=/usr/bin/ccache',
'ac_add_options --disable-elf-hack # --enable-elf-hack conflicts with --enable-profiling',
]
whitelist['nightly']['macosx-universal'] += [
'ac_add_options --with-macbundlename-prefix=Firefox',
'mk_add_options MOZ_MAKE_FLAGS="-j12"',
'ac_add_options --with-ccache',
'ac_add_options --disable-install-strip',
'ac_add_options --enable-instruments',
'ac_add_options --enable-dtrace',
]
whitelist['nightly']['win32'] += [
'. $topsrcdir/configs/mozilla2/win32/include/choose-make-flags',
'mk_add_options MOZ_MAKE_FLAGS=-j1',
'if test "$IS_NIGHTLY" != ""; then',
'ac_add_options --disable-auto-deps',
'fi',
'ac_add_options --enable-metro',
]
for platform in all_platforms:
whitelist['release'][platform] = [
'ac_add_options --enable-update-channel=release',
'ac_add_options --enable-official-branding',
'mk_add_options MOZ_MAKE_FLAGS="-j4"',
'export BUILDING_RELEASE=1',
]
whitelist['release']['win32'] += ['mk_add_options MOZ_PGO=1']
whitelist['release']['linux32'] += [
'export MOZILLA_OFFICIAL=1',
'export MOZ_TELEMETRY_REPORTING=1',
'mk_add_options MOZ_PGO=1',
"mk_add_options PROFILE_GEN_SCRIPT='$(PYTHON) @MOZ_OBJDIR@/_profile/pgo/profileserver.py 10'",
]
whitelist['release']['linux64'] += [
'export MOZILLA_OFFICIAL=1',
'export MOZ_TELEMETRY_REPORTING=1',
'mk_add_options MOZ_PGO=1',
"mk_add_options PROFILE_GEN_SCRIPT='$(PYTHON) @MOZ_OBJDIR@/_profile/pgo/profileserver.py 10'",
]
if __name__ == '__main__':
import pprint
pprint.pprint(whitelist)

Просмотреть файл

@ -7,8 +7,6 @@ topsrcdir = @top_srcdir@
srcdir = @srcdir@
VPATH = @srcdir@
include $(topsrcdir)/config/config.mk
include $(topsrcdir)/config/rules.mk
libs::

Просмотреть файл

@ -228,6 +228,12 @@ let StyleSheet = function(form, debuggee) {
this._client.addListener("propertyChange", this._onPropertyChange);
this._client.addListener("styleApplied", this._onStyleApplied);
// Backwards compatibility
this._client.addListener("sourceLoad-" + this._actor, this._onSourceLoad);
this._client.addListener("propertyChange-" + this._actor, this._onPropertyChange);
this._client.addListener("styleApplied-" + this._actor, this._onStyleApplied);
// set initial property values
for (let attr in form) {
this[attr] = form[attr];
@ -324,5 +330,9 @@ StyleSheet.prototype = {
this._client.removeListener("sourceLoad", this._onSourceLoad);
this._client.removeListener("propertyChange", this._onPropertyChange);
this._client.removeListener("styleApplied", this._onStyleApplied);
this._client.removeListener("sourceLoad-" + this._actor, this._onSourceLoad);
this._client.removeListener("propertyChange-" + this._actor, this._onPropertyChange);
this._client.removeListener("styleApplied-" + this._actor, this._onStyleApplied);
}
}

Просмотреть файл

@ -8,7 +8,6 @@ srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
include $(topsrcdir)/config/config.mk
include $(topsrcdir)/config/rules.mk

Просмотреть файл

@ -161,7 +161,7 @@ var ContextCommands = {
openLinkInNewTab: function cc_openLinkInNewTab() {
Browser.addTab(ContextMenuUI.popupState.linkURL, false, Browser.selectedTab);
ContextUI.peekTabs();
ContextUI.peekTabs(kOpenInNewTabAnimationDelayMsec);
},
copyLink: function cc_copyLink() {

Просмотреть файл

@ -10,12 +10,6 @@ const kContextUIDismissEvent = "MozContextUIDismiss";
const kContextUITabsShowEvent = "MozContextUITabsShow";
// add more as needed...
// delay for ContextUI's dismissTabsWithDelay
const kHideContextAndTrayDelayMsec = 3000;
// delay when showing the tab bar briefly as a new tab opens
const kNewTabAnimationDelayMsec = 1000;
/*
* Manages context UI (navbar, tabbar, appbar) and track visibility. Also
* tracks events that summon and hide the context UI.
@ -160,35 +154,24 @@ var ContextUI = {
/*
* Briefly show the tab bar and then hide it. Fires context ui events.
*/
peekTabs: function peekTabs() {
if (this.tabbarVisible) {
setTimeout(function () {
ContextUI.dismissTabsWithDelay(kNewTabAnimationDelayMsec);
}, 0);
} else {
BrowserUI.setOnTabAnimationEnd(function () {
ContextUI.dismissTabsWithDelay(kNewTabAnimationDelayMsec);
});
peekTabs: function peekTabs(aDelay) {
if (!this.tabbarVisible)
this.displayTabs();
}
ContextUI.dismissTabsWithDelay(aDelay);
},
/*
* Dismiss tab bar after a delay. Fires context ui events.
*/
dismissTabsWithDelay: function (aDelay) {
aDelay = aDelay || kHideContextAndTrayDelayMsec;
aDelay = aDelay || kNewTabAnimationDelayMsec;
this._clearDelayedTimeout();
this._hidingId = setTimeout(function () {
ContextUI.dismissTabs();
}, aDelay);
},
// Cancel any pending delayed dismiss
cancelDismiss: function cancelDismiss() {
this._clearDelayedTimeout();
},
// Display the nav bar
displayNavbar: function () {
this._clearDelayedTimeout();
@ -201,12 +184,6 @@ var ContextUI = {
this._setIsExpanded(true);
},
// Display the app bar
displayContextAppbar: function () {
this._clearDelayedTimeout();
Elements.contextappbar.show();
},
// Dismiss the navbar if visible.
dismissNavbar: function dismissNavbar() {
Elements.navbar.dismiss();
@ -312,15 +289,9 @@ var ContextUI = {
if (aEvent.button == 0 && this.isVisible)
this.dismiss();
break;
case 'URLChanged':
this.dismissTabs();
break;
case 'TabSelect':
this.dismissTabs();
break;
case 'ToolPanelShown':
case 'ToolPanelHidden':
case "ToolPanelShown":
case "ToolPanelHidden":
case "touchstart":
case "AlertActive":
this.dismiss();

Просмотреть файл

@ -84,8 +84,10 @@ const WebProgress = {
let spec = aJson.location;
let location = spec.split("#")[0]; // Ignore fragment identifier changes.
if (aTab == Browser.selectedTab)
if (aTab == Browser.selectedTab) {
BrowserUI.updateURI();
BrowserUI.update();
}
let locationHasChanged = (location != aTab.browser.lastLocation);
if (locationHasChanged) {
@ -123,22 +125,15 @@ const WebProgress = {
_networkStart: function _networkStart(aJson, aTab) {
aTab.startLoading();
if (aTab == Browser.selectedTab) {
if (aTab == Browser.selectedTab)
BrowserUI.update(TOOLBARSTATE_LOADING);
// We should at least show something in the URLBar until
// the load has progressed further along
if (aTab.browser.currentURI.spec == "about:blank")
BrowserUI.updateURI({ captionOnly: true });
}
},
_networkStop: function _networkStop(aJson, aTab) {
aTab.endLoading();
if (aTab == Browser.selectedTab) {
if (aTab == Browser.selectedTab)
BrowserUI.update(TOOLBARSTATE_LOADED);
}
},
_windowStart: function _windowStart(aJson, aTab) {
@ -162,7 +157,7 @@ const WebProgress = {
// 'Whoosh' in
this._progressCount = kProgressMarginStart;
Elements.progress.style.width = this._progressCount + "%";
Elements.progress.style.width = this._progressCount + "%";
Elements.progress.removeAttribute("fade");
// Create a pulse timer to keep things moving even if we don't
@ -204,7 +199,7 @@ const WebProgress = {
_progressStop: function _progressStop(aJson, aTab) {
this._progressActive = false;
// 'Whoosh out' and fade
Elements.progress.style.width = "100%";
Elements.progress.style.width = "100%";
Elements.progress.setAttribute("fade", true);
},
@ -213,7 +208,7 @@ const WebProgress = {
return;
// Close out fade finished, reset
if (data.propertyName == "opacity") {
Elements.progress.style.width = "0px";
Elements.progress.style.width = "0px";
Elements.progressContainer.setAttribute("collapsed", true);
}
},

Просмотреть файл

@ -115,7 +115,7 @@ var Appbar = {
}
var x = this.menuButton.getBoundingClientRect().left;
var y = Elements.navbar.getBoundingClientRect().top;
var y = Elements.toolbar.getBoundingClientRect().top;
ContextMenuUI.showContextMenu({
json: {
types: typesArray,

Просмотреть файл

@ -1,473 +0,0 @@
<?xml version="1.0" encoding="Windows-1252" ?>
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
<!DOCTYPE bindings [
<!ENTITY % browserDTD SYSTEM "chrome://browser/locale/browser.dtd">
%browserDTD;
]>
<bindings
xmlns="http://www.mozilla.org/xbl"
xmlns:xbl="http://www.mozilla.org/xbl"
xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<binding id="autocomplete" extends="chrome://global/content/bindings/autocomplete.xml#autocomplete">
<implementation>
<constructor>
<![CDATA[
this.minResultsForPopup = 0;
this.popup._input = this;
]]>
</constructor>
<method name="openPopup">
<body>
<![CDATA[
this.popup.openAutocompletePopup(this, null);
]]>
</body>
</method>
<method name="closePopup">
<body>
<![CDATA[
this.popup.closePopup(this, null);
]]>
</body>
</method>
<method name="formatValue">
<body>
<![CDATA[
BrowserUI.formatURI();
]]>
</body>
</method>
<method name="trimValue">
<parameter name="aURL"/>
<body><![CDATA[
return BrowserUI.trimURL(aURL);
]]></body>
</method>
</implementation>
<handlers>
<handler event="click" phase="capturing">
<![CDATA[
// If the urlbar is not already focused, focus it and select the contents.
if (Elements.urlbarState.getAttribute("mode") != "edit") {
BrowserUI._editURI(true);
}
]]>
</handler>
<handler event="dblclick" phase="capturing">
<![CDATA[
let selectAll = Services.prefs.getBoolPref("browser.urlbar.doubleClickSelectsAll");
if (selectAll)
this.select();
]]>
</handler>
<handler event="contextmenu" phase="capturing">
<![CDATA[
let box = this.inputField.parentNode;
box.showContextMenu(this, event, true);
]]>
</handler>
<handler event="keypress" phase="capturing" keycode="VK_RETURN">
<![CDATA[
event.preventDefault();
event.stopPropagation();
this.popup.handleCompletion();
]]>
</handler>
</handlers>
</binding>
<binding id="autocomplete-popup">
<content orient="horizontal">
<xul:vbox id="results-vbox" class="meta-section viewable-height" flex="1">
<xul:label class="meta-section-title" value="&autocompleteResultsHeader.label;"/>
<richgrid id="results-richgrid" deferlayout="true" anonid="results" seltype="single" flex="1"/>
</xul:vbox>
<xul:vbox id="searches-vbox" class="meta-section viewable-height" flex="1">
<xul:label class="meta-section-title" value="&autocompleteSearchesHeader.label;"/>
<richgrid id="searches-richgrid" deferlayout="true" anonid="searches" seltype="single" flex="1"/>
</xul:vbox>
</content>
<implementation implements="nsIAutoCompletePopup, nsIObserver">
<constructor>
<![CDATA[
Services.obs.addObserver(this, "browser-search-engine-modified", false);
this.updateSearchEngines();
this._results.controller = this;
this._searches.controller = this;
]]>
</constructor>
<destructor>
<![CDATA[
Services.obs.removeObserver(this, "browser-search-engine-modified");
]]>
</destructor>
<method name="handleItemClick">
<parameter name="aItem"/>
<body>
<![CDATA[
if (aItem.control == this._searches) {
let engineName = aItem.getAttribute("value");
BrowserUI.doOpenSearch(engineName);
} else {
let url = aItem.getAttribute("value");
Browser.loadURI(url);
}
]]>
</body>
</method>
<!-- nsIAutocompleteInput -->
<field name="_input">null</field>
<field name="_popupOpen">false</field>
<property name="overrideValue" readonly="true" onget="return null;"/>
<property name="selectedItem">
<getter>
<![CDATA[
return this._isGridBound(this._results) ? this._results.selectedItem : null;
]]>
</getter>
<setter>
<![CDATA[
return this._isGridBound(this._results) ? this._results.selectedItem : null;
]]>
</setter>
</property>
<property name="selectedIndex">
<getter>
<![CDATA[
return this._isGridBound(this._results) ? this._results.selectedIndex : -1;
]]>
</getter>
<setter>
<![CDATA[
return this._isGridBound(this._results) ? this._results.selectedIndex : -1;
]]>
</setter>
</property>
<property name="input" readonly="true" onget="return this._input;"/>
<property name="popupOpen" readonly="true" onget="return this._popupOpen;"/>
<property name="_matchCount" readonly="true" onget="return this.input.controller.matchCount;"/>
<method name="openAutocompletePopup">
<parameter name="aInput"/>
<parameter name="aElement"/>
<body>
<![CDATA[
if (this._popupOpen)
return;
ContextUI.dismissContextAppbar();
this._input = aInput;
this._popupOpen = true;
this._grid = this._results;
this.clearSelection();
this.invalidate();
this._results.arrangeItemsNow();
this._searches.arrangeItemsNow();
this._fire("autocompletestart");
]]>
</body>
</method>
<method name="gridBoundCallback">
<body>
<![CDATA[
this.updateResults();
]]>
</body>
</method>
<method name="closePopup">
<body>
<![CDATA[
if (!this._popupOpen)
return;
this.input.controller.stopSearch();
this._popupOpen = false;
this._fire("autocompleteend");
]]>
</body>
</method>
<method name="invalidate">
<body>
<![CDATA[
if (!this._popupOpen)
return;
this.updateResults();
this.updateSearchEngineSubtitles();
]]>
</body>
</method>
<method name="selectBy">
<parameter name="aReverse"/>
<parameter name="aPage"/>
<body>
<![CDATA[
let handleOnSelect = this._handleOnSelect;
this._handleOnSelect = false;
// TODO <jwilde>: Pressing page up/down should jump between rows,
// not just items in the grid
// Move between grids if we're at the edge of one
if ((this._grid.isSelectionAtEnd && !aReverse) ||
(this._grid.isSelectionAtStart && aReverse)) {
let index = aReverse ? this._otherGrid.itemCount - 1 : 0;
this._otherGrid.selectedIndex = index;
} else {
this._grid.offsetSelection(aReverse ? -1 : 1);
}
this._handleOnSelect = handleOnSelect;
]]>
</body>
</method>
<!-- nsIObserver -->
<method name="observe">
<parameter name="aSubject"/>
<parameter name="aTopic"/>
<parameter name="aData"/>
<body>
<![CDATA[
if (aTopic != "browser-search-engine-modified")
return;
switch (aData) {
case "engine-added":
case "engine-removed":
case "engine-changed":
this.updateSearchEngines();
break;
case "engine-current":
// Not relevant
break;
}
]]>
</body>
</method>
<!-- Interface for updating various components of the popup. -->
<method name="updateResults">
<body>
<![CDATA[
if (!this._isGridBound(this._results))
return;
if (!this.input)
return;
let controller = this.input.controller;
let lastMatch = this._matchCount - 1;
let iterCount = Math.max(this._results.itemCount, this._matchCount);
// Swap out existing items for new search hit results
for (let i = 0; i < iterCount; i++) {
if (i > lastMatch) {
let lastItem = this._results.itemCount - 1;
this._results.removeItemAt(lastItem, true);
continue;
}
let value = controller.getValueAt(i);
let label = controller.getCommentAt(i) || value;
let iconURI = controller.getImageAt(i);
let item = this._results.getItemAtIndex(i);
if (item == null) {
item = this._results.appendItem(label, value, true);
item.setAttribute("autocomplete", "true");
} else {
item.setAttribute("label", label);
item.setAttribute("value", value);
}
item.setAttribute("iconURI", iconURI);
}
this._results.arrangeItems();
]]>
</body>
</method>
<method name="updateSearchEngines">
<body><![CDATA[
Services.search.init(this._onSearchServiceInit.bind(this));
]]></body>
</method>
<method name="_onSearchServiceInit">
<body>
<![CDATA[
if (!this._isGridBound(this._searches))
return;
this._engines = Services.search.getVisibleEngines();
while (this._searches.itemCount > 0)
this._searches.removeItemAt(0, true);
this._engines.forEach(function (anEngine) {
let item = this._searches.appendItem(anEngine.name, anEngine.name, true);
item.setAttribute("autocomplete", "true");
item.setAttribute("search", "true");
let iconURI = anEngine.iconURI ? anEngine.iconURI.spec : "";
item.setAttribute("iconURI", iconURI);
}.bind(this));
this._searches.arrangeItems();
]]>
</body>
</method>
<method name="updateSearchEngineSubtitles">
<body>
<![CDATA[
if (!this._isGridBound(this._searches))
return;
let searchString = this.input.controller.searchString;
let label = Strings.browser.formatStringFromName("opensearch.search", [searchString], 1);
for (let i = 0, len = this._searches.itemCount; i < len; i++) {
let item = this._searches.getItemAtIndex(i);
item.setAttribute("label", label);
item.refresh && item.refresh();
}
]]>
</body>
</method>
<!-- Interface for handling actions across grids -->
<method name="handleCompletion">
<body>
<![CDATA[
if (this._grid == this._results) {
this.input.controller.handleEnter(false);
return;
}
if (this._grid == this._searches) {
let engine = this._engines[this._grid.selectedIndex];
BrowserUI.doOpenSearch(engine.name);
this.closePopup();
return;
}
]]>
</body>
</method>
<method name="clearSelection">
<body>
<![CDATA[
if (this._isGridBound(this._results))
this._results.clearSelection();
if (this._isGridBound(this._searches))
this._searches.clearSelection();
]]>
</body>
</method>
<!-- Helpers -->
<field name="_engines">[]</field>
<field name="_handleOnSelect">true</field>
<field name="_grid">null</field>
<property name="_results" readonly="true" onget="return document.getAnonymousElementByAttribute(this, 'anonid', 'results');"/>
<property name="_searches" readonly="true" onget="return document.getAnonymousElementByAttribute(this, 'anonid', 'searches');"/>
<property name="_otherGrid" readonly="true">
<getter>
<![CDATA[
return (this._grid == this._results) ? this._searches : this._results;
]]>
</getter>
</property>
<method name="_isGridBound">
<parameter name="aGrid"/>
<body>
<![CDATA[
return aGrid && aGrid.itemCount != undefined;
]]>
</body>
</method>
<method name="_fire">
<parameter name="aName"/>
<body>
<![CDATA[
let event = document.createEvent("Events");
event.initEvent(aName, true, false);
this.dispatchEvent(event);
]]>
</body>
</method>
</implementation>
<handlers>
<handler event="select">
<![CDATA[
let grid = event.originalTarget;
if (grid != this._grid) {
if (this._grid.clearSelection)
this._grid.clearSelection();
this._grid = grid;
}
if (this._handleOnSelect && this._results.selectedItem) {
BrowserUI.goToURI(
this._results.selectedItem.getAttribute("value"));
this.closePopup();
} else if (this._handleOnSelect) {
this.handleCompletion();
}
]]>
</handler>
<handler event="contentgenerated">
<![CDATA[
let grid = event.originalTarget;
if (grid == this._searches)
this.updateSearchEngines();
]]>
</handler>
</handlers>
</binding>
</bindings>

Просмотреть файл

@ -86,12 +86,20 @@
<method name="handleItemClick">
<parameter name="aItem"/>
<parameter name="aEvent"/>
<body>
<![CDATA[
if(!this.isBound)
return;
if (this.controller)
this.controller.handleItemClick(aItem);
if ("single" == this.getAttribute("seltype")) {
// we'll republish this as a selectionchange event on the grid
aEvent.stopPropagation();
this.selectItem(aItem);
}
if (this.controller && this.controller.handleItemClick)
this.controller.handleItemClick(aItem, aEvent);
]]>
</body>
</method>

Просмотреть файл

@ -0,0 +1,838 @@
<?xml version="1.0" encoding="Windows-1252" ?>
<!-- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at http://mozilla.org/MPL/2.0/. -->
<!DOCTYPE bindings [
<!ENTITY % browserDTD SYSTEM "chrome://browser/locale/browser.dtd">
%browserDTD;
]>
<bindings
xmlns="http://www.mozilla.org/xbl"
xmlns:xbl="http://www.mozilla.org/xbl"
xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<binding id="urlbar" extends="chrome://global/content/bindings/autocomplete.xml#autocomplete">
<implementation implements="nsIObserver">
<constructor>
<![CDATA[
this._mayFormat = Services.prefs.getBoolPref("browser.urlbar.formatting.enabled");
this._mayTrimURLs = Services.prefs.getBoolPref("browser.urlbar.trimURLs");
this._maySelectAll = Services.prefs.getBoolPref("browser.urlbar.doubleClickSelectsAll");
Services.prefs.addObserver("browser.urlbar.formatting.enabled", this, false);
Services.prefs.addObserver("browser.urlbar.trimURLs", this, false);
Services.prefs.addObserver("browser.urlbar.doubleClickSelectsAll", this, false);
this.inputField.controllers.insertControllerAt(0, this._copyCutValueController);
this.minResultsForPopup = 0;
this.popup._input = this;
]]>
</constructor>
<destructor>
<![CDATA[
Services.prefs.removeObserver("browser.urlbar.formatting.enabled", this);
Services.prefs.removeObserver("browser.urlbar.trimURLs", this);
Services.prefs.removeObserver("browser.urlbar.doubleClickSelectsAll", this);
]]>
</destructor>
<field name="_mayFormat"/>
<field name="_mayTrimURLs"/>
<field name="_maySelectAll"/>
<field name="_lastKnownGoodURL"/>
<method name="openPopup">
<body>
<![CDATA[
this.popup.openAutocompletePopup(this, null);
]]>
</body>
</method>
<method name="closePopup">
<body>
<![CDATA[
this.popup.closePopup(this, null);
]]>
</body>
</method>
<!-- URI Display: Domain Highlighting -->
<method name="_clearFormatting">
<body>
<![CDATA[
if (!this._mayFormat)
return;
let controller = this.editor.selectionController;
let selection = controller.getSelection(controller.SELECTION_URLSECONDARY);
selection.removeAllRanges();
]]>
</body>
</method>
<method name="formatValue">
<body>
<![CDATA[
if (!this._mayFormat || this.isEditing)
return;
let controller = this.editor.selectionController;
let selection = controller.getSelection(controller.SELECTION_URLSECONDARY);
selection.removeAllRanges();
let textNode = this.editor.rootElement.firstChild;
let value = textNode.textContent;
let protocol = value.match(/^[a-z\d.+\-]+:(?=[^\d])/);
if (protocol &&
["http:", "https:", "ftp:"].indexOf(protocol[0]) == -1)
return;
let matchedURL = value.match(/^((?:[a-z]+:\/\/)?(?:[^\/]+@)?)(.+?)(?::\d+)?(?:\/|$)/);
if (!matchedURL)
return;
let [, preDomain, domain] = matchedURL;
let baseDomain = domain;
let subDomain = "";
// getBaseDomainFromHost doesn't recognize IPv6 literals in brackets as IPs (bug 667159)
if (domain[0] != "[") {
try {
baseDomain = Services.eTLD.getBaseDomainFromHost(domain);
if (!domain.endsWith(baseDomain)) {
// getBaseDomainFromHost converts its resultant to ACE.
let IDNService = Cc["@mozilla.org/network/idn-service;1"]
.getService(Ci.nsIIDNService);
baseDomain = IDNService.convertACEtoUTF8(baseDomain);
}
} catch (e) {}
}
if (baseDomain != domain) {
subDomain = domain.slice(0, -baseDomain.length);
}
let rangeLength = preDomain.length + subDomain.length;
if (rangeLength) {
let range = document.createRange();
range.setStart(textNode, 0);
range.setEnd(textNode, rangeLength);
selection.addRange(range);
}
let startRest = preDomain.length + domain.length;
if (startRest < value.length) {
let range = document.createRange();
range.setStart(textNode, startRest);
range.setEnd(textNode, value.length);
selection.addRange(range);
}
]]>
</body>
</method>
<!-- URI Display: Scheme and Trailing Slash Triming -->
<method name="_trimURL">
<parameter name="aURL"/>
<body>
<![CDATA[
// This function must not modify the given URL such that calling
// nsIURIFixup::createFixupURI with the rfdesult will produce a different URI.
return aURL /* remove single trailing slash for http/https/ftp URLs */
.replace(/^((?:http|https|ftp):\/\/[^/]+)\/$/, "$1")
/* remove http:// unless the host starts with "ftp\d*\." or contains "@" */
.replace(/^http:\/\/((?!ftp\d*\.)[^\/@]+(?:\/|$))/, "$1");
]]>
</body>
</method>
<method name="_getSelectedValueForClipboard">
<body>
<![CDATA[
// Grab the actual input field's value, not our value, which could include moz-action:
let inputVal = this.inputField.value;
let selectedVal = inputVal.substring(this.selectionStart, this.electionEnd);
// If the selection doesn't start at the beginning or doesn't span the full domain or
// the URL bar is modified, nothing else to do here.
if (this.selectionStart > 0 || this.valueIsTyped)
return selectedVal;
// The selection doesn't span the full domain if it doesn't contain a slash and is
// followed by some character other than a slash.
if (!selectedVal.contains("/")) {
let remainder = inputVal.replace(selectedVal, "");
if (remainder != "" && remainder[0] != "/")
return selectedVal;
}
let uriFixup = Cc["@mozilla.org/docshell/urifixup;1"].getService(Ci.nsIURIFixup);
let uri;
try {
uri = uriFixup.createFixupURI(inputVal, Ci.nsIURIFixup.FIXUP_FLAG_USE_UTF8);
} catch (e) {}
if (!uri)
return selectedVal;
// Only copy exposable URIs
try {
uri = uriFixup.createExposableURI(uri);
} catch (ex) {}
// If the entire URL is selected, just use the actual loaded URI.
if (inputVal == selectedVal) {
// ... but only if isn't a javascript: or data: URI, since those
// are hard to read when encoded
if (!uri.schemeIs("javascript") && !uri.schemeIs("data")) {
// Parentheses are known to confuse third-party applications (bug 458565).
selectedVal = uri.spec.replace(/[()]/g, function (c) escape(c));
}
return selectedVal;
}
// Just the beginning of the URL is selected, check for a trimmed value
let spec = uri.spec;
let trimmedSpec = this._trimURL(spec);
if (spec != trimmedSpec) {
// Prepend the portion that trimURL removed from the beginning.
// This assumes trimURL will only truncate the URL at
// the beginning or end (or both).
let trimmedSegments = spec.split(trimmedSpec);
selectedVal = trimmedSegments[0] + selectedVal;
}
return selectedVal;
]]>
</body>
</method>
<field name="_copyCutValueController">
<![CDATA[
({
urlbar: this,
doCommand: function(aCommand) {
let urlbar = this.urlbar;
let val = urlbar._getSelectedValueForClipboard();
if (!val)
return;
if (aCommand == "cmd_cut" && this.isCommandEnabled(aCommand)) {
let start = urlbar.selectionStart;
let end = urlbar.selectionEnd;
urlbar.inputField.value = urlbar.inputField.value.substring(0, start) +
urlbar.inputField.value.substring(end);
urlbar.selectionStart = urlbar.selectionEnd = start;
}
Cc["@mozilla.org/widget/clipboardhelper;1"]
.getService(Ci.nsIClipboardHelper)
.copyString(val, document);
},
supportsCommand: function(aCommand) {
switch (aCommand) {
case "cmd_copy":
case "cmd_cut":
return true;
}
return false;
},
isCommandEnabled: function(aCommand) {
let urlbar = this.urlbar;
return this.supportsCommand(aCommand) &&
(aCommand != "cmd_cut" || !urlbar.readOnly) &&
urlbar.selectionStart < urlbar.selectionEnd;
},
onEvent: function(aEventName) {}
})
]]>
</field>
<method name="trimValue">
<parameter name="aURL"/>
<body>
<![CDATA[
return (this._mayTrimURLs) ? this._trimURL(aURL) : aURL;
]]>
</body>
</method>
<!-- URI Editing -->
<property name="isEditing" readonly="true">
<getter>
<![CDATA[
return Elements.urlbarState.getAttribute("mode") == "edit";
]]>
</getter>
</property>
<method name="beginEditing">
<parameter name="aShouldDismiss"/>
<body>
<![CDATA[
if (this.isEditing)
return;
Elements.urlbarState.setAttribute("mode", "edit");
this._lastKnownGoodURL = this.value;
if (!this.focused)
this.focus();
this._clearFormatting();
this.select();
if (aShouldDismiss)
ContextUI.dismissTabs();
]]>
</body>
</method>
<method name="endEditing">
<parameter name="aShouldRevert"/>
<body>
<![CDATA[
if (!this.isEditing)
return;
Elements.urlbarState.setAttribute("mode", "view");
this.closePopup();
this.formatValue();
if (this.focused)
this.blur();
if (aShouldRevert)
this.value = this._lastKnownGoodURL;
]]>
</body>
</method>
<!-- URI Submission -->
<method name="_canonizeURL">
<parameter name="aURL"/>
<parameter name="aTriggeringEvent"/>
<body>
<![CDATA[
if (!aURL)
return "";
// Only add the suffix when the URL bar value isn't already "URL-like",
// and only if we get a keyboard event, to match user expectations.
if (/^\s*[^.:\/\s]+(?:\/.*|\s*)$/i.test(aURL)) {
let accel = aTriggeringEvent.ctrlKey;
let shift = aTriggeringEvent.shiftKey;
let suffix = "";
switch (true) {
case (accel && shift):
suffix = ".org/";
break;
case (shift):
suffix = ".net/";
break;
case (accel):
try {
suffix = gPrefService.getCharPref("browser.fixup.alternate.suffix");
if (suffix.charAt(suffix.length - 1) != "/")
suffix += "/";
} catch(e) {
suffix = ".com/";
}
break;
}
if (suffix) {
// trim leading/trailing spaces (bug 233205)
aURL = aURL.trim();
// Tack www. and suffix on. If user has appended directories, insert
// suffix before them (bug 279035). Be careful not to get two slashes.
let firstSlash = aURL.indexOf("/");
if (firstSlash >= 0) {
aURL = aURL.substring(0, firstSlash) + suffix + aURL.substring(firstSlash + 1);
} else {
aURL = aURL + suffix;
}
aURL = "http://www." + aURL;
}
}
return aURL;
]]>
</body>
</method>
<method name="submitURL">
<parameter name="aEvent"/>
<body>
<![CDATA[
// If the address was typed in by a user, tidy it up
if (aEvent instanceof KeyEvent)
this.value = this._canonizeURL(this.value, aEvent);
this.endEditing();
BrowserUI.goToURI(this.value);
return true;
]]>
</body>
</method>
<method name="submitSearch">
<parameter name="anEngineName"/>
<body>
<![CDATA[
this.endEditing();
BrowserUI.doOpenSearch(anEngineName);
return true;
]]>
</body>
</method>
<!-- nsIObserver -->
<method name="observe">
<parameter name="aSubject"/>
<parameter name="aTopic"/>
<parameter name="aData"/>
<body>
<![CDATA[
if (aTopic != "nsPref:changed")
return;
switch (aData) {
case "browser.urlbar.formatting.enabled":
this._mayFormat = Services.prefs.getBoolPref(aData);
break;
case "browser.urlbar.trimURLs":
this._mayTrimURLs = Services.prefs.getBoolPref(aData);
break;
case "browser.urlbar.doubleClickSelectsAll":
this._maySelectAll = Services.prefs.getBoolPref(aData);
break;
}
]]>
</body>
</method>
</implementation>
<handlers>
<!-- Entering editing mode -->
<handler event="input" phase="capturing">
<![CDATA[
// Ensures that paste-and-go actually brings the URL bar into editing mode
// and displays the half-height autocomplete popup.
this.beginEditing();
this.openPopup();
]]>
</handler>
<handler event="click" phase="capturing">
<![CDATA[
this.beginEditing(true);
]]>
</handler>
<!-- Editing mode behaviors -->
<handler event="dblclick" phase="capturing">
<![CDATA[
if (this._maySelectAll) this.select();
]]>
</handler>
<handler event="contextmenu" phase="capturing">
<![CDATA[
let box = this.inputField.parentNode;
box.showContextMenu(this, event, true);
]]>
</handler>
<!-- Leaving editing mode -->
<handler event="blur" phase="capturing">
<![CDATA[
this.endEditing();
]]>
</handler>
<handler event="keypress" phase="capturing" keycode="VK_RETURN">
<![CDATA[
if (this.popup.submitSelected())
return;
if (this.submitURL(event))
return;
]]>
</handler>
</handlers>
</binding>
<binding id="urlbar-autocomplete">
<content orient="horizontal">
<xul:vbox id="results-vbox" flex="1">
<xul:label class="meta-section-title" value="&autocompleteResultsHeader.label;"/>
<richgrid id="results-richgrid" rows="3" deferlayout="true" anonid="results" seltype="single" flex="1"/>
</xul:vbox>
<xul:vbox id="searches-vbox" flex="1">
<xul:label class="meta-section-title" value="&autocompleteSearchesHeader.label;"/>
<richgrid id="searches-richgrid" rows="3" deferlayout="true" anonid="searches" seltype="single" flex="1"/>
</xul:vbox>
</content>
<implementation implements="nsIAutoCompletePopup, nsIObserver">
<constructor>
<![CDATA[
this.hidden = true;
Services.obs.addObserver(this, "browser-search-engine-modified", false);
this._results.controller = this;
this._searches.controller = this;
]]>
</constructor>
<destructor>
<![CDATA[
Services.obs.removeObserver(this, "browser-search-engine-modified");
]]>
</destructor>
<!-- nsIAutocompleteInput -->
<field name="_input">null</field>
<property name="input" readonly="true" onget="return this._input;"/>
<property name="matchCount" readonly="true" onget="return this.input.controller.matchCount;"/>
<property name="popupOpen" readonly="true" onget="return !this.hidden"/>
<property name="overrideValue" readonly="true" onget="return null;"/>
<property name="selectedItem">
<getter>
<![CDATA[
return this._isGridBound(this._results) ? this._results.selectedItem : null;
]]>
</getter>
<setter>
<![CDATA[
return this._isGridBound(this._results) ? this._results.selectedItem : null;
]]>
</setter>
</property>
<property name="selectedIndex">
<getter>
<![CDATA[
return this._isGridBound(this._results) ? this._results.selectedIndex : -1;
]]>
</getter>
<setter>
<![CDATA[
return this._isGridBound(this._results) ? this._results.selectedIndex : -1;
]]>
</setter>
</property>
<method name="openAutocompletePopup">
<parameter name="aInput"/>
<parameter name="aElement"/>
<body>
<![CDATA[
if (this.popupOpen)
return;
ContextUI.dismissContextAppbar();
this._input = aInput;
this._grid = this._results;
this.clearSelection();
this.invalidate();
this._results.arrangeItemsNow();
this._searches.arrangeItemsNow();
this.hidden = false;
]]>
</body>
</method>
<method name="closePopup">
<body>
<![CDATA[
if (!this.popupOpen)
return;
this.input.controller.stopSearch();
this.hidden = true;
]]>
</body>
</method>
<!-- Updating grid content -->
<field name="_grid">null</field>
<field name="_results" readonly="true">document.getAnonymousElementByAttribute(this, 'anonid', 'results');</field>
<field name="_searches" readonly="true">document.getAnonymousElementByAttribute(this, 'anonid', 'searches');</field>
<property name="_otherGrid" readonly="true">
<getter>
<![CDATA[
if (this._grid == null)
return null;
return (this._grid == this._results) ? this._searches : this._results;
]]>
</getter>
</property>
<method name="_isGridBound">
<parameter name="aGrid"/>
<body>
<![CDATA[
return aGrid && aGrid.isBound;
]]>
</body>
</method>
<method name="invalidate">
<body>
<![CDATA[
if (!this.popupOpen)
return;
this.updateResults();
this.updateSearchEngineSubtitles();
]]>
</body>
</method>
<!-- Updating grid content: results -->
<method name="updateResults">
<body>
<![CDATA[
if (!this._isGridBound(this._results))
return;
if (!this.input)
return;
let controller = this.input.controller;
let lastMatch = this.matchCount - 1;
let iterCount = Math.max(this._results.itemCount, this.matchCount);
// Swap out existing items for new search hit results
for (let i = 0; i < iterCount; i++) {
if (i > lastMatch) {
let lastItem = this._results.itemCount - 1;
this._results.removeItemAt(lastItem, true);
continue;
}
let value = controller.getValueAt(i);
let label = controller.getCommentAt(i) || value;
let iconURI = controller.getImageAt(i);
let item = this._results.getItemAtIndex(i);
if (item == null) {
item = this._results.appendItem(label, value, true);
item.setAttribute("autocomplete", "true");
} else {
item.setAttribute("label", label);
item.setAttribute("value", value);
}
item.setAttribute("iconURI", iconURI);
}
this._results.arrangeItems();
]]>
</body>
</method>
<!-- Updating grid content: search engines -->
<field name="_engines">[]</field>
<method name="_initSearchEngines">
<body>
<![CDATA[
Services.search.init(this.updateSearchEngineGrid.bind(this));
]]>
</body>
</method>
<method name="updateSearchEngineGrid">
<body>
<![CDATA[
if (!this._isGridBound(this._searches))
return;
this._engines = Services.search.getVisibleEngines();
while (this._searches.itemCount > 0)
this._searches.removeItemAt(0, true);
this._engines.forEach(function (anEngine) {
let item = this._searches.appendItem(anEngine.name, anEngine.name, true);
item.setAttribute("autocomplete", "true");
item.setAttribute("search", "true");
let iconURI = anEngine.iconURI ? anEngine.iconURI.spec : "";
item.setAttribute("iconURI", iconURI);
}.bind(this));
this._searches.arrangeItems();
]]>
</body>
</method>
<method name="updateSearchEngineSubtitles">
<body>
<![CDATA[
if (!this._isGridBound(this._searches))
return;
let searchString = this.input.controller.searchString;
let label = Strings.browser.formatStringFromName("opensearch.search", [searchString], 1);
for (let i = 0, len = this._searches.itemCount; i < len; i++) {
let item = this._searches.getItemAtIndex(i);
item.setAttribute("label", label);
item.refresh && item.refresh();
}
]]>
</body>
</method>
<!-- Selecting results -->
<method name="selectBy">
<parameter name="aReverse"/>
<parameter name="aPage"/>
<body>
<![CDATA[
if (!this._isGridBound(this._results) ||
!this._isGridBound(this._searches))
return;
// Move between grids if we're at the edge of one.
if ((this._grid.isSelectionAtEnd && !aReverse) ||
(this._grid.isSelectionAtStart && aReverse)) {
let index = !aReverse ? 0 : this._otherGrid.itemCount - 1;
this._otherGrid.selectedIndex = index;
} else {
this._grid.offsetSelection(aReverse ? -1 : 1);
}
]]>
</body>
</method>
<method name="clearSelection">
<body>
<![CDATA[
if (this._isGridBound(this._results))
this._results.clearSelection();
if (this._isGridBound(this._searches))
this._searches.clearSelection();
]]>
</body>
</method>
<!-- Submitting selected results -->
<method name="submitSelected">
<body>
<![CDATA[
if (this._isGridBound(this._results) &&
this._results.selectedIndex >= 0) {
let url = this.input.controller.getValueAt(this._results.selectedIndex);
this.input.value = url;
return this.input.submitURL();
}
if (this._isGridBound(this._searches) &&
this._searches.selectedIndex >= 0) {
let engine = this._engines[this._searches.selectedIndex];
return this.input.submitSearch(engine.name);
}
return false;
]]>
</body>
</method>
<method name="handleItemClick">
<parameter name="aItem"/>
<parameter name="aEvent"/>
<body>
<![CDATA[
this.submitSelected();
]]>
</body>
</method>
<!-- nsIObserver -->
<method name="observe">
<parameter name="aSubject"/>
<parameter name="aTopic"/>
<parameter name="aData"/>
<body>
<![CDATA[
switch (aTopic) {
case "browser-search-engine-modified":
this.updateSearchEngineGrid();
break;
}
]]>
</body>
</method>
</implementation>
<handlers>
<handler event="contentgenerated">
<![CDATA[
let grid = event.originalTarget;
if (grid == this._searches)
this._initSearchEngines();
if (grid == this._results)
this.updateResults();
]]>
</handler>
<handler event="select">
<![CDATA[
let grid = event.originalTarget;
// If a selection was made on a different grid,
// remove selection from the current grid.
if (grid != this._grid) {
this._grid.clearSelection();
this._grid = this._otherGrid;
}
]]>
</handler>
</handlers>
</binding>
</bindings>

Просмотреть файл

@ -2,6 +2,7 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
Cu.import("resource://gre/modules/PageThumbs.jsm");
Cu.import("resource://gre/modules/devtools/dbg-server.jsm")
@ -22,6 +23,13 @@ const kStartOverlayURI = "about:start";
const debugServerStateChanged = "devtools.debugger.remote-enabled";
const debugServerPortChanged = "devtools.debugger.remote-port";
// delay when showing the tab bar briefly after a new (empty) tab opens
const kNewTabAnimationDelayMsec = 1000;
// delay when showing the tab bar after opening a link on a new tab
const kOpenInNewTabAnimationDelayMsec = 3000;
// delay before closing tab bar after selecting another tab
const kSelectTabAnimationDelayMsec = 500;
/**
* Cache of commonly used elements.
*/
@ -74,9 +82,10 @@ var BrowserUI = {
get _back() { return document.getElementById("cmd_back"); },
get _forward() { return document.getElementById("cmd_forward"); },
lastKnownGoodURL: "", //used when the user wants to escape unfinished url entry
init: function() {
lastKnownGoodURL: "", // used when the user wants to escape unfinished url entry
ready: false, // used for tests to determine when delayed initialization is done
init: function() {
// start the debugger now so we can use it on the startup code as well
if (Services.prefs.getBoolPref(debugServerStateChanged)) {
this.runDebugServer();
@ -100,11 +109,7 @@ var BrowserUI = {
window.addEventListener("MozImprecisePointer", this, true);
Services.prefs.addObserver("browser.cache.disk_cache_ssl", this, false);
Services.prefs.addObserver("browser.urlbar.formatting.enabled", this, false);
Services.prefs.addObserver("browser.urlbar.trimURLs", this, false);
Services.obs.addObserver(this, "metro_viewstate_changed", false);
this._edit.inputField.controllers.insertControllerAt(0, this._copyCutURIController);
// Init core UI modules
ContextUI.init();
@ -120,16 +125,17 @@ var BrowserUI = {
// We can delay some initialization until after startup. We wait until
// the first page is shown, then dispatch a UIReadyDelayed event.
messageManager.addMessageListener("pageshow", function() {
messageManager.addMessageListener("pageshow", function onPageShow() {
if (getBrowser().currentURI.spec == "about:blank")
return;
messageManager.removeMessageListener("pageshow", arguments.callee, true);
messageManager.removeMessageListener("pageshow", onPageShow);
setTimeout(function() {
let event = document.createEvent("Events");
event.initEvent("UIReadyDelayed", true, false);
window.dispatchEvent(event);
BrowserUI.ready = true;
}, 0);
});
@ -139,9 +145,9 @@ var BrowserUI = {
});
// Delay the panel UI and Sync initialization
window.addEventListener("UIReadyDelayed", function(aEvent) {
window.addEventListener("UIReadyDelayed", function delayedInit(aEvent) {
Util.dumpLn("* delay load started...");
window.removeEventListener(aEvent.type, arguments.callee, false);
window.removeEventListener("UIReadyDelayed", delayedInit, false);
// Login Manager and Form History initialization
Cc["@mozilla.org/login-manager;1"].getService(Ci.nsILoginManager);
@ -291,10 +297,22 @@ var BrowserUI = {
* Navigation
*/
/* Updates the overall state of the toolbar, but not the URL bar. */
update: function(aState) {
let uri = this.getDisplayURI(Browser.selectedBrowser);
StartUI.update(uri);
this._updateButtons();
this._updateToolbar();
},
/* Updates the URL bar. */
updateURI: function(aOptions) {
let uri = this.getDisplayURI(Browser.selectedBrowser);
let cleanURI = Util.isURLEmpty(uri) ? "" : uri;
this._edit.value = cleanURI;
},
getDisplayURI: function(browser) {
let uri = browser.currentURI;
let spec = uri.spec;
@ -313,64 +331,18 @@ var BrowserUI = {
return spec;
},
/**
* Some prefs that have consequences in both Metro and Desktop such as
* app-update prefs, are automatically pulled from Desktop here.
*/
_pullDesktopControlledPrefs: function() {
function pullDesktopControlledPrefType(prefType, prefFunc) {
try {
registry.create(Ci.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER,
"Software\\Mozilla\\Firefox\\Metro\\Prefs\\" + prefType,
Ci.nsIWindowsRegKey.ACCESS_ALL);
for (let i = 0; i < registry.valueCount; i++) {
let prefName = registry.getValueName(i);
let prefValue = registry.readStringValue(prefName);
if (prefType == Ci.nsIPrefBranch.PREF_BOOL) {
prefValue = prefValue == "true";
}
Services.prefs[prefFunc](prefName, prefValue);
}
} catch (ex) {
Util.dumpLn("Could not pull for prefType " + prefType + ": " + ex);
} finally {
registry.close();
}
}
let registry = Cc["@mozilla.org/windows-registry-key;1"].
createInstance(Ci.nsIWindowsRegKey);
pullDesktopControlledPrefType(Ci.nsIPrefBranch.PREF_INT, "setIntPref");
pullDesktopControlledPrefType(Ci.nsIPrefBranch.PREF_BOOL, "setBoolPref");
pullDesktopControlledPrefType(Ci.nsIPrefBranch.PREF_STRING, "setCharPref");
},
/* Set the location to the current content */
updateURI: function(aOptions) {
aOptions = aOptions || {};
let uri = this.getDisplayURI(Browser.selectedBrowser);
let cleanURI = Util.isURLEmpty(uri) ? "" : uri;
this._setURI(cleanURI);
if ("captionOnly" in aOptions && aOptions.captionOnly)
return;
StartUI.update(uri);
this._updateButtons();
this._updateToolbar();
},
goToURI: function(aURI) {
aURI = aURI || this._edit.value;
if (!aURI)
return;
this._edit.value = aURI;
// Make sure we're online before attempting to load
Util.forceOnline();
BrowserUI.showContent(aURI);
content.focus();
this._setURI(aURI);
Browser.selectedBrowser.focus();
Task.spawn(function() {
let postData = {};
@ -387,75 +359,27 @@ var BrowserUI = {
});
},
handleUrlbarEnter: function handleUrlbarEnter(aEvent) {
let url = this._edit.value;
if (aEvent instanceof KeyEvent)
url = this._canonizeURL(url, aEvent);
this.goToURI(url);
},
_canonizeURL: function _canonizeURL(aUrl, aTriggeringEvent) {
if (!aUrl)
return "";
// Only add the suffix when the URL bar value isn't already "URL-like",
// and only if we get a keyboard event, to match user expectations.
if (/^\s*[^.:\/\s]+(?:\/.*|\s*)$/i.test(aUrl)) {
let accel = aTriggeringEvent.ctrlKey;
let shift = aTriggeringEvent.shiftKey;
let suffix = "";
switch (true) {
case (accel && shift):
suffix = ".org/";
break;
case (shift):
suffix = ".net/";
break;
case (accel):
try {
suffix = gPrefService.getCharPref("browser.fixup.alternate.suffix");
if (suffix.charAt(suffix.length - 1) != "/")
suffix += "/";
} catch(e) {
suffix = ".com/";
}
break;
}
if (suffix) {
// trim leading/trailing spaces (bug 233205)
aUrl = aUrl.trim();
// Tack www. and suffix on. If user has appended directories, insert
// suffix before them (bug 279035). Be careful not to get two slashes.
let firstSlash = aUrl.indexOf("/");
if (firstSlash >= 0) {
aUrl = aUrl.substring(0, firstSlash) + suffix + aUrl.substring(firstSlash + 1);
} else {
aUrl = aUrl + suffix;
}
aUrl = "http://www." + aUrl;
}
}
return aUrl;
},
doOpenSearch: function doOpenSearch(aName) {
// save the current value of the urlbar
let searchValue = this._edit.value;
let engine = Services.search.getEngineByName(aName);
let submission = engine.getSubmission(searchValue, null);
this._edit.value = submission.uri.spec;
// Make sure we're online before attempting to load
Util.forceOnline();
BrowserUI.showContent();
Browser.selectedBrowser.focus();
let engine = Services.search.getEngineByName(aName);
let submission = engine.getSubmission(searchValue, null);
Browser.loadURI(submission.uri.spec, { postData: submission.postData });
Task.spawn(function () {
Browser.loadURI(submission.uri.spec, { postData: submission.postData });
// loadURI may open a new tab, so get the selectedBrowser afterward.
Browser.selectedBrowser.userTypedValue = submission.uri.spec;
this._titleChanged(Browser.selectedBrowser);
// loadURI may open a new tab, so get the selectedBrowser afterward.
Browser.selectedBrowser.userTypedValue = submission.uri.spec;
BrowserUI._titleChanged(Browser.selectedBrowser);
});
},
/*********************************
@ -465,21 +389,9 @@ var BrowserUI = {
newTab: function newTab(aURI, aOwner) {
aURI = aURI || kStartOverlayURI;
let tab = Browser.addTab(aURI, true, aOwner);
ContextUI.peekTabs();
return tab;
},
newOrSelectTab: function newOrSelectTab(aURI, aOwner) {
let tabs = Browser.tabs;
for (let i = 0; i < tabs.length; i++) {
if (tabs[i].browser.currentURI.spec == aURI) {
Browser.selectedTab = tabs[i];
return;
}
}
this.newTab(aURI, aOwner);
},
setOnTabAnimationEnd: function setOnTabAnimationEnd(aCallback) {
Elements.tabs.addEventListener("animationend", function onAnimationEnd() {
Elements.tabs.removeEventListener("animationend", onAnimationEnd);
@ -502,9 +414,9 @@ var BrowserUI = {
}
this.setOnTabAnimationEnd(function() {
Browser.closeTab(tabToClose, { forceClose: true } );
if (wasCollapsed)
ContextUI.dismissTabsWithDelay(kNewTabAnimationDelayMsec);
Browser.closeTab(tabToClose, { forceClose: true } );
if (wasCollapsed)
ContextUI.dismissTabsWithDelay(kNewTabAnimationDelayMsec);
});
},
@ -546,7 +458,7 @@ var BrowserUI = {
selectTabAndDismiss: function selectTabAndDismiss(aTab) {
this.selectTab(aTab);
ContextUI.dismissTabs();
ContextUI.dismissTabsWithDelay(kSelectTabAnimationDelayMsec);
},
selectTabAtIndex: function selectTabAtIndex(aIndex) {
@ -621,12 +533,6 @@ var BrowserUI = {
case "browser.cache.disk_cache_ssl":
this._sslDiskCacheEnabled = Services.prefs.getBoolPref(aData);
break;
case "browser.urlbar.formatting.enabled":
this._formattingEnabled = Services.prefs.getBoolPref(aData);
break;
case "browser.urlbar.trimURLs":
this._mayTrimURLs = Services.prefs.getBoolPref(aData);
break;
case debugServerStateChanged:
if (Services.prefs.getBoolPref(aData)) {
this.runDebugServer();
@ -641,7 +547,7 @@ var BrowserUI = {
break;
case "metro_viewstate_changed":
this._adjustDOMforViewState();
let autocomplete = document.getElementById("start-autocomplete");
let autocomplete = document.getElementById("urlbar-autocomplete");
if (aData == "snapped") {
FlyoutPanelsUI.hide();
// Order matters (need grids to get dimensions, etc), now
@ -660,6 +566,37 @@ var BrowserUI = {
* Internal utils
*/
/**
* Some prefs that have consequences in both Metro and Desktop such as
* app-update prefs, are automatically pulled from Desktop here.
*/
_pullDesktopControlledPrefs: function() {
function pullDesktopControlledPrefType(prefType, prefFunc) {
try {
registry.create(Ci.nsIWindowsRegKey.ROOT_KEY_CURRENT_USER,
"Software\\Mozilla\\Firefox\\Metro\\Prefs\\" + prefType,
Ci.nsIWindowsRegKey.ACCESS_ALL);
for (let i = 0; i < registry.valueCount; i++) {
let prefName = registry.getValueName(i);
let prefValue = registry.readStringValue(prefName);
if (prefType == Ci.nsIPrefBranch.PREF_BOOL) {
prefValue = prefValue == "true";
}
Services.prefs[prefFunc](prefName, prefValue);
}
} catch (ex) {
Util.dumpLn("Could not pull for prefType " + prefType + ": " + ex);
} finally {
registry.close();
}
}
let registry = Cc["@mozilla.org/windows-registry-key;1"].
createInstance(Ci.nsIWindowsRegKey);
pullDesktopControlledPrefType(Ci.nsIPrefBranch.PREF_INT, "setIntPref");
pullDesktopControlledPrefType(Ci.nsIPrefBranch.PREF_BOOL, "setBoolPref");
pullDesktopControlledPrefType(Ci.nsIPrefBranch.PREF_STRING, "setCharPref");
},
_adjustDOMforViewState: function() {
if (MetroUtils.immersive) {
let currViewState = "";
@ -727,204 +664,6 @@ var BrowserUI = {
Elements.urlbarState.setAttribute("mode", "view");
},
_trimURL: function _trimURL(aURL) {
// This function must not modify the given URL such that calling
// nsIURIFixup::createFixupURI with the result will produce a different URI.
return aURL /* remove single trailing slash for http/https/ftp URLs */
.replace(/^((?:http|https|ftp):\/\/[^/]+)\/$/, "$1")
/* remove http:// unless the host starts with "ftp\d*\." or contains "@" */
.replace(/^http:\/\/((?!ftp\d*\.)[^\/@]+(?:\/|$))/, "$1");
},
trimURL: function trimURL(aURL) {
return this.mayTrimURLs ? this._trimURL(aURL) : aURL;
},
_setURI: function _setURI(aURL) {
this._edit.value = aURL;
this.lastKnownGoodURL = aURL;
},
_getSelectedURIForClipboard: function _getSelectedURIForClipboard() {
// Grab the actual input field's value, not our value, which could include moz-action:
let inputVal = this._edit.inputField.value;
let selectedVal = inputVal.substring(this._edit.selectionStart, this._edit.electionEnd);
// If the selection doesn't start at the beginning or doesn't span the full domain or
// the URL bar is modified, nothing else to do here.
if (this._edit.selectionStart > 0 || this._edit.valueIsTyped)
return selectedVal;
// The selection doesn't span the full domain if it doesn't contain a slash and is
// followed by some character other than a slash.
if (!selectedVal.contains("/")) {
let remainder = inputVal.replace(selectedVal, "");
if (remainder != "" && remainder[0] != "/")
return selectedVal;
}
let uriFixup = Cc["@mozilla.org/docshell/urifixup;1"].getService(Ci.nsIURIFixup);
let uri;
try {
uri = uriFixup.createFixupURI(inputVal, Ci.nsIURIFixup.FIXUP_FLAG_USE_UTF8);
} catch (e) {}
if (!uri)
return selectedVal;
// Only copy exposable URIs
try {
uri = uriFixup.createExposableURI(uri);
} catch (ex) {}
// If the entire URL is selected, just use the actual loaded URI.
if (inputVal == selectedVal) {
// ... but only if isn't a javascript: or data: URI, since those
// are hard to read when encoded
if (!uri.schemeIs("javascript") && !uri.schemeIs("data")) {
// Parentheses are known to confuse third-party applications (bug 458565).
selectedVal = uri.spec.replace(/[()]/g, function (c) escape(c));
}
return selectedVal;
}
// Just the beginning of the URL is selected, check for a trimmed value
let spec = uri.spec;
let trimmedSpec = this.trimURL(spec);
if (spec != trimmedSpec) {
// Prepend the portion that trimURL removed from the beginning.
// This assumes trimURL will only truncate the URL at
// the beginning or end (or both).
let trimmedSegments = spec.split(trimmedSpec);
selectedVal = trimmedSegments[0] + selectedVal;
}
return selectedVal;
},
_copyCutURIController: {
doCommand: function(aCommand) {
let urlbar = BrowserUI._edit;
let val = BrowserUI._getSelectedURIForClipboard();
if (!val)
return;
if (aCommand == "cmd_cut" && this.isCommandEnabled(aCommand)) {
let start = urlbar.selectionStart;
let end = urlbar.selectionEnd;
urlbar.inputField.value = urlbar.inputField.value.substring(0, start) +
urlbar.inputField.value.substring(end);
urlbar.selectionStart = urlbar.selectionEnd = start;
}
Cc["@mozilla.org/widget/clipboardhelper;1"]
.getService(Ci.nsIClipboardHelper)
.copyString(val, document);
},
supportsCommand: function(aCommand) {
switch (aCommand) {
case "cmd_copy":
case "cmd_cut":
return true;
}
return false;
},
isCommandEnabled: function(aCommand) {
let urlbar = BrowserUI._edit;
return this.supportsCommand(aCommand) &&
(aCommand != "cmd_cut" || !urlbar.readOnly) &&
urlbar.selectionStart < urlbar.selectionEnd;
},
onEvent: function(aEventName) {}
},
_editURI: function _editURI(aShouldDismiss) {
this._edit.focus();
this._edit.select();
Elements.urlbarState.setAttribute("mode", "edit");
StartUI.show();
if (aShouldDismiss) {
ContextUI.dismissTabs();
}
},
formatURI: function formatURI() {
if (!this.formattingEnabled ||
Elements.urlbarState.getAttribute("mode") == "edit")
return;
let controller = this._edit.editor.selectionController;
let selection = controller.getSelection(controller.SELECTION_URLSECONDARY);
selection.removeAllRanges();
let textNode = this._edit.editor.rootElement.firstChild;
let value = textNode.textContent;
let protocol = value.match(/^[a-z\d.+\-]+:(?=[^\d])/);
if (protocol &&
["http:", "https:", "ftp:"].indexOf(protocol[0]) == -1)
return;
let matchedURL = value.match(/^((?:[a-z]+:\/\/)?(?:[^\/]+@)?)(.+?)(?::\d+)?(?:\/|$)/);
if (!matchedURL)
return;
let [, preDomain, domain] = matchedURL;
let baseDomain = domain;
let subDomain = "";
// getBaseDomainFromHost doesn't recognize IPv6 literals in brackets as IPs (bug 667159)
if (domain[0] != "[") {
try {
baseDomain = Services.eTLD.getBaseDomainFromHost(domain);
if (!domain.endsWith(baseDomain)) {
// getBaseDomainFromHost converts its resultant to ACE.
let IDNService = Cc["@mozilla.org/network/idn-service;1"]
.getService(Ci.nsIIDNService);
baseDomain = IDNService.convertACEtoUTF8(baseDomain);
}
} catch (e) {}
}
if (baseDomain != domain) {
subDomain = domain.slice(0, -baseDomain.length);
}
let rangeLength = preDomain.length + subDomain.length;
if (rangeLength) {
let range = document.createRange();
range.setStart(textNode, 0);
range.setEnd(textNode, rangeLength);
selection.addRange(range);
}
let startRest = preDomain.length + domain.length;
if (startRest < value.length) {
let range = document.createRange();
range.setStart(textNode, startRest);
range.setEnd(textNode, value.length);
selection.addRange(range);
}
},
_clearURIFormatting: function _clearURIFormatting() {
if (!this.formattingEnabled)
return;
let controller = this._edit.editor.selectionController;
let selection = controller.getSelection(controller.SELECTION_URLSECONDARY);
selection.removeAllRanges();
},
_urlbarBlurred: function _urlbarBlurred() {
let state = Elements.urlbarState;
if (state.getAttribute("mode") == "edit")
state.removeAttribute("mode");
this._updateToolbar();
this.formatURI();
},
_closeOrQuit: function _closeOrQuit() {
// Close active dialog, if we have one. If not then close the application.
if (!BrowserUI.isContentShowing()) {
@ -985,10 +724,7 @@ var BrowserUI = {
aEvent.preventDefault();
if (this._edit.popupOpen) {
this._edit.value = this.lastKnownGoodURL;
this._edit.closePopup();
StartUI.hide();
ContextUI.dismiss();
this._edit.endEditing(true);
return;
}
@ -1205,24 +941,6 @@ var BrowserUI = {
return this._sslDiskCacheEnabled;
},
_formattingEnabled: null,
get formattingEnabled() {
if (this._formattingEnabled === null) {
this._formattingEnabled = Services.prefs.getBoolPref("browser.urlbar.formatting.enabled");
}
return this._formattingEnabled;
},
_mayTrimURLs: null,
get mayTrimURLs() {
if (this._mayTrimURLs === null) {
this._mayTrimURLs = Services.prefs.getBoolPref("browser.urlbar.trimURLs");
}
return this._mayTrimURLs;
},
supportsCommand : function(cmd) {
var isSupported = false;
switch (cmd) {
@ -1302,7 +1020,7 @@ var BrowserUI = {
break;
case "cmd_openLocation":
ContextUI.displayNavbar();
this._editURI(true);
this._edit.beginEditing(true);
break;
case "cmd_addBookmark":
ContextUI.displayNavbar();
@ -1332,7 +1050,8 @@ var BrowserUI = {
break;
case "cmd_newTab":
this.newTab();
this._editURI(false);
this._edit.beginEditing(false);
ContextUI.peekTabs(kNewTabAnimationDelayMsec);
break;
case "cmd_closeTab":
this.closeTab();
@ -1372,9 +1091,8 @@ var BrowserUI = {
};
var StartUI = {
get isVisible() { return this.isStartPageVisible || this.isFiltering; },
get isVisible() { return this.isStartPageVisible; },
get isStartPageVisible() { return Elements.windowState.hasAttribute("startpage"); },
get isFiltering() { return Elements.windowState.hasAttribute("filtering"); },
get maxResultsPerSection() {
return Services.prefs.getIntPref("browser.display.startUI.maxresults");
@ -1389,8 +1107,6 @@ var StartUI = {
],
init: function init() {
Elements.startUI.addEventListener("autocompletestart", this, false);
Elements.startUI.addEventListener("autocompleteend", this, false);
Elements.startUI.addEventListener("contextmenu", this, false);
Elements.startUI.addEventListener("click", this, false);
Elements.startUI.addEventListener("MozMousePixelScroll", this, false);
@ -1429,24 +1145,6 @@ var StartUI = {
return true;
},
/** Show the autocomplete popup */
filter: function filter() {
if (this.isFiltering)
return;
BrowserUI._edit.openPopup();
Elements.windowState.setAttribute("filtering", "true");
},
/** Hide the autocomplete popup */
unfilter: function unfilter() {
if (!this.isFiltering)
return;
BrowserUI._edit.closePopup();
Elements.windowState.removeAttribute("filtering");
},
/** Hide the Firefox start page */
hide: function hide(aURI) {
aURI = aURI || Browser.selectedBrowser.currentURI.spec;
@ -1455,8 +1153,6 @@ var StartUI = {
Elements.contentShowing.removeAttribute("disabled");
Elements.windowState.removeAttribute("startpage");
this.unfilter();
return true;
},
@ -1488,12 +1184,6 @@ var StartUI = {
handleEvent: function handleEvent(aEvent) {
switch (aEvent.type) {
case "autocompletestart":
this.filter();
break;
case "autocompleteend":
this.unfilter();
break;
case "contextmenu":
let event = document.createEvent("Events");
event.initEvent("MozEdgeUICompleted", true, false);

Просмотреть файл

@ -95,11 +95,11 @@ setting[type="menulist"] {
}
#urlbar-edit {
-moz-binding: url("chrome://browser/content/bindings/autocomplete.xml#autocomplete");
-moz-binding: url("chrome://browser/content/bindings/urlbar.xml#urlbar");
}
#start-autocomplete {
-moz-binding: url("chrome://browser/content/bindings/autocomplete.xml#autocomplete-popup");
#urlbar-autocomplete {
-moz-binding: url("chrome://browser/content/bindings/urlbar.xml#urlbar-autocomplete");
}
richgrid {

Просмотреть файл

@ -574,6 +574,7 @@ var Browser = {
} else {
// Update all of our UI to reflect the new tab's location
BrowserUI.updateURI();
BrowserUI.update();
let event = document.createEvent("Events");
event.initEvent("TabSelect", true, false);
@ -1578,7 +1579,7 @@ Tab.prototype = {
// Ensure that history is initialized
history.QueryInterface(Ci.nsISHistoryInternal);
for (let i = 0, length = otherHistory.index; i <= length; i++)
history.addEntry(otherHistory.getEntryAtIndex(i, false), true);
},

Просмотреть файл

@ -179,7 +179,8 @@
<vbox id="page">
<vbox id="tray" class="tray-toolbar" observes="bcast_windowState" >
<!-- Tabs -->
<hbox id="tabs-container" observes="bcast_windowState">
<!-- onclick handler to work around bug 837242 -->
<hbox id="tabs-container" observes="bcast_windowState" onclick="void(0);">
<box id="tabs" flex="1"
observes="bcast_preciseInput"
onselect="BrowserUI.selectTabAndDismiss(this);"
@ -228,8 +229,6 @@
onclick="PanelUI.show('remotetabs-container');" inputProcessing="true"/>
</scrollbox>
</hbox>
<!-- Autocompletion interface -->
<box id="start-autocomplete" observes="bcast_windowState"/>
</hbox>
</vbox> <!-- end tray -->
@ -256,44 +255,48 @@
<hbox id="progress-control" />
</hbox>
<!-- Main Toolbar -->
<toolbar id="toolbar" observes="bcast_windowState" flex="1">
<observes element="bcast_windowState" attribute="*"/>
<observes element="bcast_urlbarState" attribute="*"/>
<vbox id="toolbar-autocomplete" flex="1">
<!-- Autocomplete -->
<scrollbox flex="1">
<hbox id="urlbar-autocomplete" observes="bcast_windowState"/>
</scrollbox>
<toolbarbutton id="back-button" class="appbar-primary" command="cmd_back"/>
<toolbarbutton id="forward-button" class="appbar-primary" command="cmd_forward"/>
<!-- Main Toolbar -->
<toolbar id="toolbar" observes="bcast_windowState" flex="1">
<observes element="bcast_windowState" attribute="*"/>
<observes element="bcast_urlbarState" attribute="*"/>
<hbox id="urlbar-container" flex="1" observes="bcast_urlbarState">
<hbox id="urlbar" flex="1">
<box id="identity-box" role="button">
<hbox id="identity-box-inner" align="center" mousethrough="always">
<image id="identity-icon"/>
</hbox>
</box>
<toolbarbutton id="back-button" class="appbar-primary" command="cmd_back"/>
<toolbarbutton id="forward-button" class="appbar-primary" command="cmd_forward"/>
<textbox id="urlbar-edit"
type="url"
class="uri-element"
autocompletesearch="history"
autocompletepopup="start-autocomplete"
completeselectedindex="true"
placeholder="&urlbar.emptytext;"
flex="1"
onpaste="this.focus();"
ontextentered="BrowserUI.handleUrlbarEnter(param);"
onblur="BrowserUI._urlbarBlurred();"/>
<hbox id="urlbar-container" flex="1" observes="bcast_urlbarState">
<hbox id="urlbar" flex="1">
<box id="identity-box" role="button">
<hbox id="identity-box-inner" align="center" mousethrough="always">
<image id="identity-icon"/>
</hbox>
</box>
<textbox id="urlbar-edit"
type="url"
class="uri-element"
autocompletesearch="history"
autocompletepopup="urlbar-autocomplete"
completeselectedindex="true"
placeholder="&urlbar.emptytext;"
flex="1"/>
</hbox>
<toolbarbutton id="reload-button" oncommand="CommandUpdater.doCommand(event.shiftKey ? 'cmd_forceReload' : 'cmd_reload');"/>
<toolbarbutton id="stop-button" command="cmd_stop"/>
</hbox>
<toolbarbutton id="reload-button" oncommand="CommandUpdater.doCommand(event.shiftKey ? 'cmd_forceReload' : 'cmd_reload');"/>
<toolbarbutton id="stop-button" command="cmd_stop"/>
</hbox>
<toolbarbutton id="download-button" oncommand="Appbar.onDownloadButton()"/>
<toolbarbutton id="star-button" class="appbar-primary" type="checkbox" oncommand="Appbar.onStarButton()"/>
<toolbarbutton id="pin-button" class="appbar-primary" type="checkbox" oncommand="Appbar.onPinButton()"/>
<toolbarbutton id="menu-button" class="appbar-primary" oncommand="Appbar.onMenuButton(event)"/>
</toolbar>
<toolbarbutton id="download-button" oncommand="Appbar.onDownloadButton()"/>
<toolbarbutton id="star-button" class="appbar-primary" type="checkbox" oncommand="Appbar.onStarButton()"/>
<toolbarbutton id="pin-button" class="appbar-primary" type="checkbox" oncommand="Appbar.onPinButton()"/>
<toolbarbutton id="menu-button" class="appbar-primary" oncommand="Appbar.onMenuButton(event)"/>
</toolbar>
</vbox>
</appbar>
<vbox id="panel-container" hidden="true" class="window-width window-height meta" observes="bcast_windowState">
@ -353,7 +356,7 @@
<button class="findbar-item previous-button" command="cmd_findPrevious"/>
<button class="findbar-item next-button" command="cmd_findNext"/>
<spacer flex="1"/>
<button class="findbar-item close-button" command="cmd_findClose"/>
<button id="findbar-close" class="findbar-item close-button" command="cmd_findClose"/>
</appbar>
<!-- Context button bar -->

Просмотреть файл

@ -338,6 +338,7 @@ function MenuPopup(aPanel, aPopup) {
this._panel = aPanel;
this._popup = aPopup;
this._wantTypeBehind = false;
this._willReshowPopup = false;
window.addEventListener('MozAppbarShowing', this, false);
}
@ -346,9 +347,19 @@ MenuPopup.prototype = {
get _commands() { return this._popup.childNodes[0]; },
show: function (aPositionOptions) {
if (this._visible)
return;
if (this._visible) {
this._willReshowPopup = true;
let self = this;
this._panel.addEventListener("transitionend", function () {
self._show(aPositionOptions);
self._panel.removeEventListener("transitionend", arguments.callee);
});
} else {
this._show(aPositionOptions);
}
},
_show: function (aPositionOptions) {
window.addEventListener("keypress", this, true);
window.addEventListener("mousedown", this, true);
Elements.stack.addEventListener("PopupChanged", this, false);
@ -362,9 +373,12 @@ MenuPopup.prototype = {
self._panel.removeEventListener("transitionend", arguments.callee);
self._panel.removeAttribute("showingfrom");
let eventName = self._willReshowPopup ? "popupmoved" : "popupshown";
let event = document.createEvent("Events");
event.initEvent("popupshown", true, false);
document.dispatchEvent(event);
event.initEvent(eventName, true, false);
self._panel.dispatchEvent(event);
self._willReshowPopup = false;
});
let popupFrom = !aPositionOptions.bottomAligned ? "above" : "below";
@ -393,9 +407,11 @@ MenuPopup.prototype = {
self._popup.style.maxWidth = "none";
self._popup.style.maxHeight = "none";
let event = document.createEvent("Events");
event.initEvent("popuphidden", true, false);
document.dispatchEvent(event);
if (!self._willReshowPopup) {
let event = document.createEvent("Events");
event.initEvent("popuphidden", true, false);
self._panel.dispatchEvent(event);
}
});
this._panel.setAttribute("hiding", "true");

Просмотреть файл

@ -21,7 +21,7 @@ chrome.jar:
content/bindings/dialog.xml (content/bindings/dialog.xml)
content/bindings/arrowbox.xml (content/bindings/arrowbox.xml)
content/bindings/grid.xml (content/bindings/grid.xml)
content/bindings/autocomplete.xml (content/bindings/autocomplete.xml)
content/bindings/urlbar.xml (content/bindings/urlbar.xml)
content/bindings/appbar.xml (content/bindings/appbar.xml)
content/bindings/flyoutpanel.xml (content/bindings/flyoutpanel.xml)
content/bindings/selectionoverlay.xml (content/bindings/selectionoverlay.xml)

Просмотреть файл

@ -12,6 +12,7 @@ include $(DEPTH)/config/autoconf.mk
BROWSER_TESTS = \
head.js \
browser_urlbar.js \
browser_bookmarks.js \
browser_canonizeURL.js \
browser_context_menu_tests.js \
@ -20,6 +21,8 @@ BROWSER_TESTS = \
browser_context_menu_tests_03.html \
browser_context_ui.js \
browser_downloads.js \
browser_findbar.js \
browser_findbar.html \
browser_history.js \
browser_onscreen_keyboard.js \
browser_onscreen_keyboard.html \
@ -60,6 +63,7 @@ BROWSER_TEST_RESOURCES = \
res/textblock01.html \
res/textinput01.html \
res/textarea01.html \
res/testEngine.xml \
$(NULL)
libs:: $(BROWSER_TESTS)

Просмотреть файл

@ -16,6 +16,6 @@ function test() {
[" example/a ", {ctrlKey: true}, "http://www.example.com/a"]
];
for (let [input, modifiers, result] of testcases) {
is(BrowserUI._canonizeURL(input, modifiers), result, input + " -> " + result);
is(BrowserUI._edit._canonizeURL(input, modifiers), result, input + " -> " + result);
}
}

Просмотреть файл

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Find bar tests</title>
</head>
<body>
<p>Find bar tests</title>
</body>
</html>

Просмотреть файл

@ -0,0 +1,56 @@
/* vim: set ts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
function test() {
runTests();
}
gTests.push({
desc: "Access the find bar with the keyboard",
run: function() {
let tab = yield addTab(chromeRoot + "browser_findbar.html");
yield waitForCondition(() => BrowserUI.ready);
is(Elements.findbar.isShowing, false, "Find bar is hidden by default");
EventUtils.synthesizeKey("f", { accelKey: true });
yield waitForEvent(Elements.findbar, "transitionend");
is(Elements.findbar.isShowing, true, "Show find bar with Ctrl-F");
let textbox = document.getElementById("findbar-textbox");
is(textbox.value, "", "Find bar is empty");
EventUtils.sendString("bar");
is(textbox.value, "bar", "Type 'bar' into find bar");
EventUtils.synthesizeKey("VK_ESCAPE", { accelKey: true });
yield waitForEvent(Elements.findbar, "transitionend");
is(Elements.findbar.isShowing, false, "Hide find bar with Esc");
Browser.closeTab(tab);
}
});
gTests.push({
desc: "Show and hide the find bar with mouse",
run: function() {
let tab = yield addTab(chromeRoot + "browser_findbar.html");
yield waitForCondition(() => BrowserUI.ready);
is(Elements.findbar.isShowing, false, "Find bar is hidden by default");
ContextUI.displayNavbar();
EventUtils.sendMouseEvent({ type: "click" }, "menu-button");
EventUtils.sendMouseEvent({ type: "click" }, "context-findinpage");
yield waitForEvent(Elements.findbar, "transitionend");
is(Elements.findbar.isShowing, true, "Show find bar with menu item");
EventUtils.synthesizeMouse(document.getElementById("findbar-close"), 1, 1, {});
yield waitForEvent(Elements.findbar, "transitionend");
is(Elements.findbar.isShowing, false, "Hide find bar with close button");
Browser.closeTab(tab);
}
});

Просмотреть файл

@ -56,7 +56,7 @@ gTests.push({
var touchdrag = new TouchDragAndHold();
yield touchdrag.start(gWindow, xpos, ypos, 900, ypos);
yield waitForCondition(function () {
return getTrimmedSelection(edit).toString() ==
return getTrimmedSelection(edit).toString() ==
"mochitests/content/metro/browser/metro/base/tests/mochitest/res/textblock01.html";
}, kCommonWaitMs, kCommonPollMs);
touchdrag.end();
@ -69,6 +69,29 @@ gTests.push({
},
});
gTests.push({
desc: "bug 887120 - tap & hold to paste into urlbar",
run: function bug887120_test() {
gWindow = window;
yield showNavBar();
let edit = document.getElementById("urlbar-edit");
SpecialPowers.clipboardCopyString("mozilla");
sendContextMenuClickToElement(window, edit);
yield waitForEvent(document, "popupshown");
ok(ContextMenuUI._menuPopup._visible, "is visible");
let paste = document.getElementById("context-paste");
ok(!paste.hidden, "paste item is visible");
sendElementTap(window, paste);
ok(edit.popup.popupOpen, "bug: popup should be showing");
delete window.r;
}
});
function test() {
if (!isLandscapeMode()) {
todo(false, "browser_selection_tests need landscape mode to run.");

Просмотреть файл

@ -0,0 +1,232 @@
// -*- Mode: js2; tab-width: 2; indent-tabs-mode: nil; js2-basic-offset: 2; js2-skip-preprocessor-directives: t; -*-
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
var gEdit = null;
/*=============================================================================
Search engine mocking utilities
=============================================================================*/
var gEngine = null;
const kSearchEngineName = "Foo";
const kSearchEngineURI = chromeRoot + "res/testEngine.xml";
/*
* addMockSearchDefault - adds a mock search engine to the top of the engine list.
*/
function addMockSearchDefault(aTimeoutMs) {
let deferred = Promise.defer();
let timeoutMs = aTimeoutMs || kDefaultWait;
let timerID = 0;
function engineAddObserver(aSubject, aTopic, aData) {
if (aData != "engine-added")
return;
gEngine = Services.search.getEngineByName(kSearchEngineName);
Services.obs.removeObserver(engineAddObserver, "browser-search-engine-modified");
clearTimeout(timerID);
gEngine.hidden = false;
ok(gEngine, "mock engine was added");
deferred.resolve();
}
if (gEngine) {
deferred.resolve();
return deferred.promise;
}
timerID = setTimeout(function ids_canceller() {
Services.obs.removeObserver(engineAddObserver, "browser-search-engine-modified");
deferred.reject(new Error("search add timeout"));
}, timeoutMs);
Services.obs.addObserver(engineAddObserver, "browser-search-engine-modified", false);
Services.search.addEngine(kSearchEngineURI, Ci.nsISearchEngine.DATA_XML,
"data:image/x-icon,%00", false);
return deferred.promise;
}
/*
* removeMockSearchDefault - removes mock "Foo" search engine.
*/
function removeMockSearchDefault(aTimeoutMs) {
let deferred = Promise.defer();
let timeoutMs = aTimeoutMs || kDefaultWait;
let timerID = 0;
function engineRemoveObserver(aSubject, aTopic, aData) {
if (aData != "engine-removed")
return;
clearTimeout(timerID);
gEngine = null;
Services.obs.removeObserver(engineRemoveObserver, "browser-search-engine-modified");
deferred.resolve();
}
if (!gEngine) {
deferred.resolve();
return deferred.promise;
}
timerID = setTimeout(function ids_canceller() {
Services.obs.removeObserver(engineRemoveObserver, "browser-search-engine-modified");
deferred.reject(new Error("search remove timeout"));
}, timeoutMs);
Services.obs.addObserver(engineRemoveObserver, "browser-search-engine-modified", false);
Services.search.removeEngine(gEngine);
return deferred.promise;
}
/*=============================================================================
Test cases
=============================================================================*/
function test() {
runTests();
}
function setUp() {
if (!gEdit)
gEdit = document.getElementById("urlbar-edit");
yield addTab("about:start");
yield showNavBar();
yield waitForCondition(function () {
return StartUI.isStartPageVisible;
});
}
function tearDown() {
yield removeMockSearchDefault();
Browser.closeTab(Browser.selectedTab, { forceClose: true });
delete window.r;
}
gTests.push({
desc: "search engines update",
setUp: setUp,
tearDown: tearDown,
run: function testSearchEngine() {
// If the XBL hasn't initialized yet, open the popup so that it will.
if (gEdit.popup._searches == undefined) {
gEdit.openPopup();
gEdit.closePopup();
}
let numSearches = gEdit.popup._searches.itemCount;
function getEngineItem() {
return gEdit.popup._searches.querySelector("richgriditem[value="+kSearchEngineName+"]");
}
yield addMockSearchDefault();
ok(gEdit.popup._searches.itemCount == numSearches + 1, "added search engine count");
ok(getEngineItem(), "added search engine item");
yield removeMockSearchDefault();
ok(gEdit.popup._searches.itemCount == numSearches, "normal search engine count");
ok(!getEngineItem(), "added search engine item");
}
});
gTests.push({
desc: "display autocomplete while typing, handle enter",
setUp: setUp,
tearDown: tearDown,
run: function testUrlbarTyping() {
sendElementTap(window, gEdit);
ok(gEdit.isEditing, "focus urlbar: in editing mode");
ok(!gEdit.popup.popupOpen, "focus urlbar: popup not open yet");
EventUtils.sendString("about:blank", window);
let opened = yield waitForCondition(() => gEdit.popup.popupOpen);
ok(opened, "type in urlbar: popup opens");
EventUtils.synthesizeKey("VK_RETURN", {}, window);
let closed = yield waitForCondition(() => !gEdit.popup.popupOpen);
ok(closed, "hit enter in urlbar: popup closes, page loads");
ok(!gEdit.isEditing, "hit enter in urlbar: not in editing mode");
}
});
gTests.push({
desc: "display and select a search with keyboard",
setUp: setUp,
tearDown: tearDown,
run: function testSearchKeyboard() {
yield addMockSearchDefault();
sendElementTap(window, gEdit);
ok(gEdit.isEditing, "focus urlbar: in editing mode");
ok(!gEdit.popup.popupOpen, "focus urlbar: popup not open yet");
let search = "mozilla";
EventUtils.sendString(search, window);
yield waitForCondition(() => gEdit.popup.popupOpen);
// XXX We should probably change the keyboard selection behavior entirely,
// given that it makes little to no sense, but that's a job for a later patch.
EventUtils.synthesizeKey("VK_DOWN", {}, window);
is(gEdit.popup.selectedIndex, -1, "key select search: no result selected");
is(gEdit.popup._searches.selectedIndex, 0, "key select search: first search selected");
let engines = Services.search.getVisibleEngines();
for (let i = 0, max = engines.length - 1; i < max; i++) {
is(gEdit.popup._searches.selectedIndex, i, "key select search: next index");
EventUtils.synthesizeKey("VK_DOWN", {}, window);
}
let existingValue = gEdit.value;
EventUtils.synthesizeKey("VK_RETURN", {}, window);
yield waitForCondition(() => gEdit.value != existingValue);
let closed = yield waitForCondition(() => !gEdit.popup.popupOpen);
ok(closed, "hit enter in urlbar: popup closes, page loads");
ok(!gEdit.isEditing, "hit enter in urlbar: not in editing mode");
let searchSubmission = gEngine.getSubmission(search, null);
let trimmedSubmission = gEdit.trimValue(searchSubmission.uri.spec);
is(gEdit.value, trimmedSubmission, "hit enter in urlbar: search conducted");
yield removeMockSearchDefault();
}
});
gTests.push({
desc: "display and select a search with touch",
setUp: setUp,
tearDown: tearDown,
run: function testUrlbarSearchesTouch() {
yield addMockSearchDefault();
sendElementTap(window, gEdit);
ok(gEdit.isEditing, "focus urlbar: in editing mode");
ok(!gEdit.popup.popupOpen, "focus urlbar: popup not open yet");
let search = "mozilla";
EventUtils.sendString(search, window);
yield waitForCondition(() => gEdit.popup.popupOpen);
sendElementTap(window, gEdit.popup._searches.lastChild);
let closed = yield waitForCondition(() => !gEdit.popup.popupOpen);
ok(closed, "tap search option: popup closes, page loads");
ok(!gEdit.isEditing, "tap search option: not in editing mode");
let searchSubmission = gEngine.getSubmission(search, null);
let trimmedSubmission = gEdit.trimValue(searchSubmission.uri.spec);
is(gEdit.value, trimmedSubmission, "tap search option: search conducted");
}
});

Просмотреть файл

@ -708,8 +708,8 @@ TouchDragAndHold.prototype = {
System utilities
=============================================================================*/
/*
* emptyClipboard - clear the windows clipbaord.
/*
* emptyClipboard - clear the windows clipboard.
*/
function emptyClipboard() {
Cc["@mozilla.org/widget/clipboard;1"].getService(Ci.nsIClipboard)

Просмотреть файл

@ -0,0 +1,12 @@
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/"
xmlns:moz="http://www.mozilla.org/2006/browser/search/">
<ShortName>Foo</ShortName>
<Description>Foo Search</Description>
<InputEncoding>utf-8</InputEncoding>
<Image width="16" height="16">data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAABGklEQVQoz2NgGB6AnZ1dUlJSXl4eSDIyMhLW4Ovr%2B%2Fr168uXL69Zs4YoG%2BLi4i5dusTExMTGxsbNzd3f37937976%2BnpmZmagbHR09J49e5YvX66kpATVEBYW9ubNm2nTphkbG7e2tp44cQLIuHfvXm5urpaWFlDKysqqu7v73LlzECMYIiIiHj58mJCQoKKicvXq1bS0NKBgW1vbjh074uPjgeqAXE1NzSdPnvDz84M0AEUvXLgAsW379u1z5swBen3jxo2zZ892cHB4%2BvQp0KlAfwI1cHJyghQFBwfv2rULokFXV%2FfixYu7d%2B8GGqGgoMDKyrpu3br9%2B%2FcDuXl5eVA%2FAEWBfoWHAdAYoNuAYQ0XAeoUERFhGDYAAPoUaT2dfWJuAAAAAElFTkSuQmCC</Image>
<Url type="text/html" method="GET" template="http://mochi.test:8888/browser/browser/components/search/test/?search">
<Param name="test" value="{searchTerms}"/>
</Url>
<moz:SearchForm>http://mochi.test:8888/browser/browser/components/search/test/</moz:SearchForm>
<moz:Alias>fooalias</moz:Alias>
</OpenSearchDescription>

Просмотреть файл

@ -8,5 +8,4 @@ srcdir = @srcdir@
VPATH = @srcdir@
include $(DEPTH)/config/autoconf.mk
include $(topsrcdir)/config/config.mk
include $(topsrcdir)/config/rules.mk

Просмотреть файл

@ -248,7 +248,7 @@ documenttab[selected] .documenttab-selection {
/* Toolbar ------------------------------------------------------------------ */
#toolbar {
#toolbar-autocomplete {
background-color: @panel_light_color@;
}
@ -364,7 +364,7 @@ appbar {
font-size: 0;
}
appbar > toolbar {
appbar toolbar {
-moz-appearance: none;
-moz-box-align: center;
border: 0;
@ -373,7 +373,7 @@ appbar > toolbar {
font-size: 1rem;
}
appbar > toolbar > toolbarbutton {
appbar toolbar > toolbarbutton {
border: 0;
margin: 0 @toolbar_horizontal_spacing@;
padding: 0;

Просмотреть файл

@ -194,16 +194,17 @@ menulist {
min-width: @touch_action_minwidth@; /* keep the button from being too narrow */
border: 0 none;
-moz-box-align: center;
font-weight: 600;
}
.menu-popup richlistitem:not([disabled]):hover {
background-color: #dedad0;
background-color: #ccc;
color: black;
}
.menu-popup richlistitem:not([disabled]):active {
background-color: @selected_color@ !important;
color: black;
background-color: black;
color: white;
}
.menu-popup > richlistbox[left-hand="true"] > richlistitem {
@ -214,7 +215,7 @@ menulist {
padding-right: 50px;
}
/* form select popup */
/* Additional styles applied to popups for form <select> elements. */
#select-container {
padding: 0;
@ -233,7 +234,7 @@ menulist {
}
/* listcell element doesn't have flex="1" so we need to force it */
#select-commands .option-command > listcell {
.option-command > listcell {
-moz-box-flex: 1 !important;
}
@ -244,8 +245,8 @@ menulist {
}
.option-command.selected {
background-color: @selected_color@ !important;
color: black;
background-color: #ff8000;
color: white;
}
.option-command.optgroup {
@ -255,12 +256,12 @@ menulist {
}
.option-command:not([disabled]):hover {
background-color: #dedad0;
background-color: #f0f0f0;
color: black;
}
.option-command:not([disabled]):active {
background-color: @selected_color@ !important;
background-color: #d3d3d3;
color: black;
}

Просмотреть файл

@ -162,6 +162,23 @@ this.Social = {
if (topic == "provider-added" || topic == "provider-removed") {
this._updateProviderCache(data);
Services.obs.notifyObservers(null, "social:providers-changed", null);
return;
}
if (topic == "provider-update") {
// a provider has self-updated its manifest, we need to update our
// cache and possibly reload if it was the current provider.
let provider = data;
SocialService.getOrderedProviderList(function(providers) {
Social._updateProviderCache(providers);
Services.obs.notifyObservers(null, "social:providers-changed", null);
// if we need a reload, do it now
if (provider.enabled) {
Social.enabled = false;
Services.tm.mainThread.dispatch(function() {
Social.enabled = true;
}, Components.interfaces.nsIThread.DISPATCH_NORMAL);
}
});
}
}.bind(this));
},

Просмотреть файл

@ -91,11 +91,6 @@ toolbarbutton.bookmark-item[open="true"] {
height: 16px;
}
#PlacesToolbarItems > .bookmark-item:not([image]):not([label=""]):not([container]) > .toolbarbutton-icon {
display: none;
}
/* Prevent [mode="icons"] from hiding the label */
.bookmark-item > .toolbarbutton-text {
display: -moz-box !important;

Просмотреть файл

@ -216,11 +216,6 @@ toolbarbutton.bookmark-item > menupopup {
max-height: 16px;
}
#PlacesToolbarItems > .bookmark-item:not([image]):not([label=""]):not([container]) > .toolbarbutton-icon {
display: none;
}
.bookmark-item > .toolbarbutton-icon[label]:not([label=""]),
.bookmark-item > .toolbarbutton-icon[type="menu"] {
-moz-margin-end: 5px;

Просмотреть файл

@ -33,17 +33,17 @@
rgba(229,114,0,0));
%else
%if MOZ_UPDATE_CHANNEL == aurora
color: hsl(214,90%,23%);
background-image: linear-gradient(hsla(208,99%,37%,0),
hsla(214,90%,23%,.5) 35%,
hsla(214,90%,23%,.5) 65%,
hsla(214,90%,23%,0));
color: rgb(51,30,84);
background-image: linear-gradient(rgba(51,30,84,0),
rgba(51,30,84,.5) 35%,
rgba(51,30,84,.5) 65%,
rgba(51,30,84,0));
%else
color: hsl(211,33%,32%);
background-image: linear-gradient(hsla(211,33%,32%,0),
hsla(211,33%,32%,.5) 35%,
hsla(211,33%,32%,.5) 65%,
hsla(211,33%,32%,0));
color: rgb(0,33,71);
background-image: linear-gradient(rgba(0,33,71,0),
rgba(0,33,71,.5) 35%,
rgba(0,33,71,.5) 65%,
rgba(0,33,71,0));
%endif
%endif
}

Просмотреть файл

@ -90,6 +90,18 @@
border-color: hsla(206,100%,60%,.65) hsla(206,100%,55%,.65) hsla(206,100%,50%,.65);
}
#sidebar-header {
-moz-appearance: none;
color: black;
background-color: #EEF3FA;
border-bottom: none;
text-shadow: none;
}
#sidebar-title {
font-weight: bold;
}
.sidebar-splitter {
border: 0;
-moz-border-end: 1px solid #A9B7C9;

Просмотреть файл

@ -612,10 +612,6 @@ toolbarbutton.bookmark-item[open="true"] {
height: 16px;
}
#PlacesToolbarItems > .bookmark-item:not([image]):not([label=""]):not([container]) > .toolbarbutton-icon {
display: none;
}
/* Prevent [mode="icons"] from hiding the label */
.bookmark-item > .toolbarbutton-text {
display: -moz-box !important;

Просмотреть файл

@ -15,4 +15,8 @@
background-color: transparent;
border-top: none;
}
.sidebar-placesTreechildren::-moz-tree-cell-text(leaf, hover) {
text-decoration: none;
}
}

Просмотреть файл

@ -244,27 +244,15 @@ if test "$OS_TARGET" = "Android" -a -z "$gonkdir"; then
else
AC_MSG_ERROR([Couldn't find path to gnu-libstdc++ in the android ndk])
fi
elif test -e "$android_ndk/sources/cxx-stl/stlport/src/iostream.cpp" ; then
if test -e "$android_ndk/sources/cxx-stl/stlport/libs/$ANDROID_CPU_ARCH/libstlport_static.a"; then
STLPORT_LDFLAGS="-L$_objdir/build/stlport -L$android_ndk/sources/cxx-stl/stlport/libs/$ANDROID_CPU_ARCH/"
elif test -e "$android_ndk/tmp/ndk-digit/build/install/sources/cxx-stl/stlport/libs/$ANDROID_CPU_ARCH/libstlport_static.a"; then
STLPORT_LDFLAGS="-L$_objdir/build/stlport -L$android_ndk/tmp/ndk-digit/build/install/sources/cxx-stl/stlport/libs/$ANDROID_CPU_ARCH/"
else
AC_MSG_ERROR([Couldn't find path to stlport in the android ndk])
fi
STLPORT_SOURCES="$android_ndk/sources/cxx-stl/stlport"
STLPORT_CPPFLAGS="-I$_objdir/build/stlport -I$android_ndk/sources/cxx-stl/stlport/stlport"
STLPORT_LIBS="-lstlport_static -static-libstdc++"
elif test "$target" != "arm-android-eabi"; then
dnl fail if we're not building with NDKr4
AC_MSG_ERROR([Couldn't find path to stlport in the android ndk])
else
STLPORT_CPPFLAGS="-I$_topsrcdir/build/stlport/stlport -I$android_ndk/sources/cxx-stl/system/include"
STLPORT_LIBS="$_objdir/build/stlport/libstlport_static.a -static-libstdc++"
fi
fi
CXXFLAGS="$CXXFLAGS $STLPORT_CPPFLAGS"
LDFLAGS="$LDFLAGS $STLPORT_LDFLAGS"
LIBS="$LIBS $STLPORT_LIBS"
fi
AC_SUBST([STLPORT_SOURCES])
AC_SUBST([MOZ_ANDROID_LIBSTDCXX])
AC_SUBST([STLPORT_LIBS])
])

Просмотреть файл

@ -0,0 +1,53 @@
#!/usr/bin/python
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import subprocess
import sys
from os import path
from buildconfig import substs
def determine_platform():
platform_mapping = {'WINNT': {'x86_64': 'win64',
'i386': 'win32'},
'Darwin': {'x86_64': 'macosx-universal',
'i386':'macosx-universal'},
'Linux': {'x86_64': 'linux64',
'i386': 'linux32'}}
os_type = substs['OS_TARGET']
cpu_type = substs['TARGET_CPU']
return platform_mapping.get(os_type, {}).get(cpu_type, None)
def main():
""" A wrapper script that calls compare-mozconfig.py
based on the platform that the machine is building for"""
platform = determine_platform()
if platform is not None:
python_exe = substs['PYTHON']
topsrcdir = substs['top_srcdir']
# construct paths and args for compare-mozconfig
browser_dir = path.join(topsrcdir, 'browser')
script_path = path.join(topsrcdir, 'build/compare-mozconfig/compare-mozconfigs.py')
whitelist_path = path.join(browser_dir, 'config/mozconfigs/whitelist')
beta_mozconfig_path = path.join(browser_dir, 'config/mozconfigs', platform, 'beta')
release_mozconfig_path = path.join(browser_dir, 'config/mozconfigs', platform, 'release')
nightly_mozconfig_path = path.join(browser_dir, 'config/mozconfigs', platform, 'nightly')
# compare beta vs nightly
ret_code = subprocess.call([python_exe, script_path, '--whitelist',
whitelist_path, '--no-download',
platform + ',' + beta_mozconfig_path +
',' + nightly_mozconfig_path])
if ret_code > 0:
sys.exit(ret_code)
# compare release vs nightly
ret_code = subprocess.call([python_exe, script_path, '--whitelist',
whitelist_path, '--no-download',
platform + ',' + release_mozconfig_path +
',' + nightly_mozconfig_path])

Просмотреть файл

@ -0,0 +1,68 @@
#!/usr/bin/python
import logging
import os
import site
import sys
import urllib2
site.addsitedir(os.path.join(os.path.dirname(__file__), "../../lib/python"))
from release.sanity import verify_mozconfigs
from release.info import readConfig
from util.hg import make_hg_url
FAILURE_CODE = 1
SUCCESS_CODE = 0
def get_mozconfig(path, options):
"""Consumes a path and returns a list of lines from
the mozconfig file. If download is required, the path
specified should be relative to the root of the hg
repository e.g browser/config/mozconfigs/linux32/nightly"""
if options.no_download:
return open(path, 'r').readlines()
else:
url = make_hg_url(options.hghost, options.branch, 'http',
options.revision, path)
return urllib2.urlopen(url).readlines()
if __name__ == '__main__':
from optparse import OptionParser
parser = OptionParser()
parser.add_option('--branch', dest='branch')
parser.add_option('--revision', dest='revision')
parser.add_option('--hghost', dest='hghost', default='hg.mozilla.org')
parser.add_option('--whitelist', dest='whitelist')
parser.add_option('--no-download', action='store_true', dest='no_download',
default=False)
options, args = parser.parse_args()
logging.basicConfig(level=logging.INFO)
missing_args = options.branch is None or options.revision is None
if not options.no_download and missing_args:
logging.error('Not enough arguments to download mozconfigs')
sys.exit(FAILURE_CODE)
mozconfig_whitelist = readConfig(options.whitelist, ['whitelist'])
for arg in args:
platform, mozconfig_path, nightly_mozconfig_path = arg.split(',')
mozconfig_lines = get_mozconfig(mozconfig_path, options)
nightly_mozconfig_lines = get_mozconfig(nightly_mozconfig_path, options)
mozconfig_pair = (mozconfig_path, mozconfig_lines)
nightly_mozconfig_pair = (nightly_mozconfig_path,
nightly_mozconfig_lines)
passed = verify_mozconfigs(mozconfig_pair, nightly_mozconfig_pair,
platform, mozconfig_whitelist)
if passed:
logging.info('Mozconfig check passed!')
else:
logging.error('Mozconfig check failed!')
sys.exit(FAILURE_CODE)
sys.exit(SUCCESS_CODE)

Просмотреть файл

@ -19,8 +19,7 @@ toolkit/library
security/manager
security/dbm
security/nss
accessible/build
accessible
accessible
dom
content
layout

Просмотреть файл

@ -131,6 +131,7 @@ def bootstrap(topsrcdir, mozilla_dir=None):
os.makedirs(state_env_dir, mode=0o770)
print('Please re-run mach.')
sys.exit(1)
state_dir = state_env_dir
else:
if not os.path.exists(state_user_dir):
print(STATE_DIR_FIRST_RUN.format(userdir=state_user_dir))
@ -146,6 +147,7 @@ def bootstrap(topsrcdir, mozilla_dir=None):
os.mkdir(state_user_dir)
print('Please re-run mach.')
sys.exit(1)
state_dir = state_user_dir
try:
import mach.main
@ -153,7 +155,12 @@ def bootstrap(topsrcdir, mozilla_dir=None):
sys.path[0:0] = [os.path.join(mozilla_dir, path) for path in SEARCH_PATHS]
import mach.main
def populate_context(context):
context.state_dir = state_dir
mach = mach.main.Mach(topsrcdir)
mach.populate_context_handler = populate_context
for category, meta in CATEGORIES.items():
mach.define_category(category, meta['short'], meta['long'],
meta['priority'])

Просмотреть файл

@ -9,7 +9,7 @@ if CONFIG['OS_ARCH'] not in ('WINNT', 'OS2'):
elif CONFIG['OS_ARCH'] == 'WINNT':
DIRS += ['win32']
if CONFIG['STLPORT_SOURCES']:
if CONFIG['OS_TARGET'] == 'Android' and not CONFIG['MOZ_ANDROID_LIBSTDCXX']:
DIRS += ['stlport']
if CONFIG['MOZ_WIDGET_TOOLKIT'] == 'android':

218
build/release/info.py Normal file
Просмотреть файл

@ -0,0 +1,218 @@
from datetime import datetime
import os
from os import path
import re
import shutil
import sys
from urllib2 import urlopen
from release.paths import makeCandidatesDir
import logging
log = logging.getLogger(__name__)
# If version has two parts with no trailing specifiers like "rc", we
# consider it a "final" release for which we only create a _RELEASE tag.
FINAL_RELEASE_REGEX = "^\d+\.\d+$"
class ConfigError(Exception):
pass
def getBuildID(platform, product, version, buildNumber, nightlyDir='nightly',
server='stage.mozilla.org'):
infoTxt = makeCandidatesDir(product, version, buildNumber, nightlyDir,
protocol='http', server=server) + \
'%s_info.txt' % platform
try:
buildInfo = urlopen(infoTxt).read()
except:
log.error("Failed to retrieve %s" % infoTxt)
raise
for line in buildInfo.splitlines():
key, value = line.rstrip().split('=', 1)
if key == 'buildID':
return value
def findOldBuildIDs(product, version, buildNumber, platforms,
nightlyDir='nightly', server='stage.mozilla.org'):
ids = {}
if buildNumber <= 1:
return ids
for n in range(1, buildNumber):
for platform in platforms:
if platform not in ids:
ids[platform] = []
try:
id = getBuildID(platform, product, version, n, nightlyDir,
server)
ids[platform].append(id)
except Exception, e:
log.error("Hit exception: %s" % e)
return ids
def getReleaseConfigName(product, branch, version=None, staging=False):
# XXX: Horrible hack for bug 842741. Because Thunderbird release
# and esr both build out of esr17 repositories we'll bump the wrong
# config for release without this.
if product == 'thunderbird' and 'esr17' in branch and version and 'esr' not in version:
cfg = 'release-thunderbird-comm-release.py'
else:
cfg = 'release-%s-%s.py' % (product, branch)
if staging:
cfg = 'staging_%s' % cfg
return cfg
def readReleaseConfig(configfile, required=[]):
return readConfig(configfile, keys=['releaseConfig'], required=required)
def readBranchConfig(dir, localconfig, branch, required=[]):
shutil.copy(localconfig, path.join(dir, "localconfig.py"))
oldcwd = os.getcwd()
os.chdir(dir)
sys.path.append(".")
try:
return readConfig("config.py", keys=['BRANCHES', branch],
required=required)
finally:
os.chdir(oldcwd)
sys.path.remove(".")
def readConfig(configfile, keys=[], required=[]):
c = {}
execfile(configfile, c)
for k in keys:
c = c[k]
items = c.keys()
err = False
for key in required:
if key not in items:
err = True
log.error("Required item `%s' missing from %s" % (key, c))
if err:
raise ConfigError("Missing at least one item in config, see above")
return c
def isFinalRelease(version):
return bool(re.match(FINAL_RELEASE_REGEX, version))
def getBaseTag(product, version):
product = product.upper()
version = version.replace('.', '_')
return '%s_%s' % (product, version)
def getTags(baseTag, buildNumber, buildTag=True):
t = ['%s_RELEASE' % baseTag]
if buildTag:
t.append('%s_BUILD%d' % (baseTag, int(buildNumber)))
return t
def getRuntimeTag(tag):
return "%s_RUNTIME" % tag
def getReleaseTag(tag):
return "%s_RELEASE" % tag
def generateRelbranchName(version, prefix='GECKO'):
return '%s%s_%s_RELBRANCH' % (
prefix, version.replace('.', ''),
datetime.now().strftime('%Y%m%d%H'))
def getReleaseName(product, version, buildNumber):
return '%s-%s-build%s' % (product.title(), version, str(buildNumber))
def getRepoMatchingBranch(branch, sourceRepositories):
for sr in sourceRepositories.values():
if branch in sr['path']:
return sr
return None
def fileInfo(filepath, product):
"""Extract information about a release file. Returns a dictionary with the
following keys set:
'product', 'version', 'locale', 'platform', 'contents', 'format',
'pathstyle'
'contents' is one of 'complete', 'installer'
'format' is one of 'mar' or 'exe'
'pathstyle' is either 'short' or 'long', and refers to if files are all in
one directory, with the locale as part of the filename ('short' paths,
firefox 3.0 style filenames), or if the locale names are part of the
directory structure, but not the file name itself ('long' paths,
firefox 3.5+ style filenames)
"""
try:
# Mozilla 1.9.0 style (aka 'short') paths
# e.g. firefox-3.0.12.en-US.win32.complete.mar
filename = os.path.basename(filepath)
m = re.match("^(%s)-([0-9.]+)\.([-a-zA-Z]+)\.(win32)\.(complete|installer)\.(mar|exe)$" % product, filename)
if not m:
raise ValueError("Could not parse: %s" % filename)
return {'product': m.group(1),
'version': m.group(2),
'locale': m.group(3),
'platform': m.group(4),
'contents': m.group(5),
'format': m.group(6),
'pathstyle': 'short',
'leading_path': '',
}
except:
# Mozilla 1.9.1 and on style (aka 'long') paths
# e.g. update/win32/en-US/firefox-3.5.1.complete.mar
# win32/en-US/Firefox Setup 3.5.1.exe
ret = {'pathstyle': 'long'}
if filepath.endswith('.mar'):
ret['format'] = 'mar'
m = re.search("update/(win32|linux-i686|linux-x86_64|mac|mac64)/([-a-zA-Z]+)/(%s)-(\d+\.\d+(?:\.\d+)?(?:\w+(?:\d+)?)?)\.(complete)\.mar" % product, filepath)
if not m:
raise ValueError("Could not parse: %s" % filepath)
ret['platform'] = m.group(1)
ret['locale'] = m.group(2)
ret['product'] = m.group(3)
ret['version'] = m.group(4)
ret['contents'] = m.group(5)
ret['leading_path'] = ''
elif filepath.endswith('.exe'):
ret['format'] = 'exe'
ret['contents'] = 'installer'
# EUballot builds use a different enough style of path than others
# that we can't catch them in the same regexp
if filepath.find('win32-EUballot') != -1:
ret['platform'] = 'win32'
m = re.search("(win32-EUballot/)([-a-zA-Z]+)/((?i)%s) Setup (\d+\.\d+(?:\.\d+)?(?:\w+\d+)?(?:\ \w+\ \d+)?)\.exe" % product, filepath)
if not m:
raise ValueError("Could not parse: %s" % filepath)
ret['leading_path'] = m.group(1)
ret['locale'] = m.group(2)
ret['product'] = m.group(3).lower()
ret['version'] = m.group(4)
else:
m = re.search("(partner-repacks/[-a-zA-Z0-9_]+/|)(win32|mac|linux-i686)/([-a-zA-Z]+)/((?i)%s) Setup (\d+\.\d+(?:\.\d+)?(?:\w+(?:\d+)?)?(?:\ \w+\ \d+)?)\.exe" % product, filepath)
if not m:
raise ValueError("Could not parse: %s" % filepath)
ret['leading_path'] = m.group(1)
ret['platform'] = m.group(2)
ret['locale'] = m.group(3)
ret['product'] = m.group(4).lower()
ret['version'] = m.group(5)
else:
raise ValueError("Unknown filetype for %s" % filepath)
return ret

124
build/release/sanity.py Normal file
Просмотреть файл

@ -0,0 +1,124 @@
import difflib
import logging
import re
import urllib2
from util.commands import run_cmd, get_output
from util.hg import get_repo_name, make_hg_url
from subprocess import CalledProcessError
log = logging.getLogger(__name__)
def check_buildbot():
"""check if buildbot command works"""
try:
run_cmd(['buildbot', '--version'])
except CalledProcessError:
log.error("FAIL: buildbot command doesn't work", exc_info=True)
raise
def find_version(contents, versionNumber):
"""Given an open readable file-handle look for the occurrence
of the version # in the file"""
ret = re.search(re.compile(re.escape(versionNumber), re.DOTALL), contents)
return ret
def locale_diff(locales1, locales2):
""" accepts two lists and diffs them both ways, returns any differences
found """
diff_list = [locale for locale in locales1 if not locale in locales2]
diff_list.extend(locale for locale in locales2 if not locale in locales1)
return diff_list
def get_buildbot_username_param():
cmd = ['buildbot', 'sendchange', '--help']
output = get_output(cmd)
if "-W, --who=" in output:
return "--who"
else:
return "--username"
def sendchange(branch, revision, username, master, products):
"""Send the change to buildbot to kick off the release automation"""
if isinstance(products, basestring):
products = [products]
cmd = [
'buildbot',
'sendchange',
get_buildbot_username_param(),
username,
'--master',
master,
'--branch',
branch,
'-p',
'products:%s' % ','.join(products),
'-p',
'script_repo_revision:%s' % revision,
'release_build'
]
logging.info("Executing: %s" % cmd)
run_cmd(cmd)
def verify_mozconfigs(mozconfig_pair, nightly_mozconfig_pair, platform,
mozconfigWhitelist={}):
"""Compares mozconfig to nightly_mozconfig and compare to an optional
whitelist of known differences. mozconfig_pair and nightly_mozconfig_pair
are pairs containing the mozconfig's identifier and the list of lines in
the mozconfig."""
# unpack the pairs to get the names, the names are just for
# identifying the mozconfigs when logging the error messages
mozconfig_name, mozconfig_lines = mozconfig_pair
nightly_mozconfig_name, nightly_mozconfig_lines = nightly_mozconfig_pair
missing_args = mozconfig_lines == [] or nightly_mozconfig_lines == []
if missing_args:
log.info("Missing mozconfigs to compare for %s" % platform)
return False
success = True
diffInstance = difflib.Differ()
diff_result = diffInstance.compare(mozconfig_lines, nightly_mozconfig_lines)
diffList = list(diff_result)
for line in diffList:
clean_line = line[1:].strip()
if (line[0] == '-' or line[0] == '+') and len(clean_line) > 1:
# skip comment lines
if clean_line.startswith('#'):
continue
# compare to whitelist
message = ""
if line[0] == '-':
if platform in mozconfigWhitelist.get('release', {}):
if clean_line in \
mozconfigWhitelist['release'][platform]:
continue
elif line[0] == '+':
if platform in mozconfigWhitelist.get('nightly', {}):
if clean_line in \
mozconfigWhitelist['nightly'][platform]:
continue
else:
log.warning("%s not in %s %s!" % (
clean_line, platform,
mozconfigWhitelist['nightly'][platform]))
else:
log.error("Skipping line %s!" % line)
continue
message = "found in %s but not in %s: %s"
if line[0] == '-':
log.error(message % (mozconfig_name,
nightly_mozconfig_name, clean_line))
else:
log.error(message % (nightly_mozconfig_name,
mozconfig_name, clean_line))
success = False
return success

115
build/stlport/Android.mk Normal file
Просмотреть файл

@ -0,0 +1,115 @@
LOCAL_PATH := $(call my-dir)
# Normally, we distribute the NDK with prebuilt binaries of STLport
# in $LOCAL_PATH/<abi>/. However,
#
STLPORT_FORCE_REBUILD := $(strip $(STLPORT_FORCE_REBUILD))
ifndef STLPORT_FORCE_REBUILD
ifeq (,$(strip $(wildcard $(LOCAL_PATH)/libs/$(TARGET_ARCH_ABI)/libstlport_static.a)))
$(call __ndk_info,WARNING: Rebuilding STLport libraries from sources!)
$(call __ndk_info,You might want to use $$NDK/build/tools/build-stlport.sh)
$(call __ndk_info,in order to build prebuilt versions to speed up your builds!)
STLPORT_FORCE_REBUILD := true
endif
endif
libstlport_path := $(LOCAL_PATH)
libstlport_src_files := \
src/dll_main.cpp \
src/fstream.cpp \
src/strstream.cpp \
src/sstream.cpp \
src/ios.cpp \
src/stdio_streambuf.cpp \
src/istream.cpp \
src/ostream.cpp \
src/iostream.cpp \
src/codecvt.cpp \
src/collate.cpp \
src/ctype.cpp \
src/monetary.cpp \
src/num_get.cpp \
src/num_put.cpp \
src/num_get_float.cpp \
src/num_put_float.cpp \
src/numpunct.cpp \
src/time_facets.cpp \
src/messages.cpp \
src/locale.cpp \
src/locale_impl.cpp \
src/locale_catalog.cpp \
src/facets_byname.cpp \
src/complex.cpp \
src/complex_io.cpp \
src/complex_trig.cpp \
src/string.cpp \
src/bitset.cpp \
src/allocators.cpp \
src/c_locale.c \
src/cxa.c \
libstlport_cflags := -D_GNU_SOURCE
libstlport_cppflags := -fuse-cxa-atexit
libstlport_c_includes := $(libstlport_path)/stlport
#It is much more practical to include the sources of GAbi++ in our builds
# of STLport. This is similar to what the GNU libstdc++ does (it includes
# its own copy of libsupc++)
#
# This simplifies usage, since you only have to list a single library
# as a dependency, instead of two, especially when using the standalone
# toolchain.
#
include $(dir $(LOCAL_PATH))/gabi++/sources.mk
libstlport_c_includes += $(libgabi++_c_includes)
ifneq ($(STLPORT_FORCE_REBUILD),true)
$(call ndk_log,Using prebuilt STLport libraries)
include $(CLEAR_VARS)
LOCAL_MODULE := stlport_static
LOCAL_SRC_FILES := libs/$(TARGET_ARCH_ABI)/lib$(LOCAL_MODULE).a
LOCAL_EXPORT_C_INCLUDES := $(libstlport_c_includes)
LOCAL_CPP_FEATURES := rtti
include $(PREBUILT_STATIC_LIBRARY)
include $(CLEAR_VARS)
LOCAL_MODULE := stlport_shared
LOCAL_SRC_FILES := libs/$(TARGET_ARCH_ABI)/lib$(LOCAL_MODULE).so
LOCAL_EXPORT_C_INCLUDES := $(libstlport_c_includes)
LOCAL_CPP_FEATURES := rtti
include $(PREBUILT_SHARED_LIBRARY)
else # STLPORT_FORCE_REBUILD == true
$(call ndk_log,Rebuilding STLport libraries from sources)
include $(CLEAR_VARS)
LOCAL_MODULE := stlport_static
LOCAL_CPP_EXTENSION := .cpp .cc
LOCAL_SRC_FILES := $(libstlport_src_files)
LOCAL_SRC_FILES += $(libgabi++_src_files:%=../gabi++/%)
LOCAL_CFLAGS := $(libstlport_cflags)
LOCAL_CPPFLAGS := $(libstlport_cppflags)
LOCAL_C_INCLUDES := $(libstlport_c_includes)
LOCAL_EXPORT_C_INCLUDES := $(libstlport_c_includes)
LOCAL_CPP_FEATURES := rtti exceptions
include $(BUILD_STATIC_LIBRARY)
include $(CLEAR_VARS)
LOCAL_MODULE := stlport_shared
LOCAL_CPP_EXTENSION := .cpp .cc
LOCAL_SRC_FILES := $(libstlport_src_files)
LOCAL_SRC_FILES += $(libgabi++_src_files:%=../gabi++/%)
LOCAL_CFLAGS := $(libstlport_cflags)
LOCAL_CPPFLAGS := $(libstlport_cppflags)
LOCAL_C_INCLUDES := $(libstlport_c_includes)
LOCAL_EXPORT_C_INCLUDES := $(libstlport_c_includes)
LOCAL_CPP_FEATURES := rtti exceptions
include $(BUILD_SHARED_LIBRARY)
endif # STLPORT_FORCE_REBUILD == true

27
build/stlport/LICENSE Normal file
Просмотреть файл

@ -0,0 +1,27 @@
Boris Fomitchev grants Licensee a non-exclusive, non-transferable, royalty-free license to use STLport and its documentation without fee.
By downloading, using, or copying STLport or any portion thereof, Licensee agrees to abide by the intellectual property laws and all other applicable laws of the United States of America, and to all of the terms and conditions of this Agreement.
Licensee shall maintain the following copyright and permission notices on STLport sources and its documentation unchanged :
Copyright 1999,2000 Boris Fomitchev
This material is provided "as is", with absolutely no warranty expressed or implied. Any use is at your own risk.
Permission to use or copy this software for any purpose is hereby granted without fee, provided the above notices are retained on all copies. Permission to modify the code and to distribute modified code is granted, provided the above notices are retained, and a notice that the code was modified is included with the above copyright notice.
The Licensee may distribute binaries compiled with STLport (whether original or modified) without any royalties or restrictions.
The Licensee may distribute original or modified STLport sources, provided that:
The conditions indicated in the above permission notice are met;
The following copyright notices are retained when present, and conditions provided in accompanying permission notices are met :
Copyright 1994 Hewlett-Packard Company
Copyright 1996,97 Silicon Graphics Computer Systems, Inc.
Copyright 1997 Moscow Center for SPARC Technology.
Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. Hewlett-Packard Company makes no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty.
Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. Silicon Graphics makes no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty.
Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. Moscow Center for SPARC Technology makes no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty.

Просмотреть файл

Просмотреть файл

@ -17,12 +17,12 @@ STL_FLAGS =
# installing it in dist/lib.
LIBRARY = $(LIB_PREFIX)$(LIBRARY_NAME).$(LIB_SUFFIX)
VPATH += $(STLPORT_SOURCES)/src
VPATH += $(srcdir)/src
CSRCS = $(notdir $(wildcard $(STLPORT_SOURCES)/src/*.c))
CSRCS = $(notdir $(wildcard $(srcdir)/src/*.c))
include $(topsrcdir)/config/rules.mk
DEFINES += -D_GNU_SOURCE
CXXFLAGS += -fuse-cxa-atexit
INCLUDES += -I$(STLPORT_SOURCES)/stlport
INCLUDES += -I$(srcdir)/stlport

69
build/stlport/README Normal file
Просмотреть файл

@ -0,0 +1,69 @@
STLport for Android
WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
This feature is currently in beta. In case of issue
please contact the android-ndk support forum or
file bugs at http://b.android.com
WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
This directory contains a port of STLport for Android, which provides
a simple STL implementation. Note that it currently does not support
C++ exceptions and RTTI. Support for wchar_t and locales is probably buggy.
You can either use it as a static or shared library.
1/ The static library is recommended if you will only produce
one shared library for your project. All necessary STLport functions
will be added to it. This option should also generate smaller
overall binaries.
2/ The shared library, is recommended if you want to produce
several shared libraries in your project, because it avoids copying the
same STLport functions to each one of them, and having different instances
of the same global variables (which can easily conflict or result in
undefined behaviour).
To use the *static* library, define APP_STL in your Application.mk as follows:
APP_STL := stlport_static
To use the *shared* library, use "stlport_shared" instead:
APP_STL := stlport_shared
Note that, in this case, you will need, in your application, to explicitely
load the 'stlport_shared' library before any library that depends on it.
For example:
static {
System.loadLibrary("stlport_shared");
System.loadLibrary("foo");
System.loadLibrary("bar");
}
If both libfoo.so and libbar.so depend on STLport.
You can build the STLport unit test program by doing the following:
cd $NDK
tests/run-tests.sh --test=test-stlport
If you have an Android device connected to your machine, this will
automatically try to run the generated test command. Note that for now
a few tests are still failing (mostly related to wchar_t and locales).
They should be fixed hopefully by a later release of this library.
The NDK comes with prebuilt binaries for this library to speed up development.
You can however rebuild them from sources in your own application build by
defining STLPORT_FORCE_REBUILD to 'true' in your Application.mk as in:
STLPORT_FORCE_REBUILD := true
VERSION INFORMATION: This module is based on STLport version 5.2.0

Просмотреть файл

@ -0,0 +1,9 @@
Version: 5.2.1
Changes:
* Added _android.h included by _system.h
* Do not use linux float functions in num_get_float.cpp as Android does not
have them.
* _mbstate_t.h cannot define its own mbstate_t as bionic already defines
it.
* _pair.h needs to define bionic's (sgi's) internal pair header guard.

Просмотреть файл

@ -0,0 +1,7 @@
This copy of STLport was taken from the Android NDK r8e.
Android specific changes are listed in README.android.
The libs/ directory containing prebuilt static libraries was removed.
The following patches are applied on top:
- android-mozilla-config.patch: Adjusts Android-specific configuration
to the mozilla codebase use of the STL.

Просмотреть файл

@ -0,0 +1,64 @@
**********************************************************************
* README file for STLport 5.0 *
* *
**********************************************************************
This directory contains the STLport-5.0 release.
What's inside :
README - this file
INSTALL - installation instructions
bin - installation directory for STLport unit tests;
it may contain more subdirs, if you use
crosscompilation
build/lib - build directory for STLport library (if you use
STLport iostreams and/or locale only)
build/test/unit - build directory for regression (unit) tests
build/test/eh - build directory for exception handling tests
stlport - main STLport include directory
src - source for iostreams implementation and other parts
that aren't pure template code
lib - installation directory for STLport library (if you
use STLport iostreams and/or locale only);
it may contain more subdirs, if you use
crosscompilation
test/unit - unit (regression) tests
test/eh - exception handling test using STLport iostreams
etc - miscellanous files (ChangeLog, TODO, scripts, etc.)
GETTING STLPORT
To download the latest version of STLport, please be sure to visit
https://sourceforge.net/project/showfiles.php?group_id=146814
LEGALESE
This software is being distributed under the following terms:
*
*
* Copyright (c) 1994
* Hewlett-Packard Company
*
* Copyright (c) 1996-1999
* Silicon Graphics Computer Systems, Inc.
*
* Copyright (c) 1997
* Moscow Center for SPARC Technology
*
* Copyright (c) 1999-2003
* Boris Fomitchev
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
**********************************************************************

Просмотреть файл

@ -0,0 +1,82 @@
diff --git a/stlport/stl/config/_android.h b/stlport/stl/config/_android.h
--- a/stlport/stl/config/_android.h
+++ b/stlport/stl/config/_android.h
@@ -10,18 +10,18 @@
#define _PTHREADS
// Don't have native <cplusplus> headers
#define _STLP_HAS_NO_NEW_C_HEADERS 1
// Use unix for streams
#define _STLP_USE_UNIX_IO 1
-// We do have rtti support now through GAbi++
-#undef _STLP_NO_RTTI
+// We don't want rtti support
+#define _STLP_NO_RTTI 1
// C library is in the global namespace.
#define _STLP_VENDOR_GLOBAL_CSTD 1
// Don't have underlying local support.
#undef _STLP_REAL_LOCALE_IMPLEMENTED
// No pthread_spinlock_t in Android
@@ -32,48 +32,42 @@
// Little endian platform.
#define _STLP_LITTLE_ENDIAN 1
// No <exception> headers
#undef _STLP_NO_EXCEPTION_HEADER
// No throwing exceptions
-#undef _STLP_NO_EXCEPTIONS
-
+#define _STLP_NO_EXCEPTIONS 1
+#define _STLP_NO_EXCEPTION_HEADER 1
// No need to define our own namespace
#define _STLP_NO_OWN_NAMESPACE 1
// Use __new_alloc instead of __node_alloc, so we don't need static functions.
#define _STLP_USE_SIMPLE_NODE_ALLOC 1
// Don't use extern versions of range errors, so we don't need to
// compile as a library.
#define _STLP_USE_NO_EXTERN_RANGE_ERRORS 1
// The system math library doesn't have long double variants, e.g
// sinl, cosl, etc
#define _STLP_NO_VENDOR_MATH_L 1
-// Define how to include our native headers.
-#define _STLP_NATIVE_HEADER(header) <usr/include/header>
-#define _STLP_NATIVE_C_HEADER(header) <../include/header>
-#define _STLP_NATIVE_CPP_C_HEADER(header) <../../gabi++/include/header>
-#define _STLP_NATIVE_CPP_RUNTIME_HEADER(header) <../../gabi++/include/header>
-#define _STLP_NATIVE_OLD_STREAMS_HEADER(header) <usr/include/header>
-
// Include most of the gcc settings.
#include <stl/config/_gcc.h>
// Do not use glibc, Android is missing some things.
#undef _STLP_USE_GLIBC
// No exceptions.
-#undef _STLP_NO_UNCAUGHT_EXCEPT_SUPPORT
-#undef _STLP_NO_UNEXPECTED_EXCEPT_SUPPORT
+#define _STLP_NO_UNCAUGHT_EXCEPT_SUPPORT 1
+#define _STLP_NO_UNEXPECTED_EXCEPT_SUPPORT 1
-#ifndef _ANDROID_NDK_BLAZE_
-// Android does have include_next but it doesn't work well in our build system.
-#undef _STLP_HAS_INCLUDE_NEXT
-#endif
+#define _STLP_HAS_INCLUDE_NEXT 1
+
+// Use operator new instead of stlport own node allocator
+#undef _STLP_USE_NEWALLOC
+#define _STLP_USE_NEWALLOC 1
#endif /* __stl_config__android_h */

Просмотреть файл

@ -4,10 +4,8 @@
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
CONFIGURE_SUBST_FILES += ['stl/config/_android.h']
CPP_SOURCES += [
'$(notdir $(wildcard $(STLPORT_SOURCES)/src/*.cpp))',
'$(notdir $(wildcard $(srcdir)/src/*.cpp))',
]
LIBRARY_NAME = 'stlport_static'

Просмотреть файл

@ -0,0 +1,117 @@
/*
* Copyright (c) 1999
* Silicon Graphics Computer Systems, Inc.
*
* Copyright (c) 1999
* Boris Fomitchev
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
#ifndef _STLP_STDIO_FILE_H
#define _STLP_STDIO_FILE_H
/* This file provides a low-level interface between the internal
* representation of struct FILE, from the C stdio library, and
* the C++ I/O library. */
#ifndef _STLP_CSTDIO
# include <cstdio>
#endif
#ifndef _STLP_CSTDDEF
# include <cstddef>
#endif
#if defined (__MSL__)
# include <unix.h> /* get the definition of fileno */
#endif
_STLP_BEGIN_NAMESPACE
#if defined (_STLP_WCE)
inline int _FILE_fd(const FILE *__f) {
/* Check if FILE is one of the three standard streams
We do this check first, because invoking _fileno() on one of them
causes a terminal window to be created. This also happens if you do
any IO on them, but merely retrieving the filedescriptor shouldn't
already do that.
Obviously this is pretty implementation-specific because it requires
that indeed the first three FDs are always the same, but that is not
only common but almost guaranteed. */
for (int __fd = 0; __fd != 3; ++__fd) {
if (__f == _getstdfilex(__fd))
return __fd;
}
/* Normal files. */
return (int)::_fileno((FILE*)__f);
}
# elif defined (_STLP_SCO_OPENSERVER) || defined (__NCR_SVR)
inline int _FILE_fd(const FILE *__f) { return __f->__file; }
# elif defined (__sun) && defined (_LP64)
inline int _FILE_fd(const FILE *__f) { return (int) __f->__pad[2]; }
#elif defined (__hpux) /* && defined(__hppa) && defined(__HP_aCC)) */ || \
defined (__MVS__) || \
defined (_STLP_USE_UCLIBC) /* should be before _STLP_USE_GLIBC */
inline int _FILE_fd(const FILE *__f) { return fileno(__CONST_CAST(FILE*, __f)); }
#elif defined (_STLP_USE_GLIBC)
inline int _FILE_fd(const FILE *__f) { return __f->_fileno; }
#elif defined (__BORLANDC__)
inline int _FILE_fd(const FILE *__f) { return __f->fd; }
#elif defined (__MWERKS__)
/* using MWERKS-specific defines here to detect other OS targets
* dwa: I'm not sure they provide fileno for all OS's, but this should
* work for Win32 and WinCE
* Hmm, at least for Novell NetWare __dest_os == __mac_os true too..
* May be both __dest_os and __mac_os defined and empty? - ptr */
# if __dest_os == __mac_os
inline int _FILE_fd(const FILE *__f) { return ::fileno(__CONST_CAST(FILE*, __f)); }
# else
inline int _FILE_fd(const FILE *__f) { return ::_fileno(__CONST_CAST(FILE*, __f)); }
# endif
#elif defined (__QNXNTO__) || defined (__WATCOMC__) || defined (__EMX__)
inline int _FILE_fd(const FILE *__f) { return __f->_handle; }
#elif defined (__Lynx__)
/* the prototypes are taken from LynxOS patch for STLport 4.0 */
inline int _FILE_fd(const FILE *__f) { return __f->_fd; }
#else /* The most common access to file descriptor. */
inline int _FILE_fd(const FILE *__f) { return __f->_file; }
#endif
_STLP_END_NAMESPACE
#endif /* _STLP_STDIO_FILE_H */
/* Local Variables:
* mode:C++
* End: */

Просмотреть файл

@ -0,0 +1,46 @@
/*
* Copyright (c) 1999
* Silicon Graphics Computer Systems, Inc.
*
* Copyright (c) 1999
* Boris Fomitchev
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
#ifndef ACQUIRE_RELEASE_H
#define ACQUIRE_RELEASE_H
#include "c_locale.h"
_STLP_BEGIN_NAMESPACE
_STLP_MOVE_TO_PRIV_NAMESPACE
_Locale_ctype* _STLP_CALL __acquire_ctype(const char* &name, char *buf, _Locale_name_hint* hint, int *__err_code);
_Locale_codecvt* _STLP_CALL __acquire_codecvt(const char* &name, char *buf, _Locale_name_hint* hint, int *__err_code);
_Locale_numeric* _STLP_CALL __acquire_numeric(const char* &name, char *buf, _Locale_name_hint* hint, int *__err_code);
_Locale_collate* _STLP_CALL __acquire_collate(const char* &name, char *buf, _Locale_name_hint* hint, int *__err_code);
_Locale_monetary* _STLP_CALL __acquire_monetary(const char* &name, char *buf, _Locale_name_hint* hint, int *__err_code);
_Locale_time* _STLP_CALL __acquire_time(const char* &name, char *buf, _Locale_name_hint*, int *__err_code);
_Locale_messages* _STLP_CALL __acquire_messages(const char* &name, char *buf, _Locale_name_hint* hint, int *__err_code);
void _STLP_CALL __release_ctype(_Locale_ctype* cat);
void _STLP_CALL __release_codecvt(_Locale_codecvt* cat);
void _STLP_CALL __release_numeric(_Locale_numeric* cat);
void _STLP_CALL __release_collate(_Locale_collate* cat);
void _STLP_CALL __release_monetary(_Locale_monetary* cat);
void _STLP_CALL __release_time(_Locale_time* __time);
void _STLP_CALL __release_messages(_Locale_messages* cat);
_STLP_MOVE_TO_STD_NAMESPACE
_STLP_END_NAMESPACE
#endif /* ACQUIRE_RELEASE_H */

Просмотреть файл

@ -0,0 +1,21 @@
#ifndef ALIGNED_BUFFER_H
#define ALIGNED_BUFFER_H
_STLP_BEGIN_NAMESPACE
// this is for fake initialization
template<class T>
union _Stl_aligned_buffer {
char buf[sizeof(T)];
struct { double a; double b; } padding;
T* operator&() {
return __REINTERPRET_CAST(T*, this);
}
T const* operator&() const {
return __REINTERPRET_CAST(T const*, this);
}
};
_STLP_END_NAMESPACE
#endif

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -0,0 +1,156 @@
/*
* Copyright (c) 1998
* Silicon Graphics Computer Systems, Inc.
*
* Copyright (c) 1999
* Boris Fomitchev
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
#include "stlport_prefix.h"
#include <bitset>
_STLP_BEGIN_NAMESPACE
_STLP_MOVE_TO_PRIV_NAMESPACE
// ------------------------------------------------------------
// Lookup tables for find and count operations.
size_t _Bs_G::_S_count(const unsigned char *__first,
const unsigned char *__last)
{
static const unsigned char _bit_count[256] = {
0, /* 0 */ 1, /* 1 */ 1, /* 2 */ 2, /* 3 */ 1, /* 4 */
2, /* 5 */ 2, /* 6 */ 3, /* 7 */ 1, /* 8 */ 2, /* 9 */
2, /* 10 */ 3, /* 11 */ 2, /* 12 */ 3, /* 13 */ 3, /* 14 */
4, /* 15 */ 1, /* 16 */ 2, /* 17 */ 2, /* 18 */ 3, /* 19 */
2, /* 20 */ 3, /* 21 */ 3, /* 22 */ 4, /* 23 */ 2, /* 24 */
3, /* 25 */ 3, /* 26 */ 4, /* 27 */ 3, /* 28 */ 4, /* 29 */
4, /* 30 */ 5, /* 31 */ 1, /* 32 */ 2, /* 33 */ 2, /* 34 */
3, /* 35 */ 2, /* 36 */ 3, /* 37 */ 3, /* 38 */ 4, /* 39 */
2, /* 40 */ 3, /* 41 */ 3, /* 42 */ 4, /* 43 */ 3, /* 44 */
4, /* 45 */ 4, /* 46 */ 5, /* 47 */ 2, /* 48 */ 3, /* 49 */
3, /* 50 */ 4, /* 51 */ 3, /* 52 */ 4, /* 53 */ 4, /* 54 */
5, /* 55 */ 3, /* 56 */ 4, /* 57 */ 4, /* 58 */ 5, /* 59 */
4, /* 60 */ 5, /* 61 */ 5, /* 62 */ 6, /* 63 */ 1, /* 64 */
2, /* 65 */ 2, /* 66 */ 3, /* 67 */ 2, /* 68 */ 3, /* 69 */
3, /* 70 */ 4, /* 71 */ 2, /* 72 */ 3, /* 73 */ 3, /* 74 */
4, /* 75 */ 3, /* 76 */ 4, /* 77 */ 4, /* 78 */ 5, /* 79 */
2, /* 80 */ 3, /* 81 */ 3, /* 82 */ 4, /* 83 */ 3, /* 84 */
4, /* 85 */ 4, /* 86 */ 5, /* 87 */ 3, /* 88 */ 4, /* 89 */
4, /* 90 */ 5, /* 91 */ 4, /* 92 */ 5, /* 93 */ 5, /* 94 */
6, /* 95 */ 2, /* 96 */ 3, /* 97 */ 3, /* 98 */ 4, /* 99 */
3, /* 100 */ 4, /* 101 */ 4, /* 102 */ 5, /* 103 */ 3, /* 104 */
4, /* 105 */ 4, /* 106 */ 5, /* 107 */ 4, /* 108 */ 5, /* 109 */
5, /* 110 */ 6, /* 111 */ 3, /* 112 */ 4, /* 113 */ 4, /* 114 */
5, /* 115 */ 4, /* 116 */ 5, /* 117 */ 5, /* 118 */ 6, /* 119 */
4, /* 120 */ 5, /* 121 */ 5, /* 122 */ 6, /* 123 */ 5, /* 124 */
6, /* 125 */ 6, /* 126 */ 7, /* 127 */ 1, /* 128 */ 2, /* 129 */
2, /* 130 */ 3, /* 131 */ 2, /* 132 */ 3, /* 133 */ 3, /* 134 */
4, /* 135 */ 2, /* 136 */ 3, /* 137 */ 3, /* 138 */ 4, /* 139 */
3, /* 140 */ 4, /* 141 */ 4, /* 142 */ 5, /* 143 */ 2, /* 144 */
3, /* 145 */ 3, /* 146 */ 4, /* 147 */ 3, /* 148 */ 4, /* 149 */
4, /* 150 */ 5, /* 151 */ 3, /* 152 */ 4, /* 153 */ 4, /* 154 */
5, /* 155 */ 4, /* 156 */ 5, /* 157 */ 5, /* 158 */ 6, /* 159 */
2, /* 160 */ 3, /* 161 */ 3, /* 162 */ 4, /* 163 */ 3, /* 164 */
4, /* 165 */ 4, /* 166 */ 5, /* 167 */ 3, /* 168 */ 4, /* 169 */
4, /* 170 */ 5, /* 171 */ 4, /* 172 */ 5, /* 173 */ 5, /* 174 */
6, /* 175 */ 3, /* 176 */ 4, /* 177 */ 4, /* 178 */ 5, /* 179 */
4, /* 180 */ 5, /* 181 */ 5, /* 182 */ 6, /* 183 */ 4, /* 184 */
5, /* 185 */ 5, /* 186 */ 6, /* 187 */ 5, /* 188 */ 6, /* 189 */
6, /* 190 */ 7, /* 191 */ 2, /* 192 */ 3, /* 193 */ 3, /* 194 */
4, /* 195 */ 3, /* 196 */ 4, /* 197 */ 4, /* 198 */ 5, /* 199 */
3, /* 200 */ 4, /* 201 */ 4, /* 202 */ 5, /* 203 */ 4, /* 204 */
5, /* 205 */ 5, /* 206 */ 6, /* 207 */ 3, /* 208 */ 4, /* 209 */
4, /* 210 */ 5, /* 211 */ 4, /* 212 */ 5, /* 213 */ 5, /* 214 */
6, /* 215 */ 4, /* 216 */ 5, /* 217 */ 5, /* 218 */ 6, /* 219 */
5, /* 220 */ 6, /* 221 */ 6, /* 222 */ 7, /* 223 */ 3, /* 224 */
4, /* 225 */ 4, /* 226 */ 5, /* 227 */ 4, /* 228 */ 5, /* 229 */
5, /* 230 */ 6, /* 231 */ 4, /* 232 */ 5, /* 233 */ 5, /* 234 */
6, /* 235 */ 5, /* 236 */ 6, /* 237 */ 6, /* 238 */ 7, /* 239 */
4, /* 240 */ 5, /* 241 */ 5, /* 242 */ 6, /* 243 */ 5, /* 244 */
6, /* 245 */ 6, /* 246 */ 7, /* 247 */ 5, /* 248 */ 6, /* 249 */
6, /* 250 */ 7, /* 251 */ 6, /* 252 */ 7, /* 253 */ 7, /* 254 */
8 /* 255 */
};
size_t __result(0);
while ( __first < __last ) {
__result += _bit_count[*(__first++)];
}
return __result;
}
unsigned char _Bs_G::_S_first_one(unsigned char __byte)
{
static const unsigned char _first_one[256] = {
0, /* 0 */ 0, /* 1 */ 1, /* 2 */ 0, /* 3 */ 2, /* 4 */
0, /* 5 */ 1, /* 6 */ 0, /* 7 */ 3, /* 8 */ 0, /* 9 */
1, /* 10 */ 0, /* 11 */ 2, /* 12 */ 0, /* 13 */ 1, /* 14 */
0, /* 15 */ 4, /* 16 */ 0, /* 17 */ 1, /* 18 */ 0, /* 19 */
2, /* 20 */ 0, /* 21 */ 1, /* 22 */ 0, /* 23 */ 3, /* 24 */
0, /* 25 */ 1, /* 26 */ 0, /* 27 */ 2, /* 28 */ 0, /* 29 */
1, /* 30 */ 0, /* 31 */ 5, /* 32 */ 0, /* 33 */ 1, /* 34 */
0, /* 35 */ 2, /* 36 */ 0, /* 37 */ 1, /* 38 */ 0, /* 39 */
3, /* 40 */ 0, /* 41 */ 1, /* 42 */ 0, /* 43 */ 2, /* 44 */
0, /* 45 */ 1, /* 46 */ 0, /* 47 */ 4, /* 48 */ 0, /* 49 */
1, /* 50 */ 0, /* 51 */ 2, /* 52 */ 0, /* 53 */ 1, /* 54 */
0, /* 55 */ 3, /* 56 */ 0, /* 57 */ 1, /* 58 */ 0, /* 59 */
2, /* 60 */ 0, /* 61 */ 1, /* 62 */ 0, /* 63 */ 6, /* 64 */
0, /* 65 */ 1, /* 66 */ 0, /* 67 */ 2, /* 68 */ 0, /* 69 */
1, /* 70 */ 0, /* 71 */ 3, /* 72 */ 0, /* 73 */ 1, /* 74 */
0, /* 75 */ 2, /* 76 */ 0, /* 77 */ 1, /* 78 */ 0, /* 79 */
4, /* 80 */ 0, /* 81 */ 1, /* 82 */ 0, /* 83 */ 2, /* 84 */
0, /* 85 */ 1, /* 86 */ 0, /* 87 */ 3, /* 88 */ 0, /* 89 */
1, /* 90 */ 0, /* 91 */ 2, /* 92 */ 0, /* 93 */ 1, /* 94 */
0, /* 95 */ 5, /* 96 */ 0, /* 97 */ 1, /* 98 */ 0, /* 99 */
2, /* 100 */ 0, /* 101 */ 1, /* 102 */ 0, /* 103 */ 3, /* 104 */
0, /* 105 */ 1, /* 106 */ 0, /* 107 */ 2, /* 108 */ 0, /* 109 */
1, /* 110 */ 0, /* 111 */ 4, /* 112 */ 0, /* 113 */ 1, /* 114 */
0, /* 115 */ 2, /* 116 */ 0, /* 117 */ 1, /* 118 */ 0, /* 119 */
3, /* 120 */ 0, /* 121 */ 1, /* 122 */ 0, /* 123 */ 2, /* 124 */
0, /* 125 */ 1, /* 126 */ 0, /* 127 */ 7, /* 128 */ 0, /* 129 */
1, /* 130 */ 0, /* 131 */ 2, /* 132 */ 0, /* 133 */ 1, /* 134 */
0, /* 135 */ 3, /* 136 */ 0, /* 137 */ 1, /* 138 */ 0, /* 139 */
2, /* 140 */ 0, /* 141 */ 1, /* 142 */ 0, /* 143 */ 4, /* 144 */
0, /* 145 */ 1, /* 146 */ 0, /* 147 */ 2, /* 148 */ 0, /* 149 */
1, /* 150 */ 0, /* 151 */ 3, /* 152 */ 0, /* 153 */ 1, /* 154 */
0, /* 155 */ 2, /* 156 */ 0, /* 157 */ 1, /* 158 */ 0, /* 159 */
5, /* 160 */ 0, /* 161 */ 1, /* 162 */ 0, /* 163 */ 2, /* 164 */
0, /* 165 */ 1, /* 166 */ 0, /* 167 */ 3, /* 168 */ 0, /* 169 */
1, /* 170 */ 0, /* 171 */ 2, /* 172 */ 0, /* 173 */ 1, /* 174 */
0, /* 175 */ 4, /* 176 */ 0, /* 177 */ 1, /* 178 */ 0, /* 179 */
2, /* 180 */ 0, /* 181 */ 1, /* 182 */ 0, /* 183 */ 3, /* 184 */
0, /* 185 */ 1, /* 186 */ 0, /* 187 */ 2, /* 188 */ 0, /* 189 */
1, /* 190 */ 0, /* 191 */ 6, /* 192 */ 0, /* 193 */ 1, /* 194 */
0, /* 195 */ 2, /* 196 */ 0, /* 197 */ 1, /* 198 */ 0, /* 199 */
3, /* 200 */ 0, /* 201 */ 1, /* 202 */ 0, /* 203 */ 2, /* 204 */
0, /* 205 */ 1, /* 206 */ 0, /* 207 */ 4, /* 208 */ 0, /* 209 */
1, /* 210 */ 0, /* 211 */ 2, /* 212 */ 0, /* 213 */ 1, /* 214 */
0, /* 215 */ 3, /* 216 */ 0, /* 217 */ 1, /* 218 */ 0, /* 219 */
2, /* 220 */ 0, /* 221 */ 1, /* 222 */ 0, /* 223 */ 5, /* 224 */
0, /* 225 */ 1, /* 226 */ 0, /* 227 */ 2, /* 228 */ 0, /* 229 */
1, /* 230 */ 0, /* 231 */ 3, /* 232 */ 0, /* 233 */ 1, /* 234 */
0, /* 235 */ 2, /* 236 */ 0, /* 237 */ 1, /* 238 */ 0, /* 239 */
4, /* 240 */ 0, /* 241 */ 1, /* 242 */ 0, /* 243 */ 2, /* 244 */
0, /* 245 */ 1, /* 246 */ 0, /* 247 */ 3, /* 248 */ 0, /* 249 */
1, /* 250 */ 0, /* 251 */ 2, /* 252 */ 0, /* 253 */ 1, /* 254 */
0, /* 255 */
};
return _first_one[__byte];
}
_STLP_MOVE_TO_STD_NAMESPACE
_STLP_END_NAMESPACE

Просмотреть файл

@ -0,0 +1,29 @@
/*
* Copyright (c) 1999
* Silicon Graphics Computer Systems, Inc.
*
* Copyright (c) 1999
* Boris Fomitchev
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
#include "stlport_prefix.h"
#include "c_locale.h"
#if defined (_STLP_WIN32) && !defined (_STLP_WCE)
# include "c_locale_win32/c_locale_win32.c"
#elif defined (_STLP_USE_GLIBC2_LOCALIZATION)
# include "c_locale_glibc/c_locale_glibc2.c" /* glibc 2.2 and newer */
#else
# include "c_locale_dummy/c_locale_dummy.c"
#endif

Просмотреть файл

@ -0,0 +1,450 @@
/*
* Copyright (c) 1999
* Silicon Graphics Computer Systems, Inc.
*
* Copyright (c) 1999
* Boris Fomitchev
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
/*
* It is impossible to write the C++ locale library in terms of locales
* as defined in the C standard. Instead, we write the C++ locale and I/O
* library in terms of a low level C-like interface. This file defines
* that interface.
*
* The low-level locale interface can't be written portably; there
* must be a version of it for each platform that the C++ library
* is ported to. On many systems this interface may be a thin wrapper
* for existing functionality.
*/
#ifndef _STLP_C_LOCALE_IMPL_H
#define _STLP_C_LOCALE_IMPL_H
#include "stlport_prefix.h"
#include <wchar.h> /* for mbstate_t */
#include <stl/c_locale.h>
struct _Locale_name_hint;
#if defined (_GNU_SOURCE) && defined (__GLIBC__) && \
((__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
# define _STLP_USE_GLIBC2_LOCALIZATION
# include <nl_types.h>
typedef nl_catd nl_catd_type;
#else
typedef int nl_catd_type;
#endif
/*
* A number: the maximum length of a simple locale name.
* (i.e. a name like like en_US, as opposed to a name like
* en_US/de_AT/de_AT/es_MX/en_US/en_US) */
#define _Locale_MAX_SIMPLE_NAME 256
#ifdef __cplusplus
extern "C" {
#endif
/*
* Typedefs:
*/
typedef unsigned short int _Locale_mask_t;
/* Function called during STLport library load phase. Might contain any
* code necessary to the platform localization layer.
*/
void _Locale_init(void);
/* Function called during STLport library unload. Might contain any
* code necessary to the platform localization layer.
*/
void _Locale_final(void);
/* Create a category of the locale with the given name.
*
* The char* argument is a simple (not a composite) locale name, which may
* neither be an empty string nor a null pointer.
*
* These functions return NULL to indicate failure. Failure reason should be reported
* using the __err_code pointer.
*/
struct _Locale_ctype* _Locale_ctype_create(const char *, struct _Locale_name_hint*, int * /* __err_code */);
struct _Locale_codecvt* _Locale_codecvt_create(const char *, struct _Locale_name_hint*, int * /* __err_code */);
struct _Locale_numeric* _Locale_numeric_create(const char *, struct _Locale_name_hint*, int * /* __err_code */);
struct _Locale_time* _Locale_time_create(const char *, struct _Locale_name_hint*, int * /* __err_code */);
struct _Locale_collate* _Locale_collate_create(const char *, struct _Locale_name_hint*, int * /* __err_code */);
struct _Locale_monetary* _Locale_monetary_create(const char *, struct _Locale_name_hint*, int * /* __err_code */);
struct _Locale_messages* _Locale_messages_create(const char *, struct _Locale_name_hint*, int * /* __err_code */);
/* Give error reason on failure of one of the _Locale_*_create functions. Available
* reasons are:
* 0: No specific error reason has been reported.
* 1: No platform support for the given facet.
* 2: Unknown locale name
* 3: No platform API for localization support.
* 4: No more memory
*/
#define _STLP_LOC_UNDEFINED 0
#define _STLP_LOC_UNSUPPORTED_FACET_CATEGORY 1
#define _STLP_LOC_UNKNOWN_NAME 2
#define _STLP_LOC_NO_PLATFORM_SUPPORT 3
#define _STLP_LOC_NO_MEMORY 4
/* Release a category of a locale
*
* These functions are used to release a category acquired with the
* according _Locale_*_create() functions.
*/
void _Locale_ctype_destroy(struct _Locale_ctype *);
void _Locale_codecvt_destroy(struct _Locale_codecvt *);
void _Locale_numeric_destroy(struct _Locale_numeric *);
void _Locale_time_destroy(struct _Locale_time *);
void _Locale_collate_destroy(struct _Locale_collate *);
void _Locale_monetary_destroy(struct _Locale_monetary *);
void _Locale_messages_destroy(struct _Locale_messages *);
/*
* Returns the name of the user's default locale in each
* category, as a null-terminated string. A NULL value
* means the default "C" locale.
*/
const char * _Locale_ctype_default(char * __buf);
const char * _Locale_numeric_default(char * __buf);
const char * _Locale_time_default(char * __buf);
const char * _Locale_collate_default(char * __buf);
const char * _Locale_monetary_default(char * __buf);
const char * _Locale_messages_default(char * __buf);
/* Retrieve the name of the given category
*
* __buf points to a buffer that can hold at least _Locale_MAX_SIMPLE_NAME
* characters. These functions store the name, as a null-terminated
* string, in __buf. This function can't fail, at worst name is truncated.
*/
char const* _Locale_ctype_name(const struct _Locale_ctype *, char* __buf);
char const* _Locale_codecvt_name(const struct _Locale_codecvt *, char* __buf);
char const* _Locale_numeric_name(const struct _Locale_numeric *, char* __buf);
char const* _Locale_time_name(const struct _Locale_time *, char* __buf);
char const* _Locale_collate_name(const struct _Locale_collate *, char* __buf);
char const* _Locale_monetary_name(const struct _Locale_monetary *, char* __buf);
char const* _Locale_messages_name(const struct _Locale_messages *, char* __buf);
/*
* cname is a (possibly composite) locale name---i.e. a name that can
* be passed to setlocale. __buf points to an array large enough to
* store at least _Locale_MAX_SIMPLE_NAME characters, and each of these
* functions extracts the name of a single category, stores it in buf
* as a null-terminated string, and returns buf.
*/
char const* _Locale_extract_ctype_name(const char *cname, char *__buf,
struct _Locale_name_hint* __hint, int *__err_code);
char const* _Locale_extract_numeric_name(const char *cname, char *__buf,
struct _Locale_name_hint* __hint, int *__err_code);
char const* _Locale_extract_time_name(const char *cname, char *__buf,
struct _Locale_name_hint* __hint, int *__err_code);
char const* _Locale_extract_collate_name(const char *cname, char *__buf,
struct _Locale_name_hint* __hint, int *__err_code);
char const* _Locale_extract_monetary_name(const char *cname, char *__buf,
struct _Locale_name_hint* __hint, int *__err_code);
char const* _Locale_extract_messages_name(const char *cname, char *__buf,
struct _Locale_name_hint* __hint, int *__err_code);
/* Functions to improve locale creation process. For some locale API (Win32)
* you need to find a locale identification from the name which can be a
* rather expensive operation especially if you do so for all facets of a
* locale. Those functions can be used to extract from a API dependent facet
* struct the information necessary to skip this lookup process for other
* facets creation. If not supported those function should return NULL.
*/
struct _Locale_name_hint* _Locale_get_ctype_hint(struct _Locale_ctype*);
struct _Locale_name_hint* _Locale_get_numeric_hint(struct _Locale_numeric*);
struct _Locale_name_hint* _Locale_get_time_hint(struct _Locale_time*);
struct _Locale_name_hint* _Locale_get_collate_hint(struct _Locale_collate*);
struct _Locale_name_hint* _Locale_get_monetary_hint(struct _Locale_monetary*);
struct _Locale_name_hint* _Locale_get_messages_hint(struct _Locale_messages*);
/*
* FUNCTIONS THAT USE CTYPE
*/
/*
* Narrow character functions:
*/
/*
* Returns a pointer to the beginning of the ctype table. The table is
* at least 257 bytes long; if p is the pointer returned by this
* function, then p[c] is valid if c is EOF or if p is any value of
* type unsigned char.
*/
const _Locale_mask_t * _Locale_ctype_table(struct _Locale_ctype *);
/*
* c is either EOF, or an unsigned char value.
*/
int _Locale_toupper(struct _Locale_ctype *, int /* c */);
int _Locale_tolower(struct _Locale_ctype *, int /* c */);
#ifndef _STLP_NO_WCHAR_T
/*
* Wide character functions:
*/
_Locale_mask_t _WLocale_ctype(struct _Locale_ctype *, wint_t, _Locale_mask_t);
wint_t _WLocale_tolower(struct _Locale_ctype *, wint_t);
wint_t _WLocale_toupper(struct _Locale_ctype *, wint_t);
/*
* Multibyte functions:
*/
/*
* Returns the number of bytes of the longest allowed multibyte
* character in the current encoding.
*/
int _WLocale_mb_cur_max(struct _Locale_codecvt *);
/*
* Returns the number of bytes of the shortest allowed multibyte
* character in the current encoding.
*/
int _WLocale_mb_cur_min(struct _Locale_codecvt *);
/*
* Returns 1 if the current multibyte encoding is stateless
* and does not require the use of an mbstate_t value.
*/
int _WLocale_is_stateless(struct _Locale_codecvt *);
/*
* Almost identical to mbrtowc, from 4.6.5.3.2 of NA1. The only
* important difference is that mbrtowc treats null wide characters
* as special, and we don't. Specifically: examines the characters
* in [from, from + n), extracts a single wide character, and stores
* it in *to. Modifies shift_state if appropriate. The return value,
* which is always positive, is the number of characters extracted from
* the input sequence. Return value is (size_t) -1 if there was an
* encoding error in the input sequence, and (size_t) -2 if
* [from, from + n) is correct but not complete. None of the pointer
* arguments may be null pointers.
*/
size_t _WLocale_mbtowc(struct _Locale_codecvt *,
wchar_t * /* to */,
const char * /* from */, size_t /* n */,
mbstate_t *);
/*
* Again, very similar to wcrtomb. The differences are that (1) it
* doesn't treat null characters as special; and (2) it stores at most
* n characters. Converts c to a multibyte sequence, stores that
* sequence in the array 'to', and returns the length of the sequence.
* Modifies shift_state if appropriate. The return value is (size_t) -1
* if c is not a valid wide character, and (size_t) -2 if the length of
* the multibyte character sequence is greater than n.
*/
size_t _WLocale_wctomb(struct _Locale_codecvt *,
char *, size_t,
const wchar_t,
mbstate_t *);
/*
* Inserts whatever characters are necessary to restore st to an
* initial shift state. Sets *next to buf + m, where m is the number
* of characters inserted. (0 <= m <= n.) Returns m to indicate
* success, (size_t) -1 to indicate error, (size_t) -2 to indicate
* partial success (more than n characters needed). For success or partial
* success, sets *next to buf + m.
*/
size_t _WLocale_unshift(struct _Locale_codecvt *,
mbstate_t *,
char *, size_t, char **);
#endif
/*
* FUNCTIONS THAT USE COLLATE
*/
/*
* Compares the two sequences [s1, s1 + n1) and [s2, s2 + n2). Neither
* sequence is assumed to be null-terminated, and null characters
* aren't special. If the two sequences are the same up through
* min(n1, n2), then the sequence that compares less is whichever one
* is shorter.
*/
int _Locale_strcmp(struct _Locale_collate *,
const char * /* s1 */, size_t /* n1 */,
const char * /* s2 */, size_t /* n2 */);
#ifndef _STLP_NO_WCHAR_T
int _WLocale_strcmp(struct _Locale_collate *,
const wchar_t * /* s1 */, size_t /* n1 */,
const wchar_t * /* s2 */, size_t /* n2 */);
#endif
/*
* Creates a transformed version of the string [s2, s2 + n2). The
* string may contain embedded null characters; nulls aren't special.
* The transformed string begins at s1, and contains at most n1
* characters. The return value is the length of the transformed
* string. If the return value is greater than n1 then this is an
* error condition: it indicates that there wasn't enough space. In
* that case, the contents of [s1, s1 + n1) is unspecified.
*/
size_t _Locale_strxfrm(struct _Locale_collate *,
char * /* s1 */, size_t /* n1 */,
const char * /* s2 */, size_t /* n2 */);
#ifndef _STLP_NO_WCHAR_T
size_t _WLocale_strxfrm(struct _Locale_collate *,
wchar_t * /* s1 */, size_t /* n1 */,
const wchar_t * /* s2 */, size_t /* n2 */);
#endif
/*
* FUNCTIONS THAT USE NUMERIC
*/
/*
* Equivalent to the first three fields in struct lconv. (C standard,
* section 7.4.)
*/
char _Locale_decimal_point(struct _Locale_numeric *);
char _Locale_thousands_sep(struct _Locale_numeric *);
const char * _Locale_grouping(struct _Locale_numeric *);
#ifndef _STLP_NO_WCHAR_T
wchar_t _WLocale_decimal_point(struct _Locale_numeric *);
wchar_t _WLocale_thousands_sep(struct _Locale_numeric *);
#endif
/*
* Return "true" and "false" in English locales, and something
* appropriate in non-English locales.
*/
const char * _Locale_true(struct _Locale_numeric *);
const char * _Locale_false(struct _Locale_numeric *);
#ifndef _STLP_NO_WCHAR_T
const wchar_t * _WLocale_true(struct _Locale_numeric *, wchar_t* /* buf */, size_t /* bufSize */);
const wchar_t * _WLocale_false(struct _Locale_numeric *, wchar_t* /* buf */, size_t /* bufSize */);
#endif
/*
* FUNCTIONS THAT USE MONETARY
*/
/*
* Return the obvious fields of struct lconv.
*/
const char * _Locale_int_curr_symbol(struct _Locale_monetary *);
const char * _Locale_currency_symbol(struct _Locale_monetary *);
char _Locale_mon_decimal_point(struct _Locale_monetary *);
char _Locale_mon_thousands_sep(struct _Locale_monetary *);
const char * _Locale_mon_grouping(struct _Locale_monetary *);
const char * _Locale_positive_sign(struct _Locale_monetary *);
const char * _Locale_negative_sign(struct _Locale_monetary *);
char _Locale_int_frac_digits(struct _Locale_monetary *);
char _Locale_frac_digits(struct _Locale_monetary *);
int _Locale_p_cs_precedes(struct _Locale_monetary *);
int _Locale_p_sep_by_space(struct _Locale_monetary *);
int _Locale_p_sign_posn(struct _Locale_monetary *);
int _Locale_n_cs_precedes(struct _Locale_monetary *);
int _Locale_n_sep_by_space(struct _Locale_monetary *);
int _Locale_n_sign_posn(struct _Locale_monetary *);
#ifndef _STLP_NO_WCHAR_T
const wchar_t * _WLocale_int_curr_symbol(struct _Locale_monetary *, wchar_t* /* buf */, size_t /* bufSize */);
const wchar_t * _WLocale_currency_symbol(struct _Locale_monetary *, wchar_t* /* buf */, size_t /* bufSize */);
wchar_t _WLocale_mon_decimal_point(struct _Locale_monetary *);
wchar_t _WLocale_mon_thousands_sep(struct _Locale_monetary *);
const wchar_t * _WLocale_positive_sign(struct _Locale_monetary *, wchar_t* /* buf */, size_t /* bufSize */);
const wchar_t * _WLocale_negative_sign(struct _Locale_monetary *, wchar_t* /* buf */, size_t /* bufSize */);
#endif
/*
* FUNCTIONS THAT USE TIME
*/
/*
* month is in the range [0, 12).
*/
const char * _Locale_full_monthname(struct _Locale_time *, int /* month */);
const char * _Locale_abbrev_monthname(struct _Locale_time *, int /* month */);
#ifndef _STLP_NO_WCHAR_T
const wchar_t * _WLocale_full_monthname(struct _Locale_time *, int /* month */,
wchar_t* /* buf */, size_t /* bufSize */);
const wchar_t * _WLocale_abbrev_monthname(struct _Locale_time *, int /* month */,
wchar_t* /* buf */, size_t /* bufSize */);
#endif
/*
* day is in the range [0, 7). Sunday is 0.
*/
const char * _Locale_full_dayofweek(struct _Locale_time *, int /* day */);
const char * _Locale_abbrev_dayofweek(struct _Locale_time *, int /* day */);
#ifndef _STLP_NO_WCHAR_T
const wchar_t * _WLocale_full_dayofweek(struct _Locale_time *, int /* day */,
wchar_t* /* buf */, size_t /* bufSize */);
const wchar_t * _WLocale_abbrev_dayofweek(struct _Locale_time *, int /* day */,
wchar_t* /* buf */, size_t /* bufSize */);
#endif
const char * _Locale_d_t_fmt(struct _Locale_time *);
const char * _Locale_d_fmt(struct _Locale_time *);
const char * _Locale_t_fmt(struct _Locale_time *);
const char * _Locale_long_d_t_fmt(struct _Locale_time*);
const char * _Locale_long_d_fmt(struct _Locale_time*);
const char * _Locale_am_str(struct _Locale_time *);
const char * _Locale_pm_str(struct _Locale_time *);
#ifndef _STLP_NO_WCHAR_T
const wchar_t * _WLocale_am_str(struct _Locale_time *,
wchar_t* /* buf */, size_t /* bufSize */);
const wchar_t * _WLocale_pm_str(struct _Locale_time *,
wchar_t* /* buf */, size_t /* bufSize */);
#endif
/*
* FUNCTIONS THAT USE MESSAGES
*/
/*
* Very similar to catopen, except that it uses the given message
* category to determine which catalog to open.
*/
nl_catd_type _Locale_catopen(struct _Locale_messages*, const char*);
/* Complementary to _Locale_catopen.
* The catalog must be a value that was returned by a previous call
* to _Locale_catopen.
*/
void _Locale_catclose(struct _Locale_messages*, nl_catd_type);
/*
* Returns a string, identified by a set index and a message index,
* from an opened message catalog. Returns the supplied default if
* no such string exists.
*/
const char * _Locale_catgets(struct _Locale_messages *, nl_catd_type,
int, int,const char *);
#ifdef __cplusplus
}
#endif
#endif /* _STLP_C_LOCALE_IMPL_H */

Просмотреть файл

@ -0,0 +1,531 @@
/*
* Copyright (c) 1999
* Silicon Graphics Computer Systems, Inc.
*
* Copyright (c) 1999
* Boris Fomitchev
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
/* This is a "stub" implementation of the "c_locale.h" interface,
intended for operating systems where we have not yet written
a real implementation. A C++ library using this stub implementation
is still standard-conforming, since the C++ standard does not require
that any locales other than "C" be supported.
*/
#include <string.h>
#include <wchar.h>
#include <ctype.h>
#include <wctype.h>
#include <limits.h>
#if defined (_STLP_USE_SAFE_STRING_FUNCTIONS)
# define _STLP_STRNCPY(D, DS, S, C) strncpy_s(D, DS, S, C)
# if !defined (_STLP_NO_WCHAR_T)
# define _STLP_WCSNCPY(D, DS, S, C) wcsncpy_s(D, DS, S, C)
# endif
#else
# define _STLP_STRNCPY(D, DS, S, C) strncpy(D, S, C)
# if !defined (_STLP_NO_WCHAR_T)
# define _STLP_WCSNCPY(D, DS, S, C) wcsncpy(D, S, C)
# endif
#endif
static const char *_C_name = "C";
static const char *_empty_str = "";
#ifndef _STLP_NO_WCHAR_T
#if defined(WCHAR_MAX) && WCHAR_MAX == 255
static const wchar_t *_empty_wstr = "";
#else
static const wchar_t *_empty_wstr = L"";
#endif
#endif
static _Locale_mask_t ctable[256];
/* Framework functions */
void _Locale_init(void) {
/* Ctype table for the ASCII character set. */
char c;
/* We might never reach 128 when char is signed. */
for (c = 0; /* c != 128 */; ++c) {
if (isalpha(c)) ctable[(unsigned char)c] |= _Locale_ALPHA;
if (iscntrl(c)) ctable[(unsigned char)c] |= _Locale_CNTRL;
if (isdigit(c)) ctable[(unsigned char)c] |= _Locale_DIGIT;
if (isprint(c)) ctable[(unsigned char)c] |= _Locale_PRINT;
if (ispunct(c)) ctable[(unsigned char)c] |= _Locale_PUNCT;
if (isspace(c)) ctable[(unsigned char)c] |= _Locale_SPACE;
if (isxdigit(c)) ctable[(unsigned char)c] |= _Locale_XDIGIT;
if (isupper(c)) ctable[(unsigned char)c] |= _Locale_UPPER;
if (islower(c)) ctable[(unsigned char)c] |= _Locale_LOWER;
if (c == 127) break;
}
/* ASCII is a 7-bit code, so everything else is non-ASCII. */
memset(&(ctable[128]), 0, 128 * sizeof(_Locale_mask_t));
}
void _Locale_final(void)
{}
void* _Locale_create(const char* name, int *__err_code) {
if (name[0] == 'C' && name[1] == 0)
{ return (void*)0x1; }
*__err_code = _STLP_LOC_NO_PLATFORM_SUPPORT; return 0;
}
struct _Locale_ctype* _Locale_ctype_create(const char *name,
struct _Locale_name_hint* hint, int *__err_code)
{ return (struct _Locale_ctype*)_Locale_create(name, __err_code); }
struct _Locale_codecvt* _Locale_codecvt_create(const char *name,
struct _Locale_name_hint* hint, int *__err_code)
{ return (struct _Locale_codecvt*)_Locale_create(name, __err_code); }
struct _Locale_numeric* _Locale_numeric_create(const char *name,
struct _Locale_name_hint* hint, int *__err_code)
{ return (struct _Locale_numeric*)_Locale_create(name, __err_code); }
struct _Locale_time* _Locale_time_create(const char *name,
struct _Locale_name_hint* hint, int *__err_code)
{ return (struct _Locale_time*)_Locale_create(name, __err_code); }
struct _Locale_collate* _Locale_collate_create(const char *name,
struct _Locale_name_hint* hint, int *__err_code)
{ return (struct _Locale_collate*)_Locale_create(name, __err_code); }
struct _Locale_monetary* _Locale_monetary_create(const char *name,
struct _Locale_name_hint* hint, int *__err_code)
{ return (struct _Locale_monetary*)_Locale_create(name, __err_code); }
struct _Locale_messages* _Locale_messages_create(const char *name,
struct _Locale_name_hint* hint, int *__err_code)
{ return (struct _Locale_messages*)_Locale_create(name, __err_code); }
const char *_Locale_ctype_default(char* buf) { return _C_name; }
const char *_Locale_numeric_default(char * buf) { return _C_name; }
const char *_Locale_time_default(char* buf) { return _C_name; }
const char *_Locale_collate_default(char* buf) { return _C_name; }
const char *_Locale_monetary_default(char* buf) { return _C_name; }
const char *_Locale_messages_default(char* buf) { return _C_name; }
char const* _Locale_ctype_name(const struct _Locale_ctype *lctype, char* buf)
{ return _C_name; }
char const* _Locale_codecvt_name(const struct _Locale_codecvt *lcodecvt, char* buf)
{ return _C_name; }
char const* _Locale_numeric_name(const struct _Locale_numeric *lnum, char* buf)
{ return _C_name; }
char const* _Locale_time_name(const struct _Locale_time *ltime, char* buf)
{ return _C_name; }
char const* _Locale_collate_name(const struct _Locale_collate *lcol, char* buf)
{ return _C_name; }
char const* _Locale_monetary_name(const struct _Locale_monetary *lmon, char* buf)
{ return _C_name; }
char const* _Locale_messages_name(const struct _Locale_messages *lmes, char* buf)
{ return _C_name; }
void _Locale_ctype_destroy(struct _Locale_ctype *lctype) {}
void _Locale_codecvt_destroy(struct _Locale_codecvt *lcodecvt) {}
void _Locale_numeric_destroy(struct _Locale_numeric *lnum) {}
void _Locale_time_destroy(struct _Locale_time *ltime) {}
void _Locale_collate_destroy(struct _Locale_collate *lcol) {}
void _Locale_monetary_destroy(struct _Locale_monetary *lmon) {}
void _Locale_messages_destroy(struct _Locale_messages *lmes) {}
static char const* _Locale_extract_name(const char* name, int *__err_code) {
// When the request is the default locale or the "C" locale we answer "C".
if (name[0] == 0 ||
(name[0] == 'C' && name[1] == 0))
{ return _C_name; }
*__err_code = _STLP_LOC_NO_PLATFORM_SUPPORT; return 0;
}
char const* _Locale_extract_ctype_name(const char *name, char *buf,
struct _Locale_name_hint* hint, int *__err_code)
{ return _Locale_extract_name(name, __err_code); }
char const* _Locale_extract_numeric_name(const char *name, char *buf,
struct _Locale_name_hint* hint, int *__err_code)
{ return _Locale_extract_name(name, __err_code); }
char const* _Locale_extract_time_name(const char*name, char *buf,
struct _Locale_name_hint* hint, int *__err_code)
{ return _Locale_extract_name(name, __err_code); }
char const* _Locale_extract_collate_name(const char *name, char *buf,
struct _Locale_name_hint* hint, int *__err_code)
{ return _Locale_extract_name(name, __err_code); }
char const* _Locale_extract_monetary_name(const char *name, char *buf,
struct _Locale_name_hint* hint, int *__err_code)
{ return _Locale_extract_name(name, __err_code); }
char const* _Locale_extract_messages_name(const char *name, char *buf,
struct _Locale_name_hint* hint, int *__err_code)
{ return _Locale_extract_name(name, __err_code); }
struct _Locale_name_hint* _Locale_get_ctype_hint(struct _Locale_ctype* ctype)
{ return 0; }
struct _Locale_name_hint* _Locale_get_numeric_hint(struct _Locale_numeric* numeric)
{ return 0; }
struct _Locale_name_hint* _Locale_get_time_hint(struct _Locale_time* time)
{ return 0; }
struct _Locale_name_hint* _Locale_get_collate_hint(struct _Locale_collate* collate)
{ return 0; }
struct _Locale_name_hint* _Locale_get_monetary_hint(struct _Locale_monetary* monetary)
{ return 0; }
struct _Locale_name_hint* _Locale_get_messages_hint(struct _Locale_messages* messages)
{ return 0; }
/* ctype */
const _Locale_mask_t* _Locale_ctype_table(struct _Locale_ctype* lctype) {
_STLP_MARK_PARAMETER_AS_UNUSED(lctype)
return ctable;
}
int _Locale_toupper(struct _Locale_ctype*lctype, int c)
{ return toupper(c); }
int _Locale_tolower(struct _Locale_ctype*lctype, int c)
{ return tolower(c); }
#ifndef _STLP_NO_WCHAR_T
_Locale_mask_t _WLocale_ctype(struct _Locale_ctype *lctype, wint_t wc, _Locale_mask_t mask) {
_Locale_mask_t ret = 0;
if ((mask & _Locale_ALPHA) != 0 && iswalpha(wc))
ret |= _Locale_ALPHA;
if ((mask & _Locale_CNTRL) != 0 && iswcntrl(wc))
ret |= _Locale_CNTRL;
if ((mask & _Locale_DIGIT) != 0 && iswdigit(wc))
ret |= _Locale_DIGIT;
if ((mask & _Locale_PRINT) != 0 && iswprint(wc))
ret |= _Locale_PRINT;
if ((mask & _Locale_PUNCT) != 0 && iswpunct(wc))
ret |= _Locale_PUNCT;
if ((mask & _Locale_SPACE) != 0 && iswspace(wc))
ret |= _Locale_SPACE;
if ((mask & _Locale_XDIGIT) != 0 && iswxdigit(wc))
ret |= _Locale_XDIGIT;
if ((mask & _Locale_UPPER) != 0 && iswupper(wc))
ret |= _Locale_UPPER;
if ((mask & _Locale_LOWER) != 0 && iswlower(wc))
ret |= _Locale_LOWER;
return ret;
}
wint_t _WLocale_tolower(struct _Locale_ctype *lctype, wint_t wc)
{ return towlower(wc); }
wint_t _WLocale_toupper(struct _Locale_ctype *lctype, wint_t wc)
{ return towupper(wc); }
int _WLocale_mb_cur_max (struct _Locale_codecvt *lcodecvt) { return 1; }
int _WLocale_mb_cur_min (struct _Locale_codecvt *lcodecvt) { return 1; }
int _WLocale_is_stateless (struct _Locale_codecvt *lcodecvt) { return 1; }
size_t _WLocale_mbtowc(struct _Locale_codecvt *lcodecvt,
wchar_t *to,
const char *from, size_t n,
mbstate_t *st)
{ *to = *from; return 1; }
size_t _WLocale_wctomb(struct _Locale_codecvt *lcodecvt,
char *to, size_t n,
const wchar_t c,
mbstate_t *st)
{ *to = (char)c; return 1; }
size_t _WLocale_unshift(struct _Locale_codecvt *lcodecvt,
mbstate_t *st,
char *buf, size_t n, char ** next)
{ *next = buf; return 0; }
#endif
/* Collate */
int _Locale_strcmp(struct _Locale_collate* lcol,
const char* s1, size_t n1, const char* s2, size_t n2) {
int ret = 0;
char buf1[64], buf2[64];
while (n1 > 0 || n2 > 0) {
size_t bufsize1 = n1 < 63 ? n1 : 63;
size_t bufsize2 = n2 < 63 ? n2 : 63;
_STLP_STRNCPY(buf1, 64, s1, bufsize1); buf1[bufsize1] = 0;
_STLP_STRNCPY(buf2, 64, s2, bufsize2); buf2[bufsize2] = 0;
ret = strcmp(buf1, buf2);
if (ret != 0) return ret < 0 ? -1 : 1;
s1 += bufsize1; n1 -= bufsize1;
s2 += bufsize2; n2 -= bufsize2;
}
return ret == 0 ? 0 : (ret < 0 ? -1 : 1);
}
#ifndef _STLP_NO_WCHAR_T
int _WLocale_strcmp(struct _Locale_collate* lcol,
const wchar_t* s1, size_t n1, const wchar_t* s2, size_t n2) {
int ret = 0;
wchar_t buf1[64], buf2[64];
while (n1 > 0 || n2 > 0) {
size_t bufsize1 = n1 < 63 ? n1 : 63;
size_t bufsize2 = n2 < 63 ? n2 : 63;
_STLP_WCSNCPY(buf1, 64, s1, bufsize1); buf1[bufsize1] = 0;
_STLP_WCSNCPY(buf2, 64, s2, bufsize2); buf2[bufsize2] = 0;
ret = wcscmp(buf1, buf2);
if (ret != 0) return ret < 0 ? -1 : 1;
s1 += bufsize1; n1 -= bufsize1;
s2 += bufsize2; n2 -= bufsize2;
}
return ret == 0 ? 0 : (ret < 0 ? -1 : 1);
}
#endif
size_t _Locale_strxfrm(struct _Locale_collate* lcol,
char* dest, size_t dest_n,
const char* src, size_t src_n) {
if (dest != 0) {
_STLP_STRNCPY(dest, dest_n, src, dest_n - 1); dest[dest_n - 1] = 0;
}
return src_n;
}
#ifndef _STLP_NO_WCHAR_T
size_t _WLocale_strxfrm(struct _Locale_collate* lcol,
wchar_t* dest, size_t dest_n,
const wchar_t* src, size_t src_n) {
if (dest != 0) {
_STLP_WCSNCPY(dest, dest_n, src, dest_n - 1); dest[dest_n - 1] = 0;
}
return src_n;
}
#endif
/* Numeric */
char _Locale_decimal_point(struct _Locale_numeric* lnum)
{ return '.'; }
char _Locale_thousands_sep(struct _Locale_numeric* lnum)
{ return ','; }
const char* _Locale_grouping(struct _Locale_numeric * lnum)
{ return _empty_str; }
const char * _Locale_true(struct _Locale_numeric * lnum)
{ return "true"; }
const char * _Locale_false(struct _Locale_numeric * lnum)
{ return "false"; }
#ifndef _STLP_NO_WCHAR_T
wchar_t _WLocale_decimal_point(struct _Locale_numeric* lnum)
{ return L'.'; }
wchar_t _WLocale_thousands_sep(struct _Locale_numeric* lnum)
{ return L','; }
#if defined(WCHAR_MAX) && WCHAR_MAX == 255
const wchar_t * _WLocale_true(struct _Locale_numeric* lnum, wchar_t* buf, size_t bufSize)
{ return "true"; }
const wchar_t * _WLocale_false(struct _Locale_numeric* lnum, wchar_t* buf, size_t bufSize)
{ return "false"; }
#else
const wchar_t * _WLocale_true(struct _Locale_numeric* lnum, wchar_t* buf, size_t bufSize)
{ return L"true"; }
const wchar_t * _WLocale_false(struct _Locale_numeric* lnum, wchar_t* buf, size_t bufSize)
{ return L"false"; }
#endif
#endif
/* Monetary */
const char* _Locale_int_curr_symbol(struct _Locale_monetary * lmon)
{ return _empty_str; }
const char* _Locale_currency_symbol(struct _Locale_monetary * lmon)
{ return _empty_str; }
char _Locale_mon_decimal_point(struct _Locale_monetary * lmon)
{ return '.'; }
char _Locale_mon_thousands_sep(struct _Locale_monetary * lmon)
{ return ','; }
const char* _Locale_mon_grouping(struct _Locale_monetary * lmon)
{ return _empty_str; }
const char* _Locale_positive_sign(struct _Locale_monetary * lmon)
{ return _empty_str; }
const char* _Locale_negative_sign(struct _Locale_monetary * lmon)
{ return _empty_str; }
char _Locale_int_frac_digits(struct _Locale_monetary * lmon)
{ return 0; }
char _Locale_frac_digits(struct _Locale_monetary * lmon)
{ return 0; }
int _Locale_p_cs_precedes(struct _Locale_monetary * lmon)
{ return CHAR_MAX; }
int _Locale_p_sep_by_space(struct _Locale_monetary * lmon)
{ return CHAR_MAX; }
int _Locale_p_sign_posn(struct _Locale_monetary * lmon)
{ return CHAR_MAX; }
int _Locale_n_cs_precedes(struct _Locale_monetary * lmon)
{ return CHAR_MAX; }
int _Locale_n_sep_by_space(struct _Locale_monetary * lmon)
{ return CHAR_MAX; }
int _Locale_n_sign_posn(struct _Locale_monetary * lmon)
{ return CHAR_MAX; }
#ifndef _STLP_NO_WCHAR_T
const wchar_t* _WLocale_int_curr_symbol(struct _Locale_monetary * lmon,
wchar_t* buf, size_t bufSize)
{ return _empty_wstr; }
const wchar_t* _WLocale_currency_symbol(struct _Locale_monetary * lmon,
wchar_t* buf, size_t bufSize)
{ return _empty_wstr; }
wchar_t _WLocale_mon_decimal_point(struct _Locale_monetary * lmon)
{ return L'.'; }
wchar_t _WLocale_mon_thousands_sep(struct _Locale_monetary * lmon)
{ return L','; }
const wchar_t* _WLocale_positive_sign(struct _Locale_monetary * lmon,
wchar_t* buf, size_t bufSize)
{ return _empty_wstr; }
const wchar_t* _WLocale_negative_sign(struct _Locale_monetary * lmon,
wchar_t* buf, size_t bufSize)
{ return _empty_wstr; }
#endif
/* Time */
static const char* full_monthname[] =
{ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" };
const char * _Locale_full_monthname(struct _Locale_time * ltime, int n)
{ return full_monthname[n]; }
static const char* abbrev_monthname[] =
{ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
const char * _Locale_abbrev_monthname(struct _Locale_time * ltime, int n)
{ return abbrev_monthname[n]; }
static const char* full_dayname[] =
{ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
const char * _Locale_full_dayofweek(struct _Locale_time * ltime, int n)
{ return full_dayname[n]; }
static const char* abbrev_dayname[] =
{ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
const char * _Locale_abbrev_dayofweek(struct _Locale_time * ltime, int n)
{ return abbrev_dayname[n]; }
const char* _Locale_d_t_fmt(struct _Locale_time* ltime)
{ return "%m/%d/%y"; }
const char* _Locale_d_fmt(struct _Locale_time* ltime)
{ return "%m/%d/%y"; }
const char* _Locale_t_fmt(struct _Locale_time* ltime)
{ return "%H:%M:%S"; }
const char* _Locale_long_d_t_fmt(struct _Locale_time* ltime)
{ return _empty_str; }
const char* _Locale_long_d_fmt(struct _Locale_time* ltime)
{ return _empty_str; }
const char* _Locale_am_str(struct _Locale_time* ltime)
{ return "AM"; }
const char* _Locale_pm_str(struct _Locale_time* ltime)
{ return "PM"; }
#ifndef _STLP_NO_WCHAR_T
#if defined(WCHAR_MAX) && WCHAR_MAX == 255
static const wchar_t* full_wmonthname[] =
{ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" };
const wchar_t * _WLocale_full_monthname(struct _Locale_time * ltime, int n,
wchar_t* buf, size_t bufSize)
{ return full_wmonthname[n]; }
static const wchar_t* abbrev_wmonthname[] =
{ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
const wchar_t * _WLocale_abbrev_monthname(struct _Locale_time * ltime, int n,
wchar_t* buf, size_t bufSize)
{ return abbrev_wmonthname[n]; }
static const wchar_t* full_wdayname[] =
{ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
const wchar_t * _WLocale_full_dayofweek(struct _Locale_time * ltime, int n,
wchar_t* buf, size_t bufSize)
{ return full_wdayname[n]; }
static const wchar_t* abbrev_wdayname[] =
{ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
const wchar_t * _WLocale_abbrev_dayofweek(struct _Locale_time * ltime, int n,
wchar_t* buf, size_t bufSize)
{ return abbrev_wdayname[n]; }
const wchar_t* _WLocale_am_str(struct _Locale_time* ltime,
wchar_t* buf, size_t bufSize)
{ return "AM"; }
const wchar_t* _WLocale_pm_str(struct _Locale_time* ltime,
wchar_t* buf, size_t bufSize)
{ return "PM"; }
#else /* WCHAR_MAX != 255 */
static const wchar_t* full_wmonthname[] =
{ L"January", L"February", L"March", L"April", L"May", L"June",
L"July", L"August", L"September", L"October", L"November", L"December" };
const wchar_t * _WLocale_full_monthname(struct _Locale_time * ltime, int n,
wchar_t* buf, size_t bufSize)
{ return full_wmonthname[n]; }
static const wchar_t* abbrev_wmonthname[] =
{ L"Jan", L"Feb", L"Mar", L"Apr", L"May", L"Jun",
L"Jul", L"Aug", L"Sep", L"Oct", L"Nov", L"Dec" };
const wchar_t * _WLocale_abbrev_monthname(struct _Locale_time * ltime, int n,
wchar_t* buf, size_t bufSize)
{ return abbrev_wmonthname[n]; }
static const wchar_t* full_wdayname[] =
{ L"Sunday", L"Monday", L"Tuesday", L"Wednesday", L"Thursday", L"Friday", L"Saturday" };
const wchar_t * _WLocale_full_dayofweek(struct _Locale_time * ltime, int n,
wchar_t* buf, size_t bufSize)
{ return full_wdayname[n]; }
static const wchar_t* abbrev_wdayname[] =
{ L"Sun", L"Mon", L"Tue", L"Wed", L"Thu", L"Fri", L"Sat" };
const wchar_t * _WLocale_abbrev_dayofweek(struct _Locale_time * ltime, int n,
wchar_t* buf, size_t bufSize)
{ return abbrev_wdayname[n]; }
const wchar_t* _WLocale_am_str(struct _Locale_time* ltime,
wchar_t* buf, size_t bufSize)
{ return L"AM"; }
const wchar_t* _WLocale_pm_str(struct _Locale_time* ltime,
wchar_t* buf, size_t bufSize)
{ return L"PM"; }
#endif /* WCHAR_MAX != 255 */
#endif
/* Messages */
nl_catd_type _Locale_catopen(struct _Locale_messages* lmes, const char* name)
{ return -1; }
void _Locale_catclose(struct _Locale_messages* lmes, nl_catd_type cat) {}
const char* _Locale_catgets(struct _Locale_messages* lmes, nl_catd_type cat,
int setid, int msgid, const char *dfault)
{ return dfault; }

Просмотреть файл

@ -0,0 +1,705 @@
#include <locale.h>
#include <langinfo.h>
#include <stdio.h>
#include <stdlib.h>
#include <wctype.h>
#include <string.h>
#include <stdint.h>
static const char *_empty_str = "";
static const char *_C_name = "C";
static wchar_t* _ToWChar(const char* buf, wchar_t *wbuf, size_t wbufSize) {
wchar_t *wcur = wbuf;
wchar_t *wend = wbuf + wbufSize - 1;
for (; wcur != wend && *buf != 0; ++buf, ++wcur)
*wcur = *buf;
*wcur = 0;
return wbuf;
}
#if 0
struct _Locale_ctype
{
locale_t __cloc;
};
struct _Locale_numeric
{
locale_t __cloc;
};
struct _Locale_time
{
locale_t __cloc;
};
struct _Locale_collate
{
locale_t __cloc;
};
struct _Locale_monetary
{
locale_t __cloc;
};
struct _Locale_messages
{
locale_t __cloc;
};
#endif
void _Locale_init()
{}
void _Locale_final()
{}
struct _Locale_ctype *_Locale_ctype_create(const char *nm, struct _Locale_name_hint* hint,
int *__err_code) {
*__err_code = _STLP_LOC_UNKNOWN_NAME;
return (struct _Locale_ctype*)newlocale(LC_CTYPE_MASK, nm, NULL);
}
struct _Locale_codecvt *_Locale_codecvt_create(const char *nm, struct _Locale_name_hint* hint,
int *__err_code) {
// Glibc do not support multibyte manipulation for the moment, it simply implements "C".
if (nm[0] == 'C' && nm[1] == 0)
{ return (struct _Locale_codecvt*)0x01; }
*__err_code = _STLP_LOC_NO_PLATFORM_SUPPORT; return 0;
}
struct _Locale_numeric *_Locale_numeric_create(const char *nm, struct _Locale_name_hint* hint,
int *__err_code) {
*__err_code = _STLP_LOC_UNKNOWN_NAME;
return (struct _Locale_numeric*)newlocale(LC_NUMERIC_MASK, nm, NULL);
}
struct _Locale_time *_Locale_time_create(const char *nm, struct _Locale_name_hint* hint,
int *__err_code) {
*__err_code = _STLP_LOC_UNKNOWN_NAME;
return (struct _Locale_time*)newlocale(LC_TIME_MASK, nm, NULL);
}
struct _Locale_collate *_Locale_collate_create(const char *nm, struct _Locale_name_hint* hint,
int *__err_code) {
*__err_code = _STLP_LOC_UNKNOWN_NAME;
return (struct _Locale_collate*)newlocale(LC_COLLATE_MASK, nm, NULL);
}
struct _Locale_monetary *_Locale_monetary_create(const char *nm, struct _Locale_name_hint* hint,
int *__err_code) {
*__err_code = _STLP_LOC_UNKNOWN_NAME;
return (struct _Locale_monetary*)newlocale(LC_MONETARY_MASK, nm, NULL);
}
struct _Locale_messages *_Locale_messages_create(const char *nm, struct _Locale_name_hint* hint,
int *__err_code) {
*__err_code = _STLP_LOC_UNKNOWN_NAME;
return (struct _Locale_messages*)newlocale(LC_MESSAGES_MASK, nm, NULL);
}
/*
try to see locale category LC should be used from environment;
according POSIX, the order is
1. LC_ALL
2. category (LC_CTYPE, LC_NUMERIC, ... )
3. LANG
If set nothing, return "C" (this really implementation-specific).
*/
static const char *_Locale_aux_default( const char *LC, char *nm )
{
char *name = getenv( "LC_ALL" );
if ( name != NULL && *name != 0 ) {
return name;
}
name = getenv( LC );
if ( name != NULL && *name != 0 ) {
return name;
}
name = getenv( "LANG" );
if ( name != NULL && *name != 0 ) {
return name;
}
return _C_name;
}
const char *_Locale_ctype_default( char *nm )
{
return _Locale_aux_default( "LC_CTYPE", nm );
}
const char *_Locale_numeric_default( char *nm )
{
return _Locale_aux_default( "LC_NUMERIC", nm );
}
const char *_Locale_time_default( char *nm )
{
return _Locale_aux_default( "LC_TIME", nm );
}
const char *_Locale_collate_default( char *nm )
{
return _Locale_aux_default( "LC_COLLATE", nm );
}
const char *_Locale_monetary_default( char *nm )
{
return _Locale_aux_default( "LC_MONETARY", nm );
}
const char *_Locale_messages_default( char *nm )
{
return _Locale_aux_default( "LC_MESSAGES", nm );
}
char const*_Locale_ctype_name( const struct _Locale_ctype *__loc, char *buf )
{
return ((locale_t)__loc)->__names[LC_CTYPE];
}
char const*_Locale_codecvt_name( const struct _Locale_codecvt *__loc, char *buf )
{
return _C_name;
}
char const*_Locale_numeric_name( const struct _Locale_numeric *__loc, char *buf )
{
return ((locale_t)__loc)->__names[LC_NUMERIC];
}
char const*_Locale_time_name( const struct _Locale_time *__loc, char *buf )
{
return ((locale_t)__loc)->__names[LC_TIME];
}
char const*_Locale_collate_name( const struct _Locale_collate *__loc, char *buf )
{
return ((locale_t)__loc)->__names[LC_COLLATE];
}
char const*_Locale_monetary_name( const struct _Locale_monetary *__loc, char *buf )
{
return ((locale_t)__loc)->__names[LC_MONETARY];
}
char const*_Locale_messages_name( const struct _Locale_messages *__loc, char *buf )
{
return ((locale_t)__loc)->__names[LC_MESSAGES];
}
void _Locale_ctype_destroy( struct _Locale_ctype *__loc )
{ freelocale((locale_t)__loc); }
void _Locale_codecvt_destroy( struct _Locale_codecvt *__loc )
{}
void _Locale_numeric_destroy( struct _Locale_numeric *__loc )
{ freelocale((locale_t)__loc); }
void _Locale_time_destroy( struct _Locale_time *__loc )
{ freelocale((locale_t)__loc); }
void _Locale_collate_destroy( struct _Locale_collate *__loc )
{ freelocale((locale_t)__loc); }
void _Locale_monetary_destroy( struct _Locale_monetary *__loc )
{ freelocale((locale_t)__loc); }
void _Locale_messages_destroy( struct _Locale_messages* __loc )
{ freelocale((locale_t)__loc); }
/*
* locale loc expected either locale name indeed (platform-specific)
* or string like "LC_CTYPE=LocaleNameForCType;LC_NUMERIC=LocaleNameForNum;"
*
*/
static char const*__Extract_locale_name( const char *loc, const char *category, char *buf )
{
char *expr;
size_t len_name;
if( loc[0]=='L' && loc[1]=='C' && loc[2]=='_') {
expr = strstr( (char*)loc, category );
if ( expr == NULL )
return NULL; /* Category not found. */
++expr;
len_name = strcspn( expr, ";" );
len_name = len_name >= _Locale_MAX_SIMPLE_NAME ? _Locale_MAX_SIMPLE_NAME - 1 : len_name;
strncpy( buf, expr, len_name );
buf[len_name] = 0;
return buf;
}
return loc;
}
char const*_Locale_extract_ctype_name(const char *loc, char *buf,
struct _Locale_name_hint* hint, int *__err_code)
{ return __Extract_locale_name( loc, "LC_CTYPE=", buf ); }
char const*_Locale_extract_numeric_name(const char *loc, char *buf,
struct _Locale_name_hint* hint, int *__err_code)
{ return __Extract_locale_name( loc, "LC_NUMERIC=", buf ); }
char const*_Locale_extract_time_name(const char *loc, char *buf,
struct _Locale_name_hint* hint, int *__err_code)
{ return __Extract_locale_name( loc, "LC_TIME=", buf ); }
char const*_Locale_extract_collate_name(const char *loc, char *buf,
struct _Locale_name_hint* hint, int *__err_code)
{ return __Extract_locale_name( loc, "LC_COLLATE=", buf ); }
char const*_Locale_extract_monetary_name(const char *loc, char *buf,
struct _Locale_name_hint* hint, int *__err_code)
{ return __Extract_locale_name( loc, "LC_MONETARY=", buf ); }
char const*_Locale_extract_messages_name(const char *loc, char *buf,
struct _Locale_name_hint* hint, int *__err_code)
{ return __Extract_locale_name( loc, "LC_MESSAGES=", buf ); }
struct _Locale_name_hint* _Locale_get_ctype_hint(struct _Locale_ctype* ctype)
{ return 0; }
struct _Locale_name_hint* _Locale_get_numeric_hint(struct _Locale_numeric* numeric)
{ return 0; }
struct _Locale_name_hint* _Locale_get_time_hint(struct _Locale_time* time)
{ return 0; }
struct _Locale_name_hint* _Locale_get_collate_hint(struct _Locale_collate* collate)
{ return 0; }
struct _Locale_name_hint* _Locale_get_monetary_hint(struct _Locale_monetary* monetary)
{ return 0; }
struct _Locale_name_hint* _Locale_get_messages_hint(struct _Locale_messages* messages)
{ return 0; }
/* ctype */
const _Locale_mask_t *_Locale_ctype_table( struct _Locale_ctype *__loc )
{
/* return table with masks (upper, lower, alpha, etc.) */
_STLP_STATIC_ASSERT( sizeof(_Locale_mask_t) == sizeof(((locale_t)__loc)->__ctype_b[0]) )
return ((locale_t)__loc)->__ctype_b;
}
int _Locale_toupper( struct _Locale_ctype *__loc, int c )
{ return ((locale_t)__loc)->__ctype_toupper[c]; }
int _Locale_tolower( struct _Locale_ctype *__loc, int c )
{ return ((locale_t)__loc)->__ctype_tolower[c]; }
#if !defined (_STLP_NO_WCHAR_T)
_Locale_mask_t _WLocale_ctype( struct _Locale_ctype *__loc, wint_t wc, _Locale_mask_t __mask )
{
_Locale_mask_t ret = 0;
if ((__mask & _Locale_ALPHA) != 0 && iswalpha_l(wc, (locale_t)__loc))
ret |= _Locale_ALPHA;
if ((__mask & _Locale_CNTRL) != 0 && iswcntrl_l(wc, (locale_t)__loc))
ret |= _Locale_CNTRL;
if ((__mask & _Locale_DIGIT) != 0 && iswdigit_l(wc, (locale_t)__loc))
ret |= _Locale_DIGIT;
if ((__mask & _Locale_PRINT) != 0 && iswprint_l(wc, (locale_t)__loc))
ret |= _Locale_PRINT;
if ((__mask & _Locale_PUNCT) != 0 && iswpunct_l(wc, (locale_t)__loc))
ret |= _Locale_PUNCT;
if ((__mask & _Locale_SPACE) != 0 && iswspace_l(wc, (locale_t)__loc))
ret |= _Locale_SPACE;
if ((__mask & _Locale_XDIGIT) != 0 && iswxdigit_l(wc, (locale_t)__loc))
ret |= _Locale_XDIGIT;
if ((__mask & _Locale_UPPER) != 0 && iswupper_l(wc, (locale_t)__loc))
ret |= _Locale_UPPER;
if ((__mask & _Locale_LOWER) != 0 && iswlower_l(wc, (locale_t)__loc))
ret |= _Locale_LOWER;
return ret;
}
wint_t _WLocale_tolower( struct _Locale_ctype *__loc, wint_t c )
{
return towlower_l( c, ((locale_t)__loc) );
}
wint_t _WLocale_toupper( struct _Locale_ctype *__loc, wint_t c )
{
return towupper_l( c, ((locale_t)__loc) );
}
#endif
int _WLocale_mb_cur_max( struct _Locale_codecvt * lcodecvt) { return 1; }
int _WLocale_mb_cur_min( struct _Locale_codecvt * lcodecvt) { return 1; }
int _WLocale_is_stateless( struct _Locale_codecvt * lcodecvt) { return 1; }
#if !defined (_STLP_NO_WCHAR_T)
size_t _WLocale_mbtowc(struct _Locale_codecvt *lcodecvt,
wchar_t *to,
const char *from, size_t n,
mbstate_t *st)
{ *to = *from; return 1; }
size_t _WLocale_wctomb(struct _Locale_codecvt *lcodecvt,
char *to, size_t n,
const wchar_t c,
mbstate_t *st)
{ *to = (char)c; return 1; }
#endif
size_t _WLocale_unshift(struct _Locale_codecvt *lcodecvt,
mbstate_t *st,
char *buf, size_t n, char ** next)
{ *next = buf; return 0; }
/* Collate */
int _Locale_strcmp(struct _Locale_collate * __loc,
const char *s1, size_t n1,
const char *s2, size_t n2) {
int ret = 0;
char buf1[64], buf2[64];
while (n1 > 0 || n2 > 0) {
size_t bufsize1 = n1 < 63 ? n1 : 63;
size_t bufsize2 = n2 < 63 ? n2 : 63;
strncpy(buf1, s1, bufsize1); buf1[bufsize1] = 0;
strncpy(buf2, s2, bufsize2); buf2[bufsize2] = 0;
ret = strcoll_l(buf1, buf2, (locale_t)__loc);
if (ret != 0) return ret;
s1 += bufsize1; n1 -= bufsize1;
s2 += bufsize2; n2 -= bufsize2;
}
return ret;
}
#if !defined (_STLP_NO_WCHAR_T)
int _WLocale_strcmp(struct _Locale_collate *__loc,
const wchar_t *s1, size_t n1,
const wchar_t *s2, size_t n2) {
int ret = 0;
wchar_t buf1[64], buf2[64];
while (n1 > 0 || n2 > 0) {
size_t bufsize1 = n1 < 63 ? n1 : 63;
size_t bufsize2 = n2 < 63 ? n2 : 63;
wcsncpy(buf1, s1, bufsize1); buf1[bufsize1] = 0;
wcsncpy(buf2, s2, bufsize2); buf2[bufsize2] = 0;
ret = wcscoll_l(buf1, buf2, (locale_t)__loc);
if (ret != 0) return ret;
s1 += bufsize1; n1 -= bufsize1;
s2 += bufsize2; n2 -= bufsize2;
}
return ret;
}
#endif
size_t _Locale_strxfrm(struct _Locale_collate *__loc,
char *dest, size_t dest_n,
const char *src, size_t src_n )
{
const char *real_src;
char *buf = NULL;
size_t result;
if (src_n == 0)
{
if (dest != NULL) dest[0] = 0;
return 0;
}
if (src[src_n] != 0) {
buf = malloc(src_n + 1);
strncpy(buf, src, src_n);
buf[src_n] = 0;
real_src = buf;
}
else
real_src = src;
result = strxfrm_l(dest, real_src, dest_n, (locale_t)__loc);
if (buf != NULL) free(buf);
return result;
}
# ifndef _STLP_NO_WCHAR_T
size_t _WLocale_strxfrm( struct _Locale_collate *__loc,
wchar_t *dest, size_t dest_n,
const wchar_t *src, size_t src_n )
{
const wchar_t *real_src;
wchar_t *buf = NULL;
size_t result;
if (src_n == 0)
{
if (dest != NULL) dest[0] = 0;
return 0;
}
if (src[src_n] != 0) {
buf = malloc((src_n + 1) * sizeof(wchar_t));
wcsncpy(buf, src, src_n);
buf[src_n] = 0;
real_src = buf;
}
else
real_src = src;
result = wcsxfrm_l(dest, real_src, dest_n, (locale_t)__loc);
if (buf != NULL) free(buf);
return result;
}
# endif
/* Numeric */
char _Locale_decimal_point(struct _Locale_numeric *__loc)
{
return *(nl_langinfo_l(RADIXCHAR, (locale_t)__loc));
}
char _Locale_thousands_sep(struct _Locale_numeric *__loc)
{
return *(nl_langinfo_l(THOUSEP, (locale_t)__loc));
}
const char* _Locale_grouping(struct _Locale_numeric *__loc)
{
return (_Locale_thousands_sep(__loc) != 0 ) ? (nl_langinfo_l(GROUPING, (locale_t)__loc)) : _empty_str;
}
const char *_Locale_true(struct _Locale_numeric *__loc)
{
return nl_langinfo_l(YESSTR, (locale_t)__loc);
}
const char *_Locale_false(struct _Locale_numeric *__loc)
{
return nl_langinfo_l(NOSTR, (locale_t)__loc);
}
#ifndef _STLP_NO_WCHAR_T
wchar_t _WLocale_decimal_point(struct _Locale_numeric *__loc)
{ return (wchar_t)_Locale_decimal_point(__loc); }
wchar_t _WLocale_thousands_sep(struct _Locale_numeric *__loc)
{ return (wchar_t)_Locale_thousands_sep(__loc); }
const wchar_t *_WLocale_true(struct _Locale_numeric *__loc, wchar_t *buf, size_t bufSize)
{ return _ToWChar(_Locale_true(__loc), buf, bufSize); }
const wchar_t *_WLocale_false(struct _Locale_numeric *__loc, wchar_t *buf, size_t bufSize)
{ return _ToWChar(_Locale_false(__loc), buf, bufSize); }
#endif
/* Monetary */
const char *_Locale_int_curr_symbol(struct _Locale_monetary *__loc)
{
return nl_langinfo_l(INT_CURR_SYMBOL, (locale_t)__loc);
}
const char *_Locale_currency_symbol(struct _Locale_monetary *__loc)
{
return nl_langinfo_l(CURRENCY_SYMBOL, (locale_t)__loc);
}
char _Locale_mon_decimal_point(struct _Locale_monetary * __loc)
{
return *(nl_langinfo_l(MON_DECIMAL_POINT,(locale_t)__loc));
}
char _Locale_mon_thousands_sep(struct _Locale_monetary *__loc)
{
return *(nl_langinfo_l(MON_THOUSANDS_SEP, (locale_t)__loc));
}
#ifndef _STLP_NO_WCHAR_T
const wchar_t *_WLocale_int_curr_symbol(struct _Locale_monetary *__loc, wchar_t *buf, size_t bufSize)
{ return _ToWChar(_Locale_int_curr_symbol(__loc), buf, bufSize); }
const wchar_t *_WLocale_currency_symbol(struct _Locale_monetary *__loc, wchar_t *buf, size_t bufSize)
{ return _ToWChar(_Locale_currency_symbol(__loc), buf, bufSize); }
wchar_t _WLocale_mon_decimal_point(struct _Locale_monetary * __loc)
{ return (wchar_t)_Locale_mon_decimal_point(__loc); }
wchar_t _WLocale_mon_thousands_sep(struct _Locale_monetary * __loc)
{ return (wchar_t)_Locale_mon_thousands_sep(__loc); }
const wchar_t *_WLocale_positive_sign(struct _Locale_monetary *__loc, wchar_t *buf, size_t bufSize)
{ return _ToWChar(_Locale_positive_sign(__loc), buf, bufSize); }
const wchar_t *_WLocale_negative_sign(struct _Locale_monetary *__loc, wchar_t *buf, size_t bufSize)
{ return _ToWChar(_Locale_negative_sign(__loc), buf, bufSize); }
#endif
const char *_Locale_mon_grouping(struct _Locale_monetary *__loc)
{
return (_Locale_mon_thousands_sep( __loc ) != 0 ) ? nl_langinfo_l(MON_GROUPING, (locale_t)__loc) : _empty_str;
}
const char *_Locale_positive_sign(struct _Locale_monetary *__loc)
{
return nl_langinfo_l(POSITIVE_SIGN, (locale_t)__loc);
}
const char *_Locale_negative_sign(struct _Locale_monetary *__loc)
{
return nl_langinfo_l(NEGATIVE_SIGN, (locale_t)__loc);
}
char _Locale_int_frac_digits(struct _Locale_monetary *__loc)
{
/* We are forced to manually handled the "C" locale for consistency with
* the default implementation in STLport. */
const char* lname = ((locale_t)__loc)->__names[LC_MONETARY];
if (lname[0] == 'C' && lname[1] == 0)
return 0;
return *(nl_langinfo_l(INT_FRAC_DIGITS, (locale_t)__loc));
}
char _Locale_frac_digits(struct _Locale_monetary *__loc)
{
/* We are forced to manually handled the "C" locale for consistency with
* the default implementation in STLport. */
const char* lname = ((locale_t)__loc)->__names[LC_MONETARY];
if (lname[0] == 'C' && lname[1] == 0)
return 0;
return *(nl_langinfo_l(FRAC_DIGITS, (locale_t)__loc));
}
/* 1 if currency_symbol precedes a positive value, 0 if succeeds */
int _Locale_p_cs_precedes(struct _Locale_monetary *__loc)
{
return *(nl_langinfo_l(P_CS_PRECEDES, (locale_t)__loc));
}
/* 1 if a space separates currency_symbol from a positive value. */
int _Locale_p_sep_by_space(struct _Locale_monetary *__loc)
{
return *(nl_langinfo_l(P_SEP_BY_SPACE, (locale_t)__loc));
}
/*
* 0 Parentheses surround the quantity and currency_symbol
* 1 The sign string precedes the quantity and currency_symbol
* 2 The sign string succeeds the quantity and currency_symbol.
* 3 The sign string immediately precedes the currency_symbol.
* 4 The sign string immediately succeeds the currency_symbol.
*/
int _Locale_p_sign_posn(struct _Locale_monetary *__loc)
{
return *(nl_langinfo_l(P_SIGN_POSN, (locale_t)__loc));
}
/* 1 if currency_symbol precedes a negative value, 0 if succeeds */
int _Locale_n_cs_precedes(struct _Locale_monetary *__loc)
{
return *(nl_langinfo_l(N_CS_PRECEDES, (locale_t)__loc));
}
/* 1 if a space separates currency_symbol from a negative value. */
int _Locale_n_sep_by_space(struct _Locale_monetary *__loc)
{
return *(nl_langinfo_l(N_SEP_BY_SPACE, (locale_t)__loc));
}
/*
* 0 Parentheses surround the quantity and currency_symbol
* 1 The sign string precedes the quantity and currency_symbol
* 2 The sign string succeeds the quantity and currency_symbol.
* 3 The sign string immediately precedes the currency_symbol.
* 4 The sign string immediately succeeds the currency_symbol.
*/
int _Locale_n_sign_posn(struct _Locale_monetary *__loc)
{
return *(nl_langinfo_l(N_SIGN_POSN, (locale_t)__loc));
}
/* Time */
const char *_Locale_full_monthname(struct _Locale_time *__loc, int _m )
{
return nl_langinfo_l(MON_1 + _m, (locale_t)__loc);
}
const char *_Locale_abbrev_monthname(struct _Locale_time *__loc, int _m )
{
return nl_langinfo_l(ABMON_1 + _m, (locale_t)__loc);
}
const char *_Locale_full_dayofweek(struct _Locale_time *__loc, int _d )
{
return nl_langinfo_l(DAY_1 + _d, (locale_t)__loc);
}
const char *_Locale_abbrev_dayofweek(struct _Locale_time *__loc, int _d )
{
return nl_langinfo_l(ABDAY_1 + _d, (locale_t)__loc);
}
const char *_Locale_d_t_fmt(struct _Locale_time *__loc)
{
return nl_langinfo_l(D_T_FMT, (locale_t)__loc);
}
const char *_Locale_d_fmt(struct _Locale_time *__loc )
{
return nl_langinfo_l(D_FMT, (locale_t)__loc);
}
const char *_Locale_t_fmt(struct _Locale_time *__loc )
{
return nl_langinfo_l(T_FMT, (locale_t)__loc);
}
const char *_Locale_long_d_t_fmt(struct _Locale_time *__loc )
{
return nl_langinfo_l(ERA_D_T_FMT, (locale_t)__loc);
}
const char *_Locale_long_d_fmt(struct _Locale_time *__loc )
{
return nl_langinfo_l(ERA_D_FMT, (locale_t)__loc);
}
const char *_Locale_am_str(struct _Locale_time *__loc )
{
return nl_langinfo_l(AM_STR, (locale_t)__loc);
}
const char *_Locale_pm_str(struct _Locale_time* __loc )
{
return nl_langinfo_l(PM_STR, (locale_t)__loc);
}
#ifndef _STLP_NO_WCHAR_T
const wchar_t *_WLocale_full_monthname(struct _Locale_time *__loc, int _m, wchar_t *buf, size_t bufSize)
{ return _ToWChar(_Locale_full_monthname(__loc, _m), buf, bufSize); }
const wchar_t *_WLocale_abbrev_monthname(struct _Locale_time *__loc, int _m, wchar_t *buf, size_t bufSize)
{ return _ToWChar(_Locale_abbrev_monthname(__loc, _m), buf, bufSize); }
const wchar_t *_WLocale_full_dayofweek(struct _Locale_time *__loc, int _d, wchar_t *buf, size_t bufSize)
{ return _ToWChar(_Locale_full_dayofweek(__loc, _d), buf, bufSize); }
const wchar_t *_WLocale_abbrev_dayofweek(struct _Locale_time *__loc, int _d, wchar_t *buf, size_t bufSize)
{ return _ToWChar(_Locale_abbrev_dayofweek(__loc, _d), buf, bufSize); }
const wchar_t *_WLocale_am_str(struct _Locale_time *__loc, wchar_t *buf, size_t bufSize)
{ return _ToWChar(_Locale_am_str(__loc), buf, bufSize); }
const wchar_t *_WLocale_pm_str(struct _Locale_time* __loc, wchar_t *buf, size_t bufSize)
{ return _ToWChar(_Locale_pm_str(__loc), buf, bufSize); }
#endif
/* Messages */
nl_catd_type _Locale_catopen(struct _Locale_messages *__loc, const char *__cat_name )
{
return catopen( __cat_name, NL_CAT_LOCALE );
}
void _Locale_catclose(struct _Locale_messages *__loc, nl_catd_type __cat )
{
catclose( __cat );
}
const char *_Locale_catgets(struct _Locale_messages *__loc, nl_catd_type __cat,
int __setid, int __msgid, const char *dfault)
{
return catgets( __cat, __setid, __msgid, dfault );
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -0,0 +1,314 @@
/*
* Copyright (c) 2007 2008
* Francois Dumont
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
#if defined (_STLP_USE_SAFE_STRING_FUNCTIONS)
# define _STLP_WCSNCPY(D, DS, S, C) wcsncpy_s(D, DS, S, C)
#else
# define _STLP_WCSNCPY(D, DS, S, C) wcsncpy(D, S, C)
#endif
static const wchar_t* __wtrue_name = L"true";
static const wchar_t* __wfalse_name = L"false";
typedef struct _Locale_codecvt {
_Locale_lcid_t lc;
UINT cp;
unsigned char cleads[256 / CHAR_BIT];
unsigned char max_char_size;
DWORD mbtowc_flags;
DWORD wctomb_flags;
} _Locale_codecvt_t;
/* Ctype */
_Locale_mask_t _WLocale_ctype(_Locale_ctype_t* ltype, wint_t c,
_Locale_mask_t which_bits) {
wchar_t buf[2];
WORD out[2];
buf[0] = c; buf[1] = 0;
GetStringTypeW(CT_CTYPE1, buf, -1, out);
_STLP_MARK_PARAMETER_AS_UNUSED(ltype)
return (_Locale_mask_t)(MapCtypeMask(out[0]) & which_bits);
}
wint_t _WLocale_tolower(_Locale_ctype_t* ltype, wint_t c) {
wchar_t in_c = c;
wchar_t res;
LCMapStringW(ltype->lc.id, LCMAP_LOWERCASE, &in_c, 1, &res, 1);
return res;
}
wint_t _WLocale_toupper(_Locale_ctype_t* ltype, wint_t c) {
wchar_t in_c = c;
wchar_t res;
LCMapStringW(ltype->lc.id, LCMAP_UPPERCASE, &in_c, 1, &res, 1);
return res;
}
_Locale_codecvt_t* _Locale_codecvt_create(const char * name, _Locale_lcid_t* lc_hint, int *__err_code) {
char cp_name[MAX_CP_LEN + 1];
unsigned char *ptr;
CPINFO CPInfo;
int i;
_Locale_codecvt_t *lcodecvt = (_Locale_codecvt_t*)malloc(sizeof(_Locale_codecvt_t));
if (!lcodecvt) { *__err_code = _STLP_LOC_NO_MEMORY; return lcodecvt; }
memset(lcodecvt, 0, sizeof(_Locale_codecvt_t));
if (__GetLCIDFromName(name, &lcodecvt->lc.id, cp_name, lc_hint) == -1)
{ free(lcodecvt); *__err_code = _STLP_LOC_UNKNOWN_NAME; return NULL; }
lcodecvt->cp = atoi(cp_name);
if (!GetCPInfo(lcodecvt->cp, &CPInfo)) { free(lcodecvt); return NULL; }
if (lcodecvt->cp != CP_UTF7 && lcodecvt->cp != CP_UTF8) {
lcodecvt->mbtowc_flags = MB_PRECOMPOSED;
lcodecvt->wctomb_flags = WC_COMPOSITECHECK | WC_SEPCHARS;
}
lcodecvt->max_char_size = CPInfo.MaxCharSize;
if (CPInfo.MaxCharSize > 1) {
for (ptr = (unsigned char*)CPInfo.LeadByte; *ptr && *(ptr + 1); ptr += 2)
for (i = *ptr; i <= *(ptr + 1); ++i) lcodecvt->cleads[i / CHAR_BIT] |= (0x01 << i % CHAR_BIT);
}
return lcodecvt;
}
char const* _Locale_codecvt_name(const _Locale_codecvt_t* lcodecvt, char* buf) {
char cp_buf[MAX_CP_LEN + 1];
my_ltoa(lcodecvt->cp, cp_buf);
return __GetLocaleName(lcodecvt->lc.id, cp_buf, buf);
}
void _Locale_codecvt_destroy(_Locale_codecvt_t* lcodecvt) {
if (!lcodecvt) return;
free(lcodecvt);
}
int _WLocale_mb_cur_max (_Locale_codecvt_t * lcodecvt)
{ return lcodecvt->max_char_size; }
int _WLocale_mb_cur_min (_Locale_codecvt_t *lcodecvt) {
_STLP_MARK_PARAMETER_AS_UNUSED(lcodecvt)
return 1;
}
int _WLocale_is_stateless (_Locale_codecvt_t * lcodecvt)
{ return (lcodecvt->max_char_size == 1) ? 1 : 0; }
static int __isleadbyte(int i, unsigned char *ctable) {
unsigned char c = (unsigned char)i;
return (ctable[c / CHAR_BIT] & (0x01 << c % CHAR_BIT));
}
static int __mbtowc(_Locale_codecvt_t *l, wchar_t *dst, const char *from, unsigned int count) {
int result;
if (l->cp == CP_UTF7 || l->cp == CP_UTF8) {
result = MultiByteToWideChar(l->cp, l->mbtowc_flags, from, count, dst, 1);
if (result == 0) {
switch (GetLastError()) {
case ERROR_NO_UNICODE_TRANSLATION:
return -2;
default:
return -1;
}
}
}
else {
if (count == 1 && __isleadbyte(*from, l->cleads)) return (size_t)-2;
result = MultiByteToWideChar(l->cp, l->mbtowc_flags, from, count, dst, 1);
if (result == 0) return -1;
}
return result;
}
size_t _WLocale_mbtowc(_Locale_codecvt_t *lcodecvt, wchar_t *to,
const char *from, size_t n, mbstate_t *shift_state) {
int result;
_STLP_MARK_PARAMETER_AS_UNUSED(shift_state)
if (lcodecvt->max_char_size == 1) { /* Single byte encoding. */
result = MultiByteToWideChar(lcodecvt->cp, lcodecvt->mbtowc_flags, from, 1, to, 1);
if (result == 0) return (size_t)-1;
return result;
}
else { /* Multi byte encoding. */
int retval;
unsigned int count = 1;
while (n--) {
retval = __mbtowc(lcodecvt, to, from, count);
if (retval == -2)
{ if (++count > ((unsigned int)lcodecvt->max_char_size)) return (size_t)-1; }
else if (retval == -1)
{ return (size_t)-1; }
else
{ return count; }
}
return (size_t)-2;
}
}
size_t _WLocale_wctomb(_Locale_codecvt_t *lcodecvt, char *to, size_t n,
const wchar_t c, mbstate_t *shift_state) {
int size = WideCharToMultiByte(lcodecvt->cp, lcodecvt->wctomb_flags, &c, 1, NULL, 0, NULL, NULL);
if (!size) return (size_t)-1;
if ((size_t)size > n) return (size_t)-2;
if (n > INT_MAX)
/* Limiting the output buf size to INT_MAX seems like reasonable to transform a single wchar_t. */
n = INT_MAX;
WideCharToMultiByte(lcodecvt->cp, lcodecvt->wctomb_flags, &c, 1, to, (int)n, NULL, NULL);
_STLP_MARK_PARAMETER_AS_UNUSED(shift_state)
return (size_t)size;
}
size_t _WLocale_unshift(_Locale_codecvt_t *lcodecvt, mbstate_t *st,
char *buf, size_t n, char **next) {
/* _WLocale_wctomb do not even touch to st, there is nothing to unshift in this localization implementation. */
_STLP_MARK_PARAMETER_AS_UNUSED(lcodecvt)
_STLP_MARK_PARAMETER_AS_UNUSED(st)
_STLP_MARK_PARAMETER_AS_UNUSED(&n)
*next = buf;
return 0;
}
/* Collate */
/* This function takes care of the potential size_t DWORD different size. */
static int _WLocale_strcmp_aux(_Locale_collate_t* lcol,
const wchar_t* s1, size_t n1,
const wchar_t* s2, size_t n2) {
int result = CSTR_EQUAL;
while (n1 > 0 || n2 > 0) {
DWORD size1 = trim_size_t_to_DWORD(n1);
DWORD size2 = trim_size_t_to_DWORD(n2);
result = CompareStringW(lcol->lc.id, 0, s1, size1, s2, size2);
if (result != CSTR_EQUAL)
break;
n1 -= size1;
n2 -= size2;
}
return result;
}
int _WLocale_strcmp(_Locale_collate_t* lcol,
const wchar_t* s1, size_t n1,
const wchar_t* s2, size_t n2) {
int result;
result = _WLocale_strcmp_aux(lcol, s1, n1, s2, n2);
return (result == CSTR_EQUAL) ? 0 : (result == CSTR_LESS_THAN) ? -1 : 1;
}
size_t _WLocale_strxfrm(_Locale_collate_t* lcol,
wchar_t* dst, size_t dst_size,
const wchar_t* src, size_t src_size) {
int result, i;
/* see _Locale_strxfrm: */
if (src_size > INT_MAX) {
if (dst != 0) {
_STLP_WCSNCPY(dst, dst_size, src, src_size);
}
return src_size;
}
if (dst_size > INT_MAX) {
dst_size = INT_MAX;
}
result = LCMapStringW(lcol->lc.id, LCMAP_SORTKEY, src, (int)src_size, dst, (int)dst_size);
if (result != 0 && dst != 0) {
for (i = result - 1; i >= 0; --i) {
dst[i] = ((unsigned char*)dst)[i];
}
}
return result != 0 ? result - 1 : 0;
}
/* Numeric */
wchar_t _WLocale_decimal_point(_Locale_numeric_t* lnum) {
wchar_t buf[4];
GetLocaleInfoW(lnum->lc.id, LOCALE_SDECIMAL, buf, 4);
return buf[0];
}
wchar_t _WLocale_thousands_sep(_Locale_numeric_t* lnum) {
wchar_t buf[4];
GetLocaleInfoW(lnum->lc.id, LOCALE_STHOUSAND, buf, 4);
return buf[0];
}
const wchar_t * _WLocale_true(_Locale_numeric_t* lnum, wchar_t* buf, size_t bufSize) {
_STLP_MARK_PARAMETER_AS_UNUSED(lnum)
_STLP_MARK_PARAMETER_AS_UNUSED(buf)
_STLP_MARK_PARAMETER_AS_UNUSED(&bufSize)
return __wtrue_name;
}
const wchar_t * _WLocale_false(_Locale_numeric_t* lnum, wchar_t* buf, size_t bufSize) {
_STLP_MARK_PARAMETER_AS_UNUSED(lnum)
_STLP_MARK_PARAMETER_AS_UNUSED(buf)
_STLP_MARK_PARAMETER_AS_UNUSED(&bufSize)
return __wfalse_name;
}
/* Monetary */
const wchar_t* _WLocale_int_curr_symbol(_Locale_monetary_t * lmon, wchar_t* buf, size_t bufSize)
{ GetLocaleInfoW(lmon->lc.id, LOCALE_SINTLSYMBOL, buf, (int)bufSize); return buf; }
const wchar_t* _WLocale_currency_symbol(_Locale_monetary_t * lmon, wchar_t* buf, size_t bufSize)
{ GetLocaleInfoW(lmon->lc.id, LOCALE_SCURRENCY, buf, (int)bufSize); return buf; }
wchar_t _WLocale_mon_decimal_point(_Locale_monetary_t * lmon)
{ return lmon->decimal_point[0]; }
wchar_t _WLocale_mon_thousands_sep(_Locale_monetary_t * lmon)
{ return lmon->thousands_sep[0]; }
const wchar_t* _WLocale_positive_sign(_Locale_monetary_t * lmon, wchar_t* buf, size_t bufSize)
{ GetLocaleInfoW(lmon->lc.id, LOCALE_SPOSITIVESIGN, buf, (int)bufSize); return buf; }
const wchar_t* _WLocale_negative_sign(_Locale_monetary_t * lmon, wchar_t* buf, size_t bufSize)
{ GetLocaleInfoW(lmon->lc.id, LOCALE_SNEGATIVESIGN, buf, (int)bufSize); return buf; }
/* Time */
const wchar_t * _WLocale_full_monthname(_Locale_time_t * ltime, int month,
wchar_t* buf, size_t bufSize)
{ GetLocaleInfoW(ltime->lc.id, LOCALE_SMONTHNAME1 + month, buf, (int)bufSize); return buf; }
const wchar_t * _WLocale_abbrev_monthname(_Locale_time_t * ltime, int month,
wchar_t* buf, size_t bufSize)
{ GetLocaleInfoW(ltime->lc.id, LOCALE_SABBREVMONTHNAME1 + month, buf, (int)bufSize); return buf; }
const wchar_t * _WLocale_full_dayofweek(_Locale_time_t * ltime, int day,
wchar_t* buf, size_t bufSize)
{ GetLocaleInfoW(ltime->lc.id, LOCALE_SDAYNAME1 + day, buf, (int)bufSize); return buf; }
const wchar_t * _WLocale_abbrev_dayofweek(_Locale_time_t * ltime, int day,
wchar_t* buf, size_t bufSize)
{ GetLocaleInfoW(ltime->lc.id, LOCALE_SABBREVDAYNAME1 + day, buf, (int)bufSize); return buf; }
const wchar_t* _WLocale_am_str(_Locale_time_t* ltime,
wchar_t* buf, size_t bufSize)
{ GetLocaleInfoW(ltime->lc.id, LOCALE_S1159, buf, (int)bufSize); return buf; }
const wchar_t* _WLocale_pm_str(_Locale_time_t* ltime,
wchar_t* buf, size_t bufSize)
{ GetLocaleInfoW(ltime->lc.id, LOCALE_S2359, buf, (int)bufSize); return buf; }

Просмотреть файл

@ -0,0 +1,143 @@
/*
* Copyright (c) 1999
* Silicon Graphics Computer Systems, Inc.
*
* Copyright (c) 1999
* Boris Fomitchev
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
#include "stlport_prefix.h"
#include <locale>
#include <algorithm>
_STLP_BEGIN_NAMESPACE
//----------------------------------------------------------------------
// codecvt<char, char, mbstate_t>
codecvt<char, char, mbstate_t>::~codecvt() {}
int codecvt<char, char, mbstate_t>::do_length(state_type&,
const char* from,
const char* end,
size_t mx) const
{ return (int)(min) ( __STATIC_CAST(size_t, (end - from)), mx); }
int codecvt<char, char, mbstate_t>::do_max_length() const _STLP_NOTHROW
{ return 1; }
bool
codecvt<char, char, mbstate_t>::do_always_noconv() const _STLP_NOTHROW
{ return true; }
int
codecvt<char, char, mbstate_t>::do_encoding() const _STLP_NOTHROW
{ return 1; }
codecvt_base::result
codecvt<char, char, mbstate_t>::do_unshift(state_type& /* __state */,
char* __to,
char* /* __to_limit */,
char*& __to_next) const
{ __to_next = __to; return noconv; }
codecvt_base::result
codecvt<char, char, mbstate_t>::do_in (state_type& /* __state */ ,
const char* __from,
const char* /* __from_end */,
const char*& __from_next,
char* __to,
char* /* __to_end */,
char*& __to_next) const
{ __from_next = __from; __to_next = __to; return noconv; }
codecvt_base::result
codecvt<char, char, mbstate_t>::do_out(state_type& /* __state */,
const char* __from,
const char* /* __from_end */,
const char*& __from_next,
char* __to,
char* /* __to_limit */,
char*& __to_next) const
{ __from_next = __from; __to_next = __to; return noconv; }
#if !defined (_STLP_NO_WCHAR_T)
//----------------------------------------------------------------------
// codecvt<wchar_t, char, mbstate_t>
codecvt<wchar_t, char, mbstate_t>::~codecvt() {}
codecvt<wchar_t, char, mbstate_t>::result
codecvt<wchar_t, char, mbstate_t>::do_out(state_type& /* state */,
const intern_type* from,
const intern_type* from_end,
const intern_type*& from_next,
extern_type* to,
extern_type* to_limit,
extern_type*& to_next) const {
ptrdiff_t len = (min) (from_end - from, to_limit - to);
copy(from, from + len, to);
from_next = from + len;
to_next = to + len;
return ok;
}
codecvt<wchar_t, char, mbstate_t>::result
codecvt<wchar_t, char, mbstate_t>::do_in (state_type& /* state */,
const extern_type* from,
const extern_type* from_end,
const extern_type*& from_next,
intern_type* to,
intern_type* to_limit,
intern_type*& to_next) const {
ptrdiff_t len = (min) (from_end - from, to_limit - to);
copy(__REINTERPRET_CAST(const unsigned char*, from),
__REINTERPRET_CAST(const unsigned char*, from) + len, to);
from_next = from + len;
to_next = to + len;
return ok;
}
codecvt<wchar_t, char, mbstate_t>::result
codecvt<wchar_t, char, mbstate_t>::do_unshift(state_type& /* state */,
extern_type* to,
extern_type* ,
extern_type*& to_next) const {
to_next = to;
return noconv;
}
int codecvt<wchar_t, char, mbstate_t>::do_encoding() const _STLP_NOTHROW
{ return 1; }
bool codecvt<wchar_t, char, mbstate_t>::do_always_noconv() const _STLP_NOTHROW
{ return true; }
int codecvt<wchar_t, char, mbstate_t>::do_length(state_type&,
const extern_type* from,
const extern_type* end,
size_t mx) const
{ return (int)(min) ((size_t) (end - from), mx); }
int codecvt<wchar_t, char, mbstate_t>::do_max_length() const _STLP_NOTHROW
{ return 1; }
#endif /* wchar_t */
_STLP_END_NAMESPACE
// Local Variables:
// mode:C++
// End:

Просмотреть файл

@ -0,0 +1,69 @@
/*
* Copyright (c) 1999
* Silicon Graphics Computer Systems, Inc.
*
* Copyright (c) 1999
* Boris Fomitchev
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
#include "stlport_prefix.h"
#include <locale>
_STLP_BEGIN_NAMESPACE
// collate<char>
collate<char>::~collate() {}
int collate<char>::do_compare(const char* low1, const char* high1,
const char* low2, const char* high2) const
{ return _STLP_PRIV __lexicographical_compare_3way(low1, high1, low2, high2); }
string collate<char>::do_transform(const char* low, const char* high) const
{ return string(low, high); }
long collate<char>::do_hash(const char* low, const char* high) const {
unsigned long result = 0;
for ( ; low < high; ++low)
result = 5 * result + *low;
return result;
}
#if !defined (_STLP_NO_WCHAR_T)
// collate<wchar_t>
collate<wchar_t>::~collate() {}
int
collate<wchar_t>::do_compare(const wchar_t* low1, const wchar_t* high1,
const wchar_t* low2, const wchar_t* high2) const
{ return _STLP_PRIV __lexicographical_compare_3way(low1, high1, low2, high2); }
wstring collate<wchar_t>::do_transform(const wchar_t* low, const wchar_t* high) const
{ return wstring(low, high); }
long collate<wchar_t>::do_hash(const wchar_t* low, const wchar_t* high) const {
unsigned long result = 0;
for ( ; low < high; ++low)
result = 5 * result + *low;
return result;
}
#endif
_STLP_END_NAMESPACE
// Local Variables:
// mode:C++
// End:

Просмотреть файл

@ -0,0 +1,353 @@
/*
* Copyright (c) 1999
* Silicon Graphics Computer Systems, Inc.
*
* Copyright (c) 1999
* Boris Fomitchev
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
#include "stlport_prefix.h"
#include <numeric>
#include <cmath>
#include <complex>
#if defined (_STLP_MSVC_LIB) && (_STLP_MSVC_LIB >= 1400)
// hypot is deprecated.
# if defined (_STLP_MSVC)
# pragma warning (disable : 4996)
# elif defined (__ICL)
# pragma warning (disable : 1478)
# endif
#endif
_STLP_BEGIN_NAMESPACE
// Complex division and square roots.
// Absolute value
_STLP_TEMPLATE_NULL
_STLP_DECLSPEC float _STLP_CALL abs(const complex<float>& __z)
{ return ::hypot(__z._M_re, __z._M_im); }
_STLP_TEMPLATE_NULL
_STLP_DECLSPEC double _STLP_CALL abs(const complex<double>& __z)
{ return ::hypot(__z._M_re, __z._M_im); }
#if !defined (_STLP_NO_LONG_DOUBLE)
_STLP_TEMPLATE_NULL
_STLP_DECLSPEC long double _STLP_CALL abs(const complex<long double>& __z)
{ return ::hypot(__z._M_re, __z._M_im); }
#endif
// Phase
_STLP_TEMPLATE_NULL
_STLP_DECLSPEC float _STLP_CALL arg(const complex<float>& __z)
{ return ::atan2(__z._M_im, __z._M_re); }
_STLP_TEMPLATE_NULL
_STLP_DECLSPEC double _STLP_CALL arg(const complex<double>& __z)
{ return ::atan2(__z._M_im, __z._M_re); }
#if !defined (_STLP_NO_LONG_DOUBLE)
_STLP_TEMPLATE_NULL
_STLP_DECLSPEC long double _STLP_CALL arg(const complex<long double>& __z)
{ return ::atan2(__z._M_im, __z._M_re); }
#endif
// Construct a complex number from polar representation
_STLP_TEMPLATE_NULL
_STLP_DECLSPEC complex<float> _STLP_CALL polar(const float& __rho, const float& __phi)
{ return complex<float>(__rho * ::cos(__phi), __rho * ::sin(__phi)); }
_STLP_TEMPLATE_NULL
_STLP_DECLSPEC complex<double> _STLP_CALL polar(const double& __rho, const double& __phi)
{ return complex<double>(__rho * ::cos(__phi), __rho * ::sin(__phi)); }
#if !defined (_STLP_NO_LONG_DOUBLE)
_STLP_TEMPLATE_NULL
_STLP_DECLSPEC complex<long double> _STLP_CALL polar(const long double& __rho, const long double& __phi)
{ return complex<long double>(__rho * ::cos(__phi), __rho * ::sin(__phi)); }
#endif
// Division
template <class _Tp>
static void _divT(const _Tp& __z1_r, const _Tp& __z1_i,
const _Tp& __z2_r, const _Tp& __z2_i,
_Tp& __res_r, _Tp& __res_i) {
_Tp __ar = __z2_r >= 0 ? __z2_r : -__z2_r;
_Tp __ai = __z2_i >= 0 ? __z2_i : -__z2_i;
if (__ar <= __ai) {
_Tp __ratio = __z2_r / __z2_i;
_Tp __denom = __z2_i * (1 + __ratio * __ratio);
__res_r = (__z1_r * __ratio + __z1_i) / __denom;
__res_i = (__z1_i * __ratio - __z1_r) / __denom;
}
else {
_Tp __ratio = __z2_i / __z2_r;
_Tp __denom = __z2_r * (1 + __ratio * __ratio);
__res_r = (__z1_r + __z1_i * __ratio) / __denom;
__res_i = (__z1_i - __z1_r * __ratio) / __denom;
}
}
template <class _Tp>
static void _divT(const _Tp& __z1_r,
const _Tp& __z2_r, const _Tp& __z2_i,
_Tp& __res_r, _Tp& __res_i) {
_Tp __ar = __z2_r >= 0 ? __z2_r : -__z2_r;
_Tp __ai = __z2_i >= 0 ? __z2_i : -__z2_i;
if (__ar <= __ai) {
_Tp __ratio = __z2_r / __z2_i;
_Tp __denom = __z2_i * (1 + __ratio * __ratio);
__res_r = (__z1_r * __ratio) / __denom;
__res_i = - __z1_r / __denom;
}
else {
_Tp __ratio = __z2_i / __z2_r;
_Tp __denom = __z2_r * (1 + __ratio * __ratio);
__res_r = __z1_r / __denom;
__res_i = - (__z1_r * __ratio) / __denom;
}
}
void _STLP_CALL
complex<float>::_div(const float& __z1_r, const float& __z1_i,
const float& __z2_r, const float& __z2_i,
float& __res_r, float& __res_i)
{ _divT(__z1_r, __z1_i, __z2_r, __z2_i, __res_r, __res_i); }
void _STLP_CALL
complex<float>::_div(const float& __z1_r,
const float& __z2_r, const float& __z2_i,
float& __res_r, float& __res_i)
{ _divT(__z1_r, __z2_r, __z2_i, __res_r, __res_i); }
void _STLP_CALL
complex<double>::_div(const double& __z1_r, const double& __z1_i,
const double& __z2_r, const double& __z2_i,
double& __res_r, double& __res_i)
{ _divT(__z1_r, __z1_i, __z2_r, __z2_i, __res_r, __res_i); }
void _STLP_CALL
complex<double>::_div(const double& __z1_r,
const double& __z2_r, const double& __z2_i,
double& __res_r, double& __res_i)
{ _divT(__z1_r, __z2_r, __z2_i, __res_r, __res_i); }
#if !defined (_STLP_NO_LONG_DOUBLE)
void _STLP_CALL
complex<long double>::_div(const long double& __z1_r, const long double& __z1_i,
const long double& __z2_r, const long double& __z2_i,
long double& __res_r, long double& __res_i)
{ _divT(__z1_r, __z1_i, __z2_r, __z2_i, __res_r, __res_i); }
void _STLP_CALL
complex<long double>::_div(const long double& __z1_r,
const long double& __z2_r, const long double& __z2_i,
long double& __res_r, long double& __res_i)
{ _divT(__z1_r, __z2_r, __z2_i, __res_r, __res_i); }
#endif
//----------------------------------------------------------------------
// Square root
template <class _Tp>
static complex<_Tp> sqrtT(const complex<_Tp>& z) {
_Tp re = z._M_re;
_Tp im = z._M_im;
_Tp mag = ::hypot(re, im);
complex<_Tp> result;
if (mag == 0.f) {
result._M_re = result._M_im = 0.f;
} else if (re > 0.f) {
result._M_re = ::sqrt(0.5f * (mag + re));
result._M_im = im/result._M_re/2.f;
} else {
result._M_im = ::sqrt(0.5f * (mag - re));
if (im < 0.f)
result._M_im = - result._M_im;
result._M_re = im/result._M_im/2.f;
}
return result;
}
complex<float> _STLP_CALL
sqrt(const complex<float>& z) { return sqrtT(z); }
complex<double> _STLP_CALL
sqrt(const complex<double>& z) { return sqrtT(z); }
#if !defined (_STLP_NO_LONG_DOUBLE)
complex<long double> _STLP_CALL
sqrt(const complex<long double>& z) { return sqrtT(z); }
#endif
// exp, log, pow for complex<float>, complex<double>, and complex<long double>
//----------------------------------------------------------------------
// exp
template <class _Tp>
static complex<_Tp> expT(const complex<_Tp>& z) {
_Tp expx = ::exp(z._M_re);
return complex<_Tp>(expx * ::cos(z._M_im),
expx * ::sin(z._M_im));
}
_STLP_DECLSPEC complex<float> _STLP_CALL exp(const complex<float>& z)
{ return expT(z); }
_STLP_DECLSPEC complex<double> _STLP_CALL exp(const complex<double>& z)
{ return expT(z); }
#if !defined (_STLP_NO_LONG_DOUBLE)
_STLP_DECLSPEC complex<long double> _STLP_CALL exp(const complex<long double>& z)
{ return expT(z); }
#endif
//----------------------------------------------------------------------
// log10
template <class _Tp>
static complex<_Tp> log10T(const complex<_Tp>& z, const _Tp& ln10_inv) {
complex<_Tp> r;
r._M_im = ::atan2(z._M_im, z._M_re) * ln10_inv;
r._M_re = ::log10(::hypot(z._M_re, z._M_im));
return r;
}
_STLP_DECLSPEC complex<float> _STLP_CALL log10(const complex<float>& z)
{
const float LN10_INVF = 1.f / ::log(10.f);
return log10T(z, LN10_INVF);
}
_STLP_DECLSPEC complex<double> _STLP_CALL log10(const complex<double>& z)
{
const double LN10_INV = 1. / ::log10(10.);
return log10T(z, LN10_INV);
}
#if !defined (_STLP_NO_LONG_DOUBLE)
_STLP_DECLSPEC complex<long double> _STLP_CALL log10(const complex<long double>& z)
{
const long double LN10_INVL = 1.l / ::log(10.l);
return log10T(z, LN10_INVL);
}
#endif
//----------------------------------------------------------------------
// log
template <class _Tp>
static complex<_Tp> logT(const complex<_Tp>& z) {
complex<_Tp> r;
r._M_im = ::atan2(z._M_im, z._M_re);
r._M_re = ::log(::hypot(z._M_re, z._M_im));
return r;
}
_STLP_DECLSPEC complex<float> _STLP_CALL log(const complex<float>& z)
{ return logT(z); }
_STLP_DECLSPEC complex<double> _STLP_CALL log(const complex<double>& z)
{ return logT(z); }
#ifndef _STLP_NO_LONG_DOUBLE
_STLP_DECLSPEC complex<long double> _STLP_CALL log(const complex<long double>& z)
{ return logT(z); }
# endif
//----------------------------------------------------------------------
// pow
template <class _Tp>
static complex<_Tp> powT(const _Tp& a, const complex<_Tp>& b) {
_Tp logr = ::log(a);
_Tp x = ::exp(logr * b._M_re);
_Tp y = logr * b._M_im;
return complex<_Tp>(x * ::cos(y), x * ::sin(y));
}
template <class _Tp>
static complex<_Tp> powT(const complex<_Tp>& z_in, int n) {
complex<_Tp> z = z_in;
z = _STLP_PRIV __power(z, (n < 0 ? -n : n), multiplies< complex<_Tp> >());
if (n < 0)
return _Tp(1.0) / z;
else
return z;
}
template <class _Tp>
static complex<_Tp> powT(const complex<_Tp>& a, const _Tp& b) {
_Tp logr = ::log(::hypot(a._M_re,a._M_im));
_Tp logi = ::atan2(a._M_im, a._M_re);
_Tp x = ::exp(logr * b);
_Tp y = logi * b;
return complex<_Tp>(x * ::cos(y), x * ::sin(y));
}
template <class _Tp>
static complex<_Tp> powT(const complex<_Tp>& a, const complex<_Tp>& b) {
_Tp logr = ::log(::hypot(a._M_re,a._M_im));
_Tp logi = ::atan2(a._M_im, a._M_re);
_Tp x = ::exp(logr * b._M_re - logi * b._M_im);
_Tp y = logr * b._M_im + logi * b._M_re;
return complex<_Tp>(x * ::cos(y), x * ::sin(y));
}
_STLP_DECLSPEC complex<float> _STLP_CALL pow(const float& a, const complex<float>& b)
{ return powT(a, b); }
_STLP_DECLSPEC complex<float> _STLP_CALL pow(const complex<float>& z_in, int n)
{ return powT(z_in, n); }
_STLP_DECLSPEC complex<float> _STLP_CALL pow(const complex<float>& a, const float& b)
{ return powT(a, b); }
_STLP_DECLSPEC complex<float> _STLP_CALL pow(const complex<float>& a, const complex<float>& b)
{ return powT(a, b); }
_STLP_DECLSPEC complex<double> _STLP_CALL pow(const double& a, const complex<double>& b)
{ return powT(a, b); }
_STLP_DECLSPEC complex<double> _STLP_CALL pow(const complex<double>& z_in, int n)
{ return powT(z_in, n); }
_STLP_DECLSPEC complex<double> _STLP_CALL pow(const complex<double>& a, const double& b)
{ return powT(a, b); }
_STLP_DECLSPEC complex<double> _STLP_CALL pow(const complex<double>& a, const complex<double>& b)
{ return powT(a, b); }
#if !defined (_STLP_NO_LONG_DOUBLE)
_STLP_DECLSPEC complex<long double> _STLP_CALL pow(const long double& a,
const complex<long double>& b)
{ return powT(a, b); }
_STLP_DECLSPEC complex<long double> _STLP_CALL pow(const complex<long double>& z_in, int n)
{ return powT(z_in, n); }
_STLP_DECLSPEC complex<long double> _STLP_CALL pow(const complex<long double>& a,
const long double& b)
{ return powT(a, b); }
_STLP_DECLSPEC complex<long double> _STLP_CALL pow(const complex<long double>& a,
const complex<long double>& b)
{ return powT(a, b); }
#endif
_STLP_END_NAMESPACE

Просмотреть файл

@ -0,0 +1,157 @@
/*
* Copyright (c) 1999
* Silicon Graphics Computer Systems, Inc.
*
* Copyright (c) 1999
* Boris Fomitchev
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
#include "stlport_prefix.h"
#include <complex>
#include <istream>
_STLP_BEGIN_NAMESPACE
// Specializations for narrow characters; lets us avoid the nuisance of
// widening.
_STLP_OPERATOR_SPEC
basic_ostream<char, char_traits<char> >& _STLP_CALL
operator<< (basic_ostream<char, char_traits<char> >& __os, const complex<float>& __z)
{ return __os << '(' << (double)__z.real() << ',' << (double)__z.imag() << ')'; }
_STLP_OPERATOR_SPEC
basic_ostream<char, char_traits<char> >& _STLP_CALL
operator<< (basic_ostream<char, char_traits<char> >& __os, const complex<double>& __z)
{ return __os << '(' << __z.real() << ',' << __z.imag() << ')'; }
#ifndef _STLP_NO_LONG_DOUBLE
_STLP_OPERATOR_SPEC
basic_ostream<char, char_traits<char> >& _STLP_CALL
operator<< (basic_ostream<char, char_traits<char> >& __os, const complex<long double>& __z)
{ return __os << '(' << __z.real() << ',' << __z.imag() << ')'; }
#endif
// Specialization for narrow characters; lets us avoid widen.
_STLP_OPERATOR_SPEC
basic_istream<char, char_traits<char> >& _STLP_CALL
operator>>(basic_istream<char, char_traits<char> >& __is, complex<float>& __z) {
float __re = 0;
float __im = 0;
char __c;
__is >> __c;
if (__c == '(') {
__is >> __re >> __c;
if (__c == ',')
__is >> __im >> __c;
if (__c != ')')
__is.setstate(ios_base::failbit);
}
else {
__is.putback(__c);
__is >> __re;
}
if (__is)
__z = complex<float>(__re, __im);
return __is;
}
_STLP_OPERATOR_SPEC
basic_istream<char, char_traits<char> >& _STLP_CALL
operator>>(basic_istream<char, char_traits<char> >& __is, complex<double>& __z) {
double __re = 0;
double __im = 0;
char __c;
__is >> __c;
if (__c == '(') {
__is >> __re >> __c;
if (__c == ',')
__is >> __im >> __c;
if (__c != ')')
__is.setstate(ios_base::failbit);
}
else {
__is.putback(__c);
__is >> __re;
}
if (__is)
__z = complex<double>(__re, __im);
return __is;
}
#ifndef _STLP_NO_LONG_DOUBLE
_STLP_OPERATOR_SPEC
basic_istream<char, char_traits<char> >& _STLP_CALL
operator>>(basic_istream<char, char_traits<char> >& __is, complex<long double>& __z) {
long double __re = 0;
long double __im = 0;
char __c;
__is >> __c;
if (__c == '(') {
__is >> __re >> __c;
if (__c == ',')
__is >> __im >> __c;
if (__c != ')')
__is.setstate(ios_base::failbit);
}
else {
__is.putback(__c);
__is >> __re;
}
if (__is)
__z = complex<long double>(__re, __im);
return __is;
}
#endif
// Force instantiation of complex I/O functions
#if !(defined (_STLP_NO_FORCE_INSTANTIATE) || defined (_STLP_NO_WCHAR_T))
_STLP_OPERATOR_SPEC basic_istream<wchar_t, char_traits<wchar_t> >& _STLP_CALL
operator>>(basic_istream<wchar_t, char_traits<wchar_t> >&, complex<float>&);
_STLP_OPERATOR_SPEC basic_istream<wchar_t, char_traits<wchar_t> >& _STLP_CALL
operator>>(basic_istream<wchar_t, char_traits<wchar_t> >&, complex<double>&);
#ifndef _STLP_NO_LONG_DOUBLE
_STLP_OPERATOR_SPEC basic_istream<wchar_t, char_traits<wchar_t> >& _STLP_CALL
operator>>(basic_istream<wchar_t, char_traits<wchar_t> >&, complex<long double>&);
_STLP_OPERATOR_SPEC basic_ostream<wchar_t, char_traits<wchar_t> >& _STLP_CALL
operator<<(basic_ostream<wchar_t, char_traits<wchar_t> >&, const complex<long double>&);
#endif
_STLP_OPERATOR_SPEC basic_ostream<wchar_t, char_traits<wchar_t> >& _STLP_CALL
operator<<(basic_ostream<wchar_t, char_traits<wchar_t> >&, const complex<float>&);
_STLP_OPERATOR_SPEC basic_ostream<wchar_t, char_traits<wchar_t> >& _STLP_CALL
operator<<(basic_ostream<wchar_t, char_traits<wchar_t> >&, const complex<double>&);
#endif /* _STLP_NO_WCHAR_T */
_STLP_END_NAMESPACE
// Local Variables:
// mode:C++
// End:

Просмотреть файл

@ -0,0 +1,192 @@
/*
* Copyright (c) 1999
* Silicon Graphics Computer Systems, Inc.
*
* Copyright (c) 1999
* Boris Fomitchev
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
#include "stlport_prefix.h"
// Trigonometric and hyperbolic functions for complex<float>,
// complex<double>, and complex<long double>
#include <complex>
#include <cfloat>
#include <cmath>
_STLP_BEGIN_NAMESPACE
//----------------------------------------------------------------------
// helpers
#if defined (__sgi)
static const union { unsigned int i; float f; } float_ulimit = { 0x42b2d4fc };
static const float float_limit = float_ulimit.f;
static union {
struct { unsigned int h; unsigned int l; } w;
double d;
} double_ulimit = { 0x408633ce, 0x8fb9f87d };
static const double double_limit = double_ulimit.d;
static union {
struct { unsigned int h[2]; unsigned int l[2]; } w;
long double ld;
} ldouble_ulimit = {0x408633ce, 0x8fb9f87e, 0xbd23b659, 0x4e9bd8b1};
# if !defined (_STLP_NO_LONG_DOUBLE)
# define ldouble_limit ldouble_ulimit.ld
# endif
#else
# if defined (M_LN2) && defined (FLT_MAX_EXP)
static const float float_limit = float(M_LN2 * FLT_MAX_EXP);
static const double double_limit = M_LN2 * DBL_MAX_EXP;
# else
static const float float_limit = ::log(FLT_MAX);
static const double double_limit = ::log(DBL_MAX);
# endif
# if !defined (_STLP_NO_LONG_DOUBLE)
# if defined (M_LN2l)
# define ldouble_limit (M_LN2l * LDBL_MAX_EXP)
# else
# define ldouble_limit ::log(LDBL_MAX)
# endif
# endif
#endif
//----------------------------------------------------------------------
// sin
template <class _Tp>
static complex<_Tp> sinT(const complex<_Tp>& z) {
return complex<_Tp>(::sin(z._M_re) * ::cosh(z._M_im),
::cos(z._M_re) * ::sinh(z._M_im));
}
_STLP_DECLSPEC complex<float> _STLP_CALL sin(const complex<float>& z)
{ return sinT(z); }
_STLP_DECLSPEC complex<double> _STLP_CALL sin(const complex<double>& z)
{ return sinT(z); }
#if !defined (_STLP_NO_LONG_DOUBLE)
_STLP_DECLSPEC complex<long double> _STLP_CALL sin(const complex<long double>& z)
{ return sinT(z); }
#endif
//----------------------------------------------------------------------
// cos
template <class _Tp>
static complex<_Tp> cosT(const complex<_Tp>& z) {
return complex<_Tp>(::cos(z._M_re) * ::cosh(z._M_im),
-::sin(z._M_re) * ::sinh(z._M_im));
}
_STLP_DECLSPEC complex<float> _STLP_CALL cos(const complex<float>& z)
{ return cosT(z); }
_STLP_DECLSPEC complex<double> _STLP_CALL cos(const complex<double>& z)
{ return cosT(z); }
#if !defined (_STLP_NO_LONG_DOUBLE)
_STLP_DECLSPEC complex<long double> _STLP_CALL cos(const complex<long double>& z)
{ return cosT(z); }
#endif
//----------------------------------------------------------------------
// tan
template <class _Tp>
static complex<_Tp> tanT(const complex<_Tp>& z, const _Tp& Tp_limit) {
_Tp re2 = 2.f * z._M_re;
_Tp im2 = 2.f * z._M_im;
if (::abs(im2) > Tp_limit)
return complex<_Tp>(0.f, (im2 > 0 ? 1.f : -1.f));
else {
_Tp den = ::cos(re2) + ::cosh(im2);
return complex<_Tp>(::sin(re2) / den, ::sinh(im2) / den);
}
}
_STLP_DECLSPEC complex<float> _STLP_CALL tan(const complex<float>& z)
{ return tanT(z, float_limit); }
_STLP_DECLSPEC complex<double> _STLP_CALL tan(const complex<double>& z)
{ return tanT(z, double_limit); }
#if !defined (_STLP_NO_LONG_DOUBLE)
_STLP_DECLSPEC complex<long double> _STLP_CALL tan(const complex<long double>& z)
{ return tanT(z, ldouble_limit); }
#endif
//----------------------------------------------------------------------
// sinh
template <class _Tp>
static complex<_Tp> sinhT(const complex<_Tp>& z) {
return complex<_Tp>(::sinh(z._M_re) * ::cos(z._M_im),
::cosh(z._M_re) * ::sin(z._M_im));
}
_STLP_DECLSPEC complex<float> _STLP_CALL sinh(const complex<float>& z)
{ return sinhT(z); }
_STLP_DECLSPEC complex<double> _STLP_CALL sinh(const complex<double>& z)
{ return sinhT(z); }
#if !defined (_STLP_NO_LONG_DOUBLE)
_STLP_DECLSPEC complex<long double> _STLP_CALL sinh(const complex<long double>& z)
{ return sinhT(z); }
#endif
//----------------------------------------------------------------------
// cosh
template <class _Tp>
static complex<_Tp> coshT(const complex<_Tp>& z) {
return complex<_Tp>(::cosh(z._M_re) * ::cos(z._M_im),
::sinh(z._M_re) * ::sin(z._M_im));
}
_STLP_DECLSPEC complex<float> _STLP_CALL cosh(const complex<float>& z)
{ return coshT(z); }
_STLP_DECLSPEC complex<double> _STLP_CALL cosh(const complex<double>& z)
{ return coshT(z); }
#if !defined (_STLP_NO_LONG_DOUBLE)
_STLP_DECLSPEC complex<long double> _STLP_CALL cosh(const complex<long double>& z)
{ return coshT(z); }
#endif
//----------------------------------------------------------------------
// tanh
template <class _Tp>
static complex<_Tp> tanhT(const complex<_Tp>& z, const _Tp& Tp_limit) {
_Tp re2 = 2.f * z._M_re;
_Tp im2 = 2.f * z._M_im;
if (::abs(re2) > Tp_limit)
return complex<_Tp>((re2 > 0 ? 1.f : -1.f), 0.f);
else {
_Tp den = ::cosh(re2) + ::cos(im2);
return complex<_Tp>(::sinh(re2) / den, ::sin(im2) / den);
}
}
_STLP_DECLSPEC complex<float> _STLP_CALL tanh(const complex<float>& z)
{ return tanhT(z, float_limit); }
_STLP_DECLSPEC complex<double> _STLP_CALL tanh(const complex<double>& z)
{ return tanhT(z, double_limit); }
#if !defined (_STLP_NO_LONG_DOUBLE)
_STLP_DECLSPEC complex<long double> _STLP_CALL tanh(const complex<long double>& z)
{ return tanhT(z, ldouble_limit); }
#endif
_STLP_END_NAMESPACE

486
build/stlport/src/ctype.cpp Normal file
Просмотреть файл

@ -0,0 +1,486 @@
/*
* Copyright (c) 1999
* Silicon Graphics Computer Systems, Inc.
*
* Copyright (c) 1999
* Boris Fomitchev
*
* This material is provided "as is", with absolutely no warranty expressed
* or implied. Any use is at your own risk.
*
* Permission to use or copy this software for any purpose is hereby granted
* without fee, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
#include "stlport_prefix.h"
#include <algorithm>
#include <locale>
#include <functional>
#include "c_locale.h"
_STLP_BEGIN_NAMESPACE
//----------------------------------------------------------------------
// ctype<char>
// The classic table: static data members.
#if !defined (_STLP_STATIC_CONST_INIT_BUG) && !defined (_STLP_NO_STATIC_CONST_DEFINITION)
//*TY 02/25/2000 - added workaround for MPW compilers; they confuse on in-class static const
const size_t ctype<char>::table_size;
#endif
// This macro is specifically for platforms where isprint() relies
// on separate flag
const ctype_base::mask*
ctype<char>::classic_table() _STLP_NOTHROW {
/* Ctype table for the ASCII character set. */
static const ctype_base::mask _S_classic_table[table_size] = {
cntrl /* null */,
cntrl /* ^A */,
cntrl /* ^B */,
cntrl /* ^C */,
cntrl /* ^D */,
cntrl /* ^E */,
cntrl /* ^F */,
cntrl /* ^G */,
cntrl /* ^H */,
ctype_base::mask(space | cntrl) /* tab */,
ctype_base::mask(space | cntrl) /* LF */,
ctype_base::mask(space | cntrl) /* ^K */,
ctype_base::mask(space | cntrl) /* FF */,
ctype_base::mask(space | cntrl) /* ^M */,
cntrl /* ^N */,
cntrl /* ^O */,
cntrl /* ^P */,
cntrl /* ^Q */,
cntrl /* ^R */,
cntrl /* ^S */,
cntrl /* ^T */,
cntrl /* ^U */,
cntrl /* ^V */,
cntrl /* ^W */,
cntrl /* ^X */,
cntrl /* ^Y */,
cntrl /* ^Z */,
cntrl /* esc */,
cntrl /* ^\ */,
cntrl /* ^] */,
cntrl /* ^^ */,
cntrl /* ^_ */,
ctype_base::mask(space | print) /* */,
ctype_base::mask(punct | print) /* ! */,
ctype_base::mask(punct | print) /* " */,
ctype_base::mask(punct | print) /* # */,
ctype_base::mask(punct | print) /* $ */,
ctype_base::mask(punct | print) /* % */,
ctype_base::mask(punct | print) /* & */,
ctype_base::mask(punct | print) /* ' */,
ctype_base::mask(punct | print) /* ( */,
ctype_base::mask(punct | print) /* ) */,
ctype_base::mask(punct | print) /* * */,
ctype_base::mask(punct | print) /* + */,
ctype_base::mask(punct | print) /* , */,
ctype_base::mask(punct | print) /* - */,
ctype_base::mask(punct | print) /* . */,
ctype_base::mask(punct | print) /* / */,
ctype_base::mask(digit | print | xdigit) /* 0 */,
ctype_base::mask(digit | print | xdigit) /* 1 */,
ctype_base::mask(digit | print | xdigit) /* 2 */,
ctype_base::mask(digit | print | xdigit) /* 3 */,
ctype_base::mask(digit | print | xdigit) /* 4 */,
ctype_base::mask(digit | print | xdigit) /* 5 */,
ctype_base::mask(digit | print | xdigit) /* 6 */,
ctype_base::mask(digit | print | xdigit) /* 7 */,
ctype_base::mask(digit | print | xdigit) /* 8 */,
ctype_base::mask(digit | print | xdigit) /* 9 */,
ctype_base::mask(punct | print) /* : */,
ctype_base::mask(punct | print) /* ; */,
ctype_base::mask(punct | print) /* < */,
ctype_base::mask(punct | print) /* = */,
ctype_base::mask(punct | print) /* > */,
ctype_base::mask(punct | print) /* ? */,
ctype_base::mask(punct | print) /* ! */,
ctype_base::mask(alpha | print | upper | xdigit) /* A */,
ctype_base::mask(alpha | print | upper | xdigit) /* B */,
ctype_base::mask(alpha | print | upper | xdigit) /* C */,
ctype_base::mask(alpha | print | upper | xdigit) /* D */,
ctype_base::mask(alpha | print | upper | xdigit) /* E */,
ctype_base::mask(alpha | print | upper | xdigit) /* F */,
ctype_base::mask(alpha | print | upper) /* G */,
ctype_base::mask(alpha | print | upper) /* H */,
ctype_base::mask(alpha | print | upper) /* I */,
ctype_base::mask(alpha | print | upper) /* J */,
ctype_base::mask(alpha | print | upper) /* K */,
ctype_base::mask(alpha | print | upper) /* L */,
ctype_base::mask(alpha | print | upper) /* M */,
ctype_base::mask(alpha | print | upper) /* N */,
ctype_base::mask(alpha | print | upper) /* O */,
ctype_base::mask(alpha | print | upper) /* P */,
ctype_base::mask(alpha | print | upper) /* Q */,
ctype_base::mask(alpha | print | upper) /* R */,
ctype_base::mask(alpha | print | upper) /* S */,
ctype_base::mask(alpha | print | upper) /* T */,
ctype_base::mask(alpha | print | upper) /* U */,
ctype_base::mask(alpha | print | upper) /* V */,
ctype_base::mask(alpha | print | upper) /* W */,
ctype_base::mask(alpha | print | upper) /* X */,
ctype_base::mask(alpha | print | upper) /* Y */,
ctype_base::mask(alpha | print | upper) /* Z */,
ctype_base::mask(punct | print) /* [ */,
ctype_base::mask(punct | print) /* \ */,
ctype_base::mask(punct | print) /* ] */,
ctype_base::mask(punct | print) /* ^ */,
ctype_base::mask(punct | print) /* _ */,
ctype_base::mask(punct | print) /* ` */,
ctype_base::mask(alpha | print | lower | xdigit) /* a */,
ctype_base::mask(alpha | print | lower | xdigit) /* b */,
ctype_base::mask(alpha | print | lower | xdigit) /* c */,
ctype_base::mask(alpha | print | lower | xdigit) /* d */,
ctype_base::mask(alpha | print | lower | xdigit) /* e */,
ctype_base::mask(alpha | print | lower | xdigit) /* f */,
ctype_base::mask(alpha | print | lower) /* g */,
ctype_base::mask(alpha | print | lower) /* h */,
ctype_base::mask(alpha | print | lower) /* i */,
ctype_base::mask(alpha | print | lower) /* j */,
ctype_base::mask(alpha | print | lower) /* k */,
ctype_base::mask(alpha | print | lower) /* l */,
ctype_base::mask(alpha | print | lower) /* m */,
ctype_base::mask(alpha | print | lower) /* n */,
ctype_base::mask(alpha | print | lower) /* o */,
ctype_base::mask(alpha | print | lower) /* p */,
ctype_base::mask(alpha | print | lower) /* q */,
ctype_base::mask(alpha | print | lower) /* r */,
ctype_base::mask(alpha | print | lower) /* s */,
ctype_base::mask(alpha | print | lower) /* t */,
ctype_base::mask(alpha | print | lower) /* u */,
ctype_base::mask(alpha | print | lower) /* v */,
ctype_base::mask(alpha | print | lower) /* w */,
ctype_base::mask(alpha | print | lower) /* x */,
ctype_base::mask(alpha | print | lower) /* y */,
ctype_base::mask(alpha | print | lower) /* z */,
ctype_base::mask(punct | print) /* { */,
ctype_base::mask(punct | print) /* | */,
ctype_base::mask(punct | print) /* } */,
ctype_base::mask(punct | print) /* ~ */,
cntrl /* del (0x7f)*/,
/* ASCII is a 7-bit code, so everything else is non-ASCII */
ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0),
ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0),
ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0),
ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0),
ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0),
ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0),
ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0),
ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0),
ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0),
ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0),
ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0),
ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0),
ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0),
ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0),
ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0),
ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0), ctype_base::mask(0)
};
return _S_classic_table;
}
// For every c in the range 0 <= c < 256, _S_upper[c] is the
// uppercased version of c and _S_lower[c] is the lowercased
// version. As before, these two tables assume the ASCII character
// set.
const unsigned char _S_upper[ctype<char>::table_size] =
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f,
0x60, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
0x58, 0x59, 0x5a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f,
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
};
const unsigned char _S_lower[ctype<char>::table_size] =
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
0x40, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f,
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
0x78, 0x79, 0x7a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f,
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f,
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f,
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
};
//An helper struct to check wchar_t index without generating warnings
//under some compilers (gcc) because of a limited range of value
//(when wchar_t is unsigned)
template <bool _IsSigned>
struct _WCharIndexT;
#if !(defined (__BORLANDC__) && !defined(__linux__)) && \
!(defined (__GNUC__) && (defined (__MINGW32__) || defined (__CYGWIN__))) && \
!defined (__ICL)
_STLP_TEMPLATE_NULL
struct _WCharIndexT<true> {
static bool in_range(wchar_t c, size_t upperBound) {
return c >= 0 && size_t(c) < upperBound;
}
};
#endif
_STLP_TEMPLATE_NULL
struct _WCharIndexT<false> {
static bool in_range(wchar_t c, size_t upperBound) {
return size_t(c) < upperBound;
}
};
typedef _WCharIndexT<wchar_t(-1) < 0> _WCharIndex;
// Some helper functions used in ctype<>::scan_is and scan_is_not.
struct _Ctype_is_mask : public unary_function<char, bool> {
ctype_base::mask _Mask;
const ctype_base::mask* _M_table;
_Ctype_is_mask(ctype_base::mask __m, const ctype_base::mask* __t) : _Mask(__m), _M_table(__t) {}
bool operator()(char __c) const { return (_M_table[(unsigned char) __c] & _Mask) != 0; }
};
struct _Ctype_not_mask : public unary_function<char, bool> {
ctype_base::mask _Mask;
const ctype_base::mask* _M_table;
_Ctype_not_mask(ctype_base::mask __m, const ctype_base::mask* __t) : _Mask(__m), _M_table(__t) {}
bool operator()(char __c) const { return (_M_table[(unsigned char) __c] & _Mask) == 0; }
};
ctype<char>::ctype(const ctype_base::mask * __tab, bool __del, size_t __refs) :
locale::facet(__refs),
_M_ctype_table(__tab ? __tab : classic_table()),
_M_delete(__tab && __del)
{}
ctype<char>::~ctype() {
if (_M_delete)
delete[] __CONST_CAST(ctype_base::mask *, _M_ctype_table);
}
const char*
#if defined (__DMC__)
_STLP_DECLSPEC
#endif
ctype<char>::scan_is(ctype_base::mask __m, const char* __low, const char* __high) const
{ return _STLP_STD::find_if(__low, __high, _Ctype_is_mask(__m, _M_ctype_table)); }
const char*
#if defined (__DMC__)
_STLP_DECLSPEC
#endif
ctype<char>::scan_not(ctype_base::mask __m, const char* __low, const char* __high) const
{ return _STLP_STD::find_if(__low, __high, _Ctype_not_mask(__m, _M_ctype_table)); }
char ctype<char>::do_toupper(char __c) const
{ return (char) _S_upper[(unsigned char) __c]; }
char ctype<char>::do_tolower(char __c) const
{ return (char) _S_lower[(unsigned char) __c]; }
const char* ctype<char>::do_toupper(char* __low, const char* __high) const {
for ( ; __low < __high; ++__low)
*__low = (char) _S_upper[(unsigned char) *__low];
return __high;
}
const char* ctype<char>::do_tolower(char* __low, const char* __high) const {
for ( ; __low < __high; ++__low)
*__low = (char) _S_lower[(unsigned char) *__low];
return __high;
}
char
ctype<char>::do_widen(char __c) const { return __c; }
const char*
ctype<char>::do_widen(const char* __low, const char* __high,
char* __to) const {
_STLP_PRIV __copy_trivial(__low, __high, __to);
return __high;
}
char
ctype<char>::do_narrow(char __c, char /* dfault */ ) const { return __c; }
const char*
ctype<char>::do_narrow(const char* __low, const char* __high,
char /* dfault */, char* __to) const {
_STLP_PRIV __copy_trivial(__low, __high, __to);
return __high;
}
#if !defined (_STLP_NO_WCHAR_T)
struct _Ctype_w_is_mask : public unary_function<wchar_t, bool> {
ctype_base::mask M;
const ctype_base::mask* table;
_Ctype_w_is_mask(ctype_base::mask m, const ctype_base::mask* t)
: M(m), table(t) {}
bool operator()(wchar_t c) const
{ return _WCharIndex::in_range(c, ctype<char>::table_size) && (table[c] & M); }
};
//----------------------------------------------------------------------
// ctype<wchar_t>
ctype<wchar_t>::~ctype() {}
bool ctype<wchar_t>::do_is(ctype_base::mask m, wchar_t c) const {
const ctype_base::mask * table = ctype<char>::classic_table();
return _WCharIndex::in_range(c, ctype<char>::table_size) && (m & table[c]);
}
const wchar_t* ctype<wchar_t>::do_is(const wchar_t* low, const wchar_t* high,
ctype_base::mask * vec) const {
// boris : not clear if this is the right thing to do...
const ctype_base::mask * table = ctype<char>::classic_table();
wchar_t c;
for ( ; low < high; ++low, ++vec) {
c = *low;
*vec = _WCharIndex::in_range(c, ctype<char>::table_size) ? table[c] : ctype_base::mask(0);
}
return high;
}
const wchar_t*
ctype<wchar_t>::do_scan_is(ctype_base::mask m,
const wchar_t* low, const wchar_t* high) const {
return find_if(low, high, _Ctype_w_is_mask(m, ctype<char>::classic_table()));
}
const wchar_t*
ctype<wchar_t>::do_scan_not(ctype_base::mask m,
const wchar_t* low, const wchar_t* high) const {
return find_if(low, high, not1(_Ctype_w_is_mask(m, ctype<char>::classic_table())));
}
wchar_t ctype<wchar_t>::do_toupper(wchar_t c) const {
return _WCharIndex::in_range(c, ctype<char>::table_size) ? (wchar_t)_S_upper[c]
: c;
}
const wchar_t*
ctype<wchar_t>::do_toupper(wchar_t* low, const wchar_t* high) const {
for ( ; low < high; ++low) {
wchar_t c = *low;
*low = _WCharIndex::in_range(c, ctype<char>::table_size) ? (wchar_t)_S_upper[c]
: c;
}
return high;
}
wchar_t ctype<wchar_t>::do_tolower(wchar_t c) const {
return _WCharIndex::in_range(c, ctype<char>::table_size) ? (wchar_t)_S_lower[c]
: c;
}
const wchar_t*
ctype<wchar_t>::do_tolower(wchar_t* low, const wchar_t* high) const {
for ( ; low < high; ++low) {
wchar_t c = *low;
*low = _WCharIndex::in_range(c, ctype<char>::table_size) ? (wchar_t)_S_lower[c]
: c;
}
return high;
}
wchar_t ctype<wchar_t>::do_widen(char c) const {
return (wchar_t)(unsigned char)c;
}
const char*
ctype<wchar_t>::do_widen(const char* low, const char* high,
wchar_t* dest) const {
while (low != high)
*dest++ = (wchar_t)(unsigned char)*low++;
return high;
}
char ctype<wchar_t>::do_narrow(wchar_t c, char dfault) const
{ return (unsigned char)c == c ? (char)c : dfault; }
const wchar_t* ctype<wchar_t>::do_narrow(const wchar_t* low,
const wchar_t* high,
char dfault, char* dest) const {
while (low != high) {
wchar_t c = *low++;
*dest++ = (unsigned char)c == c ? (char)c : dfault;
}
return high;
}
# endif
_STLP_END_NAMESPACE
// Local Variables:
// mode:C++
// End:

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше