Repository: snowie2000/mactype Branch: directwrite Commit: 4f16c40bb9a8 Files: 88 Total size: 1.8 MB Directory structure: gitextract_gw64c59c/ ├── .gitignore ├── EventLogging.cpp ├── EventLogging.h ├── GdiPlusTypes2.h ├── LICENSE ├── Makefile ├── Makefile.vc2005 ├── README.md ├── README_ja-JP.md ├── VersionHelper.cpp ├── VersionHelper.h ├── array.h ├── build.vc2005.bat ├── cache.cpp ├── cache.h ├── colorinvert.h ├── common.cpp ├── common.h ├── crc32.h ├── detours.h ├── directwrite.cpp ├── directwrite.h ├── dll.cpp ├── dll.h ├── doc/ │ ├── HOWTOBUILD.md │ └── glyph_to_bitmapex.diff ├── dynCodeHelper.cpp ├── dynCodeHelper.h ├── easyhook.h ├── expfunc.cpp ├── expfunc.def ├── ft - non-ref.cpp ├── ft.cpp ├── ft.h ├── ft2build.h ├── ft2vert.c ├── ft2vert.h ├── fteng.cpp ├── fteng.h ├── ftref.c ├── ftref.h ├── gdiPlusFlat2.cpp ├── gdiPlusFlat2.h ├── gdidll.rc ├── gdipp.icproj ├── gdipp.sln ├── gdipp.vcxproj ├── gdipp.vcxproj.filters ├── hash_list.cpp ├── hash_list.h ├── hook.cpp ├── hookCounter.cpp ├── hookCounter.h ├── hooklist.h ├── ivs_otft.h ├── json.hpp ├── macloader.rc ├── macloader.vcxproj ├── makelib.cmd ├── misc.cpp ├── optimize/ │ ├── UpgradeLog.XML │ ├── UpgradeLog2.XML │ ├── _UpgradeReport_Files/ │ │ ├── UpgradeReport.css │ │ └── UpgradeReport.xslt │ ├── mem_amd.icproj │ ├── mem_amd.sln │ ├── mem_amd.sln_old │ ├── mem_amd.vcproj │ ├── memcpy__amd.cpp │ ├── memcpy_amd.c │ ├── memcpy_amd.h │ └── optimize.h ├── override.cpp ├── override.h ├── ownedcs.cpp ├── ownedcs.h ├── resource ├── resource.h ├── run.cpp ├── settings.cpp ├── settings.h ├── stdint.h ├── strtoken.h ├── supinfo.h ├── tlsdata.h ├── undocAPI.h ├── wow64ext.h └── wow64layer.h ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .vs/ .vscode/ deps/ lib/ Debug*/ Rel*/ x64/ *.vcxproj.user *.DotSettings.user ================================================ FILE: EventLogging.cpp ================================================ // EventLogging.cpp: implementation of the EventLogging class. // ////////////////////////////////////////////////////////////////////// #include "EventLogging.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// EventLogging::EventLogging() //******************************************************************************* // Default Constructor is used register the event source //****************************************************************************** { // returns a handle that links the source to the registry this->m_hEventLinker = RegisterEventSource(NULL,L"MacType"); } EventLogging::~EventLogging() //******************************************************************************* // Destructor is used deregister the event source //******************************************************************************* { // Releases the handle to the registry DeregisterEventSource(m_hEventLinker); } void EventLogging::LogIt(WORD CategoryID, DWORD EventID, LPCTSTR ArrayOfStrings[], UINT NumOfArrayStr,LPVOID RawData,DWORD RawDataSize) //******************************************************************************* // Function is used to log the event into the .evt file. // Input: CategoryID is the events category classification // EventID is the events event classification // ArrayOfStrings is an array of pointers to strings that are passed for additional information gathering // NumOfArrayStr is the number of of strings in ArrayOfStrings // RawData is a void pointer to hold additional raw data for event reporting // RawDataSize is the size of RawData in bytes //******************************************************************************* { // Writes data to the event log ReportEvent(m_hEventLinker,EVENTLOG_INFORMATION_TYPE,CategoryID, EventID,NULL,NumOfArrayStr,RawDataSize,ArrayOfStrings,RawData); } ================================================ FILE: EventLogging.h ================================================ // EventLogging.h: interface for the EventLogging class. // ////////////////////////////////////////////////////////////////////// #include "common.h" #if !defined(AFX_EVENTLOGGING_H__4AED0DCC_4C48_4312_BA6F_E6B90AC47F32__INCLUDED_) #define AFX_EVENTLOGGING_H__4AED0DCC_4C48_4312_BA6F_E6B90AC47F32__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class EventLogging { public: EventLogging(); virtual ~EventLogging(); // Wrapper for ReportEvent that take care of Handle and EventType virtual void LogIt(WORD CategoryID, DWORD EventID, LPCTSTR ArrayOfStrings[] = NULL, UINT NumOfArrayStr = 0,LPVOID RawData = NULL,DWORD RawDataSize = 0); // data member to contain handle to registry HANDLE m_hEventLinker; }; #endif // !defined(AFX_EVENTLOGGING_H__4AED0DCC_4C48_4312_BA6F_E6B90AC47F32__INCLUDED_) ================================================ FILE: GdiPlusTypes2.h ================================================ /**************************************************************************\ * * Copyright (c) 1998-2001, Microsoft Corp. All Rights Reserved. * * Module Name: * * GdiplusTypes.h * * Abstract: * * GDI+ Types * \**************************************************************************/ #ifndef _GDIPLUSTYPES_H #define _GDIPLUSTYPES_H //-------------------------------------------------------------------------- // Callback functions //-------------------------------------------------------------------------- extern "C" { typedef BOOL (CALLBACK * ImageAbort)(VOID *); typedef ImageAbort DrawImageAbort; typedef ImageAbort GetThumbnailImageAbort; } // Callback for EnumerateMetafile methods. The parameters are: // recordType WMF, EMF, or EMF+ record type // flags (always 0 for WMF/EMF records) // dataSize size of the record data (in bytes), or 0 if no data // data pointer to the record data, or NULL if no data // callbackData pointer to callbackData, if any // This method can then call Metafile::PlayRecord to play the // record that was just enumerated. If this method returns // FALSE, the enumeration process is aborted. Otherwise, it continues. #if (GDIPVER >= 0x0110) // This is the main GDI+ Abort interface struct __declspec(novtable) GdiplusAbort { virtual HRESULT __stdcall Abort(void) = 0; }; #endif //(GDIPVER >= 0x0110) //-------------------------------------------------------------------------- // Primitive data types // // NOTE: // Types already defined in standard header files: // INT8 // UINT8 // INT16 // UINT16 // INT32 // UINT32 // INT64 // UINT64 // // Avoid using the following types: // LONG - use INT // ULONG - use UINT // DWORD - use UINT32 //-------------------------------------------------------------------------- typedef float REAL; #define REAL_MAX FLT_MAX #define REAL_MIN FLT_MIN #define REAL_TOLERANCE (FLT_MIN * 100) #define REAL_EPSILON 1.192092896e-07F /* FLT_EPSILON */ //-------------------------------------------------------------------------- // Forward declarations of common classes //-------------------------------------------------------------------------- class Size; class SizeF; class Point; class PointF; class Rect; class RectF; class CharacterRange; //-------------------------------------------------------------------------- // Status return values from GDI+ methods //-------------------------------------------------------------------------- enum Status { Ok = 0, GenericError = 1, InvalidParameter = 2, OutOfMemory = 3, ObjectBusy = 4, InsufficientBuffer = 5, NotImplemented = 6, Win32Error = 7, WrongState = 8, Aborted = 9, FileNotFound = 10, ValueOverflow = 11, AccessDenied = 12, UnknownImageFormat = 13, FontFamilyNotFound = 14, FontStyleNotFound = 15, NotTrueTypeFont = 16, UnsupportedGdiplusVersion = 17, GdiplusNotInitialized = 18, PropertyNotFound = 19, PropertyNotSupported = 20, #if (GDIPVER >= 0x0110) ProfileNotFound = 21, #endif //(GDIPVER >= 0x0110) }; //-------------------------------------------------------------------------- // Represents a dimension in a 2D coordinate system (floating-point coordinates) //-------------------------------------------------------------------------- class SizeF { public: SizeF() { Width = Height = 0.0f; } SizeF(IN const SizeF& size) { Width = size.Width; Height = size.Height; } SizeF(IN REAL width, IN REAL height) { Width = width; Height = height; } SizeF operator+(IN const SizeF& sz) const { return SizeF(Width + sz.Width, Height + sz.Height); } SizeF operator-(IN const SizeF& sz) const { return SizeF(Width - sz.Width, Height - sz.Height); } BOOL Equals(IN const SizeF& sz) const { return (Width == sz.Width) && (Height == sz.Height); } BOOL Empty() const { return (Width == 0.0f && Height == 0.0f); } public: REAL Width; REAL Height; }; //-------------------------------------------------------------------------- // Represents a dimension in a 2D coordinate system (integer coordinates) //-------------------------------------------------------------------------- class Size { public: Size() { Width = Height = 0; } Size(IN const Size& size) { Width = size.Width; Height = size.Height; } Size(IN INT width, IN INT height) { Width = width; Height = height; } Size operator+(IN const Size& sz) const { return Size(Width + sz.Width, Height + sz.Height); } Size operator-(IN const Size& sz) const { return Size(Width - sz.Width, Height - sz.Height); } BOOL Equals(IN const Size& sz) const { return (Width == sz.Width) && (Height == sz.Height); } BOOL Empty() const { return (Width == 0 && Height == 0); } public: INT Width; INT Height; }; //-------------------------------------------------------------------------- // Represents a location in a 2D coordinate system (floating-point coordinates) //-------------------------------------------------------------------------- class PointF { public: PointF() { X = Y = 0.0f; } PointF(IN const PointF &point) { X = point.X; Y = point.Y; } PointF(IN const SizeF &size) { X = size.Width; Y = size.Height; } PointF(IN REAL x, IN REAL y) { X = x; Y = y; } PointF operator+(IN const PointF& point) const { return PointF(X + point.X, Y + point.Y); } PointF operator-(IN const PointF& point) const { return PointF(X - point.X, Y - point.Y); } BOOL Equals(IN const PointF& point) { return (X == point.X) && (Y == point.Y); } public: REAL X; REAL Y; }; //-------------------------------------------------------------------------- // Represents a location in a 2D coordinate system (integer coordinates) //-------------------------------------------------------------------------- class Point { public: Point() { X = Y = 0; } Point(IN const Point &point) { X = point.X; Y = point.Y; } Point(IN const Size &size) { X = size.Width; Y = size.Height; } Point(IN INT x, IN INT y) { X = x; Y = y; } Point operator+(IN const Point& point) const { return Point(X + point.X, Y + point.Y); } Point operator-(IN const Point& point) const { return Point(X - point.X, Y - point.Y); } BOOL Equals(IN const Point& point) { return (X == point.X) && (Y == point.Y); } public: INT X; INT Y; }; //-------------------------------------------------------------------------- // Represents a rectangle in a 2D coordinate system (floating-point coordinates) //-------------------------------------------------------------------------- class RectF { public: RectF() { X = Y = Width = Height = 0.0f; } RectF(IN REAL x, IN REAL y, IN REAL width, IN REAL height) { X = x; Y = y; Width = width; Height = height; } RectF(IN const PointF& location, IN const SizeF& size) { X = location.X; Y = location.Y; Width = size.Width; Height = size.Height; } RectF* Clone() const { return new RectF(X, Y, Width, Height); } VOID GetLocation(OUT PointF* point) const { point->X = X; point->Y = Y; } VOID GetSize(OUT SizeF* size) const { size->Width = Width; size->Height = Height; } VOID GetBounds(OUT RectF* rect) const { rect->X = X; rect->Y = Y; rect->Width = Width; rect->Height = Height; } REAL GetLeft() const { return X; } REAL GetTop() const { return Y; } REAL GetRight() const { return X+Width; } REAL GetBottom() const { return Y+Height; } BOOL IsEmptyArea() const { return (Width <= REAL_EPSILON) || (Height <= REAL_EPSILON); } BOOL Equals(IN const RectF & rect) const { return X == rect.X && Y == rect.Y && Width == rect.Width && Height == rect.Height; } BOOL Contains(IN REAL x, IN REAL y) const { return x >= X && x < X+Width && y >= Y && y < Y+Height; } BOOL Contains(IN const PointF& pt) const { return Contains(pt.X, pt.Y); } BOOL Contains(IN const RectF& rect) const { return (X <= rect.X) && (rect.GetRight() <= GetRight()) && (Y <= rect.Y) && (rect.GetBottom() <= GetBottom()); } VOID Inflate(IN REAL dx, IN REAL dy) { X -= dx; Y -= dy; Width += 2*dx; Height += 2*dy; } VOID Inflate(IN const PointF& point) { Inflate(point.X, point.Y); } BOOL Intersect(IN const RectF& rect) { return Intersect(*this, *this, rect); } static BOOL Intersect(OUT RectF& c, IN const RectF& a, IN const RectF& b) { REAL right = min(a.GetRight(), b.GetRight()); REAL bottom = min(a.GetBottom(), b.GetBottom()); REAL left = max(a.GetLeft(), b.GetLeft()); REAL top = max(a.GetTop(), b.GetTop()); c.X = left; c.Y = top; c.Width = right - left; c.Height = bottom - top; return !c.IsEmptyArea(); } BOOL IntersectsWith(IN const RectF& rect) const { return (GetLeft() < rect.GetRight() && GetTop() < rect.GetBottom() && GetRight() > rect.GetLeft() && GetBottom() > rect.GetTop()); } static BOOL Union(OUT RectF& c, IN const RectF& a, IN const RectF& b) { REAL right = max(a.GetRight(), b.GetRight()); REAL bottom = max(a.GetBottom(), b.GetBottom()); REAL left = min(a.GetLeft(), b.GetLeft()); REAL top = min(a.GetTop(), b.GetTop()); c.X = left; c.Y = top; c.Width = right - left; c.Height = bottom - top; return !c.IsEmptyArea(); } VOID Offset(IN const PointF& point) { Offset(point.X, point.Y); } VOID Offset(IN REAL dx, IN REAL dy) { X += dx; Y += dy; } public: REAL X; REAL Y; REAL Width; REAL Height; }; //-------------------------------------------------------------------------- // Represents a rectangle in a 2D coordinate system (integer coordinates) //-------------------------------------------------------------------------- class Rect { public: Rect() { X = Y = Width = Height = 0; } Rect(IN INT x, IN INT y, IN INT width, IN INT height) { X = x; Y = y; Width = width; Height = height; } Rect(IN const Point& location, IN const Size& size) { X = location.X; Y = location.Y; Width = size.Width; Height = size.Height; } Rect* Clone() const { return new Rect(X, Y, Width, Height); } VOID GetLocation(OUT Point* point) const { point->X = X; point->Y = Y; } VOID GetSize(OUT Size* size) const { size->Width = Width; size->Height = Height; } VOID GetBounds(OUT Rect* rect) const { rect->X = X; rect->Y = Y; rect->Width = Width; rect->Height = Height; } INT GetLeft() const { return X; } INT GetTop() const { return Y; } INT GetRight() const { return X+Width; } INT GetBottom() const { return Y+Height; } BOOL IsEmptyArea() const { return (Width <= 0) || (Height <= 0); } BOOL Equals(IN const Rect & rect) const { return X == rect.X && Y == rect.Y && Width == rect.Width && Height == rect.Height; } BOOL Contains(IN INT x, IN INT y) const { return x >= X && x < X+Width && y >= Y && y < Y+Height; } BOOL Contains(IN const Point& pt) const { return Contains(pt.X, pt.Y); } BOOL Contains(IN Rect& rect) const { return (X <= rect.X) && (rect.GetRight() <= GetRight()) && (Y <= rect.Y) && (rect.GetBottom() <= GetBottom()); } VOID Inflate(IN INT dx, IN INT dy) { X -= dx; Y -= dy; Width += 2*dx; Height += 2*dy; } VOID Inflate(IN const Point& point) { Inflate(point.X, point.Y); } BOOL Intersect(IN const Rect& rect) { return Intersect(*this, *this, rect); } static BOOL Intersect(OUT Rect& c, IN const Rect& a, IN const Rect& b) { INT right = min(a.GetRight(), b.GetRight()); INT bottom = min(a.GetBottom(), b.GetBottom()); INT left = max(a.GetLeft(), b.GetLeft()); INT top = max(a.GetTop(), b.GetTop()); c.X = left; c.Y = top; c.Width = right - left; c.Height = bottom - top; return !c.IsEmptyArea(); } BOOL IntersectsWith(IN const Rect& rect) const { return (GetLeft() < rect.GetRight() && GetTop() < rect.GetBottom() && GetRight() > rect.GetLeft() && GetBottom() > rect.GetTop()); } static BOOL Union(OUT Rect& c, IN const Rect& a, IN const Rect& b) { INT right = max(a.GetRight(), b.GetRight()); INT bottom = max(a.GetBottom(), b.GetBottom()); INT left = min(a.GetLeft(), b.GetLeft()); INT top = min(a.GetTop(), b.GetTop()); c.X = left; c.Y = top; c.Width = right - left; c.Height = bottom - top; return !c.IsEmptyArea(); } VOID Offset(IN const Point& point) { Offset(point.X, point.Y); } VOID Offset(IN INT dx, IN INT dy) { X += dx; Y += dy; } public: INT X; INT Y; INT Width; INT Height; }; class PathData { public: PathData() { Count = 0; Points = NULL; Types = NULL; } ~PathData() { if (Points != NULL) { delete [] Points; } if (Types != NULL) { delete [] Types; } } private: PathData(const PathData &); PathData& operator=(const PathData &); public: INT Count; PointF* Points; __field_ecount_opt(Count) BYTE* Types; }; class CharacterRange { public: CharacterRange( INT first, INT length ) : First (first), Length (length) {} CharacterRange() : First(0), Length(0) {} CharacterRange & operator = (const CharacterRange &rhs) { First = rhs.First; Length = rhs.Length; return *this; } INT First; INT Length; }; #endif // !_GDIPLUSTYPES_HPP ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: Makefile ================================================ # usage: # nmake release build # nmake debug=1 debug build # nmake ddk=1 using DDK compiler # nmake sse=1 build for SSE capable CPUs (uses with ddk=1) # nmake clean clean all file(s) # nmake cleanobj clean object file(s) GDI_PREFIX = ..\gdi++ GDI_PREFIX_DDK = ..\gdi++ GDI_PREFIX_SSE = ..\gdi++_sse TARGET_EXE = $(GDI_PREFIX).exe TARGET_DLL = $(GDI_PREFIX).dll EXE_OBJS = run.obj gdiexe.res DLL_OBJS = hook.obj override.obj settings.obj cache.obj misc.obj expfunc.obj ft.obj fteng.obj ft2vert.obj gdidll.res LINK_LIBS = memcpy_amd.lib EXE_PREFIX = ..\gdiexe DLL_PREFIX = ..\gdidll .SUFFIXES: .c .cpp .obj .rc .res CPPFLAGS = /nologo /D "WIN32" LINKFLAGS = /nologo LINK_EXE = /map:$(EXE_PREFIX).map LINK_DLL = /map:$(DLL_PREFIX).map CPPOPT = /G6 /Gy /QI0f- /QIfdiv- LINKOPT = /opt:nowin98 /opt:icf /opt:ref !ifdef ddk TARGET_DLL = $(GDI_PREFIX_DDK).dll DLL_PREFIX = ..\gdidll !ifdef sse TARGET_EXE = $(GDI_PREFIX_SSE).exe TARGET_DLL = $(GDI_PREFIX_SSE).dll CPPOPT = $(CPPOPT) /GL /arch:SSE !else CPPOPT = /G7 /Gy /QI0f- /QIfdiv- /GL /arch:SSE2 !endif LINKOPT = $(LINKOPT) /ltcg /ignore:4070,4078 bufferoverflowU.lib LINK_LIBS = detoured_.lib detours_.lib $(LINK_LIBS) !else LINK_LIBS = detoured.lib detours.lib $(LINK_LIBS) !endif !ifdef ftstatic CPPFLAGS = $(CPPFLAGS) /D "FREETYPE_STATIC" FTLIB = freetypeMT !else FTLIB = freetype !endif !ifdef debug CPPFLAGS = $(CPPFLAGS) /Od /MDd /FD /GZ /Zi /D "DEBUG" /D "_DEBUG" LINKFLAGS = $(LINKFLAGS) /incremental:no /debug /machine:I386 /opt:ref /opt:noicf LINK_EXE = $(LINK_EXE) /pdb:$(EXE_PREFIX).pdb #LINK_DLL = $(LINK_DLL) $(FTLIB)D.lib /pdb:$(DLL_PREFIX).pdb LINK_DLL = $(LINK_DLL) $(FTLIB).lib /pdb:$(DLL_PREFIX).pdb !else CPPFLAGS = $(CPPFLAGS) $(CPPOPT) /O2 /MD LINK_DLL = $(LINK_DLL) $(LINKOPT) $(FTLIB).lib LINK_EXE = $(LINK_EXE) $(LINKOPT) !endif all: $(TARGET_EXE) $(TARGET_DLL) $(TARGET_EXE): $(EXE_OBJS) link $(LINKFLAGS) $(LINK_EXE) $(LINK_LIBS) /out:$@ $(EXE_OBJS) $(TARGET_DLL): $(DLL_OBJS) expfunc.def link /dll $(LINKFLAGS) $(LINK_DLL) $(LINK_LIBS) /def:expfunc.def /out:$@ $(DLL_OBJS) .c.obj: cl $(CPPFLAGS) /GF /GA /W3 /Fo$@ /c $< .cpp.obj: cl $(CPPFLAGS) /GF /GA /W3 /Fo$@ /c $< .rc.res: rc /l 0x411 $< clean: cleanobj @-erase "$(TARGET_EXE)" @-erase "$(TARGET_DLL)" cleanobj: @-erase $(EXE_OBJS) @-erase $(DLL_OBJS) @-erase ..\gdi???.map @-erase vc??.pdb @-erase vc??.idb @-erase "$(EXE_PREFIX).pdb" @-erase "$(DLL_PREFIX).pdb" @-erase "$(GDI_PREFIX).exp" @-erase "$(GDI_PREFIX).lib" @-erase "$(GDI_PREFIX_DDK).exp" @-erase "$(GDI_PREFIX_DDK).lib" @-erase "$(GDI_PREFIX_SSE).exp" @-erase "$(GDI_PREFIX_SSE).lib" hook.obj: hook.cpp ft.h hooklist.h override.h common.h array.h cache.h settings.h tlsdata.h fteng.h override.obj: override.cpp ft.h hooklist.h override.h common.h array.h cache.h settings.h tlsdata.h fteng.h supinfo.h cache.obj: cache.cpp hooklist.h override.h common.h array.h cache.h misc.obj: misc.cpp common.h array.h settings.obj: settings.cpp common.h array.h cache.h settings.h strtoken.h supinfo.h fteng.h expfunc.obj: expfunc.cpp common.h array.h cache.h settings.h ft.obj: ft.cpp ft.h override.h common.h array.h cache.h settings.h fteng.h ft2vert.h fteng.obj: fteng.cpp ft.h override.h common.h array.h cache.h settings.h fteng.h ft2vert.obj: ft2vert.c ft2vert.h run.obj: run.cpp expfunc.cpp supinfo.h gdiexe.rc gdiexe.res: gdiexe.rc gdidll.rc ================================================ FILE: Makefile.vc2005 ================================================ # usage: # nmake release build # nmake debug=1 debug build # nmake ddk=1 using DDK compiler # nmake oldpsdk=1 using old platform sdk (dynamic load SHILCreateFromPath()/SHFree()) # nmake clean clean all file(s) # nmake cleanobj clean object file(s) TARGET_EXE = ..\gdi++.exe TARGET_DLL = ..\gdi++.dll EXE_OBJS = run.obj gdiexe.res DLL_OBJS = hook.obj override.obj settings.obj cache.obj misc.obj expfunc.obj ft.obj fteng.obj ft2vert.obj gdidll.res memcpy_amd.obj DLL_LIBS = advapi32.lib GDI_PREFIX = ..\gdi++ EXE_PREFIX = ..\gdiexe DLL_PREFIX = ..\gdidll .SUFFIXES: .c .cpp .obj .rc .res CPPFLAGS = /nologo /D "WIN32" /I. /EHsc /D LINKFLAGS = /nologo LINK_EXE = /map:$(EXE_PREFIX).map LINK_DLL = /map:$(DLL_PREFIX).map CPPOPT = /Gy /arch:SSE LINKOPT = /opt:nowin98 /opt:icf /opt:ref !ifdef ddk GDI_PREFIX = ..\gdi++_G7-GS-SSE2_ddk TARGET_DLL = ..\gdi++_G7-GS-SSE2_ddk.dll DLL_PREFIX = ..\gdidll_G7-GS-SSE2_ddk CPPOPT = /G7 /Gy /GL /GS /arch:SSE2 LINKOPT = $(LINKOPT) /ltcg /ignore:4070,4078 bufferoverflowU.lib !endif !ifdef oldpsdk CPPFLAGS = $(CPPFLAGS) /D "OLD_PSDK" !endif !ifdef usetrace CPPFLAGS = $(CPPFLAGS) /D "USE_TRACE" !endif !ifdef ftstatic CPPFLAGS = $(CPPFLAGS) /D "FREETYPE_STATIC" FTLIB = freetypeMT !else FTLIB = freetype !endif !ifdef debug CPPFLAGS = $(CPPFLAGS) /Od /MTd /FD /GZ /Zi /D "DEBUG" /D "_DEBUG" LINKFLAGS = $(LINKFLAGS) /incremental:no /debug /machine:I386 /opt:ref /opt:noicf /Fm LINK_EXE = $(LINK_EXE) /pdb:$(EXE_PREFIX).pdb LINK_DLL = $(LINK_DLL) $(FTLIB)D.lib /pdb:$(DLL_PREFIX).pdb !else CPPFLAGS = $(CPPFLAGS) $(CPPOPT) /O2 /MT /GF /GL LINK_DLL = $(LINK_DLL) $(LINKOPT) $(FTLIB).lib LINK_EXE = $(LINK_EXE) $(LINKOPT) !endif !ifdef ddk all: $(TARGET_DLL) !else all: $(TARGET_EXE) $(TARGET_DLL) !endif $(TARGET_EXE): $(EXE_OBJS) link $(LINKFLAGS) $(LINK_EXE) /LTCG /out:$@ $(EXE_OBJS) $(TARGET_DLL): $(DLL_OBJS) expfunc.def link /dll $(LINKFLAGS) $(LINK_DLL) /LTCG /def:expfunc.def /out:$@ $(DLL_OBJS) $(DLL_LIBS) if exist $@.manifest mt -manifest $@.manifest -outputresource:$@;2 pgi: -del gdi++*.pg* link /dll $(LINKFLAGS) $(LINK_DLL) /LTCG:PGI /def:expfunc.def /out:gdi++.dll $(DLL_OBJS) $(DLL_LIBS) pgo: link /dll $(LINKFLAGS) $(LINK_DLL) /LTCG:PGO /def:expfunc.def /out:gdi++.dll $(DLL_OBJS) $(DLL_LIBS) .c.obj: cl $(CPPFLAGS) /W3 /Fo$@ /c $< .cpp.obj: cl $(CPPFLAGS) /W3 /Fo$@ /c $< .rc.res: rc /l 0x411 $< clean: cleanobj @-erase "$(TARGET_EXE)" @-erase "$(TARGET_DLL)" cleanobj: @-erase $(EXE_OBJS) @-erase $(DLL_OBJS) @-erase vc??.pdb @-erase vc??.idb @-erase "$(EXE_PREFIX).pdb" @-erase "$(DLL_PREFIX).pdb" @-erase "$(EXE_PREFIX).map" @-erase "$(DLL_PREFIX).map" @-erase "$(GDI_PREFIX).exp" @-erase "$(GDI_PREFIX).lib" memcpy_amd.obj: optimize/memcpy__amd.cpp optimize/memcpy_amd.h cl $(CPPFLAGS) /W3 /Fomemcpy_amd.obj /c optimize/memcpy__amd.cpp hook.obj: hook.cpp ft.h hooklist.h override.h common.h array.h cache.h settings.h tlsdata.h fteng.h override.obj: override.cpp ft.h hooklist.h override.h common.h array.h cache.h settings.h tlsdata.h fteng.h cache.obj: cache.cpp hooklist.h override.h common.h array.h cache.h misc.obj: misc.cpp common.h array.h settings.obj: settings.cpp common.h array.h cache.h settings.h strtoken.h expfunc.obj: expfunc.cpp common.h array.h cache.h settings.h ft.obj: ft.cpp ft.h override.h common.h array.h cache.h settings.h fteng.h ft2vert.h fteng.obj: fteng.cpp ft.h override.h common.h array.h cache.h settings.h fteng.h ft2vert.obj: ft2vert.c ft2vert.h run.obj: run.cpp expfunc.cpp gdiexe.rc gdiexe.res: gdiexe.rc gdidll.rc gdidll.res: gdidll.rc ================================================ FILE: README.md ================================================ MacType ======================== [日本語](./README_ja-JP.md) Better font rendering for Windows. Latest build ------------------ [Download](https://github.com/snowie2000/mactype/releases/latest) Official site ------------------ MacType official site: http://www.mactype.net (An archived version is restored) What's new? ------------------ - Win11 compatible - CET compatible - Updated FreeType - Support for color fonts :sunglasses: - New installer - Lots of bug fixes - Updates for multi-monitor support - Tray app can intercept explorer in Service Mode now - Tweaks for diacritics - Updates to EasyHook - Lower CPU in Tray Mode - Better DirectWrite support thanks to [しらいと](http://silight.hatenablog.jp) - Separate DirectWrite parameter adjustment - Traditional Chinese localization greatly improved thanks to GT Wang - English localization improved - Added Korea localization, thanks to 조현희 - MultiLang system improved Donation ------------------ MacType now accepts donations. Please visit http://www.mactype.net and keep an eye on the bottom right corner :heart: Thank you for your support! Your donations will keep the server running, keep me updating, and buy more coffees :coffee: Known issues --------------- - Please backup your profiles before upgrading! - Only Chinese simplified/Traditional and English are fully localized, some options may missing in MacType Tuner due to the strings missing in the language file. You can help with translations! - If you want to use MacType-patch together with MacType official release, remember to add DirectWrite=0 to your profile or you will have mysterious problems - If you're running 64 bit Windows, antimalware/antivirus software may conflict with MacType, because it sees MacType trying to modify running software. One possible workaround is to try running in Service Mode (recommended), or add HookChildProcesses=0 to your profile. See https://github.com/snowie2000/mactype/wiki/HookChildProcesses for an explanation - Office 2013 does not use DirectWrite or GDI (it uses its own custom rendering), so Office 2013 doesn't work with MacType. If this bothers you you can use Office 2010 which uses GDI or Office 2016+ which uses DirectWrite. - WPS has a built in defense that **UNLOADS** MacType automatically. The latest version has a workaround [here](https://github.com/snowie2000/mactype/wiki/WPS) thanks to wmjordan. How to get registry mode back ------------- It is no longer possible to enable registry mode via the wizard in Windows 10. We have a detailed guide on how you can enable the registry mode manually in [wiki](https://github.com/snowie2000/mactype/wiki/Enable-registry-mode-manually), get your screwdrivers ready before you head over to it. How to build ------------- Check how to build [document](https://github.com/snowie2000/mactype/blob/directwrite/doc/HOWTOBUILD.md) ================================================ FILE: README_ja-JP.md ================================================ MacType ======================== Windows のフォントレンダリングを改善。 最新ビルド ------------------ [ダウンロード](https://github.com/snowie2000/mactype/releases/latest) 公式サイト ------------------ MacType 公式サイト: http://www.mactype.net What's new? ------------------ - Win11 の互換性 - CET の互換性 - 更新された FreeType - カラーフォントのサポート :sunglasses: - 新しいインストーラー - 多くのバグ修正 - マルチモニターのサポートを更新 - サービスモードでエクスプローラーのトレイアプリを傍受 - ダイアクリティカルマークの調整 - EasyHook を更新 - トレイモードで CPU の低負荷設定 - [しらいと](http://silight.hatenablog.jp)氏による DirectWrite のサポートの向上 - DirectWrite パラメータの個別調整 - GT Wang による繁体字中国語の大幅な改善 - 英語訳の改善 - 韓国語訳の追加、조현희に感謝 - 多言語システムの改善 寄付 ------------------ MacType は現在寄付を受付中です。 http://www.mactype.net にアクセスして右下の隅にご注目ください :heart: ご支援ありがとうございます! 寄付金はサーバーの維持費、更新の継続、そしてコーヒーの購入に役立てられます :coffee: 既知の問題 --------------- - 更新をする前にプロファイルをバックアップしてください。 - 中国語 (繁体字/簡体字) と英語のみが完全にローカライズされており、言語ファイルに文字列の欠落があります。MacType Tuner で一部のオプションに欠落がある可能性があります。翻訳にご協力ください。 - MacType-patch を MacType 公式ビルドと一緒に使用したい場合は、プロファイルに「DirectWrite=0」を追加することを忘れないでください。この操作を忘れると動作に問題が発生します。 - 64 ビットの Windows を使用している場合、マルウェアまたはウィルス対策ソフトで MacType が競合する可能性があります。これは、MacType が実行中のソフトウェアを変更しようと認識するために発生します。回避策としてはサービスモード (推奨) で実行するか、プロファイルに「HookChildProcesses=0」を追加してください。
詳細な説明は https://github.com/snowie2000/mactype/wiki/HookChildProcesses を参照してください。 - Office 2013 は DirectWrite または GDI を使用していません (独自のカスタムレンダリングを使用しています)。そのため、Office 2013 で MacType は動作しません。これが気になる方は、GDI を使用している Office 2010 か DirectWrite を使用している Office 2016 以降を使用してください。 - WPS には MacType を自動的に **アンロード** する防御機能が組み込まれています。最新のバージョンでは、wmjordan の協力により[こちら](https://github.com/snowie2000/mactype/wiki/WPS)の回避策が用意されています。 レジストリモードを戻す方法 ------------- Windows 10 以降ではウィザードを使用したレジストリモードの有効化はできなくなりました。 レジストリモードを手動で有効化する方法については、[Wiki](https://github.com/snowie2000/mactype/wiki/Enable-registry-mode-manually) に詳しいガイドがあります。
アクセスする前にスクリュードライバーを準備してくださいね。 ビルドのやり方 ------------- ビルドについては[ドキュメント](https://github.com/snowie2000/mactype/blob/directwrite/doc/HOWTOBUILD.md)をご確認ください。 ================================================ FILE: VersionHelper.cpp ================================================ #include "VersionHelper.h" ////////////////////////////////////////////////////////////////////// // Konstruktion/Destruktion ////////////////////////////////////////////////////////////////////// CVersionHelper::CVersionHelper() { } CVersionHelper::~CVersionHelper() { } /***********************************************************************************/ /* */ /* Class: CVersionHelper */ /* Method: GetVersionInfo */ /* */ /* Parameters: */ /* ----------- */ /* HMODULE hLib */ /* Handle to the module that contains the resource (EXE or DLL) */ /* A value of NULL specifies the current applications resources */ /* */ /* CString csEntry */ /* Specifies the name of the resource. For more information, */ /* see the Remarks section. */ /* */ /* Return Values: */ /* -------------- */ /* If the function succeeds, the return value is a string containing the value */ /* of the specified resource. */ /* If the function fails, the returned string is empty. To get extended error */ /* information, call GetLastError. */ /* */ /* Remarks: */ /* -------- */ /* Since the Win32 API resource information is encoded in Unicode, this method */ /* also strips the strings from Unicode. */ /* */ /* The following valid values for csEntry, as specified by Microsoft are: */ /* CompanyName, FileDescription, FileVersion, InternalName, LegalCopyright, */ /* OriginalFilename, ProductName, ProductVersion, Comments, LegalTrademarks, */ /* PrivateBuild, SpecialBuild */ /* */ /* Opening the rc-file as "text" or with a text-editor allows you to add further */ /* entries to your version information structure and it is retrievable using */ /* this same method. */ /* */ /***********************************************************************************/ wstring CVersionHelper::GetVersionInfo(HMODULE hLib, wstring csEntry) { wstring csRet; if (hLib == NULL) return TEXT(""); HRSRC hVersion = FindResource(hLib, MAKEINTRESOURCE(VS_VERSION_INFO), RT_VERSION); if (hVersion != NULL) { HGLOBAL hGlobal = LoadResource(hLib, hVersion); if (hGlobal != NULL) { LPVOID versionInfo = LockResource(hGlobal); if (versionInfo != NULL) { char *pchVI = (char*)versionInfo; int dwSize = SizeofResource(hLib, hVersion); if (IsBadReadPtr(versionInfo, dwSize)) dwSize -= 4; char *pchVIcopy = new char[dwSize * 2 + 4]; memcpy(pchVIcopy, pchVI, (int)(dwSize * 2 + 4)); DWORD vLen, langD; BOOL retVal; LPVOID retbuf = NULL; static TCHAR fileEntry[256]; wsprintf(fileEntry, TEXT("\\VarFileInfo\\Translation")); retVal = VerQueryValue(pchVIcopy, fileEntry, &retbuf, (UINT *)&vLen); if (retVal && vLen == 4) { memcpy(&langD, retbuf, 4); wsprintf(fileEntry, TEXT("\\StringFileInfo\\%02X%02X%02X%02X\\%s"), (langD & 0xff00) >> 8, langD & 0xff, (langD & 0xff000000) >> 24, (langD & 0xff0000) >> 16, csEntry); } else wsprintf(fileEntry, TEXT("\\StringFileInfo\\%04X04B0\\%s"), GetUserDefaultLangID(), csEntry); if (VerQueryValue(pchVIcopy, fileEntry, &retbuf, (UINT *)&vLen)) csRet = (TCHAR*)retbuf; delete pchVIcopy; } } UnlockResource(hGlobal); FreeResource(hGlobal); } return csRet; } /***********************************************************************************/ /* */ /* Class: CGlobalFunctions */ /* Method: FormatVersion */ /* */ /* Parameters: */ /* ----------- */ /* CString cs */ /* Specifies a version number such as "FileVersion" or */ /* "ProductVersion" in the format "m, n, o, p" */ /* (e.g. "1, 2, 3, a") */ /* */ /* Return Values: */ /* -------------- */ /* If the function succeeds, the return value is a string containing the version */ /* in the format "m.nop" (e.g. "1.23a") */ /* */ /* If the function fails, the returned string is empty. */ /* */ /***********************************************************************************/ wstring CVersionHelper::FormatVersion(wstring cs) { wstring csRet; if (!cs.length()) { rtrim(cs); int iPos = cs.find(','); if (iPos == -1) return TEXT(""); ltrim(cs); rtrim(cs); csRet.Format(TEXT("%s."), cs.copy(iPos)); while (1) { cs = cs.Mid(iPos + 1); ltrim(cs); iPos = cs.find(','); if (iPos == -1) { csRet += cs; break; } csRet += cs.Left(iPos); } } return csRet; } /***********************************************************************************/ /* */ /* Class: CGlobalFunctions */ /* Method: GetFileVersionX */ /* */ /* Parameters: */ /* ----------- */ /* */ /* Return Values: */ /* -------------- */ /* If the function succeeds, the return value is a wstring containing the */ /* "FileVersion" in the format "m.nop" (e.g. "1.23a") */ /* */ /* If the function fails, the returned wstring is empty. */ /* */ /***********************************************************************************/ wstring CVersionHelper::GetFileVersionX() { if (!m_csFileVersion.length()) { wstring csVersion = FormatVersion(GetVersionInfo(NULL, TEXT("FileVersion"))); m_csFileVersion.Format(TEXT("Version %s (Build %s)"), csVersion, GetVersionInfo(NULL, TEXT("SpecialBuild"))); } return m_csFileVersion; } /***********************************************************************************/ /* */ /* Class: CGlobalFunctions */ /* Method: GetFileVersionX */ /* */ /* Parameters: */ /* ----------- */ /* */ /* Return Values: */ /* -------------- */ /* If the function succeeds, the return value is a string containing the */ /* "ProductVersion" in the format "m.nop" (e.g. "1.23a") */ /* */ /* If the function fails, the returned string is empty. */ /* */ /***********************************************************************************/ wstring CVersionHelper::GetProductVersionX() { if (!m_csProductVersion.length()) m_csProductVersion = FormatVersion(GetVersionInfo(NULL, TEXT("ProductVersion"))); return m_csProductVersion; } ================================================ FILE: VersionHelper.h ================================================ #pragma once #include #include #include #include using namespace std; class CVersionHelper { public: CVersionHelper(); virtual ~CVersionHelper(); public: wstring GetFileVersionX(); wstring GetProductVersionX(); wstring GetVersionInfo(HMODULE hLib, wstring csEntry); wstring FormatVersion(wstring cs); private: wstring m_csFileVersion; wstring m_csProductVersion; }; // cited: https://stackoverflow.com/questions/216823/whats-the-best-way-to-trim-stdstring // trim from start (in place) static inline void ltrim(std::wstring &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) { return !std::isspace(ch); })); } // trim from end (in place) static inline void rtrim(std::wstring &s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { return !std::isspace(ch); }).base(), s.end()); } ================================================ FILE: array.h ================================================ #pragma once #ifndef _INC_SHLWAPI #define NO_SHLWAPI_STRFCNS #define NO_SHLWAPI_PATH #define NO_SHLWAPI_REG #define NO_SHLWAPI_STREAM #define NO_SHLWAPI_GDI #include #endif #if !defined(_INC_SHLWAPI) || defined(NOSHLWAPI) || defined(NO_SHLWAPI_PATH) BOOL WINAPI PathIsRelative(LPCTSTR pszPath); BOOL WINAPI PathRemoveFileSpec(LPTSTR pszPath); LPTSTR WINAPI PathFindExtension(LPCTSTR pszPath); LPTSTR WINAPI PathAddBackslash(LPTSTR pszPath); LPTSTR WINAPI PathCombine(LPTSTR pszDest, LPCTSTR pszDir, LPCTSTR pszFile); #endif #include template class CArray : public CSimpleArray { public: T* Begin() const { return m_aT; } T* End() const { return m_aT + m_nSize; } }; template class CValArray : public CSimpleValArray { public: T* Begin() const { return m_aT; } T* End() const { return m_aT + m_nSize; } }; template class CPtrArray : public CValArray { }; template class CMap : public CSimpleMap { }; ================================================ FILE: build.vc2005.bat ================================================ @echo off setlocal set INCLUDE=..\..\..\freetype2\include;%INCLUDE% set LIB=..\..;%LIB% :go nmake -f Makefile.vc2005 %* if errorlevel 1 goto err goto end :err pause goto go :end endlocal rem pause ================================================ FILE: cache.cpp ================================================ #include "override.h" //CreateDIB计数,将在绘制下列次数后更新DIB区 #define BITMAP_REDUCE_COUNTER 256//默认1024 HDC CBitmapCache::CreateDC(HDC dc) { if(!m_hdc) { m_hdc = CreateCompatibleDC(dc); m_exthdc = dc; } return m_hdc; } HBITMAP CBitmapCache::CreateDIB(int width, int height, BYTE** lplpPixels) { SIZE& dibSize = m_dibSize; width = (width + 3) & ~3; if (dibSize.cx >= width && dibSize.cy >= height) { if (++m_counter < BITMAP_REDUCE_COUNTER) { *lplpPixels = m_lpPixels; return m_hbmp; } //カウンタ超過 //ただしサイズが全く同じなら再生成しない if (dibSize.cx == width && dibSize.cy == height) { m_counter = 0; *lplpPixels = m_lpPixels; return m_hbmp; } } else { if (dibSize.cx > width) { width = dibSize.cx; } if (dibSize.cy > height) { height = dibSize.cy; } } BITMAPINFOHEADER bmiHeader = { sizeof(BITMAPINFOHEADER), width, -height, 1, 32, BI_RGB }; HBITMAP hbmpNew = CreateDIBSection(CreateDC(m_exthdc), (BITMAPINFO*)&bmiHeader, DIB_RGB_COLORS, (LPVOID*)lplpPixels, NULL, 0); if (!hbmpNew) { return NULL; } TRACE(_T("width=%d, height=%d\n"), width, height); //メモリ不足等でhbmpNew==NULLの場合を想定し、 //成功したときのみキャッシュを更新 if (m_hbmp) { DeleteBitmap(m_hbmp); } m_hbmp = hbmpNew; dibSize.cx = width; dibSize.cy = height; //CreateDIBSectionは多分ページ境界かセグメント境界 m_lpPixels = *lplpPixels; m_counter = 0; return m_hbmp; } void CBitmapCache::FillSolidRect(COLORREF rgb, const RECT* lprc) { if (!m_brush || rgb!=m_bkColor) { if (m_brush) DeleteObject(m_brush); m_brush = CreateSolidBrush(rgb); m_bkColor = rgb; } FillRect(m_hdc, lprc, m_brush); //DrawHorizontalLine(lprc->left, lprc->top, lprc->right, rgb, lprc->bottom - lprc->top); /* LPBYTE lpPixels = m_lpPixels; const DWORD dwBmpBytes = m_dibSize.cx * m_dibSize.cy; rgb = RGB2DIB(rgb); //TODO: MMX or SSE化 __asm { mov edi, dword ptr [lpPixels] mov ecx, dword ptr [dwBmpBytes] mov eax, dword ptr [rgb] cld rep stosd }*/ // DWORD* p = (DWORD*)m_lpPixels; // DWORD* const pend = p + dwBmpBytes; // while (p < pend) { // *p++ = rgb; // } } //水平線を引く //(X1,Y1) (X2,Y1) // +-----------------+ ^ // | rgb | | width // +-----------------+ v void CBitmapCache::DrawHorizontalLine(int X1, int Y1, int X2, COLORREF rgb, int width) { if (!m_dibSize.cx || !m_dibSize.cy) { return; } if (X1 > X2) { const int xx = X1; X1 = X2; X2 = xx; } //クリッピング const int xSize = m_dibSize.cx; const int ySize = m_dibSize.cy; X1 = Bound(X1, 0, xSize); X2 = Bound(X2, 0, xSize); Y1 = Bound(Y1, 0, ySize); width = Max(width, 1); const int Y2 = Bound(Y1 + width, 0, ySize); rgb = RGB2DIB(rgb); DWORD* lpPixels = (DWORD*)m_lpPixels + (Y1 * xSize + X1); const int Xd = X2 - X1; const int Yd = Y2 - Y1; /* for (int yy=Y1; yy class StringHashT { private: DWORD m_dwHash; TCHAR m_szBuffer[BUFSIZE]; void UpdateHash() { DWORD dw = 0; LPWSTR p, end = m_szBuffer + BUFSIZE; for (p = m_szBuffer; *p && p < end; p++) { dw <<= 3; if (ignoreCase) { dw ^= _totlower(*p); } else { dw ^= *p; } } m_dwHash = dw; } public: StringHashT() : m_dwHash(0) { ZeroMemory(m_szBuffer, sizeof(m_szBuffer)); } StringHashT(LPCTSTR psz) { this->StringHashT::StringHashT(); _tcsncpy(m_szBuffer, psz, BUFSIZE - 1); UpdateHash(); } bool operator ==(const StringHashT& x) const { if (ignoreCase) { return !(m_dwHash != x.m_dwHash || _tcsicmp(m_szBuffer, x.m_szBuffer)); } else { return !(m_dwHash != x.m_dwHash || _tcscmp(m_szBuffer, x.m_szBuffer)); } } DWORD Hash() const { return m_dwHash; } LPCTSTR c_str() const { return m_szBuffer; } }; typedef StringHashT StringHashFont; typedef StringHashT StringHashModule; //COLORREF(RR GG BB 00) を DIB32(BB GG RR 00) に変換 #define RGB2DIB(rgb) RGB(GetBValue(rgb), GetGValue(rgb), GetRValue(rgb)) #define DIB2RGB(dib) RGB2DIB(dib) // ExtTextOutWのビットマップキャッシュ class CBitmapCache { private: HBRUSH m_brush; HDC m_hdc; HDC m_exthdc; HBITMAP m_hbmp; BYTE* m_lpPixels; SIZE m_dibSize; int m_counter; DWORD* m_CurrentPixel; COLORREF m_bkColor; NOCOPY(CBitmapCache); public: CBitmapCache() : m_hdc(NULL) , m_hbmp(NULL) , m_lpPixels(NULL) , m_counter(0) , m_CurrentPixel(NULL) , m_exthdc(NULL) , m_brush(NULL) , m_bkColor(NULL) { m_dibSize.cx = m_dibSize.cy = 0; } ~CBitmapCache() { if (m_hdc) { DeleteDC(m_hdc); } if (m_hbmp) { DeleteBitmap(m_hbmp); } if (m_brush) DeleteObject(m_brush); m_hdc = NULL; m_hbmp = NULL; m_brush = NULL; m_dibSize.cx = 0; m_dibSize.cy = 0; } const SIZE& Size() const { return m_dibSize; } BYTE* GetPixels() { Assert(m_lpPixels != NULL); return m_lpPixels; } DWORD GetPixel(int X, int Y) { if ((unsigned)X >= (unsigned)m_dibSize.cx || (unsigned)Y >= (unsigned)m_dibSize.cy) { return CLR_INVALID; } DWORD* lpPixels = (DWORD*)m_lpPixels; m_CurrentPixel = &lpPixels[Y * m_dibSize.cx + X]; DWORD dib = *m_CurrentPixel; return DIB2RGB(dib); } void SetPixelV(int X, int Y, COLORREF rgb) { // if ((unsigned)X >= (unsigned)m_dibSize.cx || (unsigned)Y >= (unsigned)m_dibSize.cy) { // return; // } DWORD* lpPixels = (DWORD*)m_lpPixels; m_CurrentPixel = &lpPixels[Y * m_dibSize.cx + X]; SetCurrentPixel(rgb); } void SetCurrentPixel(COLORREF rgb) { *m_CurrentPixel = RGB2DIB(rgb); } //本体はcache.cpp HDC CreateDC(HDC dc); HBITMAP CreateDIB(int width, int height, BYTE** lplpPixels); void FillSolidRect(COLORREF rgb, const RECT* lprc); void DrawHorizontalLine(int X1, int Y1, int X2, COLORREF rgb, int width); }; ================================================ FILE: colorinvert.h ================================================ #pragma once //formula: (x+482)^2+(y+481)^2=880^2 unsigned char InvertTable[260] = { 255,255,254,253,253,252,251,251,250,249,249,248,247,247,246,245,245,244,243,242,242,241,240,240,239,238,238,237,236,235,235,234,233,233,232,231,230,230,229,228,227,227,226,225,224,224,223,222,221,221,220,219,218,218,217,216,215,215,214,213,212,211,211,210,209,208,208,207,206,205,204,204,203,202,201,200,199,199,198,197,196,195,195,194,193,192,191,190,189,189,188,187,186,185,184,183,183,182,181,180,179,178,177,176,176,175,174,173,172,171,170,169,168,167,166,166,165,164,163,162,161,160,159,158,157,156,155,154,153,152,151,150,149,148,147,146,145,144,143,143,142,141,140,138,137,136,135,134,133,132,131,130,129,128,127,126,125,124,123,122,121,120,119,118,117,115,114,113,112,111,110,109,108,107,106,104,103,102,101,100,99,98,96,95,94,93,92,91,90,88,87,86,85,84,82,81,80,79,78,76,75,74,73,71,70,69,68,66,65,64,63,61,60,59,58,56,55,54,52,51,50,48,47,46,44,43,42,40,39,38,36,35,33,32,31,29,28,26,25,24,22,21,19,18,16,15,13,12,10,9,7,6,4,3,1,0,0,0,0,0}; ================================================ FILE: common.cpp ================================================ #include "common.h" std::wstring to_utf16le(const std::wstring& input) { std::wstring utf16_string; int len = input.length(); char* content = (char*)input.c_str(); utf16_string.reserve(len); for (size_t i = 0; i < len; i += 2) { char16_t code_unit = (static_cast(content[i]) << 8) | static_cast(content[i + 1]); utf16_string.push_back(code_unit); } return utf16_string; } std::wstring to_wide_string(const std::string& input) { std::wstring_convert> converter; return converter.from_bytes(input); } // convert wstring to string std::string to_byte_string(const std::wstring& input) { //std::wstring_convert> converter; std::wstring_convert> converter; return converter.to_bytes(input); } wstring to_lower_case(wstring str) { transform(str.begin(), str.end(), str.begin(), ::tolower); return str; } ================================================ FILE: common.h ================================================ #pragma once #define _CRT_SECURE_NO_DEPRECATE 1 #ifdef _WIN64 #define _WIN32_WINNT _WIN32_WINNT_WIN10 #define WINVER _WIN32_WINNT_VISTA #else #define _WIN32_WINNT _WIN32_WINNT_WIN10 #define WINVER _WIN32_WINNT_WIN10 #endif #define NTDDI_VERSION NTDDI_WIN10_RS3 #define WIN32_LEAN_AND_MEAN 1 #define UNICODE 1 #define _UNICODE 1 #define NOMINMAX #include #include #include //#include #include //#include #include #include #include "array.h" #include #include "ownedcs.h" #include "undocAPI.h" #include #include #include #include #include #include #include #include #include #include //#include //#include #define for if(0);else for #include #include #define STRSAFE_NO_DEPRECATE #include #define _CRTDBG_MAP_ALLOC #include #include #include #include #include using namespace std; #ifdef _M_IX86 //#include "optimize/optimize.h" #endif #define FONT_MAGIC_NUMBER 0xA8 #define ASSERT _ASSERTE #define Assert _ASSERTE #ifdef _DEBUG #define new new(_NORMAL_BLOCK, __FILE__, __LINE__) #endif #ifndef NOP_FUNCTION #if (_MSC_VER >= 1210) #define NOP_FUNCTION __noop #else #define NOP_FUNCTION (void)0 #endif //_MSC_VER #endif //!NOP_FUNCTION #ifndef C_ASSERT #define C_ASSERT(e) typedef char __C_ASSERT__[(e)?1:-1] #endif //!C_ASSERT #ifndef FORCEINLINE #if (_MSC_VER >= 1200) #define FORCEINLINE __forceinline #else #define FORCEINLINE __inline #endif //_MSC_VER #endif //!FORCEINLINE void Log(char* Msg); void Log(wchar_t* Msg); // convert string to wstring std::wstring to_wide_string(const std::string & input); // convert wstring to string std::string to_byte_string(const std::wstring & input); // convert a utf-16be string back to utf-16le string std::wstring to_utf16le(const std::wstring& input); wstring to_lower_case(wstring str); FORCEINLINE HINSTANCE GetDLLInstance() { extern HINSTANCE g_hinstDLL; return g_hinstDLL; } //排他制御 class CCriticalSectionLock { #define MAX_CRITICAL_COUNT 20 private: static CRITICAL_SECTION m_cs[MAX_CRITICAL_COUNT]; friend class CCriticalSectionLockTry; int m_index; public: enum { CS_LIBRARY, CS_CACHEDFONT, CS_FONTENG, //CS_CMAPCACHE, //CS_IMAGECACHE, CS_SETTING, CS_MAIN, CS_FONTCACHE, CS_MANAGER, CS_CREATEFONT, CS_FONTLINK, CS_FONTMAP, CS_OWNEDCS, CS_VIRTMEM, CS_DWRITE, CS_DCRELATION, }; CCriticalSectionLock(int index=CS_LIBRARY): m_index(index) { ::EnterCriticalSection(&m_cs[index]); } ~CCriticalSectionLock() { ::LeaveCriticalSection(&m_cs[m_index]); } static void Init() { for (int i=0;i //va_list #include //_vsnwprintf static void _Trace(LPCTSTR pszFormat, ...) { CCriticalSectionLock __lock; va_list argptr; va_start(argptr, pszFormat); //w(v)sprintfは1024文字以上返してこない TCHAR szBuffer[10240]; wvsprintf(szBuffer, pszFormat, argptr); //デバッガをアタッチしてる時はデバッガにメッセージを出す //if (IsDebuggerPresent()) { OutputDebugString(szBuffer); return; //} extern HANDLE g_hfDbgText; HANDLE hf = g_hfDbgText; if (!hf) { TCHAR szFileName[MAX_PATH+16]; GetModuleFileName(GetDLLInstance(), szFileName, MAX_PATH); TCHAR *p1 = _tcsrchr(szFileName, _T('\\')); if (p1 && p1 > szFileName) { *p1 = 0; TCHAR *p2 = _tcsrchr(szFileName, _T('\\')); if (p2) memmove(p2 + 1, p1 + 1, (_tcslen(p1) + 1) * sizeof(TCHAR)); } _tcscpy(szFileName + _tcslen(szFileName) - 4, L"_dbg.txt"); g_hfDbgText = hf = CreateFile(szFileName, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, NULL); if(hf != INVALID_HANDLE_VALUE) { SetFilePointer(hf, 0, NULL, FILE_BEGIN); #ifdef _UNICODE WORD w = 0xfeff; DWORD cb; WriteFile(hf, &w, sizeof(WORD), &cb, NULL); #endif } } if(hf != INVALID_HANDLE_VALUE) { DWORD cb; WriteFile(hf, szBuffer, _tcslen(szBuffer) * sizeof(TCHAR), &cb, NULL); } } #else //!_DEBUG #define TRACE NOP_FUNCTION //↓PSDK 2003R2のwinnt.h //#ifndef NOP_FUNCTION //#if (_MSC_VER >= 1210) //#define NOP_FUNCTION __noop //#else //#define NOP_FUNCTION (void)0 //#endif //#endif #endif //_DEBUG //TRACEマクロ //使用例: TRACE(_T("cx: %d\n"), cx); #ifdef USE_TRACE #define TRACE2 _Trace2 #define TRACE2_STR _Trace2_Str #define TRACE2_BIN _Trace2_Bin #include //va_list #include //_vsnwprintf static void _Trace2(LPCTSTR pszFormat, ...) { CCriticalSectionLock __lock; va_list argptr; va_start(argptr, pszFormat); //w(v)sprintfは1024文字以上返してこない TCHAR szBuffer[1024]; wvsprintf(szBuffer, pszFormat, argptr); OutputDebugString(szBuffer); } static void _Trace2_Bin(LPWSTR func, int line, LPVOID lpString, UINT cbString) { const PBYTE srcp = (const PBYTE)lpString; WCHAR buf[0x1000]; LPWSTR p = buf; for (UINT i = 0; i < 32 && i < cbString; ++i) { wsprintf(p, L"%02x ", srcp[i]); p += lstrlen(p); } *p = 0; TRACE(_T("%s %d: %d %08x %s\n"), func, line, cbString, lpString, buf); } static void _Trace2_Str(LPWSTR func, int line, LPCWSTR lpString, UINT cbString) { WCHAR buf[0x1000]; UINT len = Min(cbString, countof(buf) - 1); lstrcpyn(buf, lpString, len + 1); buf[countof(buf) - 1] = 0; TRACE(_T("%s %d: %d %s\n"), func, line, cbString, buf); LPWSTR p = buf; for (UINT i = 0; i < 32 && i < cbString; ++i) { wsprintf(p, L"%04x ", lpString[i]); p += lstrlen(p); } TRACE(_T("%s %d: %d %08x %s\n"), func, line, cbString, lpString, buf); } #else //!USE_TRACE #define TRACE2 NOP_FUNCTION #define TRACE2_STR NOP_FUNCTION #define TRACE2_BIN NOP_FUNCTION #endif //USE_TRACE class COwnedCriticalSectionLock { private: static OWNED_CRITIAL_SECTION m_cs[2]; WORD FOwner; int m_index; public: enum { OCS_FREETYPE, OCS_DC }; COwnedCriticalSectionLock():FOwner(0), m_index(OCS_FREETYPE) { EnterOwnedCritialSection(&m_cs[m_index], FOwner); } COwnedCriticalSectionLock(WORD Owner, int index=OCS_FREETYPE):FOwner(Owner), m_index(index) { EnterOwnedCritialSection(&m_cs[m_index], Owner); } ~COwnedCriticalSectionLock() { LeaveOwnedCritialSection(&m_cs[m_index], FOwner); } static void Init() { for (int i=0;i<2;i++) { InitializeOwnedCritialSection(&m_cs[i]); } } static void Term() { for (int i=0;i<2;i++) { DeleteOwnedCritialSection(&m_cs[i]); } } }; class CThreadCounter { private: static LONG interlock; public: CThreadCounter() { InterlockedIncrement(&interlock); } ~CThreadCounter() { InterlockedDecrement(&interlock); } static void Init() { interlock = 0; } static int Count() { return InterlockedExchange(&interlock, interlock); } }; class CCriticalSectionLockTry { public: BOOL TryEnter(int index=CCriticalSectionLock::CS_LIBRARY) { return ::TryEnterCriticalSection(&CCriticalSectionLock::m_cs[index]); } int CritalCount(int index=CCriticalSectionLock::CS_LIBRARY) { return CCriticalSectionLock::m_cs[index].RecursionCount; } void Leave(int index=CCriticalSectionLock::CS_LIBRARY) { ::LeaveCriticalSection(&CCriticalSectionLock::m_cs[index]); } }; // 使用後はfreeで開放する事 LPWSTR _StrDupExAtoW(LPCSTR pszMB, int cchMB, LPWSTR pszStack, int cchStack, int* pcchWC, int nACP = CP_ACP); static inline LPWSTR _StrDupAtoW(LPCSTR pszMB, int cchMB = -1, int* pcchWC = NULL) { return _StrDupExAtoW(pszMB, cchMB, NULL, 0, pcchWC); } // useful macros #define NOCOPY(T) T(const T&); T& operator=(const T&) #define countof(array) (sizeof(array)/sizeof(array[0])) #define sizeof_struct(s, m) (((int)((char*)(&((s*)0)->m) - ((char*)((s*)0)))) + sizeof(((s*)0)->m)) #ifndef offsetof #define offsetof(s,m) (size_t)&(((s*)0)->m) #endif #ifdef _DEBUG #define Verify(expr) _ASSERTE(expr) #else #define Verify(expr) (expr) #endif template FORCEINLINE T Min(T x, T y) { return (x < y) ? x : y; } template FORCEINLINE T Max(T x, T y) { return (y < x) ? x : y; } template FORCEINLINE T Bound(T x, T m, T M) { return (x < m) ? m : ((x > M) ? M : x); } template FORCEINLINE int Sgn(T x, T y) { return (x > y) ? 1 : ((x < y) ? -1 : 0); } //型チェック機能つきDeleteXXX/SelectXXX //SelectObject/DeleteObjectは使用できなくなる #ifdef _DEBUG #undef DeletePen #undef DeleteBrush #undef DeleteRgn #undef DeleteFont #undef DeleteBitmap #undef SelectPen #undef SelectBrush #undef SelectRgn #undef SelectFont #undef SelectBitmap #define _IsValidPen(hPen) \ (hPen == NULL || ::GetObjectType(hPen) == OBJ_PEN || ::GetObjectType(hPen) == OBJ_EXTPEN) #define _IsValidBrush(hBrush) \ (hBrush == NULL || ::GetObjectType(hBrush) == OBJ_BRUSH) #define _IsValidRgn(hRgn) \ (hRgn == NULL || ::GetObjectType(hRgn) == OBJ_REGION) #define _IsValidFont(hFont) \ (hFont == NULL || ::GetObjectType(hFont) == OBJ_FONT) #define _IsValidBitmap(hBitmap) \ (hBitmap == NULL || ::GetObjectType(hBitmap) == OBJ_BITMAP) #define DEFINE_DELETE_FUNCTION(type, name) \ FORCEINLINE BOOL WINAPI Delete##name(type h##name) \ { \ _ASSERTE(_IsValid##name(h##name)); \ return ::DeleteObject(h##name); \ } #define DEFINE_SELECT_FUNCTION(type, name) \ FORCEINLINE type WINAPI Select##name(HDC hDC, type h##name) \ { \ _ASSERTE(hDC != NULL); \ if (!_IsValid##name(h##name)) { \ TRACE(_T("Select object %x for DC %x"), (DWORD)h##name, (DWORD)hDC); \ }; \ return (type)::SelectObject(hDC, h##name); \ } DEFINE_DELETE_FUNCTION(HPEN, Pen) DEFINE_DELETE_FUNCTION(HBRUSH, Brush) DEFINE_DELETE_FUNCTION(HRGN, Rgn) DEFINE_DELETE_FUNCTION(HFONT, Font) DEFINE_DELETE_FUNCTION(HBITMAP, Bitmap) DEFINE_SELECT_FUNCTION(HPEN, Pen) DEFINE_SELECT_FUNCTION(HBRUSH, Brush) DEFINE_SELECT_FUNCTION(HRGN, Rgn) DEFINE_SELECT_FUNCTION(HFONT, Font) DEFINE_SELECT_FUNCTION(HBITMAP, Bitmap) #undef _IsValidPen #undef _IsValidBrush #undef _IsValidRgn #undef _IsValidFont #undef _IsValidBitmap #undef DEFINE_DELETE_FUNCTION #undef DEFINE_SELECT_FUNCTION #if (_MSC_VER >= 1300) #pragma deprecated(DeleteObject) #pragma deprecated(SelectObject) #else //_MSC_VER < 1300 #undef DeleteObject #define DeleteObject DeleteObject_instead_use_DeleteXXX #undef SelectObject #define SelectObject SelectObject_instead_use_DeleteXXX #endif //_MSC_VER #else //!_DEBUG #ifndef _INC_WINDOWSX #define DeletePen ::DeleteObject #define DeleteBrush ::DeleteObject #define DeleteRgn ::DeleteObject #define DeleteFont ::DeleteObject #define DeleteBitmap ::DeleteObject #define SelectPen(d,o) (HPEN)::SelectObject(d,o) #define SelectBrush(d,o) (HBRUSH)::SelectObject(d,o) #define SelectRgn(d,o) (HRGN)::SelectObject(d,o) #define SelectFont(d,o) (HFONT)::SelectObject(d,o) #define SelectBitmap(d,o) (HBITMAP)::SelectObject(d,o) #endif //!_INC_WINDOWSX #endif //_DEBUG //TRACEマクロ //使用例: TRACE(_T("cx: %d\n"), cx); #ifndef _WIN64 #ifdef _DEBUG FORCEINLINE static __int64 GetClockCount() { LARGE_INTEGER cycles; __asm { rdtsc mov cycles.LowPart, eax mov cycles.HighPart, edx } return cycles.QuadPart; } //使用例 //{ // CDebugElapsedCounter _cntr("hogehoge"); // : (適当な処理) //} //出力例: "hogehoge: 10000 clocks" class CDebugElapsedCounter { private: __int64 m_ilClk; LPCSTR m_pszName; public: CDebugElapsedCounter(LPCSTR psz) : m_ilClk(GetClockCount()) , m_pszName(psz) { } ~CDebugElapsedCounter() { TRACE(_T("%hs: %u clocks\n"), m_pszName, (DWORD)(GetClockCount() - m_ilClk)); } }; #else class CDebugElapsedCounter { public: CDebugElapsedCounter(LPCSTR psz) { } }; #endif #endif //String to int等系列函数的定义 /* int _StrToInt(LPCTSTR pStr, int nDefault) { #define isspace(ch) (ch == _T('\t') || ch == _T(' ')) #define isdigit(ch) ((_TUCHAR)(ch - _T('0')) <= 9) int ret; bool neg = false; LPCTSTR pStart; for (; isspace(*pStr); pStr++); switch (*pStr) { case _T('-'): neg = true; case _T('+'): pStr++; break; } pStart = pStr; ret = 0; for (; isdigit(*pStr); pStr++) { ret = 10 * ret + (*pStr - _T('0')); } if (pStr == pStart) { return nDefault; } return neg ? -ret : ret; #undef isspace #undef isdigit } int _httoi(const TCHAR *value) { struct CHexMap { TCHAR chr; int value; }; const int HexMapL = 16; CHexMap HexMap[HexMapL] = { {'0', 0}, {'1', 1}, {'2', 2}, {'3', 3}, {'4', 4}, {'5', 5}, {'6', 6}, {'7', 7}, {'8', 8}, {'9', 9}, {'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}, {'F', 15} }; TCHAR *mstr = _tcsupr(_tcsdup(value)); TCHAR *s = mstr; int result = 0; if (*s == '0' && *(s + 1) == 'X') s += 2; bool firsttime = true; while (*s != '\0') { bool found = false; for (int i = 0; i < HexMapL; i++) { if (*s == HexMap[i].chr) { if (!firsttime) result <<= 4; result |= HexMap[i].value; found = true; break; } } if (!found) break; s++; firsttime = false; } free(mstr); return result; } //atofにデフォルト値を返せるようにしたような物 float _StrToFloat(LPCTSTR pStr, float fDefault) { #define isspace(ch) (ch == _T('\t') || ch == _T(' ')) #define isdigit(ch) ((_TUCHAR)(ch - _T('0')) <= 9) int ret_i; int ret_d; float ret; bool neg = false; LPCTSTR pStart; for (; isspace(*pStr); pStr++); switch (*pStr) { case _T('-'): neg = true; case _T('+'): pStr++; break; } pStart = pStr; ret = 0; ret_i = 0; ret_d = 1; for (; isdigit(*pStr); pStr++) { ret_i = 10 * ret_i + (*pStr - _T('0')); } if (*pStr == _T('.')) { pStr++; for (; isdigit(*pStr); pStr++) { ret_i = 10 * ret_i + (*pStr - _T('0')); ret_d *= 10; } } ret = (float)ret_i / (float)ret_d; if (pStr == pStart) { return fDefault; } return neg ? -ret : ret; #undef isspace #undef isdigit }*/ void HookD2DDll(); bool HookD2D1(); void HookGdiplus(); void ChangeFileName(LPWSTR lpSrc, int nSize, LPCWSTR lpNewFileName); std::wstring MakeUniqueFontName(const std::wstring strFullName, const std::wstring strFamilyName, const std::wstring strStyleName); std::string WstringToString(const std::wstring str); ================================================ FILE: crc32.h ================================================ #pragma once #ifndef CRC32_H #define CRC32_H static unsigned int crc32_tab[] = { 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d }; class crc32 { public: static const unsigned int getCrc32(unsigned int crc, const void *buf, int size) { const unsigned char *p; p = (unsigned char *)buf; crc = crc ^ ~0U; while (size--) { crc = crc32_tab[(crc ^ *p++) & 0xFF] ^ (crc >> 8); } return crc ^ ~0U; } }; #endif ================================================ FILE: detours.h ================================================ ///////////////////////////////////////////////////////////////////////////// // // Core Detours Functionality (detours.h of detours.lib) // // Microsoft Research Detours Package, Version 4.0.1 // // Copyright (c) Microsoft Corporation. All rights reserved. // #pragma once #ifndef _DETOURS_H_ #define _DETOURS_H_ #define DETOURS_VERSION 0x4c0c1 // 0xMAJORcMINORcPATCH ////////////////////////////////////////////////////////////////////////////// // #undef DETOURS_X64 #undef DETOURS_X86 #undef DETOURS_IA64 #undef DETOURS_ARM #undef DETOURS_ARM64 #undef DETOURS_BITS #undef DETOURS_32BIT #undef DETOURS_64BIT #if defined(_X86_) #define DETOURS_X86 #define DETOURS_OPTION_BITS 64 #elif defined(_AMD64_) #define DETOURS_X64 #define DETOURS_OPTION_BITS 32 #elif defined(_IA64_) #define DETOURS_IA64 #define DETOURS_OPTION_BITS 32 #elif defined(_ARM_) #define DETOURS_ARM #elif defined(_ARM64_) #define DETOURS_ARM64 #else #error Unknown architecture (x86, amd64, ia64, arm, arm64) #endif #ifdef _WIN64 #undef DETOURS_32BIT #define DETOURS_64BIT 1 #define DETOURS_BITS 64 // If all 64bit kernels can run one and only one 32bit architecture. //#define DETOURS_OPTION_BITS 32 #else #define DETOURS_32BIT 1 #undef DETOURS_64BIT #define DETOURS_BITS 32 // If all 64bit kernels can run one and only one 32bit architecture. //#define DETOURS_OPTION_BITS 32 #endif #define VER_DETOURS_BITS DETOUR_STRINGIFY(DETOURS_BITS) ////////////////////////////////////////////////////////////////////////////// // #if (_MSC_VER < 1299) typedef LONG LONG_PTR; typedef ULONG ULONG_PTR; #endif ///////////////////////////////////////////////// SAL 2.0 Annotations w/o SAL. // // These definitions are include so that Detours will build even if the // compiler doesn't have full SAL 2.0 support. // #ifndef DETOURS_DONT_REMOVE_SAL_20 #ifdef DETOURS_TEST_REMOVE_SAL_20 #undef _Analysis_assume_ #undef _Benign_race_begin_ #undef _Benign_race_end_ #undef _Field_range_ #undef _Field_size_ #undef _In_ #undef _In_bytecount_ #undef _In_count_ #undef _In_opt_ #undef _In_opt_bytecount_ #undef _In_opt_count_ #undef _In_opt_z_ #undef _In_range_ #undef _In_reads_ #undef _In_reads_bytes_ #undef _In_reads_opt_ #undef _In_reads_opt_bytes_ #undef _In_reads_or_z_ #undef _In_z_ #undef _Inout_ #undef _Inout_opt_ #undef _Inout_z_count_ #undef _Out_ #undef _Out_opt_ #undef _Out_writes_ #undef _Outptr_result_maybenull_ #undef _Readable_bytes_ #undef _Success_ #undef _Writable_bytes_ #undef _Pre_notnull_ #endif #if defined(_Deref_out_opt_z_) && !defined(_Outptr_result_maybenull_) #define _Outptr_result_maybenull_ _Deref_out_opt_z_ #endif #if defined(_In_count_) && !defined(_In_reads_) #define _In_reads_(x) _In_count_(x) #endif #if defined(_In_opt_count_) && !defined(_In_reads_opt_) #define _In_reads_opt_(x) _In_opt_count_(x) #endif #if defined(_In_opt_bytecount_) && !defined(_In_reads_opt_bytes_) #define _In_reads_opt_bytes_(x) _In_opt_bytecount_(x) #endif #if defined(_In_bytecount_) && !defined(_In_reads_bytes_) #define _In_reads_bytes_(x) _In_bytecount_(x) #endif #ifndef _In_ #define _In_ #endif #ifndef _In_bytecount_ #define _In_bytecount_(x) #endif #ifndef _In_count_ #define _In_count_(x) #endif #ifndef _In_opt_ #define _In_opt_ #endif #ifndef _In_opt_bytecount_ #define _In_opt_bytecount_(x) #endif #ifndef _In_opt_count_ #define _In_opt_count_(x) #endif #ifndef _In_opt_z_ #define _In_opt_z_ #endif #ifndef _In_range_ #define _In_range_(x,y) #endif #ifndef _In_reads_ #define _In_reads_(x) #endif #ifndef _In_reads_bytes_ #define _In_reads_bytes_(x) #endif #ifndef _In_reads_opt_ #define _In_reads_opt_(x) #endif #ifndef _In_reads_opt_bytes_ #define _In_reads_opt_bytes_(x) #endif #ifndef _In_reads_or_z_ #define _In_reads_or_z_ #endif #ifndef _In_z_ #define _In_z_ #endif #ifndef _Inout_ #define _Inout_ #endif #ifndef _Inout_opt_ #define _Inout_opt_ #endif #ifndef _Inout_z_count_ #define _Inout_z_count_(x) #endif #ifndef _Out_ #define _Out_ #endif #ifndef _Out_opt_ #define _Out_opt_ #endif #ifndef _Out_writes_ #define _Out_writes_(x) #endif #ifndef _Outptr_result_maybenull_ #define _Outptr_result_maybenull_ #endif #ifndef _Writable_bytes_ #define _Writable_bytes_(x) #endif #ifndef _Readable_bytes_ #define _Readable_bytes_(x) #endif #ifndef _Success_ #define _Success_(x) #endif #ifndef _Pre_notnull_ #define _Pre_notnull_ #endif #ifdef DETOURS_INTERNAL #pragma warning(disable:4615) // unknown warning type (suppress with older compilers) #ifndef _Benign_race_begin_ #define _Benign_race_begin_ #endif #ifndef _Benign_race_end_ #define _Benign_race_end_ #endif #ifndef _Field_size_ #define _Field_size_(x) #endif #ifndef _Field_range_ #define _Field_range_(x,y) #endif #ifndef _Analysis_assume_ #define _Analysis_assume_(x) #endif #endif // DETOURS_INTERNAL #endif // DETOURS_DONT_REMOVE_SAL_20 ////////////////////////////////////////////////////////////////////////////// // #ifndef GUID_DEFINED #define GUID_DEFINED typedef struct _GUID { DWORD Data1; WORD Data2; WORD Data3; BYTE Data4[ 8 ]; } GUID; #ifdef INITGUID #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ const GUID name \ = { l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } } #else #define DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ const GUID name #endif // INITGUID #endif // !GUID_DEFINED #if defined(__cplusplus) #ifndef _REFGUID_DEFINED #define _REFGUID_DEFINED #define REFGUID const GUID & #endif // !_REFGUID_DEFINED #else // !__cplusplus #ifndef _REFGUID_DEFINED #define _REFGUID_DEFINED #define REFGUID const GUID * const #endif // !_REFGUID_DEFINED #endif // !__cplusplus #ifndef ARRAYSIZE #define ARRAYSIZE(x) (sizeof(x)/sizeof(x[0])) #endif // ////////////////////////////////////////////////////////////////////////////// #ifdef __cplusplus extern "C" { #endif // __cplusplus /////////////////////////////////////////////////// Instruction Target Macros. // #define DETOUR_INSTRUCTION_TARGET_NONE ((PVOID)0) #define DETOUR_INSTRUCTION_TARGET_DYNAMIC ((PVOID)(LONG_PTR)-1) #define DETOUR_SECTION_HEADER_SIGNATURE 0x00727444 // "Dtr\0" extern const GUID DETOUR_EXE_RESTORE_GUID; extern const GUID DETOUR_EXE_HELPER_GUID; #define DETOUR_TRAMPOLINE_SIGNATURE 0x21727444 // Dtr! typedef struct _DETOUR_TRAMPOLINE DETOUR_TRAMPOLINE, *PDETOUR_TRAMPOLINE; /////////////////////////////////////////////////////////// Binary Structures. // #pragma pack(push, 8) typedef struct _DETOUR_SECTION_HEADER { DWORD cbHeaderSize; DWORD nSignature; DWORD nDataOffset; DWORD cbDataSize; DWORD nOriginalImportVirtualAddress; DWORD nOriginalImportSize; DWORD nOriginalBoundImportVirtualAddress; DWORD nOriginalBoundImportSize; DWORD nOriginalIatVirtualAddress; DWORD nOriginalIatSize; DWORD nOriginalSizeOfImage; DWORD cbPrePE; DWORD nOriginalClrFlags; DWORD reserved1; DWORD reserved2; DWORD reserved3; // Followed by cbPrePE bytes of data. } DETOUR_SECTION_HEADER, *PDETOUR_SECTION_HEADER; typedef struct _DETOUR_SECTION_RECORD { DWORD cbBytes; DWORD nReserved; GUID guid; } DETOUR_SECTION_RECORD, *PDETOUR_SECTION_RECORD; typedef struct _DETOUR_CLR_HEADER { // Header versioning ULONG cb; USHORT MajorRuntimeVersion; USHORT MinorRuntimeVersion; // Symbol table and startup information IMAGE_DATA_DIRECTORY MetaData; ULONG Flags; // Followed by the rest of the IMAGE_COR20_HEADER } DETOUR_CLR_HEADER, *PDETOUR_CLR_HEADER; typedef struct _DETOUR_EXE_RESTORE { DWORD cb; DWORD cbidh; DWORD cbinh; DWORD cbclr; PBYTE pidh; PBYTE pinh; PBYTE pclr; IMAGE_DOS_HEADER idh; union { IMAGE_NT_HEADERS inh; IMAGE_NT_HEADERS32 inh32; IMAGE_NT_HEADERS64 inh64; BYTE raw[sizeof(IMAGE_NT_HEADERS64) + sizeof(IMAGE_SECTION_HEADER) * 32]; }; DETOUR_CLR_HEADER clr; } DETOUR_EXE_RESTORE, *PDETOUR_EXE_RESTORE; typedef struct _DETOUR_EXE_HELPER { DWORD cb; DWORD pid; DWORD nDlls; CHAR rDlls[4]; } DETOUR_EXE_HELPER, *PDETOUR_EXE_HELPER; #pragma pack(pop) #define DETOUR_SECTION_HEADER_DECLARE(cbSectionSize) \ { \ sizeof(DETOUR_SECTION_HEADER),\ DETOUR_SECTION_HEADER_SIGNATURE,\ sizeof(DETOUR_SECTION_HEADER),\ (cbSectionSize),\ \ 0,\ 0,\ 0,\ 0,\ \ 0,\ 0,\ 0,\ 0,\ } /////////////////////////////////////////////////////////////// Helper Macros. // #define DETOURS_STRINGIFY(x) DETOURS_STRINGIFY_(x) #define DETOURS_STRINGIFY_(x) #x ///////////////////////////////////////////////////////////// Binary Typedefs. // typedef BOOL (CALLBACK *PF_DETOUR_BINARY_BYWAY_CALLBACK)( _In_opt_ PVOID pContext, _In_opt_ LPCSTR pszFile, _Outptr_result_maybenull_ LPCSTR *ppszOutFile); typedef BOOL (CALLBACK *PF_DETOUR_BINARY_FILE_CALLBACK)( _In_opt_ PVOID pContext, _In_ LPCSTR pszOrigFile, _In_ LPCSTR pszFile, _Outptr_result_maybenull_ LPCSTR *ppszOutFile); typedef BOOL (CALLBACK *PF_DETOUR_BINARY_SYMBOL_CALLBACK)( _In_opt_ PVOID pContext, _In_ ULONG nOrigOrdinal, _In_ ULONG nOrdinal, _Out_ ULONG *pnOutOrdinal, _In_opt_ LPCSTR pszOrigSymbol, _In_opt_ LPCSTR pszSymbol, _Outptr_result_maybenull_ LPCSTR *ppszOutSymbol); typedef BOOL (CALLBACK *PF_DETOUR_BINARY_COMMIT_CALLBACK)( _In_opt_ PVOID pContext); typedef BOOL (CALLBACK *PF_DETOUR_ENUMERATE_EXPORT_CALLBACK)(_In_opt_ PVOID pContext, _In_ ULONG nOrdinal, _In_opt_ LPCSTR pszName, _In_opt_ PVOID pCode); typedef BOOL (CALLBACK *PF_DETOUR_IMPORT_FILE_CALLBACK)(_In_opt_ PVOID pContext, _In_opt_ HMODULE hModule, _In_opt_ LPCSTR pszFile); typedef BOOL (CALLBACK *PF_DETOUR_IMPORT_FUNC_CALLBACK)(_In_opt_ PVOID pContext, _In_ DWORD nOrdinal, _In_opt_ LPCSTR pszFunc, _In_opt_ PVOID pvFunc); // Same as PF_DETOUR_IMPORT_FUNC_CALLBACK but extra indirection on last parameter. typedef BOOL (CALLBACK *PF_DETOUR_IMPORT_FUNC_CALLBACK_EX)(_In_opt_ PVOID pContext, _In_ DWORD nOrdinal, _In_opt_ LPCSTR pszFunc, _In_opt_ PVOID* ppvFunc); typedef VOID * PDETOUR_BINARY; typedef VOID * PDETOUR_LOADED_BINARY; //////////////////////////////////////////////////////////// Transaction APIs. // LONG WINAPI DetourTransactionBegin(VOID); LONG WINAPI DetourTransactionAbort(VOID); LONG WINAPI DetourTransactionCommit(VOID); LONG WINAPI DetourTransactionCommitEx(_Out_opt_ PVOID **pppFailedPointer); LONG WINAPI DetourUpdateThread(_In_ HANDLE hThread); LONG WINAPI DetourAttach(_Inout_ PVOID *ppPointer, _In_ PVOID pDetour); LONG WINAPI DetourAttachEx(_Inout_ PVOID *ppPointer, _In_ PVOID pDetour, _Out_opt_ PDETOUR_TRAMPOLINE *ppRealTrampoline, _Out_opt_ PVOID *ppRealTarget, _Out_opt_ PVOID *ppRealDetour); LONG WINAPI DetourDetach(_Inout_ PVOID *ppPointer, _In_ PVOID pDetour); BOOL WINAPI DetourSetIgnoreTooSmall(_In_ BOOL fIgnore); BOOL WINAPI DetourSetRetainRegions(_In_ BOOL fRetain); PVOID WINAPI DetourSetSystemRegionLowerBound(_In_ PVOID pSystemRegionLowerBound); PVOID WINAPI DetourSetSystemRegionUpperBound(_In_ PVOID pSystemRegionUpperBound); ////////////////////////////////////////////////////////////// Code Functions. // PVOID WINAPI DetourFindFunction(_In_ LPCSTR pszModule, _In_ LPCSTR pszFunction); PVOID WINAPI DetourCodeFromPointer(_In_ PVOID pPointer, _Out_opt_ PVOID *ppGlobals); PVOID WINAPI DetourCopyInstruction(_In_opt_ PVOID pDst, _Inout_opt_ PVOID *ppDstPool, _In_ PVOID pSrc, _Out_opt_ PVOID *ppTarget, _Out_opt_ LONG *plExtra); BOOL WINAPI DetourSetCodeModule(_In_ HMODULE hModule, _In_ BOOL fLimitReferencesToModule); ///////////////////////////////////////////////////// Loaded Binary Functions. // HMODULE WINAPI DetourGetContainingModule(_In_ PVOID pvAddr); HMODULE WINAPI DetourEnumerateModules(_In_opt_ HMODULE hModuleLast); PVOID WINAPI DetourGetEntryPoint(_In_opt_ HMODULE hModule); ULONG WINAPI DetourGetModuleSize(_In_opt_ HMODULE hModule); BOOL WINAPI DetourEnumerateExports(_In_ HMODULE hModule, _In_opt_ PVOID pContext, _In_ PF_DETOUR_ENUMERATE_EXPORT_CALLBACK pfExport); BOOL WINAPI DetourEnumerateImports(_In_opt_ HMODULE hModule, _In_opt_ PVOID pContext, _In_opt_ PF_DETOUR_IMPORT_FILE_CALLBACK pfImportFile, _In_opt_ PF_DETOUR_IMPORT_FUNC_CALLBACK pfImportFunc); BOOL WINAPI DetourEnumerateImportsEx(_In_opt_ HMODULE hModule, _In_opt_ PVOID pContext, _In_opt_ PF_DETOUR_IMPORT_FILE_CALLBACK pfImportFile, _In_opt_ PF_DETOUR_IMPORT_FUNC_CALLBACK_EX pfImportFuncEx); _Writable_bytes_(*pcbData) _Readable_bytes_(*pcbData) _Success_(return != NULL) PVOID WINAPI DetourFindPayload(_In_opt_ HMODULE hModule, _In_ REFGUID rguid, _Out_ DWORD *pcbData); _Writable_bytes_(*pcbData) _Readable_bytes_(*pcbData) _Success_(return != NULL) PVOID WINAPI DetourFindPayloadEx(_In_ REFGUID rguid, _Out_ DWORD * pcbData); DWORD WINAPI DetourGetSizeOfPayloads(_In_opt_ HMODULE hModule); ///////////////////////////////////////////////// Persistent Binary Functions. // PDETOUR_BINARY WINAPI DetourBinaryOpen(_In_ HANDLE hFile); _Writable_bytes_(*pcbData) _Readable_bytes_(*pcbData) _Success_(return != NULL) PVOID WINAPI DetourBinaryEnumeratePayloads(_In_ PDETOUR_BINARY pBinary, _Out_opt_ GUID *pGuid, _Out_ DWORD *pcbData, _Inout_ DWORD *pnIterator); _Writable_bytes_(*pcbData) _Readable_bytes_(*pcbData) _Success_(return != NULL) PVOID WINAPI DetourBinaryFindPayload(_In_ PDETOUR_BINARY pBinary, _In_ REFGUID rguid, _Out_ DWORD *pcbData); PVOID WINAPI DetourBinarySetPayload(_In_ PDETOUR_BINARY pBinary, _In_ REFGUID rguid, _In_reads_opt_(cbData) PVOID pData, _In_ DWORD cbData); BOOL WINAPI DetourBinaryDeletePayload(_In_ PDETOUR_BINARY pBinary, _In_ REFGUID rguid); BOOL WINAPI DetourBinaryPurgePayloads(_In_ PDETOUR_BINARY pBinary); BOOL WINAPI DetourBinaryResetImports(_In_ PDETOUR_BINARY pBinary); BOOL WINAPI DetourBinaryEditImports(_In_ PDETOUR_BINARY pBinary, _In_opt_ PVOID pContext, _In_opt_ PF_DETOUR_BINARY_BYWAY_CALLBACK pfByway, _In_opt_ PF_DETOUR_BINARY_FILE_CALLBACK pfFile, _In_opt_ PF_DETOUR_BINARY_SYMBOL_CALLBACK pfSymbol, _In_opt_ PF_DETOUR_BINARY_COMMIT_CALLBACK pfCommit); BOOL WINAPI DetourBinaryWrite(_In_ PDETOUR_BINARY pBinary, _In_ HANDLE hFile); BOOL WINAPI DetourBinaryClose(_In_ PDETOUR_BINARY pBinary); /////////////////////////////////////////////////// Create Process & Load Dll. // typedef BOOL (WINAPI *PDETOUR_CREATE_PROCESS_ROUTINEA)( _In_opt_ LPCSTR lpApplicationName, _Inout_opt_ LPSTR lpCommandLine, _In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes, _In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes, _In_ BOOL bInheritHandles, _In_ DWORD dwCreationFlags, _In_opt_ LPVOID lpEnvironment, _In_opt_ LPCSTR lpCurrentDirectory, _In_ LPSTARTUPINFOA lpStartupInfo, _Out_ LPPROCESS_INFORMATION lpProcessInformation); typedef BOOL (WINAPI *PDETOUR_CREATE_PROCESS_ROUTINEW)( _In_opt_ LPCWSTR lpApplicationName, _Inout_opt_ LPWSTR lpCommandLine, _In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes, _In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes, _In_ BOOL bInheritHandles, _In_ DWORD dwCreationFlags, _In_opt_ LPVOID lpEnvironment, _In_opt_ LPCWSTR lpCurrentDirectory, _In_ LPSTARTUPINFOW lpStartupInfo, _Out_ LPPROCESS_INFORMATION lpProcessInformation); BOOL WINAPI DetourCreateProcessWithDllA(_In_opt_ LPCSTR lpApplicationName, _Inout_opt_ LPSTR lpCommandLine, _In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes, _In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes, _In_ BOOL bInheritHandles, _In_ DWORD dwCreationFlags, _In_opt_ LPVOID lpEnvironment, _In_opt_ LPCSTR lpCurrentDirectory, _In_ LPSTARTUPINFOA lpStartupInfo, _Out_ LPPROCESS_INFORMATION lpProcessInformation, _In_ LPCSTR lpDllName, _In_opt_ PDETOUR_CREATE_PROCESS_ROUTINEA pfCreateProcessA); BOOL WINAPI DetourCreateProcessWithDllW(_In_opt_ LPCWSTR lpApplicationName, _Inout_opt_ LPWSTR lpCommandLine, _In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes, _In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes, _In_ BOOL bInheritHandles, _In_ DWORD dwCreationFlags, _In_opt_ LPVOID lpEnvironment, _In_opt_ LPCWSTR lpCurrentDirectory, _In_ LPSTARTUPINFOW lpStartupInfo, _Out_ LPPROCESS_INFORMATION lpProcessInformation, _In_ LPCSTR lpDllName, _In_opt_ PDETOUR_CREATE_PROCESS_ROUTINEW pfCreateProcessW); #ifdef UNICODE #define DetourCreateProcessWithDll DetourCreateProcessWithDllW #define PDETOUR_CREATE_PROCESS_ROUTINE PDETOUR_CREATE_PROCESS_ROUTINEW #else #define DetourCreateProcessWithDll DetourCreateProcessWithDllA #define PDETOUR_CREATE_PROCESS_ROUTINE PDETOUR_CREATE_PROCESS_ROUTINEA #endif // !UNICODE BOOL WINAPI DetourCreateProcessWithDllExA(_In_opt_ LPCSTR lpApplicationName, _Inout_opt_ LPSTR lpCommandLine, _In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes, _In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes, _In_ BOOL bInheritHandles, _In_ DWORD dwCreationFlags, _In_opt_ LPVOID lpEnvironment, _In_opt_ LPCSTR lpCurrentDirectory, _In_ LPSTARTUPINFOA lpStartupInfo, _Out_ LPPROCESS_INFORMATION lpProcessInformation, _In_ LPCSTR lpDllName, _In_opt_ PDETOUR_CREATE_PROCESS_ROUTINEA pfCreateProcessA); BOOL WINAPI DetourCreateProcessWithDllExW(_In_opt_ LPCWSTR lpApplicationName, _Inout_opt_ LPWSTR lpCommandLine, _In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes, _In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes, _In_ BOOL bInheritHandles, _In_ DWORD dwCreationFlags, _In_opt_ LPVOID lpEnvironment, _In_opt_ LPCWSTR lpCurrentDirectory, _In_ LPSTARTUPINFOW lpStartupInfo, _Out_ LPPROCESS_INFORMATION lpProcessInformation, _In_ LPCSTR lpDllName, _In_opt_ PDETOUR_CREATE_PROCESS_ROUTINEW pfCreateProcessW); #ifdef UNICODE #define DetourCreateProcessWithDllEx DetourCreateProcessWithDllExW #else #define DetourCreateProcessWithDllEx DetourCreateProcessWithDllExA #endif // !UNICODE BOOL WINAPI DetourCreateProcessWithDllsA(_In_opt_ LPCSTR lpApplicationName, _Inout_opt_ LPSTR lpCommandLine, _In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes, _In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes, _In_ BOOL bInheritHandles, _In_ DWORD dwCreationFlags, _In_opt_ LPVOID lpEnvironment, _In_opt_ LPCSTR lpCurrentDirectory, _In_ LPSTARTUPINFOA lpStartupInfo, _Out_ LPPROCESS_INFORMATION lpProcessInformation, _In_ DWORD nDlls, _In_reads_(nDlls) LPCSTR *rlpDlls, _In_opt_ PDETOUR_CREATE_PROCESS_ROUTINEA pfCreateProcessA); BOOL WINAPI DetourCreateProcessWithDllsW(_In_opt_ LPCWSTR lpApplicationName, _Inout_opt_ LPWSTR lpCommandLine, _In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes, _In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes, _In_ BOOL bInheritHandles, _In_ DWORD dwCreationFlags, _In_opt_ LPVOID lpEnvironment, _In_opt_ LPCWSTR lpCurrentDirectory, _In_ LPSTARTUPINFOW lpStartupInfo, _Out_ LPPROCESS_INFORMATION lpProcessInformation, _In_ DWORD nDlls, _In_reads_(nDlls) LPCSTR *rlpDlls, _In_opt_ PDETOUR_CREATE_PROCESS_ROUTINEW pfCreateProcessW); #ifdef UNICODE #define DetourCreateProcessWithDlls DetourCreateProcessWithDllsW #else #define DetourCreateProcessWithDlls DetourCreateProcessWithDllsA #endif // !UNICODE BOOL WINAPI DetourProcessViaHelperA(_In_ DWORD dwTargetPid, _In_ LPCSTR lpDllName, _In_ PDETOUR_CREATE_PROCESS_ROUTINEA pfCreateProcessA); BOOL WINAPI DetourProcessViaHelperW(_In_ DWORD dwTargetPid, _In_ LPCSTR lpDllName, _In_ PDETOUR_CREATE_PROCESS_ROUTINEW pfCreateProcessW); #ifdef UNICODE #define DetourProcessViaHelper DetourProcessViaHelperW #else #define DetourProcessViaHelper DetourProcessViaHelperA #endif // !UNICODE BOOL WINAPI DetourProcessViaHelperDllsA(_In_ DWORD dwTargetPid, _In_ DWORD nDlls, _In_reads_(nDlls) LPCSTR *rlpDlls, _In_ PDETOUR_CREATE_PROCESS_ROUTINEA pfCreateProcessA); BOOL WINAPI DetourProcessViaHelperDllsW(_In_ DWORD dwTargetPid, _In_ DWORD nDlls, _In_reads_(nDlls) LPCSTR *rlpDlls, _In_ PDETOUR_CREATE_PROCESS_ROUTINEW pfCreateProcessW); #ifdef UNICODE #define DetourProcessViaHelperDlls DetourProcessViaHelperDllsW #else #define DetourProcessViaHelperDlls DetourProcessViaHelperDllsA #endif // !UNICODE BOOL WINAPI DetourUpdateProcessWithDll(_In_ HANDLE hProcess, _In_reads_(nDlls) LPCSTR *rlpDlls, _In_ DWORD nDlls); BOOL WINAPI DetourUpdateProcessWithDllEx(_In_ HANDLE hProcess, _In_ HMODULE hImage, _In_ BOOL bIs32Bit, _In_reads_(nDlls) LPCSTR *rlpDlls, _In_ DWORD nDlls); BOOL WINAPI DetourCopyPayloadToProcess(_In_ HANDLE hProcess, _In_ REFGUID rguid, _In_reads_bytes_(cbData) PVOID pvData, _In_ DWORD cbData); BOOL WINAPI DetourRestoreAfterWith(VOID); BOOL WINAPI DetourRestoreAfterWithEx(_In_reads_bytes_(cbData) PVOID pvData, _In_ DWORD cbData); BOOL WINAPI DetourIsHelperProcess(VOID); VOID CALLBACK DetourFinishHelperProcess(_In_ HWND, _In_ HINSTANCE, _In_ LPSTR, _In_ INT); // ////////////////////////////////////////////////////////////////////////////// #ifdef __cplusplus } #endif // __cplusplus //////////////////////////////////////////////// Detours Internal Definitions. // #ifdef __cplusplus #ifdef DETOURS_INTERNAL #define NOTHROW // #define NOTHROW (nothrow) ////////////////////////////////////////////////////////////////////////////// // #if (_MSC_VER < 1299) #include typedef IMAGEHLP_MODULE IMAGEHLP_MODULE64; typedef PIMAGEHLP_MODULE PIMAGEHLP_MODULE64; typedef IMAGEHLP_SYMBOL SYMBOL_INFO; typedef PIMAGEHLP_SYMBOL PSYMBOL_INFO; static inline LONG InterlockedCompareExchange(_Inout_ LONG *ptr, _In_ LONG nval, _In_ LONG oval) { return (LONG)::InterlockedCompareExchange((PVOID*)ptr, (PVOID)nval, (PVOID)oval); } #else #pragma warning(push) #pragma warning(disable:4091) // empty typedef #include #pragma warning(pop) #endif #ifdef IMAGEAPI // defined by DBGHELP.H typedef LPAPI_VERSION (NTAPI *PF_ImagehlpApiVersionEx)(_In_ LPAPI_VERSION AppVersion); typedef BOOL (NTAPI *PF_SymInitialize)(_In_ HANDLE hProcess, _In_opt_ LPCSTR UserSearchPath, _In_ BOOL fInvadeProcess); typedef DWORD (NTAPI *PF_SymSetOptions)(_In_ DWORD SymOptions); typedef DWORD (NTAPI *PF_SymGetOptions)(VOID); typedef DWORD64 (NTAPI *PF_SymLoadModule64)(_In_ HANDLE hProcess, _In_opt_ HANDLE hFile, _In_ LPSTR ImageName, _In_opt_ LPSTR ModuleName, _In_ DWORD64 BaseOfDll, _In_opt_ DWORD SizeOfDll); typedef BOOL (NTAPI *PF_SymGetModuleInfo64)(_In_ HANDLE hProcess, _In_ DWORD64 qwAddr, _Out_ PIMAGEHLP_MODULE64 ModuleInfo); typedef BOOL (NTAPI *PF_SymFromName)(_In_ HANDLE hProcess, _In_ LPSTR Name, _Out_ PSYMBOL_INFO Symbol); typedef struct _DETOUR_SYM_INFO { HANDLE hProcess; HMODULE hDbgHelp; PF_ImagehlpApiVersionEx pfImagehlpApiVersionEx; PF_SymInitialize pfSymInitialize; PF_SymSetOptions pfSymSetOptions; PF_SymGetOptions pfSymGetOptions; PF_SymLoadModule64 pfSymLoadModule64; PF_SymGetModuleInfo64 pfSymGetModuleInfo64; PF_SymFromName pfSymFromName; } DETOUR_SYM_INFO, *PDETOUR_SYM_INFO; PDETOUR_SYM_INFO DetourLoadImageHlp(VOID); #endif // IMAGEAPI #if defined(_INC_STDIO) && !defined(_CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS) #error detours.h must be included before stdio.h (or at least define _CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS earlier) #endif #define _CRT_STDIO_ARBITRARY_WIDE_SPECIFIERS 1 #ifndef DETOUR_TRACE #if DETOUR_DEBUG #define DETOUR_TRACE(x) printf x #define DETOUR_BREAK() __debugbreak() #include #include #else #define DETOUR_TRACE(x) #define DETOUR_BREAK() #endif #endif #if 1 || defined(DETOURS_IA64) // // IA64 instructions are 41 bits, 3 per bundle, plus 5 bit bundle template => 128 bits per bundle. // #define DETOUR_IA64_INSTRUCTIONS_PER_BUNDLE (3) #define DETOUR_IA64_TEMPLATE_OFFSET (0) #define DETOUR_IA64_TEMPLATE_SIZE (5) #define DETOUR_IA64_INSTRUCTION_SIZE (41) #define DETOUR_IA64_INSTRUCTION0_OFFSET (DETOUR_IA64_TEMPLATE_SIZE) #define DETOUR_IA64_INSTRUCTION1_OFFSET (DETOUR_IA64_TEMPLATE_SIZE + DETOUR_IA64_INSTRUCTION_SIZE) #define DETOUR_IA64_INSTRUCTION2_OFFSET (DETOUR_IA64_TEMPLATE_SIZE + DETOUR_IA64_INSTRUCTION_SIZE + DETOUR_IA64_INSTRUCTION_SIZE) C_ASSERT(DETOUR_IA64_TEMPLATE_SIZE + DETOUR_IA64_INSTRUCTIONS_PER_BUNDLE * DETOUR_IA64_INSTRUCTION_SIZE == 128); __declspec(align(16)) struct DETOUR_IA64_BUNDLE { public: union { BYTE data[16]; UINT64 wide[2]; }; enum { A_UNIT = 1u, I_UNIT = 2u, M_UNIT = 3u, B_UNIT = 4u, F_UNIT = 5u, L_UNIT = 6u, X_UNIT = 7u, }; struct DETOUR_IA64_METADATA { ULONG nTemplate : 8; // Instruction template. ULONG nUnit0 : 4; // Unit for slot 0 ULONG nUnit1 : 4; // Unit for slot 1 ULONG nUnit2 : 4; // Unit for slot 2 }; protected: static const DETOUR_IA64_METADATA s_rceCopyTable[33]; UINT RelocateBundle(_Inout_ DETOUR_IA64_BUNDLE* pDst, _Inout_opt_ DETOUR_IA64_BUNDLE* pBundleExtra) const; bool RelocateInstruction(_Inout_ DETOUR_IA64_BUNDLE* pDst, _In_ BYTE slot, _Inout_opt_ DETOUR_IA64_BUNDLE* pBundleExtra) const; // 120 112 104 96 88 80 72 64 56 48 40 32 24 16 8 0 // f. e. d. c. b. a. 9. 8. 7. 6. 5. 4. 3. 2. 1. 0. // 00 // f.e. d.c. b.a. 9.8. 7.6. 5.4. 3.2. 1.0. // 0000 0000 0000 0000 0000 0000 0000 001f : Template [4..0] // 0000 0000 0000 0000 0000 03ff ffff ffe0 : Zero [ 41.. 5] // 0000 0000 0000 0000 0000 3c00 0000 0000 : Zero [ 45.. 42] // 0000 0000 0007 ffff ffff c000 0000 0000 : One [ 82.. 46] // 0000 0000 0078 0000 0000 0000 0000 0000 : One [ 86.. 83] // 0fff ffff ff80 0000 0000 0000 0000 0000 : Two [123.. 87] // f000 0000 0000 0000 0000 0000 0000 0000 : Two [127..124] BYTE GetTemplate() const; // Get 4 bit opcodes. BYTE GetInst0() const; BYTE GetInst1() const; BYTE GetInst2() const; BYTE GetUnit(BYTE slot) const; BYTE GetUnit0() const; BYTE GetUnit1() const; BYTE GetUnit2() const; // Get 37 bit data. UINT64 GetData0() const; UINT64 GetData1() const; UINT64 GetData2() const; // Get/set the full 41 bit instructions. UINT64 GetInstruction(BYTE slot) const; UINT64 GetInstruction0() const; UINT64 GetInstruction1() const; UINT64 GetInstruction2() const; void SetInstruction(BYTE slot, UINT64 instruction); void SetInstruction0(UINT64 instruction); void SetInstruction1(UINT64 instruction); void SetInstruction2(UINT64 instruction); // Get/set bitfields. static UINT64 GetBits(UINT64 Value, UINT64 Offset, UINT64 Count); static UINT64 SetBits(UINT64 Value, UINT64 Offset, UINT64 Count, UINT64 Field); // Get specific read-only fields. static UINT64 GetOpcode(UINT64 instruction); // 4bit opcode static UINT64 GetX(UINT64 instruction); // 1bit opcode extension static UINT64 GetX3(UINT64 instruction); // 3bit opcode extension static UINT64 GetX6(UINT64 instruction); // 6bit opcode extension // Get/set specific fields. static UINT64 GetImm7a(UINT64 instruction); static UINT64 SetImm7a(UINT64 instruction, UINT64 imm7a); static UINT64 GetImm13c(UINT64 instruction); static UINT64 SetImm13c(UINT64 instruction, UINT64 imm13c); static UINT64 GetSignBit(UINT64 instruction); static UINT64 SetSignBit(UINT64 instruction, UINT64 signBit); static UINT64 GetImm20a(UINT64 instruction); static UINT64 SetImm20a(UINT64 instruction, UINT64 imm20a); static UINT64 GetImm20b(UINT64 instruction); static UINT64 SetImm20b(UINT64 instruction, UINT64 imm20b); static UINT64 SignExtend(UINT64 Value, UINT64 Offset); BOOL IsMovlGp() const; VOID SetInst(BYTE Slot, BYTE nInst); VOID SetInst0(BYTE nInst); VOID SetInst1(BYTE nInst); VOID SetInst2(BYTE nInst); VOID SetData(BYTE Slot, UINT64 nData); VOID SetData0(UINT64 nData); VOID SetData1(UINT64 nData); VOID SetData2(UINT64 nData); BOOL SetNop(BYTE Slot); BOOL SetNop0(); BOOL SetNop1(); BOOL SetNop2(); public: BOOL IsBrl() const; VOID SetBrl(); VOID SetBrl(UINT64 target); UINT64 GetBrlTarget() const; VOID SetBrlTarget(UINT64 target); VOID SetBrlImm(UINT64 imm); UINT64 GetBrlImm() const; UINT64 GetMovlGp() const; VOID SetMovlGp(UINT64 gp); VOID SetStop(); UINT Copy(_Out_ DETOUR_IA64_BUNDLE *pDst, _Inout_opt_ DETOUR_IA64_BUNDLE* pBundleExtra = NULL) const; }; #endif // DETOURS_IA64 #ifdef DETOURS_ARM #define DETOURS_PFUNC_TO_PBYTE(p) ((PBYTE)(((ULONG_PTR)(p)) & ~(ULONG_PTR)1)) #define DETOURS_PBYTE_TO_PFUNC(p) ((PBYTE)(((ULONG_PTR)(p)) | (ULONG_PTR)1)) #endif // DETOURS_ARM ////////////////////////////////////////////////////////////////////////////// #ifdef __cplusplus extern "C" { #endif // __cplusplus #define DETOUR_OFFLINE_LIBRARY(x) \ PVOID WINAPI DetourCopyInstruction##x(_In_opt_ PVOID pDst, \ _Inout_opt_ PVOID *ppDstPool, \ _In_ PVOID pSrc, \ _Out_opt_ PVOID *ppTarget, \ _Out_opt_ LONG *plExtra); \ \ BOOL WINAPI DetourSetCodeModule##x(_In_ HMODULE hModule, \ _In_ BOOL fLimitReferencesToModule); \ DETOUR_OFFLINE_LIBRARY(X86) DETOUR_OFFLINE_LIBRARY(X64) DETOUR_OFFLINE_LIBRARY(ARM) DETOUR_OFFLINE_LIBRARY(ARM64) DETOUR_OFFLINE_LIBRARY(IA64) #undef DETOUR_OFFLINE_LIBRARY ////////////////////////////////////////////////////////////////////////////// // // Helpers for manipulating page protection. // _Success_(return != FALSE) BOOL WINAPI DetourVirtualProtectSameExecuteEx(_In_ HANDLE hProcess, _In_ PVOID pAddress, _In_ SIZE_T nSize, _In_ DWORD dwNewProtect, _Out_ PDWORD pdwOldProtect); _Success_(return != FALSE) BOOL WINAPI DetourVirtualProtectSameExecute(_In_ PVOID pAddress, _In_ SIZE_T nSize, _In_ DWORD dwNewProtect, _Out_ PDWORD pdwOldProtect); #ifdef __cplusplus } #endif // __cplusplus ////////////////////////////////////////////////////////////////////////////// #define MM_ALLOCATION_GRANULARITY 0x10000 ////////////////////////////////////////////////////////////////////////////// #endif // DETOURS_INTERNAL #endif // __cplusplus #endif // _DETOURS_H_ // //////////////////////////////////////////////////////////////// End of File. ================================================ FILE: directwrite.cpp ================================================ #include "directwrite.h" #include "settings.h" #include "dynCodeHelper.h" void MyDebug(const TCHAR * sz, ...) { #ifdef DEBUG TCHAR szData[512] = { 0 }; va_list args; va_start(args, sz); StringCchVPrintf(szData, sizeof(szData)-1, sz, args); va_end(args); OutputDebugString(szData); #endif } #define SET_VAL(x, y) *(DWORD_PTR*)&(x) = *(DWORD_PTR*)&(y) // To hook a method, add HOOK_MANUALLY() in hooklist.h and use this. #ifdef EASYHOOK #define ISHOOKED(name) (!!HOOK_##name.Link) #else #define ISHOOKED(name) (IsHooked_##name) #endif #define HOOK(obj, name, index) { \ if (!ISHOOKED(name)) { \ AutoEnableDynamicCodeGen dynHelper(true); \ SET_VAL(ORIG_##name, (*reinterpret_cast(obj.p))[index]); \ hook_demand_##name(false); \ if (!ISHOOKED(name)) { MyDebug(L"##name hook failed"); } \ } \ }; struct ComMethodHooker { // The target function if it has been hooked BOOL (*lpIsHooked)(); // The method the vftable refers to void*(*lpGetMethod)(IUnknown* obj); // Hook the method void(*lpHookFunc)(IUnknown* obj); }; #define COM_METHOD_HOOKER(type, name, index) ComMethodHooker { \ []() -> BOOL { \ return ISHOOKED(name); \ }, \ [](IUnknown* obj) -> void* { \ return (*reinterpret_cast(obj))[index]; \ }, \ [](IUnknown* obj) -> void { \ CComPtr ptr = (type*)obj; \ HOOK(ptr, name, index); \ } \ } #define COM_METHOD_HOOKER_EMPTY() ComMethodHooker { \ []() -> BOOL { \ return false; \ }, \ [](IUnknown* obj) -> void* { \ return NULL; \ }, \ [](IUnknown* obj) -> void { \ return; \ } \ } struct Params { D2D1_TEXT_ANTIALIAS_MODE AntialiasMode; // Don't access directly. Use Get(D2D|DW)RenderingParams(). IDWriteRenderingParams *RenderingParams; FLOAT Gamma; FLOAT EnhancedContrast; FLOAT ClearTypeLevel; DWRITE_PIXEL_GEOMETRY PixelGeometry; // RenderingMode=6 is invalid for DWrite interface DWRITE_RENDERING_MODE RenderingMode; FLOAT GrayscaleEnhancedContrast; DWRITE_GRID_FIT_MODE GridFitMode; DWRITE_RENDERING_MODE1 RenderingMode1; Params(); void CreateParams(IDWriteFactory* dw_factory); }; //IDWriteFactory* g_pDWriteFactory = NULL; CComPtr g_pGdiInterop = NULL; enum D2D1RenderTargetCategory { D2D1_RENDER_TARGET_CATEGORY = 1, // ID2D1DCRenderTarget, ID2D1HwndRenderTarget, ID2D1BitmapRenderTarget D2D1_RENDER_TARGET1_CATEGORY, D2D1_DEVICE_CONTEXT_CATEGORY }; template inline HRESULT IfSupport(IUnknown* pUnknown, void(*lpFunc)(Intf*)) { CComPtr comObject; HRESULT hr = pUnknown->QueryInterface(&comObject); if (SUCCEEDED(hr)) { lpFunc(comObject); } return hr; } void Params::CreateParams(IDWriteFactory *dw_factory) { IDWriteFactory3* dw3 = NULL; IDWriteFactory2* dw2 = NULL; IDWriteFactory1* dw1 = NULL; IDWriteRenderingParams3* r3 = NULL; IDWriteRenderingParams2* r2 = NULL; IDWriteRenderingParams1* r1 = NULL; IDWriteRenderingParams* r0 = NULL; CComPtr pDWriteFactory; if (NULL == dw_factory) { ORIG_DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED, __uuidof(IDWriteFactory), reinterpret_cast(&pDWriteFactory)); dw_factory = pDWriteFactory; } HRESULT hr = dw_factory->QueryInterface(&dw3); if SUCCEEDED(hr) { hr = dw3->CreateCustomRenderingParams( this->Gamma, this->EnhancedContrast, this->GrayscaleEnhancedContrast, this->ClearTypeLevel, this->PixelGeometry, this->RenderingMode1, this->GridFitMode, &r3); dw3->Release(); if SUCCEEDED(hr) { RenderingParams = r3; return; } } hr = dw_factory->QueryInterface(&dw2); if SUCCEEDED(hr) { hr = dw2->CreateCustomRenderingParams( this->Gamma, this->EnhancedContrast, this->GrayscaleEnhancedContrast, this->ClearTypeLevel, this->PixelGeometry, this->RenderingMode, this->GridFitMode, &r2); dw2->Release(); if SUCCEEDED(hr) { RenderingParams = r2; return; } } hr = dw_factory->QueryInterface(&dw1); if SUCCEEDED(hr) { hr = dw1->CreateCustomRenderingParams( this->Gamma, this->EnhancedContrast, this->GrayscaleEnhancedContrast, this->ClearTypeLevel, this->PixelGeometry, this->RenderingMode, &r1); dw1->Release(); if SUCCEEDED(hr) { RenderingParams = r1; return; } } hr = dw_factory->CreateCustomRenderingParams( this->Gamma, this->EnhancedContrast, this->ClearTypeLevel, this->PixelGeometry, this->RenderingMode, &r0); if (SUCCEEDED(hr)) { RenderingParams = r0; return; } RenderingParams = NULL; } Params::Params() { //MessageBox(NULL, L"MakeParam", NULL, MB_OK); const CGdippSettings* pSettings = CGdippSettings::GetInstanceNoInit(); // Gamma = pSettings->GammaValueForDW(); //user defined value preferred. //if (Gamma == 0) // Gamma = pSettings->GammaValue()*pSettings->GammaValue() > 1.3 ? pSettings->GammaValue()*pSettings->GammaValue() / 2 : 0.7f; EnhancedContrast = pSettings->ContrastForDW(); ClearTypeLevel = pSettings->ClearTypeLevelForDW(); AntialiasMode = (D2D1_TEXT_ANTIALIAS_MODE)D2D1_TEXT_ANTIALIAS_MODE_DEFAULT; switch (pSettings->AntiAliasModeForDW()) { case 2: case 4: PixelGeometry = DWRITE_PIXEL_GEOMETRY_RGB; break; case 3: case 5: PixelGeometry = DWRITE_PIXEL_GEOMETRY_BGR; break; default: PixelGeometry = DWRITE_PIXEL_GEOMETRY_FLAT; AntialiasMode = D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE; } RenderingMode = (DWRITE_RENDERING_MODE)pSettings->RenderingModeForDW(); GrayscaleEnhancedContrast = pSettings->ContrastForDW(); switch (pSettings->GetFontSettings().GetHintingMode()) { case 0: GridFitMode = DWRITE_GRID_FIT_MODE_DEFAULT; break; case 1: GridFitMode = DWRITE_GRID_FIT_MODE_DISABLED; break; default: GridFitMode = DWRITE_GRID_FIT_MODE_ENABLED; break; } RenderingMode1 = (DWRITE_RENDERING_MODE1)pSettings->RenderingModeForDW(); RenderingParams = NULL; } Params* GetD2DParams() { static Params d2dParams; return &d2dParams; } Params* GetDWParams() { static Params dwParams = [] { const CGdippSettings* pSettings = CGdippSettings::GetInstanceNoInit(); Params p; if (pSettings->RenderingModeForDW() == 6) { //DW rendering in mode6 is horrible p.RenderingMode = DWRITE_RENDERING_MODE_NATURAL_SYMMETRIC; p.RenderingMode1 = DWRITE_RENDERING_MODE1_NATURAL_SYMMETRIC; } //g_DWParams.Gamma = powf(g_D2DParams.Gamma, 1.0 / 3.0); return p; }(); return &dwParams; } IDWriteRenderingParams* GetD2DRenderingParams(IDWriteRenderingParams* default) { Params* params = GetD2DParams(); static bool inited = [&] { params->CreateParams(NULL); return true; }(); if (params->RenderingParams) return params->RenderingParams; else return default; } IDWriteRenderingParams* GetDWRenderingParams(IDWriteRenderingParams* default) { Params* params = GetDWParams(); static bool inited = [&] { params->CreateParams(NULL); return true; }(); if (params->RenderingParams) return params->RenderingParams; else return default; } // Hook the implementation rather than an interface. // There are many versions but inside the DLL there's only one implementation // that supports the latest available one. Older versions are just upcasts, // they share the same vftable. void HookFactory(ID2D1Factory* pD2D1Factory) { static bool loaded = [&] { HRESULT hr; CComPtr ptr = pD2D1Factory; // index is the index in the vftable. Their order is the same as // methods declared in the header. HOOK(ptr, CreateWicBitmapRenderTarget, 13); HOOK(ptr, CreateHwndRenderTarget, 14); HOOK(ptr, CreateDxgiSurfaceRenderTarget, 15); HOOK(ptr, CreateDCRenderTarget, 16); MyDebug(L"ID2D1Factory hooked"); CComPtr ptr1; hr = pD2D1Factory->QueryInterface(&ptr1); if (SUCCEEDED(hr)){ HOOK(ptr1, CreateDevice1, 17); MyDebug(L"ID2D1Factory1 hooked"); } CComPtr ptr2; hr = pD2D1Factory->QueryInterface(&ptr2); if (SUCCEEDED(hr)){ HOOK(ptr2, CreateDevice2, 27); MyDebug(L"ID2D1Factory2 hooked"); } CComPtr ptr3; hr = pD2D1Factory->QueryInterface(&ptr3); if (SUCCEEDED(hr)){ HOOK(ptr3, CreateDevice3, 28); MyDebug(L"ID2D1Factory3 hooked"); } CComPtr ptr4; hr = pD2D1Factory->QueryInterface(&ptr4); if (SUCCEEDED(hr)){ HOOK(ptr4, CreateDevice4, 29); MyDebug(L"ID2D1Factory4 hooked"); } CComPtr ptr5; hr = pD2D1Factory->QueryInterface(&ptr5); if (SUCCEEDED(hr)){ HOOK(ptr5, CreateDevice5, 30); MyDebug(L"ID2D1Factory5 hooked"); } CComPtr ptr6; hr = pD2D1Factory->QueryInterface(&ptr6); if (SUCCEEDED(hr)){ HOOK(ptr6, CreateDevice6, 31); MyDebug(L"ID2D1Factory6 hooked"); } CComPtr ptr7; hr = pD2D1Factory->QueryInterface(&ptr7); if (SUCCEEDED(hr)){ HOOK(ptr7, CreateDevice7, 32); MyDebug(L"ID2D1Factory7 hooked"); } return true; }(); } void HookDevice(ID2D1Device* d2dDevice){ static bool loaded = [&] { CComPtr ptr = d2dDevice; HOOK(ptr, CreateDeviceContext, 4); MyDebug(L"ID2D1Device hooked"); CComPtr ptr2; HRESULT hr = (d2dDevice)->QueryInterface(&ptr2); if SUCCEEDED(hr) { HOOK(ptr2, CreateDeviceContext2, 11); MyDebug(L"ID2D1Device1 hooked"); } CComPtr ptr3; hr = (d2dDevice)->QueryInterface(&ptr3); if SUCCEEDED(hr) { HOOK(ptr3, CreateDeviceContext3, 12); MyDebug(L"ID2D1Device2 hooked"); } CComPtr ptr4; hr = (d2dDevice)->QueryInterface(&ptr4); if SUCCEEDED(hr) { HOOK(ptr4, CreateDeviceContext4, 15); MyDebug(L"ID2D1Device3 hooked"); } CComPtr ptr5; hr = (d2dDevice)->QueryInterface(&ptr5); if SUCCEEDED(hr) { HOOK(ptr5, CreateDeviceContext5, 16); MyDebug(L"ID2D1Device4 hooked"); } CComPtr ptr6; hr = (d2dDevice)->QueryInterface(&ptr6); if SUCCEEDED(hr) { HOOK(ptr6, CreateDeviceContext6, 19); MyDebug(L"ID2D1Device5 hooked"); } CComPtr ptr7; hr = (d2dDevice)->QueryInterface(&ptr7); if SUCCEEDED(hr) { HOOK(ptr7, CreateDeviceContext7, 20); MyDebug(L"ID2D1Device6 hooked"); } return true; }(); } // Hook the method if it has not been hooked. It's not thread safe. void HookRenderTargetMethod( ID2D1RenderTarget* pD2D1RenderTarget, D2D1RenderTargetCategory hookCategory, ComMethodHooker methodHookers[] ) { void* method = methodHookers[hookCategory].lpGetMethod(pD2D1RenderTarget); if (!method || methodHookers[hookCategory].lpIsHooked()) return; // fn is not available or already hooked methodHookers[hookCategory].lpHookFunc(pD2D1RenderTarget); } void HookRenderTarget( ID2D1RenderTarget* pD2D1RenderTarget, D2D1RenderTargetCategory hookCategory ){ MyDebug(L"HookRenderTarget %d", hookCategory); static bool loaded = [&] { CComPtr ptr = pD2D1RenderTarget; HOOK(ptr, CreateCompatibleRenderTarget, 12); HOOK(ptr, D2D1RenderTarget_DrawTextLayout, 28); ID2D1Factory* pD2D1Factory; pD2D1RenderTarget->GetFactory(&pD2D1Factory); if (pD2D1Factory) HookFactory(pD2D1Factory); // Actually it always implements ID2D1DeviceContext regardless of // hookCategory. CComPtr ptr1; HRESULT hr = pD2D1RenderTarget->QueryInterface(&ptr1); if (SUCCEEDED(hr)) { ID2D1Device* pD2D1Device; ptr1->GetDevice(&pD2D1Device); if (pD2D1Device) HookDevice(pD2D1Device); } return true; }(); // Some methods are duplicated across interfaces. Hook them whenever they're // available from an instance. Make sure don't hook the same function // multiple times. // // Up to two instances of the same function static ComMethodHooker hookDrawText[] = { COM_METHOD_HOOKER_EMPTY(), COM_METHOD_HOOKER(ID2D1RenderTarget, D2D1RenderTarget_DrawText, 27), COM_METHOD_HOOKER(ID2D1RenderTarget, D2D1RenderTarget_DrawText, 27), COM_METHOD_HOOKER(ID2D1DeviceContext, D2D1DeviceContext_DrawText, 27) }; // Up to three instances of the same function static ComMethodHooker hookDrawGlyphRun[] = { COM_METHOD_HOOKER_EMPTY(), COM_METHOD_HOOKER(ID2D1RenderTarget, D2D1RenderTarget_DrawGlyphRun, 29), COM_METHOD_HOOKER(ID2D1RenderTarget, D2D1RenderTarget1_DrawGlyphRun, 29), COM_METHOD_HOOKER(ID2D1DeviceContext, D2D1DeviceContext_DrawGlyphRun, 29) }; static ComMethodHooker hookSetTextAntialiasMode[] = { COM_METHOD_HOOKER_EMPTY(), COM_METHOD_HOOKER(ID2D1RenderTarget, D2D1RenderTarget_SetTextAntialiasMode, 34), COM_METHOD_HOOKER(ID2D1RenderTarget, D2D1RenderTarget_SetTextAntialiasMode, 34), COM_METHOD_HOOKER(ID2D1DeviceContext, D2D1DeviceContext_SetTextAntialiasMode, 34) }; static ComMethodHooker hookSetTextRenderingParams[] = { COM_METHOD_HOOKER_EMPTY(), COM_METHOD_HOOKER(ID2D1RenderTarget, D2D1RenderTarget_SetTextRenderingParams, 36), COM_METHOD_HOOKER(ID2D1RenderTarget, D2D1RenderTarget_SetTextRenderingParams, 36), COM_METHOD_HOOKER(ID2D1DeviceContext, D2D1DeviceContext_SetTextRenderingParams, 36) }; // Note that there's a branch in the inheritance hierarchy in // ID2D1RenderTarget. But the implementation always supports // ID2D1DeviceContext, thus multiple inheritance should take place. The // vftable for ID2D1DeviceContext is different if hookCategory is not // D2D1_DEVICE_CONTEXT_CATEGORY. It consists of thunks each of which adjusts // the this pointer and then jumps to the corresponding method for // ID2D1RenderTarget (So we don't have to hook them as well), and the other // functions for ID2D1DeviceContext. static ComMethodHooker hookDrawGlyphRun1[] = { COM_METHOD_HOOKER_EMPTY(), COM_METHOD_HOOKER(ID2D1RenderTarget, D2D1RenderTarget_DrawGlyphRun1, 82), COM_METHOD_HOOKER(ID2D1RenderTarget, D2D1RenderTarget1_DrawGlyphRun1, 82), COM_METHOD_HOOKER(ID2D1DeviceContext, D2D1DeviceContext_DrawGlyphRun1, 82) }; if (hookCategory == D2D1_RENDER_TARGET_CATEGORY) { static bool loaded1 = [&] { CCriticalSectionLock __lock(CCriticalSectionLock::CS_DWRITE); HookRenderTargetMethod(pD2D1RenderTarget, hookCategory, hookDrawText); HookRenderTargetMethod(pD2D1RenderTarget, hookCategory, hookDrawGlyphRun); HookRenderTargetMethod(pD2D1RenderTarget, hookCategory, hookSetTextAntialiasMode); HookRenderTargetMethod(pD2D1RenderTarget, hookCategory, hookSetTextRenderingParams); CComPtr ptr; HRESULT hr = pD2D1RenderTarget->QueryInterface(&ptr); if (SUCCEEDED(hr)) { HookRenderTargetMethod(ptr, hookCategory, hookDrawGlyphRun1); } return true; }(); } else if (hookCategory == D2D1_RENDER_TARGET1_CATEGORY) { static bool loaded2 = [&] { CCriticalSectionLock __lock(CCriticalSectionLock::CS_DWRITE); HookRenderTargetMethod(pD2D1RenderTarget, hookCategory, hookDrawText); HookRenderTargetMethod(pD2D1RenderTarget, hookCategory, hookDrawGlyphRun); HookRenderTargetMethod(pD2D1RenderTarget, hookCategory, hookSetTextAntialiasMode); HookRenderTargetMethod(pD2D1RenderTarget, hookCategory, hookSetTextRenderingParams); CComPtr ptr; HRESULT hr = pD2D1RenderTarget->QueryInterface(&ptr); if (SUCCEEDED(hr)) { HookRenderTargetMethod(ptr, hookCategory, hookDrawGlyphRun1); } return true; }(); } else if (hookCategory == D2D1_DEVICE_CONTEXT_CATEGORY) { static bool loaded3 = [&] { CCriticalSectionLock __lock(CCriticalSectionLock::CS_DWRITE); HookRenderTargetMethod(pD2D1RenderTarget, hookCategory, hookDrawText); HookRenderTargetMethod(pD2D1RenderTarget, hookCategory, hookDrawGlyphRun); HookRenderTargetMethod(pD2D1RenderTarget, hookCategory, hookSetTextAntialiasMode); HookRenderTargetMethod(pD2D1RenderTarget, hookCategory, hookSetTextRenderingParams); HookRenderTargetMethod(pD2D1RenderTarget, hookCategory, hookDrawGlyphRun1); return true; }(); } //pD2D1RenderTarget->SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_DEFAULT); pD2D1RenderTarget->SetTextAntialiasMode(GetD2DParams()->AntialiasMode); if (GetD2DRenderingParams(NULL)) { pD2D1RenderTarget->SetTextRenderingParams(GetD2DRenderingParams(NULL)); } } //DWrite hooks HRESULT WINAPI IMPL_CreateGlyphRunAnalysis( IDWriteFactory* This, DWRITE_GLYPH_RUN const* glyphRun, FLOAT pixelsPerDip, DWRITE_MATRIX const* transform, DWRITE_RENDERING_MODE renderingMode, DWRITE_MEASURING_MODE measuringMode, FLOAT baselineOriginX, FLOAT baselineOriginY, IDWriteGlyphRunAnalysis** glyphRunAnalysis) { HRESULT hr = E_FAIL; if (FAILED(hr) && renderingMode != DWRITE_RENDERING_MODE_ALIASED) { MyDebug(L"Try DW2"); IDWriteFactory2* f; hr = This->QueryInterface(&f); if (SUCCEEDED(hr)) { DWRITE_MATRIX m = {}; if (transform) { m = *transform; m.m11 *= pixelsPerDip; m.m12 *= pixelsPerDip; m.m21 *= pixelsPerDip; m.m22 *= pixelsPerDip; m.dx *= pixelsPerDip; m.dy *= pixelsPerDip; } else { m.m11 = pixelsPerDip; m.m22 = pixelsPerDip; } hr = f->CreateGlyphRunAnalysis( glyphRun, &m, renderingMode, measuringMode, DWRITE_GRID_FIT_MODE_DEFAULT, DWRITE_TEXT_ANTIALIAS_MODE_CLEARTYPE, baselineOriginX, baselineOriginY, glyphRunAnalysis ); f->Release(); } } if (FAILED(hr) && renderingMode != DWRITE_RENDERING_MODE_ALIASED) { MyDebug(L"Try DW1"); Params* dwParams = GetDWParams(); DWRITE_MATRIX m; DWRITE_MATRIX const* pm = transform; if (dwParams->GridFitMode == DWRITE_GRID_FIT_MODE_DISABLED) { if (transform) { m = *transform; m.m12 += 1.0f / 0xFFFF; m.m21 += 1.0f / 0xFFFF; } else { m = { 1, 1.0f / 0xFFFF, 1.0f / 0xFFFF, 1 }; } pm = &m; } hr = ORIG_CreateGlyphRunAnalysis( This, glyphRun, pixelsPerDip, pm, dwParams->RenderingMode, measuringMode, baselineOriginX, baselineOriginY, glyphRunAnalysis ); } if (FAILED(hr)) { MyDebug(L"Try Original Params"); hr = ORIG_CreateGlyphRunAnalysis( This, glyphRun, pixelsPerDip, transform, renderingMode, measuringMode, baselineOriginX, baselineOriginY, glyphRunAnalysis ); } if (SUCCEEDED(hr)) { MyDebug(L"CreateGlyphRunAnalysis hooked"); static bool loaded = [&] { CComPtr ptr = *glyphRunAnalysis; HOOK(ptr, GetAlphaBlendParams, 5); return true; }(); } return hr; } HRESULT WINAPI IMPL_GetGdiInterop( IDWriteFactory* This, IDWriteGdiInterop** gdiInterop ) { HRESULT hr = ORIG_GetGdiInterop(This, gdiInterop); static bool loaded = [&] { CComPtr gdip = *gdiInterop; HOOK(gdip, CreateBitmapRenderTarget, 7); return true; }(); MyDebug(L"IMPL_GetGdiInterop hooked"); return hr; } HRESULT WINAPI IMPL_CreateBitmapRenderTarget( IDWriteGdiInterop* This, HDC hdc, UINT32 width, UINT32 height, IDWriteBitmapRenderTarget** renderTarget ) { HRESULT hr = ORIG_CreateBitmapRenderTarget( This, hdc, width, height, renderTarget ); if (SUCCEEDED(hr)) { static bool loaded = [&] { CComPtr ptr = *renderTarget; HOOK(ptr, BitmapRenderTarget_DrawGlyphRun, 3); return true; }(); } MyDebug(L"CreateBitmapRenderTarget hooked"); return hr; } HRESULT WINAPI IMPL_GetAlphaBlendParams( IDWriteGlyphRunAnalysis* This, IDWriteRenderingParams* renderingParams, FLOAT* blendGamma, FLOAT* blendEnhancedContrast, FLOAT* blendClearTypeLevel ) { HRESULT hr = E_FAIL; if (FAILED(hr)) { hr = ORIG_GetAlphaBlendParams( This, GetDWRenderingParams(renderingParams), blendGamma, blendEnhancedContrast, blendClearTypeLevel ); } if (FAILED(hr)) { hr = ORIG_GetAlphaBlendParams( This, renderingParams, blendGamma, blendEnhancedContrast, blendClearTypeLevel ); } MyDebug(L"GetAlphaBlendParams hooked"); return hr; } HRESULT WINAPI IMPL_CreateGlyphRunAnalysis2( IDWriteFactory2* This, DWRITE_GLYPH_RUN const* glyphRun, DWRITE_MATRIX const* transform, DWRITE_RENDERING_MODE renderingMode, DWRITE_MEASURING_MODE measuringMode, DWRITE_GRID_FIT_MODE gridFitMode, DWRITE_TEXT_ANTIALIAS_MODE antialiasMode, FLOAT baselineOriginX, FLOAT baselineOriginY, IDWriteGlyphRunAnalysis** glyphRunAnalysis ) { HRESULT hr = E_FAIL; if (FAILED(hr) && renderingMode != DWRITE_RENDERING_MODE_ALIASED) { IDWriteFactory3* f; hr = This->QueryInterface(&f); if (SUCCEEDED(hr)) { hr = f->CreateGlyphRunAnalysis( glyphRun, transform, (DWRITE_RENDERING_MODE1)renderingMode, measuringMode, gridFitMode, antialiasMode, baselineOriginX, baselineOriginY, glyphRunAnalysis ); f->Release(); } } Params* dwParams = GetDWParams(); if (FAILED(hr) && renderingMode != DWRITE_RENDERING_MODE_ALIASED) { hr = ORIG_CreateGlyphRunAnalysis2( This, glyphRun, transform, dwParams->RenderingMode, measuringMode, dwParams->GridFitMode, antialiasMode, baselineOriginX, baselineOriginY, glyphRunAnalysis ); } if (FAILED(hr)) { DWRITE_MATRIX m = {}; DWRITE_MATRIX const* pm = transform; if (dwParams->GridFitMode == DWRITE_GRID_FIT_MODE_DISABLED) { if (transform) { m = *transform; m.m12 += 1.0f / 0xFFFF; m.m21 += 1.0f / 0xFFFF; } else { m = { 1, 1.0f / 0xFFFF, 1.0f / 0xFFFF, 1 }; } pm = &m; } hr = ORIG_CreateGlyphRunAnalysis2( This, glyphRun, pm, renderingMode, measuringMode, gridFitMode, antialiasMode, baselineOriginX, baselineOriginY, glyphRunAnalysis ); } if (FAILED(hr)) { hr = ORIG_CreateGlyphRunAnalysis2( This, glyphRun, transform, renderingMode, measuringMode, gridFitMode, antialiasMode, baselineOriginX, baselineOriginY, glyphRunAnalysis ); } if (SUCCEEDED(hr)) { MyDebug(L"CreateGlyphRunAnalysis2 hooked"); static bool loaded = [&] { CComPtr ptr = *glyphRunAnalysis; HOOK(ptr, GetAlphaBlendParams, 5); return true; }(); } return hr; } HRESULT WINAPI IMPL_CreateGlyphRunAnalysis3( IDWriteFactory3* This, DWRITE_GLYPH_RUN const* glyphRun, DWRITE_MATRIX const* transform, DWRITE_RENDERING_MODE1 renderingMode, DWRITE_MEASURING_MODE measuringMode, DWRITE_GRID_FIT_MODE gridFitMode, DWRITE_TEXT_ANTIALIAS_MODE antialiasMode, FLOAT baselineOriginX, FLOAT baselineOriginY, IDWriteGlyphRunAnalysis** glyphRunAnalysis ) { MyDebug(L"CreateGlyphRunAnalysis3 hooked"); Params* dwParams = GetDWParams(); HRESULT hr = E_FAIL; if (FAILED(hr) && renderingMode != DWRITE_RENDERING_MODE1_ALIASED) { hr = ORIG_CreateGlyphRunAnalysis3( This, glyphRun, transform, dwParams->RenderingMode1, measuringMode, dwParams->GridFitMode, antialiasMode, baselineOriginX, baselineOriginY, glyphRunAnalysis ); } if (FAILED(hr)) { MyDebug(L"try again with only transformation"); DWRITE_MATRIX m = {}; DWRITE_MATRIX const* pm = transform; if (dwParams->GridFitMode == DWRITE_GRID_FIT_MODE_DISABLED) { if (transform) { m = *transform; m.m12 += 1.0f / 0xFFFF; m.m21 += 1.0f / 0xFFFF; } else { m = { 1, 1.0f / 0xFFFF, 1.0f / 0xFFFF, 1 }; } pm = &m; } hr = ORIG_CreateGlyphRunAnalysis3( This, glyphRun, pm, renderingMode, measuringMode, gridFitMode, antialiasMode, baselineOriginX, baselineOriginY, glyphRunAnalysis ); } if (FAILED(hr)) { MyDebug(L"fallback to original params"); hr = ORIG_CreateGlyphRunAnalysis3( This, glyphRun, transform, renderingMode, measuringMode, gridFitMode, antialiasMode, baselineOriginX, baselineOriginY, glyphRunAnalysis ); } if (SUCCEEDED(hr)) { MyDebug(L"CreateGlyphRunAnalysis3 hooked"); static bool loaded = [&] { CComPtr ptr = *glyphRunAnalysis; HOOK(ptr, GetAlphaBlendParams, 5); return true; }(); } return hr; } //d2d1 hooks HRESULT WINAPI IMPL_D2D1CreateDevice( IDXGIDevice* dxgiDevice, CONST D2D1_CREATION_PROPERTIES* creationProperties, ID2D1Device** d2dDevice) { HRESULT hr = ORIG_D2D1CreateDevice( dxgiDevice, creationProperties, d2dDevice ); if (SUCCEEDED(hr)) { HookDevice(*d2dDevice); } MyDebug(L"IMPL_D2D1CreateDevice hooked"); return hr; } HRESULT WINAPI IMPL_D2D1CreateDeviceContext( IDXGISurface* dxgiSurface, CONST D2D1_CREATION_PROPERTIES* creationProperties, ID2D1DeviceContext** d2dDeviceContext){ HRESULT hr = ORIG_D2D1CreateDeviceContext( dxgiSurface, creationProperties, d2dDeviceContext ); if SUCCEEDED(hr) { HookRenderTarget(*d2dDeviceContext, D2D1_DEVICE_CONTEXT_CATEGORY); } MyDebug(L"IMPL_D2D1CreateDeviceContext hooked"); return hr; } HRESULT WINAPI IMPL_D2D1CreateFactory( D2D1_FACTORY_TYPE factoryType, REFIID riid, const D2D1_FACTORY_OPTIONS* pFactoryOptions, void** ppIFactory){ HRESULT hr = ORIG_D2D1CreateFactory(factoryType, riid, pFactoryOptions, ppIFactory); if (SUCCEEDED(hr)) { auto pUnknown = reinterpret_cast(*ppIFactory); ID2D1Factory* pD2D1Factory; HRESULT hr2 = pUnknown->QueryInterface(&pD2D1Factory); if (SUCCEEDED(hr2)) { HookFactory(pD2D1Factory); pD2D1Factory->Release(); } } return hr; } HRESULT WINAPI IMPL_CreateWicBitmapRenderTarget( ID2D1Factory* This, IWICBitmap* target, const D2D1_RENDER_TARGET_PROPERTIES* renderTargetProperties, ID2D1RenderTarget** renderTarget ) { HRESULT hr = ORIG_CreateWicBitmapRenderTarget( This, target, renderTargetProperties, renderTarget ); if (SUCCEEDED(hr)) { HookRenderTarget(*renderTarget, D2D1_RENDER_TARGET_CATEGORY); } MyDebug(L"IMPL_CreateWicBitmapRenderTarget hooked"); return hr; } HRESULT WINAPI IMPL_CreateHwndRenderTarget( ID2D1Factory* This, const D2D1_RENDER_TARGET_PROPERTIES* renderTargetProperties, const D2D1_HWND_RENDER_TARGET_PROPERTIES* hwndRenderTargetProperties, ID2D1HwndRenderTarget** hwndRenderTarget ) { HRESULT hr = ORIG_CreateHwndRenderTarget( This, renderTargetProperties, hwndRenderTargetProperties, hwndRenderTarget ); if (SUCCEEDED(hr)) { HookRenderTarget(*hwndRenderTarget, D2D1_RENDER_TARGET1_CATEGORY); } MyDebug(L"IMPL_CreateHwndRenderTarget hooked"); return hr; } HRESULT WINAPI IMPL_CreateDxgiSurfaceRenderTarget( ID2D1Factory* This, IDXGISurface* dxgiSurface, const D2D1_RENDER_TARGET_PROPERTIES* renderTargetProperties, ID2D1RenderTarget** renderTarget ) { HRESULT hr = ORIG_CreateDxgiSurfaceRenderTarget( This, dxgiSurface, renderTargetProperties, renderTarget ); if (SUCCEEDED(hr)) { HookRenderTarget(*renderTarget, D2D1_RENDER_TARGET_CATEGORY); } MyDebug(L"IMPL_CreateDxgiSurfaceRenderTarget hooked"); return hr; } HRESULT WINAPI IMPL_CreateDCRenderTarget( ID2D1Factory* This, const D2D1_RENDER_TARGET_PROPERTIES* renderTargetProperties, ID2D1DCRenderTarget** dcRenderTarget ) { HRESULT hr = ORIG_CreateDCRenderTarget( This, renderTargetProperties, dcRenderTarget ); if (SUCCEEDED(hr)) { HookRenderTarget(*dcRenderTarget, D2D1_RENDER_TARGET1_CATEGORY); } MyDebug(L"IMPL_CreateDCRenderTarget hooked"); return hr; } HRESULT WINAPI IMPL_CreateCompatibleRenderTarget( ID2D1RenderTarget* This, CONST D2D1_SIZE_F* desiredSize, CONST D2D1_SIZE_U* desiredPixelSize, CONST D2D1_PIXEL_FORMAT* desiredFormat, D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS options, ID2D1BitmapRenderTarget** bitmapRenderTarget ) { HRESULT hr = ORIG_CreateCompatibleRenderTarget( This, desiredSize, desiredPixelSize, desiredFormat, options, bitmapRenderTarget ); if (SUCCEEDED(hr)) { HookRenderTarget(*bitmapRenderTarget, D2D1_RENDER_TARGET1_CATEGORY); } MyDebug(L"IMPL_CreateCompatibleRenderTarget hooked"); return hr; } void WINAPI IMPL_D2D1RenderTarget_SetTextAntialiasMode( ID2D1RenderTarget* This, D2D1_TEXT_ANTIALIAS_MODE textAntialiasMode ) { MyDebug(L"IMPL_D2D1RenderTarget_SetTextAntialiasMode hooked"); ORIG_D2D1RenderTarget_SetTextAntialiasMode(This, GetD2DParams()->AntialiasMode); } void WINAPI IMPL_D2D1DeviceContext_SetTextAntialiasMode( ID2D1DeviceContext* This, D2D1_TEXT_ANTIALIAS_MODE textAntialiasMode ) { MyDebug(L"IMPL_D2D1DeviceContext_SetTextAntialiasMode hooked"); ORIG_D2D1DeviceContext_SetTextAntialiasMode(This, GetD2DParams()->AntialiasMode); } void WINAPI IMPL_D2D1RenderTarget_SetTextRenderingParams( ID2D1RenderTarget* This, _In_opt_ IDWriteRenderingParams* textRenderingParams ) { MyDebug(L"IMPL_D2D1RenderTarget_SetTextRenderingParams hooked"); ORIG_D2D1RenderTarget_SetTextRenderingParams(This, GetD2DRenderingParams(textRenderingParams)); } void WINAPI IMPL_D2D1DeviceContext_SetTextRenderingParams( ID2D1DeviceContext* This, _In_opt_ IDWriteRenderingParams* textRenderingParams ) { MyDebug(L"IMPL_D2D1DeviceContext_SetTextRenderingParams hooked"); ORIG_D2D1DeviceContext_SetTextRenderingParams(This, GetD2DRenderingParams(textRenderingParams)); } HRESULT WINAPI IMPL_CreateDeviceContext( ID2D1Device* This, D2D1_DEVICE_CONTEXT_OPTIONS options, ID2D1DeviceContext** deviceContext ) { HRESULT hr = ORIG_CreateDeviceContext( This, options, deviceContext ); if (SUCCEEDED(hr)) { HookRenderTarget(*deviceContext, D2D1_DEVICE_CONTEXT_CATEGORY); } MyDebug(L"IMPL_CreateDeviceContext hooked"); return hr; } HRESULT WINAPI IMPL_CreateDeviceContext2( ID2D1Device1* This, D2D1_DEVICE_CONTEXT_OPTIONS options, ID2D1DeviceContext1** deviceContext1 ) { HRESULT hr = ORIG_CreateDeviceContext2( This, options, deviceContext1 ); if (SUCCEEDED(hr)) { HookRenderTarget(*deviceContext1, D2D1_DEVICE_CONTEXT_CATEGORY); } MyDebug(L"IMPL_CreateDeviceContext2 hooked"); return hr; } HRESULT WINAPI IMPL_CreateDeviceContext3( ID2D1Device2* This, D2D1_DEVICE_CONTEXT_OPTIONS options, ID2D1DeviceContext2** deviceContext2 ) { HRESULT hr = ORIG_CreateDeviceContext3( This, options, deviceContext2 ); if (SUCCEEDED(hr)) { HookRenderTarget(*deviceContext2, D2D1_DEVICE_CONTEXT_CATEGORY); } MyDebug(L"IMPL_CreateDeviceContext3 hooked"); return hr; } HRESULT WINAPI IMPL_CreateDeviceContext4( ID2D1Device3* This, D2D1_DEVICE_CONTEXT_OPTIONS options, ID2D1DeviceContext3** deviceContext2 ) { HRESULT hr = ORIG_CreateDeviceContext4( This, options, deviceContext2 ); if (SUCCEEDED(hr)) { HookRenderTarget(*deviceContext2, D2D1_DEVICE_CONTEXT_CATEGORY); } MyDebug(L"IMPL_CreateDeviceContext4 hooked"); return hr; } HRESULT WINAPI IMPL_CreateDeviceContext5( ID2D1Device4* This, D2D1_DEVICE_CONTEXT_OPTIONS options, ID2D1DeviceContext4** deviceContext ) { HRESULT hr = ORIG_CreateDeviceContext5( This, options, deviceContext ); if (SUCCEEDED(hr)) { HookRenderTarget(*deviceContext, D2D1_DEVICE_CONTEXT_CATEGORY); } MyDebug(L"IMPL_CreateDeviceContext5 hooked"); return hr; } HRESULT WINAPI IMPL_CreateDeviceContext6( ID2D1Device5* This, D2D1_DEVICE_CONTEXT_OPTIONS options, ID2D1DeviceContext5** deviceContext ) { HRESULT hr = ORIG_CreateDeviceContext6( This, options, deviceContext ); if (SUCCEEDED(hr)) { HookRenderTarget(*deviceContext, D2D1_DEVICE_CONTEXT_CATEGORY); } MyDebug(L"IMPL_CreateDeviceContext6 hooked"); return hr; } HRESULT WINAPI IMPL_CreateDeviceContext7( ID2D1Device6* This, D2D1_DEVICE_CONTEXT_OPTIONS options, ID2D1DeviceContext6** deviceContext ) { HRESULT hr = ORIG_CreateDeviceContext7( This, options, deviceContext ); if (SUCCEEDED(hr)) { HookRenderTarget(*deviceContext, D2D1_DEVICE_CONTEXT_CATEGORY); } MyDebug(L"IMPL_CreateDeviceContext7 hooked"); return hr; } HRESULT WINAPI IMPL_CreateDevice1( ID2D1Factory1* This, IDXGIDevice* dxgiDevice, ID2D1Device** d2dDevice ) { HRESULT hr = ORIG_CreateDevice1( This, dxgiDevice, d2dDevice ); if (SUCCEEDED(hr)) { HookDevice(*d2dDevice); } MyDebug(L"IMPL_CreateDevice1 hooked"); return hr; } HRESULT WINAPI IMPL_CreateDevice2( ID2D1Factory2* This, IDXGIDevice* dxgiDevice, ID2D1Device1** d2dDevice1 ){ HRESULT hr = ORIG_CreateDevice2( This, dxgiDevice, d2dDevice1 ); if (SUCCEEDED(hr)) { HookDevice(*d2dDevice1); } MyDebug(L"IMPL_CreateDevice2 hooked"); return hr; } HRESULT WINAPI IMPL_CreateDevice3( ID2D1Factory3* This, IDXGIDevice* dxgiDevice, ID2D1Device2** d2dDevice2 ){ HRESULT hr = ORIG_CreateDevice3( This, dxgiDevice, d2dDevice2 ); if (SUCCEEDED(hr)) { HookDevice(*d2dDevice2); } MyDebug(L"IMPL_CreateDevice3 hooked"); return hr; } HRESULT WINAPI IMPL_CreateDevice4( ID2D1Factory4* This, IDXGIDevice* dxgiDevice, ID2D1Device3** d2dDevice3 ){ HRESULT hr = ORIG_CreateDevice4( This, dxgiDevice, d2dDevice3 ); if (SUCCEEDED(hr)) { HookDevice(*d2dDevice3); } MyDebug(L"IMPL_CreateDevice4 hooked"); return hr; } HRESULT WINAPI IMPL_CreateDevice5( ID2D1Factory5* This, IDXGIDevice* dxgiDevice, ID2D1Device4** d2dDevice4 ){ HRESULT hr = ORIG_CreateDevice5( This, dxgiDevice, d2dDevice4 ); if (SUCCEEDED(hr)) { HookDevice(*d2dDevice4); } MyDebug(L"IMPL_CreateDevice5 hooked"); return hr; } HRESULT WINAPI IMPL_CreateDevice6( ID2D1Factory6* This, IDXGIDevice* dxgiDevice, ID2D1Device5** d2dDevice5 ){ HRESULT hr = ORIG_CreateDevice6( This, dxgiDevice, d2dDevice5 ); if (SUCCEEDED(hr)) { HookDevice(*d2dDevice5); } MyDebug(L"IMPL_CreateDevice6 hooked"); return hr; } HRESULT WINAPI IMPL_CreateDevice7( ID2D1Factory7* This, IDXGIDevice* dxgiDevice, ID2D1Device6** d2dDevice6 ){ HRESULT hr = ORIG_CreateDevice7( This, dxgiDevice, d2dDevice6 ); if (SUCCEEDED(hr)) { HookDevice(*d2dDevice6); } MyDebug(L"IMPL_CreateDevice7 hooked"); return hr; } /* bool CreateFontFace(IDWriteGdiInterop* gdi, IDWriteFont*** dfont, LOGFONT* lf) { __try { gdi->CreateFontFromLOGFONT(lf, *dfont); return true; } __except(EXCEPTION_EXECUTE_HANDLER) { return false; } }*/ /* void WINAPI IMPL_SetTextRenderingParams(ID2D1RenderTarget* self, __in_opt IDWriteRenderingParams *textRenderingParams = NULL) { return ORIG_SetTextRenderingParams(self, g_D2DParamsLarge.RenderingParams); } void WINAPI IMPL_SetTextAntialiasMode(ID2D1RenderTarget* self, D2D1_TEXT_ANTIALIAS_MODE textAntialiasMode) { return ORIG_SetTextAntialiasMode(self, g_D2DParamsLarge.AntialiasMode); }*/ bool hookD2D1() { //MessageBox(NULL, L"HookD2D1", NULL, MB_OK); static bool loaded = [&] { return true; }(); return loaded; } #define FAILEXIT { /*CoUninitialize();*/ return false;} bool hookFontCreation(CComPtr& pDWriteFactory) { if (FAILED(pDWriteFactory->GetGdiInterop(&g_pGdiInterop))) FAILEXIT; //判断不正确 /* HDC dc = CreateCompatibleDC(0); CComQIPtr rt; g_pGdiInterop->CreateBitmapRenderTarget(dc, 1, 1, &rt); //used to trigger CreateBitmapRenderTarget->DrawGlyphRun hook rt.Release(); DeleteDC(dc);*/ HOOK(pDWriteFactory, CreateTextFormat, 15); CComPtr dfont = NULL; CComPtr fontcollection = NULL; CComPtr ffamily = NULL; if (FAILED(pDWriteFactory->GetSystemFontCollection(&fontcollection, false))) FAILEXIT; if (FAILED(fontcollection->GetFontFamily(0, &ffamily))) FAILEXIT; if (FAILED(ffamily->GetFont(0, &dfont))) FAILEXIT; CComPtr dfont3 = NULL; HRESULT hr = dfont->QueryInterface(&dfont3); if (FAILED(hr)) { HOOK(dfont, CreateFontFace, 13); } else { // IDWriteFont::CreateFontFace just wraps this HOOK(dfont3, CreateFontFace, 19); } return true; } bool hookDirectWrite(IUnknown ** factory) //此函数需要改进以判断是否成功hook { //CoInitialize(NULL); #ifdef DEBUG //MessageBox(NULL, L"HookDW", NULL, MB_OK); #endif static bool loaded = [&] { CComPtr pDWriteFactory; HRESULT hr1 = (*factory)->QueryInterface(&pDWriteFactory); if (FAILED(hr1)) FAILEXIT; HOOK(pDWriteFactory, CreateGlyphRunAnalysis, 23); HOOK(pDWriteFactory, GetGdiInterop, 17); const CGdippSettings* pSettings = CGdippSettings::GetInstance(); // Windows8/8.1 is too buggy, GDIinterpo doesn't work correctly if (!pSettings->IsWindows81() && !pSettings->IsWindows8() && pSettings->DelayedInited() && pSettings->GetFontSubstitutesInfo().GetSize()) hookFontCreation(pDWriteFactory); MyDebug(L"DW1 hooked"); CComPtr pDWriteFactory2; HRESULT hr2 = (*factory)->QueryInterface(&pDWriteFactory2); if (FAILED(hr2)) FAILEXIT; HOOK(pDWriteFactory2, CreateGlyphRunAnalysis2, 30); MyDebug(L"DW2 hooked"); CComPtr pDWriteFactory3; HRESULT hr3 = (*factory)->QueryInterface(&pDWriteFactory3); if (FAILED(hr3)) FAILEXIT; HOOK(pDWriteFactory3, CreateGlyphRunAnalysis3, 31); MyDebug(L"DW3 hooked"); return true; }(); return loaded; } #undef FAILEXIT #define FAILEXIT {return;} void TriggerHook(ID2D1Factory* d2d_factory) { const D2D1_PIXEL_FORMAT format = D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED); const D2D1_RENDER_TARGET_PROPERTIES properties = D2D1::RenderTargetProperties(D2D1_RENDER_TARGET_TYPE_DEFAULT, format, 0.0f, 0.0f, D2D1_RENDER_TARGET_USAGE_NONE); CComPtrtarget; if (FAILED(d2d_factory->CreateDCRenderTarget(&properties, &target))) FAILEXIT; } // The entry point of DirectWrite hooking // D2D1CreateFactory // HookFactory // ID2D1Factory // CreateWicBitmapRenderTarget // CreateHwndRenderTarget // CreateDxgiSurfaceRenderTarget // CreateDCRenderTarget // HookRenderTarget -> // ID2D1Factory // CreateDevice // HookDevice -> // D2D1CreateDevice // HookDevice // ID2D1Device // CreateDeviceContext // HookRenderTarget -> // D2D1CreateDeviceContext // HookRenderTarget // ID2D1RenderTarget // CreateCompatibleRenderTarget // HookRenderTarget -> // DrawText // DrawTextLayout // DrawGlyphRun // SetTextAntialiasMode // SetTextRenderingParams // GetFactory() // HookFactory -> // ID2D1DeviceContext // DrawGlyphRun1 // GetDevice() // HookDevice -> // DWriteCreateFactory // hookDirectWrite // IDWriteFactory // GetGdiInterop // CreateBitmapRenderTarget // IDWriteBitmapRenderTarget // DrawGlyphRun // CreateGlyphRunAnalysis // IDWriteGlyphRunAnalysis // GetAlphaBlendParams // hookFontCreation // CreateTextFormat // IDWriteTextFormat // IDWriteFont // CreateFontFace // IDWriteFontFace // IDWriteFont3 // CreateFontFace // GetFontFaceReference() // IDWriteFontFaceReference // CreateFontFace // CreateFontFaceWithSimulations // IDWriteFactory // CreateGlyphRunAnalysis // IDWriteGlyphRunAnalysis // GetAlphaBlendParams void HookD2DDll() { typedef HRESULT (WINAPI *PFN_DWriteCreateFactory)( _In_ DWRITE_FACTORY_TYPE factoryType, _In_ REFIID iid, _COM_Outptr_ IUnknown **factory ); typedef HRESULT (WINAPI *PFN_D2D1CreateFactory)( D2D1_FACTORY_TYPE factoryType, REFIID riid, const D2D1_FACTORY_OPTIONS* pFactoryOptions, void** ppIFactory ); //Sleep(30 * 1000); #ifdef DEBUG MessageBox(0, L"HookD2DDll", NULL, MB_OK); #endif HMODULE d2d1 = GetModuleHandle(_T("d2d1.dll")); HMODULE dw = GetModuleHandle(_T("dwrite.dll")); if (!d2d1) d2d1 = LoadLibrary(_T("d2d1.dll")); if (!dw) dw = LoadLibrary(_T("dwrite.dll")); void* D2D1Factory = GetProcAddress(d2d1, "D2D1CreateFactory"); void* D2D1Device = GetProcAddress(d2d1, "D2D1CreateDevice"); void* D2D1Context = GetProcAddress(d2d1, "D2D1CreateDeviceContext"); void* DWFactory = GetProcAddress(dw, "DWriteCreateFactory"); *(DWORD_PTR*)&ORIG_D2D1CreateFactory = (DWORD_PTR)D2D1Factory; *(DWORD_PTR*)&ORIG_D2D1CreateDevice = (DWORD_PTR)D2D1Device; *(DWORD_PTR*)&ORIG_D2D1CreateDeviceContext = (DWORD_PTR)D2D1Context; *(DWORD_PTR*)&ORIG_DWriteCreateFactory = (DWORD_PTR)DWFactory; if (DWFactory) { hook_demand_DWriteCreateFactory(); } if (D2D1Factory){ hook_demand_D2D1CreateFactory(); } if (D2D1Device) { hook_demand_D2D1CreateDevice(); } if (D2D1Context) { hook_demand_D2D1CreateDeviceContext(); } } /* void HookGdiplus() { InitGdiplusFuncs(); //*(DWORD_PTR*)&ORIG_D2D1CreateFactory = (DWORD_PTR)D2D1Factory; *(DWORD_PTR*)&ORIG_GdipDrawString = (DWORD_PTR)pfnGdipDrawString; hook_demand_GdipDrawString(); } GpStatus WINAPI IMPL_GdipDrawString( GpGraphics *graphics, GDIPCONST WCHAR *string, INT length, GDIPCONST GpFont *font, GDIPCONST RectF *layoutRect, GDIPCONST GpStringFormat *stringFormat, GDIPCONST GpBrush *brush ) { #define GDIPEXEC ORIG_GdipDrawString(graphics, string, length, font, layoutRect, stringFormat, brush) #define GDIPCHECK(x) if ((x)!=Ok) return GDIPEXEC if (string) { HDC dc = NULL; LOGFONTW lf = {0}; GpBrushType bt; ARGB FontColor=0 ,bkColor = 0; //GDIPLUS to gdi32 data preparation GDIPCHECK(pfnGdipGetLogFontW((GpFont*)font, graphics, &lf)); GDIPCHECK(pfnGdipGetBrushType((GpBrush*)brush, &bt)); if (bt!=BrushTypeSolidColor) return GDIPEXEC; //only solid brush is supported by GDI32 GDIPCHECK(pfnGdipGetSolidFillColor((GpSolidFill*)brush, &FontColor)); if (FontColor>>24!=0xFF) return GDIPEXEC; //only transparent and Opaque is supported. GDIPCHECK(pfnGdipGetDC(graphics, &dc)); HFONT ft = CreateFontIndirectW(&lf); HFONT oldfont = SelectFont(dc, ft); SetTextColor(dc, FontColor & 0x00FFFFFF); SetBkMode(dc, TRANSPARENT); RECT gdiRect = {ROUND(layoutRect->X), ROUND(layoutRect->Y), ROUND(layoutRect->X+layoutRect->Width), ROUND(layoutRect->Y+layoutRect->Height)}; DrawText(dc, string, length, &gdiRect, DT_WORDBREAK); //ExtTextOutW(dc, gdiRect.left, gdiRect.top, 0, &gdiRect, string, wcslen(string), NULL); SelectObject(dc, oldfont); DeleteObject(ft); pfnGdipReleaseDC(graphics, dc); return Ok; } else return ORIG_GdipDrawString(graphics, string, length, font, layoutRect, stringFormat, brush); #undef GDIPCHECK #undef GDIPEXEC } */ HRESULT WINAPI IMPL_DWriteCreateFactory(__in DWRITE_FACTORY_TYPE factoryType, __in REFIID iid, __out IUnknown **factory) { HRESULT ret = ORIG_DWriteCreateFactory(factoryType, iid, factory); if (SUCCEEDED(ret)) hookDirectWrite(factory); return ret; } HRESULT WINAPI IMPL_CreateFontFace(IDWriteFont* self, __out IDWriteFontFace** fontFace) { HRESULT ret = ORIG_CreateFontFace(self, fontFace); if (ret == S_OK) { /*static bool loaded = [&] { CComPtr dfont3 = NULL; HRESULT hr = self->QueryInterface(&dfont3); if (SUCCEEDED(hr)) { CComPtr ffref; if (SUCCEEDED(dfont3->GetFontFaceReference(&ffref)) && ffref) { // Same as IDWriteFontFaceReference1::CreateFontFace HOOK(ffref, DWriteFontFaceReference_CreateFontFace, 3); HOOK(ffref, DWriteFontFaceReference_CreateFontFaceWithSimulations, 4); } } return true; }();*/ LOGFONT lf = { 0 }; if (FAILED(g_pGdiInterop->ConvertFontFaceToLOGFONT(*fontFace, &lf))) return ret; const CGdippSettings* pSettings = CGdippSettings::GetInstance(); if (pSettings->CopyForceFont(lf, lf)) { IDWriteFont* writefont = NULL; if (FAILED(g_pGdiInterop->CreateFontFromLOGFONT(&lf, &writefont))) return ret; (*fontFace)->Release(); ORIG_CreateFontFace(writefont, fontFace); writefont->Release(); } } return ret; } bool SubstituteDWriteFont3(__out IDWriteFontFace3** fontFace3) { LOGFONT lf = { 0 }; if (FAILED(g_pGdiInterop->ConvertFontFaceToLOGFONT(*fontFace3, &lf))) return false; const CGdippSettings* pSettings = CGdippSettings::GetInstance(); if (pSettings->CopyForceFont(lf, lf)) { CComPtr writefont; if (FAILED(g_pGdiInterop->CreateFontFromLOGFONT(&lf, &writefont))) return false; CComPtr fontFaceOut; ORIG_CreateFontFace(writefont, &fontFaceOut); IDWriteFontFace3* fontFace3Out; if (FAILED(fontFaceOut->QueryInterface(&fontFace3Out))) return false; (*fontFace3)->Release(); *fontFace3 = fontFace3Out; } return true; } HRESULT WINAPI IMPL_DWriteFontFaceReference_CreateFontFace( IDWriteFontFaceReference* self, __out IDWriteFontFace3** fontFace) { HRESULT ret = ORIG_DWriteFontFaceReference_CreateFontFace(self, fontFace); if (ret == S_OK) { SubstituteDWriteFont3(fontFace); } return ret; } HRESULT WINAPI IMPL_DWriteFontFaceReference_CreateFontFaceWithSimulations( IDWriteFontFaceReference* self, DWRITE_FONT_SIMULATIONS fontFaceSimulationFlags, __out IDWriteFontFace3** fontFace) { HRESULT ret = ORIG_DWriteFontFaceReference_CreateFontFaceWithSimulations(self, fontFaceSimulationFlags, fontFace); if (ret == S_OK) { SubstituteDWriteFont3(fontFace); } return ret; } HRESULT WINAPI IMPL_CreateTextFormat(IDWriteFactory* self, __in_z WCHAR const* fontFamilyName, __maybenull IDWriteFontCollection* fontCollection, DWRITE_FONT_WEIGHT fontWeight, DWRITE_FONT_STYLE fontStyle, DWRITE_FONT_STRETCH fontStretch, FLOAT fontSize, __in_z WCHAR const* localeName, __out IDWriteTextFormat** textFormat) { LOGFONT lf = { 0 }; StringCchCopy(lf.lfFaceName, LF_FACESIZE, fontFamilyName); const CGdippSettings* pSettings = CGdippSettings::GetInstance(); if (pSettings->CopyForceFont(lf, lf)) return ORIG_CreateTextFormat(self, lf.lfFaceName, fontCollection, fontWeight, fontStyle, fontStretch, fontSize, localeName, textFormat); else return ORIG_CreateTextFormat(self, fontFamilyName, fontCollection, fontWeight, fontStyle, fontStretch, fontSize, localeName, textFormat); } void WINAPI IMPL_D2D1RenderTarget_DrawGlyphRun1( ID2D1DeviceContext *This, D2D1_POINT_2F baselineOrigin, CONST DWRITE_GLYPH_RUN *glyphRun, CONST DWRITE_GLYPH_RUN_DESCRIPTION *glyphRunDescription, ID2D1Brush *foregroundBrush, DWRITE_MEASURING_MODE measuringMode ) { Params* dwParams = GetDWParams(); if (dwParams->GridFitMode == DWRITE_GRID_FIT_MODE_DISABLED) { D2D1_MATRIX_3X2_F prev; This->GetTransform(&prev); D2D1_MATRIX_3X2_F rotate = prev; rotate.m12 += 1.0f / 0xFFFF; rotate.m21 += 1.0f / 0xFFFF; This->SetTransform(&rotate); ORIG_D2D1RenderTarget_DrawGlyphRun1( This, baselineOrigin, glyphRun, glyphRunDescription, foregroundBrush, measuringMode ); This->SetTransform(&prev); } else { ORIG_D2D1RenderTarget_DrawGlyphRun1( This, baselineOrigin, glyphRun, glyphRunDescription, foregroundBrush, measuringMode ); } } void WINAPI IMPL_D2D1RenderTarget1_DrawGlyphRun1( ID2D1DeviceContext *This, D2D1_POINT_2F baselineOrigin, CONST DWRITE_GLYPH_RUN *glyphRun, CONST DWRITE_GLYPH_RUN_DESCRIPTION *glyphRunDescription, ID2D1Brush *foregroundBrush, DWRITE_MEASURING_MODE measuringMode ) { Params* dwParams = GetDWParams(); if (dwParams->GridFitMode == DWRITE_GRID_FIT_MODE_DISABLED) { D2D1_MATRIX_3X2_F prev; This->GetTransform(&prev); D2D1_MATRIX_3X2_F rotate = prev; rotate.m12 += 1.0f / 0xFFFF; rotate.m21 += 1.0f / 0xFFFF; This->SetTransform(&rotate); ORIG_D2D1RenderTarget1_DrawGlyphRun1( This, baselineOrigin, glyphRun, glyphRunDescription, foregroundBrush, measuringMode ); This->SetTransform(&prev); } else { ORIG_D2D1RenderTarget1_DrawGlyphRun1( This, baselineOrigin, glyphRun, glyphRunDescription, foregroundBrush, measuringMode ); } } void WINAPI IMPL_D2D1DeviceContext_DrawGlyphRun1( ID2D1DeviceContext *This, D2D1_POINT_2F baselineOrigin, CONST DWRITE_GLYPH_RUN *glyphRun, CONST DWRITE_GLYPH_RUN_DESCRIPTION *glyphRunDescription, ID2D1Brush *foregroundBrush, DWRITE_MEASURING_MODE measuringMode ) { Params* dwParams = GetDWParams(); if (dwParams->GridFitMode == DWRITE_GRID_FIT_MODE_DISABLED) { D2D1_MATRIX_3X2_F prev; This->GetTransform(&prev); D2D1_MATRIX_3X2_F rotate = prev; rotate.m12 += 1.0f / 0xFFFF; rotate.m21 += 1.0f / 0xFFFF; This->SetTransform(&rotate); ORIG_D2D1DeviceContext_DrawGlyphRun1( This, baselineOrigin, glyphRun, glyphRunDescription, foregroundBrush, measuringMode ); This->SetTransform(&prev); } else { ORIG_D2D1DeviceContext_DrawGlyphRun1( This, baselineOrigin, glyphRun, glyphRunDescription, foregroundBrush, measuringMode ); } } void WINAPI IMPL_D2D1RenderTarget_DrawGlyphRun( ID2D1RenderTarget* This, D2D1_POINT_2F baselineOrigin, CONST DWRITE_GLYPH_RUN *glyphRun, ID2D1Brush *foregroundBrush, DWRITE_MEASURING_MODE measuringMode ) { Params* dwParams = GetDWParams(); if (dwParams->GridFitMode == DWRITE_GRID_FIT_MODE_DISABLED) { D2D1_MATRIX_3X2_F prev; This->GetTransform(&prev); D2D1_MATRIX_3X2_F rotate = prev; rotate.m12 += 1.0f / 0xFFFF; rotate.m21 += 1.0f / 0xFFFF; This->SetTransform(&rotate); ORIG_D2D1RenderTarget_DrawGlyphRun( This, baselineOrigin, glyphRun, foregroundBrush, measuringMode ); This->SetTransform(&prev); } else { ORIG_D2D1RenderTarget_DrawGlyphRun( This, baselineOrigin, glyphRun, foregroundBrush, measuringMode ); } } void WINAPI IMPL_D2D1RenderTarget1_DrawGlyphRun( ID2D1RenderTarget* This, D2D1_POINT_2F baselineOrigin, CONST DWRITE_GLYPH_RUN *glyphRun, ID2D1Brush *foregroundBrush, DWRITE_MEASURING_MODE measuringMode ) { Params* dwParams = GetDWParams(); if (dwParams->GridFitMode == DWRITE_GRID_FIT_MODE_DISABLED) { D2D1_MATRIX_3X2_F prev; This->GetTransform(&prev); D2D1_MATRIX_3X2_F rotate = prev; rotate.m12 += 1.0f / 0xFFFF; rotate.m21 += 1.0f / 0xFFFF; This->SetTransform(&rotate); ORIG_D2D1RenderTarget1_DrawGlyphRun( This, baselineOrigin, glyphRun, foregroundBrush, measuringMode ); This->SetTransform(&prev); } else { ORIG_D2D1RenderTarget1_DrawGlyphRun( This, baselineOrigin, glyphRun, foregroundBrush, measuringMode ); } } void WINAPI IMPL_D2D1DeviceContext_DrawGlyphRun( ID2D1DeviceContext* This, D2D1_POINT_2F baselineOrigin, CONST DWRITE_GLYPH_RUN *glyphRun, ID2D1Brush *foregroundBrush, DWRITE_MEASURING_MODE measuringMode ) { Params* dwParams = GetDWParams(); if (dwParams->GridFitMode == DWRITE_GRID_FIT_MODE_DISABLED) { D2D1_MATRIX_3X2_F prev; This->GetTransform(&prev); D2D1_MATRIX_3X2_F rotate = prev; rotate.m12 += 1.0f / 0xFFFF; rotate.m21 += 1.0f / 0xFFFF; This->SetTransform(&rotate); ORIG_D2D1DeviceContext_DrawGlyphRun( This, baselineOrigin, glyphRun, foregroundBrush, measuringMode ); This->SetTransform(&prev); } else { ORIG_D2D1DeviceContext_DrawGlyphRun( This, baselineOrigin, glyphRun, foregroundBrush, measuringMode ); } } HRESULT WINAPI IMPL_BitmapRenderTarget_DrawGlyphRun( IDWriteBitmapRenderTarget* This, FLOAT baselineOriginX, FLOAT baselineOriginY, DWRITE_MEASURING_MODE measuringMode, DWRITE_GLYPH_RUN const* glyphRun, IDWriteRenderingParams* renderingParams, COLORREF textColor, RECT* blackBoxRect) { Params* dwParams = GetDWParams(); HRESULT hr = E_FAIL; if (dwParams->GridFitMode == DWRITE_GRID_FIT_MODE_DISABLED) { DWRITE_MATRIX prev; hr = This->GetCurrentTransform(&prev); if (SUCCEEDED(hr)) { DWRITE_MATRIX rotate = prev; rotate.m12 += 1.0f / 0xFFFF; rotate.m21 += 1.0f / 0xFFFF; hr = This->SetCurrentTransform(&rotate); if (SUCCEEDED(hr)) { hr = ORIG_BitmapRenderTarget_DrawGlyphRun( This, baselineOriginX, baselineOriginY, measuringMode, glyphRun, GetDWRenderingParams(renderingParams), textColor, blackBoxRect ); This->SetCurrentTransform(&prev); } } } if (FAILED(hr)) { hr = ORIG_BitmapRenderTarget_DrawGlyphRun( This, baselineOriginX, baselineOriginY, measuringMode, glyphRun, GetDWRenderingParams(renderingParams), textColor, blackBoxRect ); if SUCCEEDED(hr) { MyDebug(L"DrawGlyphRun hooked"); } } if (FAILED(hr)) { hr = ORIG_BitmapRenderTarget_DrawGlyphRun( This, baselineOriginX, baselineOriginY, measuringMode, glyphRun, renderingParams, textColor, blackBoxRect ); if SUCCEEDED(hr) { MyDebug(L"DrawGlyphRun failed"); } } MyDebug(L"DrawGlyphRun hooked"); return hr; } void WINAPI IMPL_D2D1RenderTarget_DrawText( ID2D1RenderTarget* This, CONST WCHAR *string, UINT32 stringLength, IDWriteTextFormat *textFormat, CONST D2D1_RECT_F *layoutRect, ID2D1Brush *defaultForegroundBrush, D2D1_DRAW_TEXT_OPTIONS options, DWRITE_MEASURING_MODE measuringMode ) { Params* dwParams = GetDWParams(); if (dwParams->GridFitMode == DWRITE_GRID_FIT_MODE_DISABLED) { D2D1_MATRIX_3X2_F prev; This->GetTransform(&prev); D2D1_MATRIX_3X2_F rotate = prev; rotate.m12 += 1.0f / 0xFFFF; rotate.m21 += 1.0f / 0xFFFF; This->SetTransform(&rotate); ORIG_D2D1RenderTarget_DrawText( This, string, stringLength, textFormat, layoutRect, defaultForegroundBrush, options, measuringMode ); This->SetTransform(&prev); } else { ORIG_D2D1RenderTarget_DrawText( This, string, stringLength, textFormat, layoutRect, defaultForegroundBrush, options, measuringMode ); } } void WINAPI IMPL_D2D1DeviceContext_DrawText( ID2D1DeviceContext* This, CONST WCHAR *string, UINT32 stringLength, IDWriteTextFormat *textFormat, CONST D2D1_RECT_F *layoutRect, ID2D1Brush *defaultForegroundBrush, D2D1_DRAW_TEXT_OPTIONS options, DWRITE_MEASURING_MODE measuringMode ) { Params* dwParams = GetDWParams(); if (dwParams->GridFitMode == DWRITE_GRID_FIT_MODE_DISABLED) { D2D1_MATRIX_3X2_F prev; This->GetTransform(&prev); D2D1_MATRIX_3X2_F rotate = prev; rotate.m12 += 1.0f / 0xFFFF; rotate.m21 += 1.0f / 0xFFFF; This->SetTransform(&rotate); ORIG_D2D1DeviceContext_DrawText( This, string, stringLength, textFormat, layoutRect, defaultForegroundBrush, options, measuringMode ); This->SetTransform(&prev); } else { ORIG_D2D1DeviceContext_DrawText( This, string, stringLength, textFormat, layoutRect, defaultForegroundBrush, options, measuringMode ); } } void WINAPI IMPL_D2D1RenderTarget_DrawTextLayout( ID2D1RenderTarget* This, D2D1_POINT_2F origin, IDWriteTextLayout *textLayout, ID2D1Brush *defaultForegroundBrush, D2D1_DRAW_TEXT_OPTIONS options ) { Params* dwParams = GetDWParams(); if (dwParams->GridFitMode == DWRITE_GRID_FIT_MODE_DISABLED) { D2D1_MATRIX_3X2_F prev; This->GetTransform(&prev); D2D1_MATRIX_3X2_F rotate = prev; rotate.m12 += 1.0f / 0xFFFF; rotate.m21 += 1.0f / 0xFFFF; This->SetTransform(&rotate); ORIG_D2D1RenderTarget_DrawTextLayout( This, origin, textLayout, defaultForegroundBrush, options ); This->SetTransform(&prev); } else { ORIG_D2D1RenderTarget_DrawTextLayout( This, origin, textLayout, defaultForegroundBrush, options ); } } ================================================ FILE: directwrite.h ================================================ #include "common.h" #include #pragma once #ifdef EASYHOOK #include "easyhook.h" #define HOOK_MANUALLY HOOK_DEFINE #define HOOK_DEFINE(rettype, name, argtype, arglist) \ extern rettype(WINAPI * ORIG_##name) argtype; \ extern HOOK_TRACE_INFO HOOK_##name; #include "hooklist.h" #undef HOOK_DEFINE #undef HOOK_MANUALLY #define HOOK_MANUALLY(rettype, name, argtype, arglist) \ extern LONG hook_demand_##name(bool bForce = false); #define HOOK_DEFINE(rettype, name, argtype, arglist) ; #include "hooklist.h" #undef HOOK_DEFINE #undef HOOK_MANUALLY #else #define HOOK_MANUALLY HOOK_DEFINE #define HOOK_DEFINE(rettype, name, argtype, arglist) \ extern rettype(WINAPI * ORIG_##name) argtype; \ extern BOOL IsHooked_##name; #include "hooklist.h" #undef HOOK_DEFINE #undef HOOK_MANUALLY #define HOOK_MANUALLY(rettype, name, argtype, arglist) \ extern LONG hook_demand_##name(bool bForce = false); #define HOOK_DEFINE(rettype, name, argtype, arglist) ; #include "hooklist.h" #undef HOOK_DEFINE #undef HOOK_MANUALLY #endif ================================================ FILE: dll.cpp ================================================ #include "dll.h" CMemLoadDll::CMemLoadDll():m_bInitDllMain(true) { isLoadOk = FALSE; pImageBase = NULL; pDllMain = NULL; } CMemLoadDll::~CMemLoadDll() { if(isLoadOk) { //ASSERT(pImageBase != NULL); //ASSERT(pDllMain != NULL); //脱钩,准备卸载dll if (m_bInitDllMain) pDllMain((HINSTANCE)pImageBase,DLL_PROCESS_DETACH,0); VirtualFree((LPVOID)pImageBase, 0, MEM_RELEASE); } } //MemLoadLibrary函数从内存缓冲区数据中加载一个dll到当前进程的地址空间,缺省位置0x10000000 //返回值: 成功返回TRUE , 失败返回FALSE //lpFileData: 存放dll文件数据的缓冲区 //DataLength: 缓冲区中数据的总长度 BOOL CMemLoadDll::MemLoadLibrary(void* lpFileData, int DataLength, bool bInitDllMain, bool bFreeOnRavFail) { this->m_bInitDllMain = bInitDllMain; if(pImageBase != NULL) { return FALSE; //已经加载一个dll,还没有释放,不能加载新的dll } //检查数据有效性,并初始化 if(!CheckDataValide(lpFileData, DataLength))return FALSE; //计算所需的加载空间 int ImageSize = CalcTotalImageSize(); if(ImageSize == 0) return FALSE; // 分配虚拟内存 void *pMemoryAddress = VirtualAlloc((LPVOID)0, ImageSize, MEM_COMMIT|MEM_RESERVE, PAGE_EXECUTE_READWRITE); if(pMemoryAddress == NULL) return FALSE; else { CopyDllDatas(pMemoryAddress, lpFileData); //复制dll数据,并对齐每个段 //重定位信息 /*if(pNTHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress >0 && pNTHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size>0) { DoRelocation(pMemoryAddress); } //填充引入地址表 if(!FillRavAddress(pMemoryAddress) && bFreeOnRavFail) //修正引入地址表失败 { VirtualFree(pMemoryAddress,0,MEM_RELEASE); return FALSE; }*/ //修改页属性。应该根据每个页的属性单独设置其对应内存页的属性。这里简化一下。 //统一设置成一个属性PAGE_EXECUTE_READWRITE unsigned long old; VirtualProtect(pMemoryAddress, ImageSize, PAGE_EXECUTE_READWRITE,&old); } //修正基地址 pNTHeader->OptionalHeader.ImageBase = (DWORD)pMemoryAddress; //接下来要调用一下dll的入口函数,做初始化工作。 pDllMain = (ProcDllMain)(pNTHeader->OptionalHeader.AddressOfEntryPoint +(DWORD_PTR) pMemoryAddress); BOOL InitResult = !bInitDllMain || pDllMain((HINSTANCE)pMemoryAddress,DLL_PROCESS_ATTACH,0); if(!InitResult) //初始化失败 { pDllMain((HINSTANCE)pMemoryAddress,DLL_PROCESS_DETACH,0); VirtualFree(pMemoryAddress,0,MEM_RELEASE); pDllMain = NULL; return FALSE; } isLoadOk = TRUE; pImageBase = (DWORD_PTR)pMemoryAddress; return TRUE; } //MemGetProcAddress函数从dll中获取指定函数的地址 //返回值: 成功返回函数地址 , 失败返回NULL //lpProcName: 要查找函数的名字或者序号 FARPROC CMemLoadDll::MemGetProcAddress(LPCSTR lpProcName) { if(pNTHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress == 0 || pNTHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size == 0) return NULL; if(!isLoadOk) return NULL; DWORD OffsetStart = pNTHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress; DWORD Size = pNTHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size; PIMAGE_EXPORT_DIRECTORY pExport = (PIMAGE_EXPORT_DIRECTORY)((DWORD_PTR)pImageBase + pNTHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress); DWORD iBase = pExport->Base; DWORD iNumberOfFunctions = pExport->NumberOfFunctions; DWORD iNumberOfNames = pExport->NumberOfNames; //<= iNumberOfFunctions LPDWORD pAddressOfFunctions = (LPDWORD)(pExport->AddressOfFunctions + pImageBase); LPWORD pAddressOfOrdinals = (LPWORD)(pExport->AddressOfNameOrdinals + pImageBase); LPDWORD pAddressOfNames = (LPDWORD)(pExport->AddressOfNames + pImageBase); int iOrdinal = -1; if(((DWORD)lpProcName & 0xFFFF0000) == 0) //IT IS A ORDINAL! { iOrdinal = (DWORD)lpProcName & 0x0000FFFF - iBase; } else //use name { int iFound = -1; for(int i=0;i= 0) { iOrdinal = (DWORD)(pAddressOfOrdinals[iFound]); } } if(iOrdinal < 0 || iOrdinal >= iNumberOfFunctions ) return NULL; else { DWORD pFunctionOffset = pAddressOfFunctions[iOrdinal]; if(pFunctionOffset > OffsetStart && pFunctionOffset < (OffsetStart+Size))//maybe Export Forwarding return NULL; else return (FARPROC)(pFunctionOffset + pImageBase); } } // 重定向PE用到的地址 void CMemLoadDll::DoRelocation( void *NewBase) { /* 重定位表的结构: // DWORD sectionAddress, DWORD size (包括本节需要重定位的数据) // 例如 1000节需要修正5个重定位数据的话,重定位表的数据是 // 00 10 00 00 14 00 00 00 xxxx xxxx xxxx xxxx xxxx 0000 // ----------- ----------- ---- // 给出节的偏移 总尺寸=8+6*2 需要修正的地址 用于对齐4字节 // 重定位表是若干个相连,如果address 和 size都是0 表示结束 // 需要修正的地址是12位的,高4位是形态字,intel cpu下是3 */ //假设NewBase是0x600000,而文件中设置的缺省ImageBase是0x400000,则修正偏移量就是0x200000 DWORD Delta = (DWORD)NewBase - pNTHeader->OptionalHeader.ImageBase; //注意重定位表的位置可能和硬盘文件中的偏移地址不同,应该使用加载后的地址 PIMAGE_BASE_RELOCATION pLoc = (PIMAGE_BASE_RELOCATION)((DWORD_PTR)NewBase + pNTHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress); while((pLoc->VirtualAddress + pLoc->SizeOfBlock) != 0) //开始扫描重定位表 { WORD *pLocData = (WORD *)((DWORD_PTR)pLoc + sizeof(IMAGE_BASE_RELOCATION)); //计算本节需要修正的重定位项(地址)的数目 int NumberOfReloc = (pLoc->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION))/sizeof(WORD); for( int i=0 ; i < NumberOfReloc; i++) { if( (DWORD)(pLocData[i] & 0xF000) == 0x00003000) //这是一个需要修正的地址 { // 举例: // pLoc->VirtualAddress = 0x1000; // pLocData[i] = 0x313E; 表示本节偏移地址0x13E处需要修正 // 因此 pAddress = 基地址 + 0x113E // 里面的内容是 A1 ( 0c d4 02 10) 汇编代码是: mov eax , [1002d40c] // 需要修正1002d40c这个地址 DWORD * pAddress = (DWORD *)((DWORD_PTR)NewBase + pLoc->VirtualAddress + (pLocData[i] & 0x0FFF)); *pAddress += Delta; } } //转移到下一个节进行处理 pLoc = (PIMAGE_BASE_RELOCATION)((DWORD)pLoc + pLoc->SizeOfBlock); } } //填充引入地址表 BOOL CMemLoadDll::FillRavAddress(void *pImageBase) { // 引入表实际上是一个 IMAGE_IMPORT_DESCRIPTOR 结构数组,全部是0表示结束 // 数组定义如下: // // DWORD OriginalFirstThunk; // 0表示结束,否则指向未绑定的IAT结构数组 // DWORD TimeDateStamp; // DWORD ForwarderChain; // -1 if no forwarders // DWORD Name; // 给出dll的名字 // DWORD FirstThunk; // 指向IAT结构数组的地址(绑定后,这些IAT里面就是实际的函数地址) unsigned long Offset = pNTHeader->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress ; if(Offset == 0) return TRUE; //No Import Table PIMAGE_IMPORT_DESCRIPTOR pID = (PIMAGE_IMPORT_DESCRIPTOR)((DWORD_PTR) pImageBase + Offset); while(pID->Characteristics != 0 ) { PIMAGE_THUNK_DATA32 pRealIAT = (PIMAGE_THUNK_DATA32)((DWORD_PTR)pImageBase + pID->FirstThunk); PIMAGE_THUNK_DATA32 pOriginalIAT = (PIMAGE_THUNK_DATA32)((DWORD_PTR)pImageBase + pID->OriginalFirstThunk); //获取dll的名字 WCHAR buf[256]; //dll name; BYTE* pName = (BYTE*)((DWORD_PTR)pImageBase + pID->Name); int i; for(i=0;i<256;i++) { if(pName[i] == 0)break; buf[i] = pName[i]; } if(i>=256) return FALSE; // bad dll name else buf[i] = 0; HMODULE hDll = GetModuleHandle(buf); if(hDll == NULL)return FALSE; //NOT FOUND DLL //获取DLL中每个导出函数的地址,填入IAT //每个IAT结构是 : // union { PBYTE ForwarderString; // PDWORD Function; // DWORD Ordinal; // PIMAGE_IMPORT_BY_NAME AddressOfData; // } u1; // 长度是一个DWORD ,正好容纳一个地址。 for(i=0; ;i++) { if(pOriginalIAT[i].u1.Function == 0)break; FARPROC lpFunction = NULL; if(pOriginalIAT[i].u1.Ordinal & IMAGE_ORDINAL_FLAG) //这里的值给出的是导出序号 { lpFunction = GetProcAddress(hDll, (LPCSTR)(pOriginalIAT[i].u1.Ordinal & 0x0000FFFF)); } else //按照名字导入 { //获取此IAT项所描述的函数名称 PIMAGE_IMPORT_BY_NAME pByName = (PIMAGE_IMPORT_BY_NAME) ((DWORD_PTR)pImageBase + (DWORD)(pOriginalIAT[i].u1.AddressOfData)); // if(pByName->Hint !=0) // lpFunction = GetProcAddress(hDll, (LPCSTR)pByName->Hint); // else lpFunction = GetProcAddress(hDll, (char *)pByName->Name); } if(lpFunction != NULL) //找到了! { pRealIAT[i].u1.Function = (DWORD) lpFunction; } else return FALSE; } //move to next pID = (PIMAGE_IMPORT_DESCRIPTOR)((DWORD_PTR)pID + sizeof(IMAGE_IMPORT_DESCRIPTOR)); } return TRUE; } //CheckDataValide函数用于检查缓冲区中的数据是否有效的dll文件 //返回值: 是一个可执行的dll则返回TRUE,否则返回FALSE。 //lpFileData: 存放dll数据的内存缓冲区 //DataLength: dll文件的长度 BOOL CMemLoadDll::CheckDataValide(void* lpFileData, int DataLength) { //检查长度 if(DataLength < sizeof(IMAGE_DOS_HEADER)) return FALSE; pDosHeader = (PIMAGE_DOS_HEADER)lpFileData; // DOSͷ //检查dos头的标记 if(pDosHeader->e_magic != IMAGE_DOS_SIGNATURE) return FALSE; //0x5A4D : MZ //检查长度 if((DWORD)DataLength < (pDosHeader->e_lfanew + sizeof(IMAGE_NT_HEADERS32)) ) return FALSE; //取得pe头 pNTHeader = (PIMAGE_NT_HEADERS32)( (DWORD_PTR)lpFileData + (DWORD_PTR)pDosHeader->e_lfanew); // PEͷ //检查pe头的合法性 if(pNTHeader->Signature != IMAGE_NT_SIGNATURE) return FALSE; //0x00004550 : PE00 if((pNTHeader->FileHeader.Characteristics & IMAGE_FILE_DLL) == 0) //0x2000 : File is a DLL return FALSE; if((pNTHeader->FileHeader.Characteristics & IMAGE_FILE_EXECUTABLE_IMAGE) == 0) //0x0002 : 指出文件可以运行 return FALSE; if(pNTHeader->FileHeader.SizeOfOptionalHeader != sizeof(IMAGE_OPTIONAL_HEADER32)) return FALSE; //取得节表(段表) pSectionHeader = (PIMAGE_SECTION_HEADER)((DWORD_PTR)pNTHeader + sizeof(IMAGE_NT_HEADERS32)); //验证每个节表的空间 for(int i=0; i< pNTHeader->FileHeader.NumberOfSections; i++) { if((pSectionHeader[i].PointerToRawData + pSectionHeader[i].SizeOfRawData) > (DWORD)DataLength)return FALSE; } return TRUE; } //计算对齐边界 int CMemLoadDll::GetAlignedSize(int Origin, int Alignment) { return (Origin + Alignment - 1) / Alignment * Alignment; } //计算整个dll映像文件的尺寸 int CMemLoadDll::CalcTotalImageSize() { int Size; if(pNTHeader == NULL)return 0; int nAlign = pNTHeader->OptionalHeader.SectionAlignment; //段对齐字节数 // 计算所有头的尺寸。包括dos, coff, pe头 和 段表的大小 Size = GetAlignedSize(pNTHeader->OptionalHeader.SizeOfHeaders, nAlign); // 计算所有节的大小 for(int i=0; i < pNTHeader->FileHeader.NumberOfSections; ++i) { //得到该节的大小 int CodeSize = pSectionHeader[i].Misc.VirtualSize ; int LoadSize = pSectionHeader[i].SizeOfRawData; int MaxSize = (LoadSize > CodeSize)?(LoadSize):(CodeSize); int SectionSize = GetAlignedSize(pSectionHeader[i].VirtualAddress + MaxSize, nAlign); if(Size < SectionSize) Size = SectionSize; //Use the Max; } return Size; } //CopyDllDatas函数将dll数据复制到指定内存区域,并对齐所有节 //pSrc: 存放dll数据的原始缓冲区 //pDest:目标内存地址 void CMemLoadDll::CopyDllDatas(void* pDest, void* pSrc) { // 计算需要复制的PE头+段表字节数 int HeaderSize = pNTHeader->OptionalHeader.SizeOfHeaders; int SectionSize = pNTHeader->FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER); int MoveSize = HeaderSize + SectionSize; //复制头和段信息 memmove(pDest, pSrc, MoveSize); //复制每个节 for(int i=0; i < pNTHeader->FileHeader.NumberOfSections; ++i) { if(pSectionHeader[i].VirtualAddress == 0 || pSectionHeader[i].SizeOfRawData == 0)continue; // 定位该节在内存中的位置 void *pSectionAddress = (void *)((DWORD_PTR)pDest + pSectionHeader[i].VirtualAddress); // 复制段数据到虚拟内存 memmove((void *)pSectionAddress, (void *)((DWORD_PTR)pSrc + pSectionHeader[i].PointerToRawData), pSectionHeader[i].SizeOfRawData); } //修正指针,指向新分配的内存 //新的dos头 pDosHeader = (PIMAGE_DOS_HEADER)pDest; //新的pe头地址 pNTHeader = (PIMAGE_NT_HEADERS32)((DWORD_PTR)pDest + (DWORD_PTR)(pDosHeader->e_lfanew)); //新的节表地址 pSectionHeader = (PIMAGE_SECTION_HEADER)((DWORD_PTR)pNTHeader + sizeof(IMAGE_NT_HEADERS32)); return ; } ================================================ FILE: dll.h ================================================ #include typedef BOOL (__stdcall *ProcDllMain)(HINSTANCE, DWORD, LPVOID ); class CMemLoadDll { public: CMemLoadDll(); ~CMemLoadDll(); BOOL MemLoadLibrary( void* lpFileData , int DataLength, bool bInitDllMain, bool bFreeOnRavFail); // Dll file data buffer FARPROC MemGetProcAddress(LPCSTR lpProcName); DWORD_PTR GetImageBase() {return pImageBase;}; private: BOOL isLoadOk; BOOL CheckDataValide(void* lpFileData, int DataLength); int CalcTotalImageSize(); void CopyDllDatas(void* pDest, void* pSrc); BOOL FillRavAddress(void* pBase); void DoRelocation(void* pNewBase); int GetAlignedSize(int Origin, int Alignment); private: ProcDllMain pDllMain; private: DWORD_PTR pImageBase; bool m_bInitDllMain; PIMAGE_DOS_HEADER pDosHeader; PIMAGE_NT_HEADERS32 pNTHeader; PIMAGE_SECTION_HEADER pSectionHeader; }; ================================================ FILE: doc/HOWTOBUILD.md ================================================ # How to build 1. **Compiler / IDE** Visual Studio 2019 with v142 toolkit has been tested and is working. Toolkits down to v120 should be able to compile the code, but be aware that the `_xp` ones might refuse to use the Windows 10 SDK. 2. **Dependencies** Mactype depends on - [Freetype](https://www.freetype.org/download.html) - For the lastest version of Mactype, a customized version of FreeType is required, which can be obtained from https://github.com/snowie2000/freetype - [EasyHook](http://easyhook.github.io/) / [Detours](https://github.com/microsoft/Detours) - [IniParser (fork)](https://github.com/snowie2000/IniParser) - [wow64ext (fork)](https://github.com/snowie2000/rewolf-wow64ext) - Windows SDK (10.0.14393.0 or later) 3. **Building dependencies** - FreeType Apply `glyph_to_bitmapex.diff` before building. Always build multi-thread release. Remember to enable options you want in ftoptions.h Compile freetype as freetype.lib for x86 and freetype64.lib for x64 Static library is preferred, you are free to build freetype as independent dlls with better interchangeability but you will lose some compatibility in return, for some programs are delivered with their own copies of freetype which will conflict with your file. Set `FREETYPE_PATH` environment variable to root of freetype source. - iniParser Build as iniparser.lib and iniparser64.lib. Set `INI_PARSER_PATH` environment variable to root of IniParser project. - wow64ext Build as wow64ext.lib. x64 library is not required. Shared library also works if you prefer that. - EasyHook Only EasyHookDll project is required. Build it as easyhook32.lib and easyhook64.lib, or get the binary distributions. Dll filename is not important but you'd better give it a special name to avoid dll confliction as stated above. Do not forget to modify filename in `hook.cpp` of MacType. - Detours Since Microsoft Detours is now free and opensource, it is back to be supported and recommended. Follow the official guide to build detours.lib and detours64.lib and put them in the root of MacType. Detours lib are static libraries, so name confiction is not a thing. - Windows SDK Actually it's not something you need to build, but the installation is tricky. One word to rule them all: download **ALL COMPONENTS** in the installation list! Unless you want to waste several hours looking for these mysterious dependencies it pops to you. Don't worry, you will have a second chance to choose which component you want to install after download. 4. **Build** Last but easiest step: Put all `.lib` files you built earlier into a `lib` folder in the root of MacType, click build and enjoy. ## FAQ Q: Where are the sources of loader and tuner in the repo? A: I'm sorry, but they are still closed-source right now. Since you have the mactype source and will surely have a good understanding of how mactype works, I believe it's not a big challenge to write a loader for it. If you wrote a great loader or something else wonderful, please post an issue or a pull request. Hope we can make MacType better! ================================================ FILE: doc/glyph_to_bitmapex.diff ================================================ --- a/src/base/ftglyph.c +++ b/src/base/ftglyph.c @@ -634,6 +634,118 @@ } +FT_EXPORT_DEF(FT_Error) + FT_Glyph_To_BitmapEx(FT_Glyph* the_glyph, + FT_Render_Mode render_mode, + FT_Vector* origin, + FT_Bool destroy, + FT_Bool loadcolor, + FT_UInt glyphindex, + FT_Face face) +{ + FT_GlyphSlotRec dummy; + FT_GlyphSlot_InternalRec dummy_internal; + FT_Error error = FT_Err_Ok; + FT_Glyph b, glyph; + FT_BitmapGlyph bitmap = NULL; + const FT_Glyph_Class* clazz; + + FT_Library library; + + + /* check argument */ + if (!the_glyph) + goto Bad; + glyph = *the_glyph; + if (!glyph) + goto Bad; + + clazz = glyph->clazz; + library = glyph->library; + if (!library || !clazz) + goto Bad; + + /* when called with a bitmap glyph, do nothing and return successfully */ + if (clazz == &ft_bitmap_glyph_class) + goto Exit; + + if (!clazz->glyph_prepare) + goto Bad; + + /* we render the glyph into a glyph bitmap using a `dummy' glyph slot */ + /* then calling FT_Render_Glyph_Internal() */ + + FT_ZERO(&dummy); + FT_ZERO(&dummy_internal); + dummy.internal = &dummy_internal; + dummy.library = library; + dummy.format = clazz->glyph_format; + + if (loadcolor) { + dummy_internal.load_flags |= FT_LOAD_COLOR; + dummy.glyph_index = glyphindex; + dummy.face = face; + } + + /* create result bitmap glyph */ + error = ft_new_glyph(library, &ft_bitmap_glyph_class, &b); + if (error) + goto Exit; + bitmap = (FT_BitmapGlyph)b; + +#if 1 + /* if `origin' is set, translate the glyph image */ + if (origin) + FT_Glyph_Transform(glyph, 0, origin); +#else + FT_UNUSED(origin); +#endif + + /* prepare dummy slot for rendering */ + error = clazz->glyph_prepare(glyph, &dummy); + if (!error) + error = FT_Render_Glyph_Internal(glyph->library, &dummy, render_mode); + +#if 1 + if (!destroy && origin) + { + FT_Vector v; + + + v.x = -origin->x; + v.y = -origin->y; + FT_Glyph_Transform(glyph, 0, &v); + } +#endif + + if (error) + goto Exit; + + /* in case of success, copy the bitmap to the glyph bitmap */ + error = ft_bitmap_glyph_init((FT_Glyph)bitmap, &dummy); + if (error) + goto Exit; + + /* copy advance */ + bitmap->root.advance = glyph->advance; + + if (destroy) + FT_Done_Glyph(glyph); + + *the_glyph = FT_GLYPH(bitmap); + +Exit: + if (error && bitmap) + FT_Done_Glyph(FT_GLYPH(bitmap)); + + return error; + +Bad: + error = FT_THROW(Invalid_Argument); + goto Exit; +} + + /* documentation is in ftglyph.h */ FT_EXPORT_DEF( void ) --- a/include/freetype/ftglyph.h +++ b/include/freetype/ftglyph.h @@ -574,6 +574,14 @@ FT_Vector* origin, FT_Bool destroy ); + FT_EXPORT(FT_Error) + FT_Glyph_To_BitmapEx(FT_Glyph* the_glyph, + FT_Render_Mode render_mode, + FT_Vector* origin, + FT_Bool destroy, + FT_Bool loadcolor, + FT_UInt glyphindex, + FT_Face face); /************************************************************************** * ================================================ FILE: dynCodeHelper.cpp ================================================ #include "dynCodeHelper.h" /* * class AutoEnableDynamicCodeGen */ typedef BOOL (WINAPI *PGET_PROCESS_MITIGATION_POLICY_PROC)( _In_ HANDLE hProcess, _In_ PROCESS_MITIGATION_POLICY MitigationPolicy, _Out_ PVOID lpBuffer, _In_ SIZE_T dwLength ); AutoEnableDynamicCodeGen::PSET_THREAD_INFORMATION_PROC AutoEnableDynamicCodeGen::SetThreadInformationProc = nullptr; AutoEnableDynamicCodeGen::PGET_THREAD_INFORMATION_PROC AutoEnableDynamicCodeGen::GetThreadInformationProc = nullptr; PROCESS_MITIGATION_DYNAMIC_CODE_POLICY AutoEnableDynamicCodeGen::processPolicy; volatile bool AutoEnableDynamicCodeGen::processPolicyObtained = false; AutoEnableDynamicCodeGen::AutoEnableDynamicCodeGen(bool enable) : enabled(false) { if (enable == false) { return; } // // Snap the dynamic code generation policy for this process so that we // don't need to resolve APIs and query it each time. We expect the policy // to have been established upfront. // if (processPolicyObtained == false) { CCriticalSectionLock __lock(CCriticalSectionLock::CS_VIRTMEM); if (processPolicyObtained == false) { PGET_PROCESS_MITIGATION_POLICY_PROC GetProcessMitigationPolicyProc = nullptr; HMODULE module = GetModuleHandleW(_T("api-ms-win-core-processthreads-l1-1-3.dll")); if (module != nullptr) { GetProcessMitigationPolicyProc = (PGET_PROCESS_MITIGATION_POLICY_PROC)GetProcAddress(module, "GetProcessMitigationPolicy"); SetThreadInformationProc = (PSET_THREAD_INFORMATION_PROC)GetProcAddress(module, "SetThreadInformation"); GetThreadInformationProc = (PGET_THREAD_INFORMATION_PROC)GetProcAddress(module, "GetThreadInformation"); } if ((GetProcessMitigationPolicyProc == nullptr) || (!GetProcessMitigationPolicyProc(GetCurrentProcess(), ProcessDynamicCodePolicy, (PPROCESS_MITIGATION_DYNAMIC_CODE_POLICY)&processPolicy, sizeof(processPolicy)))) { processPolicy.ProhibitDynamicCode = 0; } processPolicyObtained = true; } } // // The process is not prohibiting dynamic code or does not allow threads // to opt out. In either case, return to the caller. // // N.B. It is OK that this policy is mutable at runtime. If a process // really does not allow thread opt-out, then the call below will fail // benignly. // if ((processPolicy.ProhibitDynamicCode == 0) || (processPolicy.AllowThreadOptOut == 0)) { return; } if (SetThreadInformationProc == nullptr || GetThreadInformationProc == nullptr) { return; } // // If dynamic code is already allowed for this thread, then don't attempt to allow it again. // DWORD threadPolicy; if ((GetThreadInformationProc(GetCurrentThread(), ThreadDynamicCodePolicy, &threadPolicy, sizeof(DWORD))) && (threadPolicy == THREAD_DYNAMIC_CODE_ALLOW)) { return; } threadPolicy = THREAD_DYNAMIC_CODE_ALLOW; BOOL result = SetThreadInformationProc(GetCurrentThread(), ThreadDynamicCodePolicy, &threadPolicy, sizeof(DWORD)); Assert(result); enabled = true; } AutoEnableDynamicCodeGen::~AutoEnableDynamicCodeGen() { if (enabled) { DWORD threadPolicy = 0; BOOL result = SetThreadInformationProc(GetCurrentThread(), ThreadDynamicCodePolicy, &threadPolicy, sizeof(DWORD)); Assert(result); enabled = false; } } ================================================ FILE: dynCodeHelper.h ================================================ #include "common.h" class AutoEnableDynamicCodeGen { public: AutoEnableDynamicCodeGen(bool enable = true); ~AutoEnableDynamicCodeGen(); private: bool enabled; typedef BOOL (WINAPI *PSET_THREAD_INFORMATION_PROC)( _In_ HANDLE hThread, _In_ THREAD_INFORMATION_CLASS ThreadInformationClass, _In_reads_bytes_(ThreadInformationSize) PVOID ThreadInformation, _In_ DWORD ThreadInformationSize ); typedef BOOL (WINAPI *PGET_THREAD_INFORMATION_PROC)( _In_ HANDLE hThread, _In_ THREAD_INFORMATION_CLASS ThreadInformationClass, _Out_writes_bytes_(ThreadInformationSize) PVOID ThreadInformation, _In_ DWORD ThreadInformationSize ); static PSET_THREAD_INFORMATION_PROC SetThreadInformationProc; static PGET_THREAD_INFORMATION_PROC GetThreadInformationProc; static PROCESS_MITIGATION_DYNAMIC_CODE_POLICY processPolicy; static volatile bool processPolicyObtained; }; ================================================ FILE: easyhook.h ================================================ /* EasyHook - The reinvention of Windows API hooking Copyright (C) 2009 Christoph Husse This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Please visit http://www.codeplex.com/easyhook for more information about the project and latest updates. */ #ifndef _EASYHOOK_H_ #define _EASYHOOK_H_ #ifdef DRIVER #include #include typedef int BOOL; typedef void* HMODULE; #else // #define NTDDI_VERSION NTDDI_WIN2KSP4 // #define _WIN32_WINNT 0x500 #define _WIN32_IE_ _WIN32_IE_WIN2KSP4 #include #include #include #endif #ifdef __cplusplus extern "C"{ #endif #ifdef EASYHOOK_EXPORTS #define EASYHOOK_API __declspec(dllexport) __stdcall #define DRIVER_SHARED_API(type, decl) EXTERN_C type EASYHOOK_API decl #else #ifndef DRIVER #ifdef STATIC_LIB #define EASYHOOK_API __stdcall #else #define EASYHOOK_API __declspec(dllimport) __stdcall #endif #define DRIVER_SHARED_API(type, decl) EXTERN_C type EASYHOOK_API decl #else #define EASYHOOK_API __stdcall #define DRIVER_SHARED_API(type, decl) typedef type EASYHOOK_API PROC_##decl; EXTERN_C type EASYHOOK_API decl #endif #endif /* This is the typical sign that a defined method is exported... Methods marked with this attribute need special attention during parameter validation and documentation. */ #define EASYHOOK_NT_EXPORT EXTERN_C NTSTATUS EASYHOOK_API #define EASYHOOK_BOOL_EXPORT EXTERN_C BOOL EASYHOOK_API #define MAX_HOOK_COUNT 128 #define MAX_ACE_COUNT 128 #define MAX_THREAD_COUNT 128 #define MAX_PASSTHRU_SIZE 1024 * 64 typedef struct _HOOK_ACL_ { ULONG Count; BOOL IsExclusive; ULONG Entries[MAX_ACE_COUNT]; }HOOK_ACL; typedef struct _LOCAL_HOOK_INFO_* PLOCAL_HOOK_INFO; typedef struct _HOOK_TRACE_INFO_ { PLOCAL_HOOK_INFO Link; }HOOK_TRACE_INFO, *TRACED_HOOK_HANDLE; typedef struct _LOCAL_HOOK_INFO_ { PLOCAL_HOOK_INFO Next; ULONG NativeSize; UCHAR* TargetProc; ULONGLONG TargetBackup; ULONGLONG TargetBackup_x64; ULONGLONG HookCopy; ULONG EntrySize; UCHAR* Trampoline; ULONG HLSIndex; ULONG HLSIdent; void* Callback; HOOK_ACL LocalACL; ULONG Signature; TRACED_HOOK_HANDLE Tracking; void* RandomValue; // fixed void* HookIntro; // fixed UCHAR* OldProc; // fixed UCHAR* HookProc; // fixed void* HookOutro; // fixed int* IsExecutedPtr; // fixed }LOCAL_HOOK_INFO, *PLOCAL_HOOK_INFO; DRIVER_SHARED_API(NTSTATUS, RtlGetLastError()); DRIVER_SHARED_API(PWCHAR, RtlGetLastErrorString()); DRIVER_SHARED_API(NTSTATUS, LhInstallHook( void* InEntryPoint, void* InHookProc, void* InCallback, TRACED_HOOK_HANDLE OutHandle)); DRIVER_SHARED_API(NTSTATUS, LhUninstallAllHooks()); DRIVER_SHARED_API(NTSTATUS, LhUninstallHook(TRACED_HOOK_HANDLE InHandle)); DRIVER_SHARED_API(NTSTATUS, LhWaitForPendingRemovals()); #ifdef STATIC_LIB BOOL APIENTRY EasyHookDllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved); #endif /* Setup the ACLs after hook installation. Please note that every hook starts suspended. You will have to set a proper ACL to make it active! */ #ifdef DRIVER DRIVER_SHARED_API(NTSTATUS, LhSetInclusiveACL( ULONG* InProcessIdList, ULONG InProcessCount, TRACED_HOOK_HANDLE InHandle)); DRIVER_SHARED_API(NTSTATUS, LhSetExclusiveACL( ULONG* InProcessIdList, ULONG InProcessCount, TRACED_HOOK_HANDLE InHandle)); DRIVER_SHARED_API(NTSTATUS, LhSetGlobalInclusiveACL( ULONG* InProcessIdList, ULONG InProcessCount)); DRIVER_SHARED_API(NTSTATUS, LhSetGlobalExclusiveACL( ULONG* InProcessIdList, ULONG InProcessCount)); DRIVER_SHARED_API(NTSTATUS, LhIsProcessIntercepted( TRACED_HOOK_HANDLE InHook, ULONG InProcessID, BOOL* OutResult)); #else EASYHOOK_NT_EXPORT LhSetInclusiveACL( ULONG* InThreadIdList, ULONG InThreadCount, TRACED_HOOK_HANDLE InHandle); EASYHOOK_NT_EXPORT LhSetExclusiveACL( ULONG* InThreadIdList, ULONG InThreadCount, TRACED_HOOK_HANDLE InHandle); EASYHOOK_NT_EXPORT LhSetGlobalInclusiveACL( ULONG* InThreadIdList, ULONG InThreadCount); EASYHOOK_NT_EXPORT LhSetGlobalExclusiveACL( ULONG* InThreadIdList, ULONG InThreadCount); EASYHOOK_NT_EXPORT LhIsThreadIntercepted( TRACED_HOOK_HANDLE InHook, ULONG InThreadID, BOOL* OutResult); #endif // !DRIVER /* The following barrier methods are meant to be used in hook handlers only! They will all fail with STATUS_NOT_SUPPORTED if called outside a valid hook handler... */ DRIVER_SHARED_API(NTSTATUS, LhBarrierGetCallback(PVOID* OutValue)); DRIVER_SHARED_API(NTSTATUS, LhBarrierGetReturnAddress(PVOID* OutValue)); DRIVER_SHARED_API(NTSTATUS, LhBarrierGetAddressOfReturnAddress(PVOID** OutValue)); DRIVER_SHARED_API(NTSTATUS, LhBarrierBeginStackTrace(PVOID* OutBackup)); DRIVER_SHARED_API(NTSTATUS, LhBarrierEndStackTrace(PVOID InBackup)); typedef struct _MODULE_INFORMATION_* PMODULE_INFORMATION; typedef struct _MODULE_INFORMATION_ { PMODULE_INFORMATION Next; UCHAR* BaseAddress; ULONG ImageSize; CHAR Path[256]; PCHAR ModuleName; }MODULE_INFORMATION; EASYHOOK_NT_EXPORT LhUpdateModuleInformation(); DRIVER_SHARED_API(NTSTATUS, LhBarrierPointerToModule( PVOID InPointer, MODULE_INFORMATION* OutModule)); DRIVER_SHARED_API(NTSTATUS, LhEnumModules( HMODULE* OutModuleArray, ULONG InMaxModuleCount, ULONG* OutModuleCount)); DRIVER_SHARED_API(NTSTATUS, LhBarrierGetCallingModule(MODULE_INFORMATION* OutModule)); DRIVER_SHARED_API(NTSTATUS, LhBarrierCallStackTrace( PVOID* OutMethodArray, ULONG InMaxMethodCount, ULONG* OutMethodCount)); #ifdef DRIVER #define DRIVER_EXPORT(proc) PROC_##proc * proc #define EASYHOOK_INTERFACE_v_1 0x0001 #define EASYHOOK_WIN32_DEVICE_NAME L"\\\\.\\EasyHook" #define EASYHOOK_DEVICE_NAME L"\\Device\\EasyHook" #define EASYHOOK_DOS_DEVICE_NAME L"\\DosDevices\\EasyHook" #define FILE_DEVICE_EASYHOOK 0x893F typedef struct _EASYHOOK_INTERFACE_API_v_1_ { DRIVER_EXPORT(RtlGetLastError); DRIVER_EXPORT(RtlGetLastErrorString); DRIVER_EXPORT(LhInstallHook); DRIVER_EXPORT(LhUninstallHook); DRIVER_EXPORT(LhWaitForPendingRemovals); DRIVER_EXPORT(LhBarrierGetCallback); DRIVER_EXPORT(LhBarrierGetReturnAddress); DRIVER_EXPORT(LhBarrierGetAddressOfReturnAddress); DRIVER_EXPORT(LhBarrierBeginStackTrace); DRIVER_EXPORT(LhBarrierEndStackTrace); DRIVER_EXPORT(LhBarrierPointerToModule); DRIVER_EXPORT(LhBarrierGetCallingModule); DRIVER_EXPORT(LhBarrierCallStackTrace); DRIVER_EXPORT(LhSetGlobalExclusiveACL); DRIVER_EXPORT(LhSetGlobalInclusiveACL); DRIVER_EXPORT(LhSetExclusiveACL); DRIVER_EXPORT(LhSetInclusiveACL); DRIVER_EXPORT(LhIsProcessIntercepted); }EASYHOOK_INTERFACE_API_v_1, *PEASYHOOK_INTERFACE_API_v_1; typedef struct _EASYHOOK_DEVICE_EXTENSION_ { ULONG MaxVersion; // enumeration of APIs EASYHOOK_INTERFACE_API_v_1 API_v_1; }EASYHOOK_DEVICE_EXTENSION, *PEASYHOOK_DEVICE_EXTENSION; static NTSTATUS EasyHookQueryInterface( ULONG InInterfaceVersion, PVOID OutInterface, PFILE_OBJECT* OutEasyHookDrv) { /* Description: Provides a convenient way to load the desired EasyHook interface. The method will only work if the EasyHook support driver is loaded, of course. If you don't need the interface anymore, you have to release the file object with ObDereferenceObject(). Parameters: - InInterfaceVersion The desired interface version. Any future EasyHook driver will ALWAYS be backward compatible. This is the reason why I provide such a flexible interface mechanism. - OutInterface A pointer to the interface structure to be filled with data. If you specify EASYHOOK_INTERFACE_v_1 as InInterfaceVersion, you will have to provide a pointer to a EASYHOOK_INTERFACE_API_v_1 structure, for example... - OutEasyHookDrv A reference to the EasyHook driver. Make sure that you dereference it if you don't need the interface any longer! As long as you keep this handle, the EasyHook driver CAN'T be unloaded... */ UNICODE_STRING DeviceName; PDEVICE_OBJECT hEasyHookDrv = NULL; NTSTATUS NtStatus = STATUS_INTERNAL_ERROR; EASYHOOK_DEVICE_EXTENSION* DevExt; /* Open log file... */ RtlInitUnicodeString(&DeviceName, EASYHOOK_DEVICE_NAME); if(!NT_SUCCESS(NtStatus = IoGetDeviceObjectPointer(&DeviceName, FILE_READ_DATA, OutEasyHookDrv, &hEasyHookDrv))) return NtStatus; __try { DevExt = (EASYHOOK_DEVICE_EXTENSION*)hEasyHookDrv->DeviceExtension; if(DevExt->MaxVersion < InInterfaceVersion) return STATUS_NOT_SUPPORTED; switch(InInterfaceVersion) { case EASYHOOK_INTERFACE_v_1: memcpy(OutInterface, &DevExt->API_v_1, sizeof(DevExt->API_v_1)); break; default: return STATUS_INVALID_PARAMETER_1; } return STATUS_SUCCESS; } __except(EXCEPTION_EXECUTE_HANDLER) { ObDereferenceObject(*OutEasyHookDrv); return NtStatus; } } #endif // DRIVER #ifndef DRIVER /* Debug helper API. */ EASYHOOK_BOOL_EXPORT DbgIsAvailable(); EASYHOOK_BOOL_EXPORT DbgIsEnabled(); EASYHOOK_NT_EXPORT DbgAttachDebugger(); EASYHOOK_NT_EXPORT DbgDetachDebugger(); EASYHOOK_NT_EXPORT DbgGetThreadIdByHandle( HANDLE InThreadHandle, ULONG* OutThreadId); EASYHOOK_NT_EXPORT DbgGetProcessIdByHandle( HANDLE InProcessHandle, ULONG* OutProcessId); EASYHOOK_NT_EXPORT DbgHandleToObjectName( HANDLE InNamedHandle, UNICODE_STRING* OutNameBuffer, ULONG InBufferSize, ULONG* OutRequiredSize); /* Injection support API. */ typedef struct _REMOTE_ENTRY_INFO_ { ULONG HostPID; UCHAR* UserData; ULONG UserDataSize; }REMOTE_ENTRY_INFO; typedef void __stdcall REMOTE_ENTRY_POINT(REMOTE_ENTRY_INFO* InRemoteInfo); #define EASYHOOK_INJECT_DEFAULT 0x00000000 #define EASYHOOK_INJECT_STEALTH 0x10000000 // (experimental) #define EASYHOOK_INJECT_NET_DEFIBRILLATOR 0x20000000 // USE THIS ONLY IN UNMANAGED CODE AND ONLY WITH CreateAndInject() FOR MANAGED PROCESSES!! EASYHOOK_NT_EXPORT RhCreateStealthRemoteThread( ULONG InTargetPID, LPTHREAD_START_ROUTINE InRemoteRoutine, PVOID InRemoteParam, HANDLE* OutRemoteThread); EASYHOOK_NT_EXPORT RhInjectLibrary( ULONG InTargetPID, ULONG InWakeUpTID, ULONG InInjectionOptions, WCHAR* InLibraryPath_x86, WCHAR* InLibraryPath_x64, PVOID InPassThruBuffer, ULONG InPassThruSize); EASYHOOK_NT_EXPORT RhCreateAndInject( WCHAR* InEXEPath, WCHAR* InCommandLine, ULONG InProcessCreationFlags, ULONG InInjectionOptions, WCHAR* InLibraryPath_x86, WCHAR* InLibraryPath_x64, PVOID InPassThruBuffer, ULONG InPassThruSize, ULONG* OutProcessId); EASYHOOK_BOOL_EXPORT RhIsX64System(); EASYHOOK_NT_EXPORT RhIsX64Process( ULONG InProcessId, BOOL* OutResult); EASYHOOK_BOOL_EXPORT RhIsAdministrator(); EASYHOOK_NT_EXPORT RhWakeUpProcess(); EASYHOOK_NT_EXPORT RhInstallSupportDriver(); EASYHOOK_NT_EXPORT RhInstallDriver( WCHAR* InDriverPath, WCHAR* InDriverName); typedef struct _GACUTIL_INFO_* HGACUTIL; #endif // !DRIVER #ifdef __cplusplus }; #endif #endif ================================================ FILE: expfunc.cpp ================================================ #ifndef _GDIPP_EXE #include "settings.h" #include "override.h" #include #include //DLLVERSIONINFO #include "undocAPI.h" #include #include #include #include #include #include "wow64ext.h" #include #include "crc32.h" // win2k以降 //#pragma comment(linker, "/subsystem:windows,5.0") #ifndef _WIN64 #ifdef DEBUG #pragma comment(lib, "wow64ext_dbg.lib") #else #pragma comment(lib, "wow64ext.lib") #endif #endif EXTERN_C LRESULT CALLBACK GetMsgProc(int code, WPARAM wParam, LPARAM lParam) { //何もしない return CallNextHookEx(NULL, code, wParam, lParam); } EXTERN_C HRESULT WINAPI GdippDllGetVersion(DLLVERSIONINFO* pdvi) { if (!pdvi || pdvi->cbSize < sizeof(DLLVERSIONINFO)) { return E_INVALIDARG; } const UINT cbSize = pdvi->cbSize; ZeroMemory(pdvi, cbSize); pdvi->cbSize = cbSize; HRSRC hRsrc = FindResource(GetDLLInstance(), MAKEINTRESOURCE(VS_VERSION_INFO), RT_VERSION); if (!hRsrc) { return E_FAIL; } HGLOBAL hGlobal = LoadResource(GetDLLInstance(), hRsrc); if (!hGlobal) { return E_FAIL; } const WORD* lpwPtr = (const WORD*)LockResource(hGlobal); if (lpwPtr[1] != sizeof(VS_FIXEDFILEINFO)) { return E_FAIL; } const VS_FIXEDFILEINFO* pvffi = (const VS_FIXEDFILEINFO*)(lpwPtr + 20); if (pvffi->dwSignature != VS_FFI_SIGNATURE || pvffi->dwStrucVersion != VS_FFI_STRUCVERSION) { return E_FAIL; } //8.0.2006.1027 // -> Major: 8, Minor: 2006, Build: 1027 pdvi->dwMajorVersion = HIWORD(pvffi->dwFileVersionMS); pdvi->dwMinorVersion = LOWORD(pvffi->dwFileVersionMS) * 10 + HIWORD(pvffi->dwFileVersionLS); pdvi->dwBuildNumber = LOWORD(pvffi->dwFileVersionLS); pdvi->dwPlatformID = DLLVER_PLATFORM_NT; if (pdvi->cbSize < sizeof(DLLVERSIONINFO2)) { return S_OK; } DLLVERSIONINFO2* pdvi2 = (DLLVERSIONINFO2*)pdvi; pdvi2->ullVersion = MAKEDLLVERULL(pdvi->dwMajorVersion, pdvi->dwMinorVersion, pdvi->dwBuildNumber, 2); return S_OK; } #endif //!_GDIPP_EXE extern LONG interlock; extern LONG g_bHookEnabled; #include "gdiPlusFlat2.h" #ifdef USE_DETOURS //detours #include "detours.h" // #define HOOK_MANUALLY(rettype, name, argtype, arglist) ; #define HOOK_DEFINE(rettype, name, argtype, arglist) \ DetourDetach(&(PVOID&)ORIG_##name, IMPL_##name); LONG hook_term() { DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); #include "hooklist.h" LONG error = DetourTransactionCommit(); if (error != NOERROR) { TRACE(_T("hook_term error: %#x\n"), error); } return error; } #undef HOOK_DEFINE #undef HOOK_MANUALLY #else #include "easyhook.h" #define HOOK_MANUALLY(rettype, name, argtype, arglist) ; #define HOOK_DEFINE(rettype, name, argtype, arglist) \ ORIG_##name = name; #pragma optimize("s", on) static LONG hook_term() { #include "hooklist.h" LhUninstallAllHooks(); return LhWaitForPendingRemovals(); } #pragma optimize("", on) #undef HOOK_DEFINE #undef HOOK_MANUALLY #endif HMODULE GetSelfModuleHandle() { MEMORY_BASIC_INFORMATION mbi; return ((::VirtualQuery(GetSelfModuleHandle, &mbi, sizeof(mbi)) != 0) ? (HMODULE) mbi.AllocationBase : NULL); } EXTERN_C void WINAPI CreateControlCenter(IControlCenter** ret) { *ret = (IControlCenter*)new CControlCenter; } EXTERN_C void WINAPI ReloadConfig() { CControlCenter::ReloadConfig(); } extern HINSTANCE g_dllInstance; EXTERN_C void SafeUnload() { static BOOL bInited = false; if (bInited) return; //防重入 bInited = true; while (CThreadCounter::Count()) Sleep(0); CCriticalSectionLock * lock = new CCriticalSectionLock; BOOL last; if (last=InterlockedExchange(&g_bHookEnabled, FALSE)) { if (hook_term()!=NOERROR) { InterlockedExchange(&g_bHookEnabled, last); bInited = false; delete lock; ExitThread(ERROR_ACCESS_DENIED); } } delete lock; while (CThreadCounter::Count()) Sleep(10); Sleep(0); do { Sleep(10); } while (CThreadCounter::Count()); //double check for xp bInited = false; FreeLibraryAndExitThread(g_dllInstance, 0); } void ChangeFileName(LPWSTR lpSrc, int nSize, LPCWSTR lpNewFileName) { for (int i = nSize; i > 0; --i){ if (lpSrc[i] == L'\\') { lpSrc[i + 1] = L'\0'; break; } } wcscat(lpSrc, lpNewFileName); } std::string WstringToString(const std::wstring str) {// wstringתstring unsigned len = str.size() * 4; setlocale(LC_CTYPE, ""); char *p = new char[len]; wcstombs(p, str.c_str(), len); std::string str1(p); delete[] p; return str1; } // make a unique name with fullname + crc32_of_fullname + familyname +stylename std::wstring MakeUniqueFontName(const std::wstring strFullName, const std::wstring strFamilyName, const std::wstring strStyleName) { return strFullName + to_wstring(crc32::getCrc32(0, strFullName.c_str(), strFullName.length() * sizeof(WCHAR))) + strFamilyName + strStyleName; } #ifndef Assert #include #define Assert _ASSERTE #endif //!Assert #include "array.h" #include #include #include "dll.h" //kernel32専用GetProcAddressモドキ FARPROC K32GetProcAddress(LPCSTR lpProcName) { #ifndef _WIN64 //序数渡しには対応しない //Assert(!IS_INTRESOURCE(lpProcName)); //kernel32のベースアドレス取得 LPBYTE pBase = (LPBYTE)GetModuleHandleA("kernel32.dll"); //この辺は100%成功するはずなのでエラーチェックしない PIMAGE_DOS_HEADER pdosh = (PIMAGE_DOS_HEADER)pBase; //Assert(pdosh->e_magic == IMAGE_DOS_SIGNATURE); PIMAGE_NT_HEADERS pnth = (PIMAGE_NT_HEADERS)(pBase + pdosh->e_lfanew); //Assert(pnth->Signature == IMAGE_NT_SIGNATURE); const DWORD offs = pnth->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress; const DWORD size = pnth->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size; if (offs == 0 || size == 0) { return NULL; } PIMAGE_EXPORT_DIRECTORY pdir = (PIMAGE_EXPORT_DIRECTORY)(pBase + offs); DWORD* pFunc = (DWORD*)(pBase + pdir->AddressOfFunctions); WORD* pOrd = (WORD*)(pBase + pdir->AddressOfNameOrdinals); DWORD* pName = (DWORD*)(pBase + pdir->AddressOfNames); for(DWORD i=0; iNumberOfFunctions; i++) { for(DWORD j=0; jNumberOfNames; j++) { if(pOrd[j] != i) continue; if(strcmp((LPCSTR)pBase + pName[j], lpProcName) != 0) continue; return (FARPROC)(pBase + pFunc[i]); } } return NULL; #else //Assert(!IS_INTRESOURCE(lpProcName)); //kernel32のベースアドレス取得 WCHAR sysdir[MAX_PATH]; GetWindowsDirectory(sysdir, MAX_PATH); wcscat(sysdir, L"\\SysWow64\\kernel32.dll"); // ¼ÓÔØkernel32.dll HANDLE hFile = CreateFile(sysdir, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL); if (hFile == INVALID_HANDLE_VALUE) return NULL; DWORD dwSize = GetFileSize(hFile, NULL); BYTE* pMem = new BYTE[dwSize]; //分配内存 ReadFile(hFile, pMem, dwSize, &dwSize, NULL);//读取文件 CloseHandle(hFile); CMemLoadDll MemDll; MemDll.MemLoadLibrary(pMem, dwSize, false, false); delete[] pMem; return FARPROC((DWORD_PTR)MemDll.MemGetProcAddress(lpProcName)-MemDll.GetImageBase()); //返回偏移值 #endif } typedef struct _UNICODE_STRING64 { USHORT Length; USHORT MaximumLength; DWORD64 Buffer; } UNICODE_STRING64, *PUNICODE_STRING64; #include class opcode_data { private: BYTE code[0x100]; //注: dllpathをWORD境界にしないと場合によっては正常に動作しない WCHAR dllpath[MAX_PATH]; UNICODE_STRING64 uniDllPath; DWORD64 hDumyDllHandle; public: opcode_data() { //int 03hで埋める FillMemory(this, sizeof(*this), 0xcc); } bool initWow64(LPDWORD remoteaddr, LONG orgEIP) //Wow64初始化 { //WORD嫬奅僠僃僢僋 C_ASSERT((offsetof(opcode_data, dllpath) & 1) == 0); register BYTE* p = code; #define emit_(t,x) *(t* UNALIGNED)p = (t)(x); p += sizeof(t) #define emit_db(b) emit_(BYTE, b) #define emit_dw(w) emit_(WORD, w) #define emit_dd(d) emit_(DWORD, d) //側偤偐GetProcAddress偱LoadLibraryW偺傾僪儗僗偑惓偟偔庢傟側偄偙偲偑偁傞偺偱 //kernel32偺僿僢僟偐傜帺慜偱庢摼偡傞 static FARPROC pfn = K32GetProcAddress("LoadLibraryExW"); if (!pfn) return false; emit_db(0x60); //pushad /* * obsolete. mov eax,fs:[0x30] mov eax,[eax+0x0c] mov esi,[eax+0x1c] lodsd move ax,[eax+$08]//这个时候eax中保存的就是k32的基址了 在win7获得的是KernelBase.dll的地址 emit_db(0x64); emit_db(0xA1); emit_db(0x30); emit_db(00); emit_db(00); emit_db(00); emit_db(0x8B); emit_db(0x40); emit_db(0x0C); emit_db(0x8B); emit_db(0x70); emit_db(0x1C); emit_db(0xAD); emit_db(0x8B); emit_db(0x40); emit_db(0x08); //use assemble to fetch kernel base */ /* faster way of simple comparison of 3 key letters of kernel32.dll. insecure but fast. 001D0001 | 64:8B1D 30000000 | mov ebx,dword ptr fs:[30] | 001D0008 | 8B5B 0C | mov ebx,dword ptr ds:[ebx+C] | 001D000B | 8B73 0C | mov esi,dword ptr ds:[ebx+C] | 001D000E | 8BD6 | mov edx,esi | 001D0010 | 8B5A 18 | mov ebx,dword ptr ds:[edx+18] | loop start 001D0013 | 8B7A 30 | mov edi,dword ptr ds:[edx+30] | 001D0016 | 0FB74A 2C | movzx ecx,word ptr ds:[edx+2C] | 001D001A | 66:83F9 18 | cmp cx,18 | 001D001E | 75 27 | jne 1D0047 | length not match 001D0020 | 85FF | test edi,edi | 001D0022 | 74 23 | je 1D0047 | 001D0024 | 8A07 | mov al,byte ptr ds:[edi] | 001D0026 | 3C 6B | cmp al,6B | 6B:'k' 001D0028 | 74 04 | je 1D002E | 001D002A | 3C 4B | cmp al,4B | 4B:'K' 001D002C | 75 19 | jne 1D0047 | not K or k 001D002E | 66:837F 0C 33 | cmp word ptr ds:[edi+C],33 | 33:'3' 001D0033 | 75 12 | jne 1D0047 | 001D0035 | 66:837F 10 2E | cmp word ptr ds:[edi+10],2E | 2E:'.' 001D003A | 75 0B | jne 1D0047 | 001D003C | 8A47 16 | mov al,byte ptr ds:[edi+16] | 001D003F | 3C 6C | cmp al,6C | 6C:'l' 001D0041 | 74 0C | je 1D004F | 001D0043 | 3C 4C | cmp al,4C | 4C:'L' 001D0045 | 74 08 | je 1D004F | 001D0047 | 8B12 | mov edx,dword ptr ds:[edx] | next entry 001D0049 | 3BD6 | cmp edx,esi | 001D004B | 75 C3 | jne 1D0010 | loop back 001D004D | EB 12 | jmp 1D0061 | not found 001D004F | 8BC3 | mov eax,ebx | eax=imagebase of kernel32.dll emit_db(0x64); emit_db(0x8B); emit_db(0x1D); emit_db(0x30); emit_db(0x00); emit_db(0x00); emit_db(0x00); emit_db(0x8B); emit_db(0x5B); emit_db(0x0C); emit_db(0x8B); emit_db(0x73); emit_db(0x0C); emit_db(0x8B); emit_db(0xD6); emit_db(0x8B); emit_db(0x5A); emit_db(0x18); emit_db(0x8B); emit_db(0x7A); emit_db(0x30); emit_db(0x0F); emit_db(0xB7); emit_db(0x4A); emit_db(0x2C); emit_db(0x66); emit_db(0x83); emit_db(0xF9); emit_db(0x18); emit_db(0x75); emit_db(0x27); emit_db(0x85); emit_db(0xFF); emit_db(0x74); emit_db(0x23); emit_db(0x8A); emit_db(0x07); emit_db(0x3C); emit_db(0x6B); emit_db(0x74); emit_db(0x04); emit_db(0x3C); emit_db(0x4B); emit_db(0x75); emit_db(0x19); emit_db(0x66); emit_db(0x83); emit_db(0x7F); emit_db(0x0C); emit_db(0x33); emit_db(0x75); emit_db(0x12); emit_db(0x66); emit_db(0x83); emit_db(0x7F); emit_db(0x10); emit_db(0x2E); emit_db(0x75); emit_db(0x0B); emit_db(0x8A); emit_db(0x47); emit_db(0x16); emit_db(0x3C); emit_db(0x6C); emit_db(0x74); emit_db(0x0C); emit_db(0x3C); emit_db(0x4C); emit_db(0x74); emit_db(0x08); emit_db(0x8B); emit_db(0x12); emit_db(0x3B); emit_db(0xD6); emit_db(0x75); emit_db(0xC3); emit_db(0xEB); emit_db(0x12); emit_db(0x8B); emit_db(0xC3); */ /* 001D0001 | BE 3FD6EC8F | mov esi,8FECD63F | target hash value for kernel32.dll 001D0006 | 64:8B0D 30000 | mov ecx,dword ptr fs:[30] | 001D000D | 8B49 0C | mov ecx,dword ptr ds:[ecx+C] | 001D0010 | 8B69 0C | mov ebp,dword ptr ds:[ecx+C] | 001D0013 | 8BD5 | mov edx,ebp | 001D0015 | 8B5A 18 | mov ebx,dword ptr ds:[edx+18] | loop start 001D0018 | 8B7A 30 | mov edi,dword ptr ds:[edx+30] | 001D001B | 0FB74A 2C | movzx ecx,word ptr ds:[edx+2C] | 001D001F | 85FF | test edi,edi | 001D0021 | 74 2E | je 1D0051 | skip for empty name dlls 001D0023 | 66:83F9 18 | cmp cx,18 | check length 001D0027 | 75 28 | jne 1D0051 | 001D0029 | D1E9 | shr ecx,1 | ecx = length of unicode name of the dll 001D002B | E3 24 | jecxz 1D0051 | 001D002D | 52 | push edx | 001D002E | 33D2 | xor edx,edx | use edx to hash dll names 001D0030 | 0FB607 | movzx eax,byte ptr ds:[edi] | letter->al with zero expanding 001D0033 | 8A67 01 | mov ah,byte ptr ds:[edi+1] | 001D0036 | 84C0 | test al,al | 001D0038 | 3C 41 | cmp al,41 | 41:'A' 001D003A | 7C 06 | jl 1D0042 | 001D003C | 3C 5A | cmp al,5A | 5A:'Z' 001D003E | 7F 02 | jg 1D0042 | 001D0040 | 04 20 | add al,20 | convert uppercased letters to lowercased 001D0042 | C1CA 0D | ror edx,D | 001D0045 | 03D0 | add edx,eax | 001D0047 | 83C7 02 | add edi,2 | next letter 001D004A | E2 E4 | loop 1D0030 | 001D004C | 3BD6 | cmp edx,esi | 001D004E | 5A | pop edx | 001D004F | 74 08 | je 1D0059 | match found 001D0051 | 8B12 | mov edx,dword ptr ds:[edx] | 001D0053 | 3BD5 | cmp edx,ebp | check if we reached the end of the link table 001D0055 | 75 BE | jne 1D0015 | 001D0057 | EB 12 | jmp 1D006B | 001D0059 | 8BC3 | mov eax,ebx | ebx->eax = image base of kernel32.dll */ DWORD hash = 0x8FECD63F; // hash of kernel32.dll emit_db(0xBE); emit_dd(hash); emit_db(0x64); emit_db(0x8B); emit_db(0x0D); emit_db(0x30); emit_db(0x00); emit_db(0x00); emit_db(0x00); emit_db(0x8B); emit_db(0x49); emit_db(0x0C); emit_db(0x8B); emit_db(0x69); emit_db(0x0C); emit_db(0x8B); emit_db(0xD5); emit_db(0x8B); emit_db(0x5A); emit_db(0x18); emit_db(0x8B); emit_db(0x7A); emit_db(0x30); emit_db(0x0F); emit_db(0xB7); emit_db(0x4A); emit_db(0x2C); emit_db(0x85); emit_db(0xFF); emit_db(0x74); emit_db(0x2E); emit_db(0x66); emit_db(0x83); emit_db(0xF9); emit_db(0x18); emit_db(0x75); emit_db(0x28); emit_db(0xD1); emit_db(0xE9); emit_db(0xE3); emit_db(0x24); emit_db(0x52); emit_db(0x33); emit_db(0xD2); emit_db(0x0F); emit_db(0xB6); emit_db(0x07); emit_db(0x8A); emit_db(0x67); emit_db(0x01); emit_db(0x84); emit_db(0xC0); emit_db(0x3C); emit_db(0x41); emit_db(0x7C); emit_db(0x06); emit_db(0x3C); emit_db(0x5A); emit_db(0x7F); emit_db(0x02); emit_db(0x04); emit_db(0x20); emit_db(0xC1); emit_db(0xCA); emit_db(0x0D); emit_db(0x03); emit_db(0xD0); emit_db(0x83); emit_db(0xC7); emit_db(0x02); emit_db(0xE2); emit_db(0xE4); emit_db(0x3B); emit_db(0xD6); emit_db(0x5A); emit_db(0x74); emit_db(0x08); emit_db(0x8B); emit_db(0x12); emit_db(0x3B); emit_db(0xD5); emit_db(0x75); emit_db(0xBE); emit_db(0xEB); emit_db(0x12); emit_db(0x8B); emit_db(0xC3); emit_dw(0x006A); //push 0 emit_dw(0x006A); //push 0 emit_db(0x68); //push dllpath emit_dd((LONG)remoteaddr + offsetof(opcode_data, dllpath)); emit_db(0x05); //add eax, LoadLibraryExW offset emit_dd(pfn); emit_dw(0xD0FF); //call eax emit_db(0x61); //popad emit_db(0xE9); //jmp original_EIP emit_dd(orgEIP - (LONG)remoteaddr - (p - code) - sizeof(LONG)); // gdi++.dllのパス int nSize = GetModuleFileNameW(GetDLLInstance(), dllpath, MAX_PATH); if (nSize) { ChangeFileName(dllpath, nSize, L"MTBootStrap.dll"); } return !!nSize; } bool init32(LPDWORD remoteaddr, LONG orgEIP) //32位程序初始化 { //WORD境界チェック C_ASSERT((offsetof(opcode_data, dllpath) & 1) == 0); register BYTE* p = code; #define emit_(t,x) *(t* UNALIGNED)p = (t)(x); p += sizeof(t) #define emit_db(b) emit_(BYTE, b) #define emit_dw(w) emit_(WORD, w) #define emit_dd(d) emit_(DWORD, d) //なぜかGetProcAddressでLoadLibraryWのアドレスが正しく取れないことがあるので //kernel32のヘッダから自前で取得する static FARPROC pfn = K32GetProcAddress("LoadLibraryW"); if(!pfn) return false; emit_db(0x60); //pushad #if _DEBUG emit_dw(0xC033); //xor eax, eax emit_db(0x50); //push eax emit_db(0x50); //push eax emit_db(0x68); //push dllpath emit_dd((LONG)remoteaddr + offsetof(opcode_data, dllpath)); emit_db(0x50); //push eax emit_db(0xB8); //mov eax, MessageBoxW emit_dd((LONG)MessageBoxW); emit_dw(0xD0FF); //call eax #endif emit_db(0x68); //push dllpath emit_dd((LONG)remoteaddr + offsetof(opcode_data, dllpath)); emit_db(0xB8); //mov eax, LoadLibraryW emit_dd(pfn); emit_dw(0xD0FF); //call eax emit_db(0x61); //popad emit_db(0xE9); //jmp original_EIP emit_dd(orgEIP - (LONG)remoteaddr - (p - code) - sizeof(LONG)); // gdi++.dllのパス int nSize = GetModuleFileNameW(GetDLLInstance(), dllpath, MAX_PATH); if (nSize) { ChangeFileName(dllpath, nSize, L"MTBootStrap.dll"); } return !!nSize; } bool init64From32(DWORD64 remoteaddr, DWORD64 orgEIP) { C_ASSERT((offsetof(opcode_data, dllpath) & 1) == 0); register BYTE* p = code; #define emit_(t,x) *(t* UNALIGNED)p = (t)(x); p += sizeof(t) #define emit_db(b) emit_(BYTE, b) #define emit_dw(w) emit_(WORD, w) #define emit_dd(d) emit_(DWORD, d) #define emit_ddp(dp) emit_(DWORD64, dp) //なぜかGetProcAddressでLoadLibraryWのアドレスが正しく取れないことがあるので //kernel32のヘッダから自前で取得する WCHAR x64Addr[30] = { 0 }; if (!GetEnvironmentVariable(L"MACTYPE_X64ADDR", x64Addr, 29)) return false; DWORD64 pfn = wcstoull(x64Addr, NULL, 10); //DWORD64 pfn = getenv("MACTYPE_X64ADDR"); //GetProcAddress64(GetModuleHandle64(L"kernelbase.dll"), "LoadLibraryW"); if (!pfn) return false; emit_db(0x50); //push rax emit_db(0x51); //push rcx emit_db(0x52); //push rdx emit_db(0x53); //push rbx emit_dd(0x28ec8348); //sub rsp,28h emit_db(0x48); //mov rcx, dllpath emit_db(0xB9); emit_ddp((DWORD64)remoteaddr + offsetof(opcode_data, dllpath)); emit_db(0x48); //mov rsi, LoadLibraryW emit_db(0xBE); emit_ddp(pfn); //emit_db(0x48); emit_db(0xFF); //call rdi emit_db(0xD6); emit_dd(0x28c48348); //add rsp,28h emit_db(0x5B); emit_db(0x5A); emit_db(0x59); emit_db(0x58); //popad emit_db(0x48); //mov rdi, orgRip emit_db(0xBE); emit_ddp(orgEIP); emit_db(0xFF); //jmp rdi emit_db(0xE6); // gdi++.dllのパス int nSize = GetModuleFileNameW(GetDLLInstance(), dllpath, MAX_PATH); if (nSize) { ChangeFileName(dllpath, nSize, L"MTBootStrap64.dll"); } return !!nSize; } bool init64From32(DWORD64 remoteaddr, DWORD64 orgEIP, DWORD dwLoaderOffset) { C_ASSERT((offsetof(opcode_data, dllpath) & 1) == 0); int nSize = GetModuleFileNameW(GetDLLInstance(), dllpath, MAX_PATH); if (nSize) { ChangeFileName(dllpath, nSize, L"MTBootStrap64.dll"); } if (!nSize) return false; uniDllPath.Length = wcslen(dllpath)*sizeof(WCHAR); uniDllPath.MaximumLength = uniDllPath.Length+2; uniDllPath.Buffer = remoteaddr + (DWORD64)offsetof(opcode_data, dllpath); //prepare PUNICODE_STRING for remote process register BYTE* p = code; #define emit_(t,x) *(t* UNALIGNED)p = (t)(x); p += sizeof(t) #define emit_db(b) emit_(BYTE, b) #define emit_dw(w) emit_(WORD, w) #define emit_dd(d) emit_(DWORD, d) #define emit_ddp(dp) emit_(DWORD64, dp) //get ntdll.dll imagebase //credit to http://www.52pojie.cn/thread-162625-1-1.html /*asm: mov rsi, [gs:60h] ; peb from teb mov rsi, [rsi+18h] ;_peb_ldr_data from peb mov rsi, [rsi+30h] ;InInitializationOrderModuleList.Flink, ntdll.dll ;mov rsi, [rsi] ;kernelbase.dll ;mov rsi, [rsi] ;kernel32.dll (not used for win7+) mov rsi, [rsi+10h] */ // emit_db(0xEB); // emit_db(0xFE); // make a dead loop emit_db(0x65); emit_db(0x48); emit_db(0x8B); emit_db(0x34); emit_db(0x25); emit_db(0x60); emit_db(0x00); emit_db(0x00); emit_db(0x00); emit_db(0x48); emit_db(0x8B); emit_db(0x76); emit_db(0x18); emit_db(0x48); emit_db(0x8B); emit_db(0x76); emit_db(0x30); // emit_db(0x48); // emit_db(0x8B); // emit_db(0x36); emit_db(0x48); emit_db(0x8B); emit_db(0x76); emit_db(0x10); //rsi = ntdll.dll baseaddress emit_db(0x50); //push rax emit_db(0x51); //push rcx emit_db(0x52); //push rdx emit_db(0x53); //push rbx emit_dd(0x28ec8348); //sub rsp,28h emit_db(0x48); emit_db(0x31); emit_db(0xc9); //xor rcx, rcx emit_db(0x48); emit_db(0x31); emit_db(0xd2); //xor rdx, rdx emit_db(0x49); emit_db(0xB8); emit_ddp((DWORD64)remoteaddr + offsetof(opcode_data, uniDllPath));//mov r8, uniDllPath emit_db(0x49); emit_db(0xB9); emit_ddp((DWORD64)remoteaddr + offsetof(opcode_data, hDumyDllHandle));//mov r9, hDumyDllHandle //emit_db(0x48); //mov rsi, LdrLoadDll //emit_db(0xBE); emit_db(0x48); emit_db(0x81); emit_db(0xC6); //add rsi, offset LdrLoadDll emit_dd(dwLoaderOffset); //emit_db(0x48); emit_db(0xFF); //call rsi emit_db(0xD6); emit_dd(0x28c48348); //add rsp,28h emit_db(0x5B); emit_db(0x5A); emit_db(0x59); emit_db(0x58); //popad emit_db(0x48); //mov rdi, orgRip emit_db(0xBE); emit_ddp(orgEIP); emit_db(0xFF); //jmp rdi emit_db(0xE6); // gdi++.dllのパス return !!nSize; } bool init(DWORD_PTR* remoteaddr, DWORD_PTR orgEIP) { //WORD境界チェック C_ASSERT((offsetof(opcode_data, dllpath) & 1) == 0); register BYTE* p = code; #undef emit_ddp #define emit_(t,x) *(t* UNALIGNED)p = (t)(x); p += sizeof(t) #define emit_db(b) emit_(BYTE, b) #define emit_dw(w) emit_(WORD, w) #define emit_dd(d) emit_(DWORD, d) #define emit_ddp(dp) emit_(DWORD_PTR, dp) //なぜかGetProcAddressでLoadLibraryWのアドレスが正しく取れないことがあるので //kernel32のヘッダから自前で取得する static FARPROC pfn = (FARPROC)((INT_PTR)CDllHelper::MyGetProcAddress(GetModuleHandle(L"kernel32.dll"), L"LoadLibraryW") - (INT_PTR)GetModuleHandle(L"kernel32.dll")); /*WCHAR msg[500] = { 0 }; wsprintf(msg, L"API paddr: 0x%I64x\r\nOffset: %x\r\nAPI addr: 0x%I64x\r\nKernel32.dll: 0x%I64x\r\nKernelBase: 0x%I64x", (DWORD_PTR)pfn, *(PDWORD)pfn, *(PDWORD)pfn + (DWORD_PTR)GetModuleHandle(L"kernel32.dll"), (DWORD_PTR)GetModuleHandle(L"kernel32.dll"), (DWORD_PTR)GetModuleHandle(L"kernelbase.dll")); MessageBoxW(NULL, msg, NULL, MB_OK);*/ //if(!pfn) // return false; //emit_db(0xEB); //emit_db(0xFE); // make a dead loop emit_db(0x50); //push rax emit_db(0x51); //push rcx emit_db(0x52); //push rdx emit_db(0x53); //push rbx /* #ifdef DEBUG emit_dd(0x28ec8348); emit_db(0x48); emit_db(0x31); emit_db(0xD0); //xor rax,rax emit_db(0x48); emit_db(0x31); emit_db(0xC9); //xor rcx,rcx emit_db(0x48); emit_db(0x31); emit_db(0xD2); //xor rdx,rdx emit_db(0x45); emit_db(0x31); emit_db(0xC0); //xor r8d,r8d emit_db(0x45); emit_db(0x31); emit_db(0xC9); //xor r9d,r9d emit_db(0x48); //mov rsi, MessageBoxW emit_db(0xBE); emit_ddp((DWORD_PTR)MessageBoxW); emit_db(0xFF); emit_db(0xD6); emit_dd(0x28c48348); #endif*/ /* //Debug function2, Sleep for 10sec. emit_dd(0x28ec8348); emit_db(0x48); //mov rsi, MessageBoxW emit_db(0xBE); emit_ddp((DWORD_PTR)Sleep); emit_db(0x48); emit_db(0xc7); emit_db(0xc1); emit_db(0x10); emit_db(0x27); emit_db(0x00); emit_db(0x00); emit_db(0xFF); emit_db(0xD6); emit_dd(0x28c48348); */ //shellcode to find imagebase of kernel32.dll (under x64) //rax will store the imagebase of kernel32.dll, fast but not reliable. does not work in some scenarios /* | 65 48 8B | mov rax,qword ptr gs:[60] | | 48 8B 40 | mov rax,qword ptr ds:[rax+18] | | 48 8B 40 | mov rax,qword ptr ds:[rax+30] | | 48 8B 00 | mov rax,qword ptr ds:[rax] | | 48 8B 00 | mov rax,qword ptr ds:[rax] | | 48 8B 40 | mov rax,qword ptr ds:[rax+10] | emit_db(0x65); emit_db(0x48); emit_db(0x8B); emit_db(0x04); emit_db(0x25); emit_db(0x60); emit_db(0x00); emit_db(0x00); emit_db(0x00); emit_db(0x48); emit_db(0x8B); emit_db(0x40); emit_db(0x18); emit_db(0x48); emit_db(0x8B); emit_db(0x40); emit_db(0x30); emit_db(0x48); emit_db(0x8B); emit_db(0x00); emit_db(0x48); emit_db(0x8B); emit_db(0x00); emit_db(0x48); emit_db(0x8B); emit_db(0x40); emit_db(0x10); */ /* plan B, accurate search through PEB 00000233B6160004 | 6548:8B0425 60000000 | mov rax,qword ptr gs:[60] | 00000233B616000D | 48:8B40 18 | mov rax,qword ptr ds:[rax+18] | 00000233B6160011 | 48:8B50 10 | mov rdx,qword ptr ds:[rax+10] | 00000233B6160015 | 4C:8B4A 30 | mov r9,qword ptr ds:[rdx+30] | 00000233B6160019 | 4C:8B42 60 | mov r8,qword ptr ds:[rdx+60] | 00000233B616001D | 0FB74A 58 | movzx ecx,word ptr ds:[rdx+58] | 00000233B6160021 | 66:83F9 18 | cmp cx,18 | 00000233B6160025 | 75 2C | jne 233B6160053 | 00000233B6160027 | 4D:85C0 | test r8,r8 | 00000233B616002A | 74 27 | je 233B6160053 | 00000233B616002C | 41:8A00 | mov al,byte ptr ds:[r8] | 00000233B616002F | 3C 6B | cmp al,6B | 6B:'k' 00000233B6160031 | 74 04 | je 233B6160037 | 00000233B6160033 | 3C 4B | cmp al,4B | 4B:'K' 00000233B6160035 | 75 1C | jne 233B6160053 | 00000233B6160037 | 6641:8378 0C 33 | cmp word ptr ds:[r8+C],33 | 33:'3' 00000233B616003D | 75 14 | jne 233B6160053 | 00000233B616003F | 6641:8378 10 2E | cmp word ptr ds:[r8+10],2E | 2E:'.' 00000233B6160045 | 75 0C | jne 233B6160053 | 00000233B6160047 | 41:8A40 16 | mov al,byte ptr ds:[r8+16] | 00000233B616004B | 3C 6C | cmp al,6C | 6C:'l' 00000233B616004D | 74 0F | je 233B616005E | found 00000233B616004F | 3C 4C | cmp al,4C | 4C:'L' 00000233B6160051 | 74 0B | je 233B616005E | found 00000233B6160053 | 48:8B12 | mov rdx,qword ptr ds:[rdx] | 00000233B6160056 | 48:3B50 10 | cmp rdx,qword ptr ds:[rax+10] | 00000233B616005A | 75 B9 | jne 233B6160015 | loop back 00000233B616005C | EB 25 | jmp 233B6160083 | not found 00000233B616005E | 49:8BC1 | mov rax,r9 | :found, r9->imagebase emit_db(0x65); emit_db(0x48); emit_db(0x8B); emit_db(0x04); emit_db(0x25); emit_db(0x60); emit_db(0x00); emit_db(0x00); emit_db(0x00); emit_db(0x48); emit_db(0x8B); emit_db(0x40); emit_db(0x18); emit_db(0x48); emit_db(0x8B); emit_db(0x50); emit_db(0x10); emit_db(0x4C); emit_db(0x8B); emit_db(0x4A); emit_db(0x30); emit_db(0x4C); emit_db(0x8B); emit_db(0x42); emit_db(0x60); emit_db(0x0F); emit_db(0xB7); emit_db(0x4A); emit_db(0x58); emit_db(0x66); emit_db(0x83); emit_db(0xF9); emit_db(0x18); emit_db(0x75); emit_db(0x2C); emit_db(0x4D); emit_db(0x85); emit_db(0xC0); emit_db(0x74); emit_db(0x27); emit_db(0x41); emit_db(0x8A); emit_db(0x00); emit_db(0x3C); emit_db(0x6B); emit_db(0x74); emit_db(0x04); emit_db(0x3C); emit_db(0x4B); emit_db(0x75); emit_db(0x1C); emit_db(0x66); emit_db(0x41); emit_db(0x83); emit_db(0x78); emit_db(0x0C); emit_db(0x33); emit_db(0x75); emit_db(0x14); emit_db(0x66); emit_db(0x41); emit_db(0x83); emit_db(0x78); emit_db(0x10); emit_db(0x2E); emit_db(0x75); emit_db(0x0C); emit_db(0x41); emit_db(0x8A); emit_db(0x40); emit_db(0x16); emit_db(0x3C); emit_db(0x6C); emit_db(0x74); emit_db(0x0F); emit_db(0x3C); emit_db(0x4C); emit_db(0x74); emit_db(0x0B); emit_db(0x48); emit_db(0x8B); emit_db(0x12); emit_db(0x48); emit_db(0x3B); emit_db(0x50); emit_db(0x10); emit_db(0x75); emit_db(0xB9); emit_db(0xEB); emit_db(0x25); emit_db(0x49); emit_db(0x8B); emit_db(0xC1); */ /* 0000024429180004 | 41:BC 72785CE1 | mov r12d,8FECD63F | 000002442918000A | 6548:8B0425 60000000 | mov rax,qword ptr gs:[60] | 0000024429180013 | 48:8B40 18 | mov rax,qword ptr ds:[rax+18] | 0000024429180017 | 48:8B50 10 | mov rdx,qword ptr ds:[rax+10] | 000002442918001B | 4C:8BFA | mov r15,rdx | r15=link start 000002442918001E | 4C:8B4A 30 | mov r9,qword ptr ds:[rdx+30] | loop start, r9=imagebase 0000024429180022 | 4C:8B42 60 | mov r8,qword ptr ds:[rdx+60] | 0000024429180026 | 0FB74A 58 | movzx ecx,word ptr ds:[rdx+58] | 000002442918002A | 83F9 18 | cmp ecx,18 | quick length check 000002442918002D | 75 2B | jne 2442918005A | 000001EE63DE002F | D1E9 | shr ecx,1 | ecx >> 1 = length 000002442918002F | 4D:33DB | xor r11,r11 | r11=hash 0000024429180032 | 41:0FB700 | movzx eax,word ptr ds:[r8] | 0000024429180036 | 0FB6D8 | movzx ebx,al | 0000024429180039 | 80FB 41 | cmp bl,41 | 41:'A' 000002442918003C | 7C 08 | jl 24429180046 | 000002442918003E | 80FB 5A | cmp bl,5A | 5A:'Z' 0000024429180041 | 7F 03 | jg 24429180046 | 0000024429180043 | 80C3 20 | add bl,20 | change uppercased letters to lowercased 0000024429180046 | 41:C1CB 0D | ror r11d,D | 000002442918004A | 44:03DB | add r11d,ebx | 000002442918004D | 49:83C0 02 | add r8,2 | 0000024429180051 | FFC9 | dec ecx | 0000024429180053 | 75 DD | jne 24429180032 | 0000024429180055 | 45:3BDC | cmp r11d,r12d | hash check 0000024429180058 | 74 0A | je 24429180064 | 000002442918005A | 48:8B12 | mov rdx,qword ptr ds:[rdx] | not found, next 000002442918005D | 49:3BD7 | cmp rdx,r15 | 0000024429180060 | 75 BC | jne 2442918001E | 0000024429180062 | EB 25 | jmp 24429180089 | not found, skip loading 0000024429180064 | 49:8BC1 | mov rax,r9 | found, rax=imagebase */ DWORD hash = 0x8FECD63F; emit_db(0x41); emit_db(0xBC); emit_dd(hash); emit_db(0x65); emit_db(0x48); emit_db(0x8B); emit_db(0x04); emit_db(0x25); emit_db(0x60); emit_db(0x00); emit_db(0x00); emit_db(0x00); emit_db(0x48); emit_db(0x8B); emit_db(0x40); emit_db(0x18); emit_db(0x48); emit_db(0x8B); emit_db(0x50); emit_db(0x10); emit_db(0x4C); emit_db(0x8B); emit_db(0xFA); emit_db(0x4C); emit_db(0x8B); emit_db(0x4A); emit_db(0x30); emit_db(0x4C); emit_db(0x8B); emit_db(0x42); emit_db(0x60); emit_db(0x0F); emit_db(0xB7); emit_db(0x4A); emit_db(0x58); emit_db(0x83); emit_db(0xF9); emit_db(0x18); emit_db(0x75); emit_db(0x2D); emit_db(0xD1); emit_db(0xE9); emit_db(0x4D); emit_db(0x33); emit_db(0xDB); emit_db(0x41); emit_db(0x0F); emit_db(0xB7); emit_db(0x00); emit_db(0x0F); emit_db(0xB6); emit_db(0xD8); emit_db(0x80); emit_db(0xFB); emit_db(0x41); emit_db(0x7C); emit_db(0x08); emit_db(0x80); emit_db(0xFB); emit_db(0x5A); emit_db(0x7F); emit_db(0x03); emit_db(0x80); emit_db(0xC3); emit_db(0x20); emit_db(0x41); emit_db(0xC1); emit_db(0xCB); emit_db(0x0D); emit_db(0x44); emit_db(0x03); emit_db(0xDB); emit_db(0x49); emit_db(0x83); emit_db(0xC0); emit_db(0x02); emit_db(0xFF); emit_db(0xC9); emit_db(0x75); emit_db(0xDD); emit_db(0x45); emit_db(0x3B); emit_db(0xDC); emit_db(0x74); emit_db(0x0A); emit_db(0x48); emit_db(0x8B); emit_db(0x12); emit_db(0x49); emit_db(0x3B); emit_db(0xD7); emit_db(0x75); emit_db(0xBA); emit_db(0xEB); emit_db(0x25); emit_db(0x49); emit_db(0x8B); emit_db(0xC1); // === end of shellcode === emit_dd(0x28ec8348); //sub rsp,28h emit_db(0x48); //mov rcx, dllpath emit_db(0xB9); emit_ddp((DWORD_PTR)remoteaddr + offsetof(opcode_data, dllpath)); emit_db(0x48); // mov rdx, rax emit_db(0x89); emit_db(0xC2); emit_db(0x48); // add rax, offset of LoadLibrary IAT emit_db(0x05); emit_dd(pfn); /* __asm: mov eax,dword ptr ds:[rax] add rdx,rax call rdx */ emit_db(0x8B); emit_db(0x00); emit_db(0x48); emit_db(0x01); emit_db(0xC2); emit_db(0xFF); emit_db(0xD2); emit_dd(0x28c48348); //add rsp,28h emit_db(0x5B); emit_db(0x5A); emit_db(0x59); emit_db(0x58); //popad emit_db(0x48); //mov rdi, orgRip emit_db(0xBE); emit_ddp(orgEIP); emit_db(0xFF); //jmp rdi emit_db(0xE6); // gdi++.dllのパス int nSize = GetModuleFileNameW(GetDLLInstance(), dllpath, MAX_PATH); if (nSize) { ChangeFileName(dllpath, nSize, L"MTBootStrap64.dll"); } return !!nSize; } }; #include // 安全的取得真实系统信息 VOID SafeGetNativeSystemInfo(__out LPSYSTEM_INFO lpSystemInfo) { if (NULL == lpSystemInfo) return; typedef VOID(WINAPI *LPFN_GetNativeSystemInfo)(LPSYSTEM_INFO lpSystemInfo); LPFN_GetNativeSystemInfo fnGetNativeSystemInfo = (LPFN_GetNativeSystemInfo)GetProcAddress(GetModuleHandle(_T("kernel32")), "GetNativeSystemInfo");; if (NULL != fnGetNativeSystemInfo) { fnGetNativeSystemInfo(lpSystemInfo); } else { GetSystemInfo(lpSystemInfo); } } // 获取操作系统位数 int GetSystemBits() { SYSTEM_INFO si; SafeGetNativeSystemInfo(&si); if (si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64 || si.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64) { return 64; } return 32; } static bool bIsOS64 = GetSystemBits() == 64; // check if running in a x64 system. #ifdef _M_IX86 // 止めているプロセスにLoadLibraryするコードを注入 EXTERN_C BOOL WINAPI GdippInjectDLL(const PROCESS_INFORMATION* ppi) { BOOL bIsX64Proc = false; if (bIsOS64 && IsWow64Process(ppi->hProcess, &bIsX64Proc) && !bIsX64Proc) { //x86 process launches a x64 process _CONTEXT64 ctx = { 0 }; ctx.ContextFlags = CONTEXT_CONTROL; if (!GetThreadContext64(ppi->hThread, &ctx)) return false; static bool bTryLoadDll64 = false; static DWORD dwLoaderOffset = 0; if (!bTryLoadDll64) { bTryLoadDll64 = true; GetEnvironmentVariable(L"MACTYPE_X64ADDR", NULL, 0); if (GetLastError() == ERROR_ENVVAR_NOT_FOUND) { DWORD64 hNtdll = 0; hNtdll = GetModuleHandle64(L"ntdll.dll"); if (hNtdll) { DWORD64 pfnLdrAddr = GetProcAddress64(hNtdll, "LdrLoadDll"); if (pfnLdrAddr) { dwLoaderOffset = (DWORD)(pfnLdrAddr - hNtdll); } } } } opcode_data local; DWORD64 remote = VirtualAllocEx64(ppi->hProcess, NULL, sizeof(opcode_data), MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (!remote) return false; bool basmIniter = dwLoaderOffset ? local.init64From32(remote, ctx.Rip, dwLoaderOffset) : local.init64From32(remote, ctx.Rip); if (!basmIniter || !WriteProcessMemory64(ppi->hProcess, remote, &local, sizeof(opcode_data), NULL)) { VirtualFreeEx64(ppi->hProcess, remote, 0, MEM_RELEASE); return false; } //FlushInstructionCache64(ppi->hProcess, remote, sizeof(opcode_data)); //FARPROC a=(FARPROC)remote; //a(); ctx.Rip = (DWORD64)remote; return !!SetThreadContext64(ppi->hThread, &ctx); } else { CONTEXT ctx = { 0 }; ctx.ContextFlags = CONTEXT_CONTROL; if (!GetThreadContext(ppi->hThread, &ctx)) return false; opcode_data local; opcode_data* remote = (opcode_data*)VirtualAllocEx(ppi->hProcess, NULL, sizeof(opcode_data), MEM_COMMIT, PAGE_EXECUTE_READWRITE); if (!remote) return false; if (!local.init32((LPDWORD)remote, ctx.Eip) || !WriteProcessMemory(ppi->hProcess, remote, &local, sizeof(opcode_data), NULL)) { VirtualFreeEx(ppi->hProcess, remote, 0, MEM_RELEASE); return false; } FlushInstructionCache(ppi->hProcess, remote, sizeof(opcode_data)); ctx.Eip = (DWORD)remote; return !!SetThreadContext(ppi->hThread, &ctx); } } #else EXTERN_C BOOL WINAPI GdippInjectDLL(const PROCESS_INFORMATION* ppi) { BOOL bWow64 = false; IsWow64Process(ppi->hProcess, &bWow64); if (bWow64) { WOW64_CONTEXT ctx = { 0 }; ctx.ContextFlags = CONTEXT_CONTROL; //CREATE_SUSPENDEDなので基本的に成功するはず if(!Wow64GetThreadContext(ppi->hThread, &ctx)) return false; opcode_data local; LPVOID remote = VirtualAllocEx(ppi->hProcess, NULL, sizeof(opcode_data), MEM_COMMIT, PAGE_EXECUTE_READWRITE); if(!remote) return false; if(!local.initWow64((LPDWORD)remote, ctx.Eip) || !WriteProcessMemory(ppi->hProcess, remote, &local, sizeof(opcode_data), NULL)) { VirtualFreeEx(ppi->hProcess, remote, 0, MEM_RELEASE); return false; } FlushInstructionCache(ppi->hProcess, remote, sizeof(opcode_data)); //FARPROC a=(FARPROC)remote; //a(); ctx.Eip = (DWORD)remote; return !!Wow64SetThreadContext(ppi->hThread, &ctx); } else { CONTEXT ctx = { 0 }; ctx.ContextFlags = CONTEXT_CONTROL; //CREATE_SUSPENDEDなので基本的に成功するはず if(!GetThreadContext(ppi->hThread, &ctx)) return false; opcode_data local; LPVOID remote = VirtualAllocEx(ppi->hProcess, NULL, sizeof(opcode_data), MEM_COMMIT, PAGE_EXECUTE_READWRITE); if(!remote) return false; if(!local.init((DWORD_PTR*)remote, ctx.Rip) || !WriteProcessMemory(ppi->hProcess, remote, &local, sizeof(opcode_data), NULL)) { VirtualFreeEx(ppi->hProcess, remote, 0, MEM_RELEASE); return false; } FlushInstructionCache(ppi->hProcess, remote, sizeof(opcode_data)); //FARPROC a=(FARPROC)remote; //a(); ctx.Rip = (DWORD_PTR)remote; return !!SetThreadContext(ppi->hThread, &ctx); } } #endif template int strlendb(const _TCHAR* psz) { const _TCHAR* p = psz; while (*p) { for (; *p; p++); p++; } return p - psz + 1; } template _TCHAR* strdupdb(const _TCHAR* psz, int pad) { int len = strlendb(psz); _TCHAR* p = (_TCHAR*)calloc(sizeof(_TCHAR), len + pad); if(p) { memcpy(p, psz, sizeof(_TCHAR) * len); } return p; } bool MultiSzToArray(LPWSTR p, CArray& arr) { for (; *p; ) { LPWSTR cp = _wcsdup(p); if(!cp || !arr.Add(cp)) { free(cp); return false; } for (; *p; p++); p++; } return true; } LPWSTR ArrayToMultiSz(CArray& arr) { size_t cch = 1; for (int i=0; i& arr, LPWSTR dir, int dirlen) { for (int i=0; i //#include #include #include #include #include #include /* FT_FREETYPE_H */ #include /* FT_CACHE_H */ //#include // FT_TRUETYPE_TAGS_H //#include // FT_TRUETYPE_TABLES_H #include // FT_OUTLINE_H #include //FT_TRIGONOMETRY_H #ifdef FT_LCD_FILTER_H #include // FT_LCD_FILTER_H #endif #include "fteng.h" #include "ft2vert.h" FT_BitmapGlyphRec empty_glyph = {};//优化控制字 #define FT_BOLD_LOW 15 #define IsFontBold(lf) ((lf).lfWeight >= FW_BOLD) #define FT_FixedToInt(x) (FT_RoundFix(x) >> 16) #define FT_PosToInt(x) (((x) + (1 << 5)) >> 6) #define RESOLUTION_X 72 #define RESOLUTION_Y 72 FT_Error New_FT_Outline_Embolden( FT_Outline* outline, FT_Pos str_h, FT_Pos str_v, FT_Int font_size); FT_Error Old_FT_Outline_Embolden( FT_Outline* outline, FT_Pos strength ); FT_Error Vert_FT_Outline_Embolden( FT_Outline* outline, FT_Pos strength ); ControlIder CID; #if _MSC_VER <= 1200 #pragma warning(disable: 4786) #endif //更新 #define RGBA(r,g,b,a) ((COLORREF)(((BYTE)(r)|((WORD)((BYTE)(g))<<8))|(((DWORD)(BYTE)(b))<<16)|(((DWORD)(BYTE)(a))<<24))) //!!Snowie COLORREF GetPaletteColor(HDC hdc, UINT paletteindex) { //if ((paletteindex>>28)%2) return 0; HPALETTE hpal=(HPALETTE)GetCurrentObject(hdc, OBJ_PAL); PALETTEENTRY lppe={}; memset(&lppe, 0, sizeof(lppe)); GetPaletteEntries(hpal, paletteindex&0xffff, 1, &lppe); return RGB(lppe.peRed, lppe.peGreen, lppe.peBlue); } void Log(char* Msg) { #ifndef _DEBUG return; #endif FILE* f=fopen(".\\gdipp.log","a"); fputs(Msg, f); fclose(f); } void Log(wchar_t* Msg) { #ifndef _DEBUG return; #endif FILE* f=_wfopen(L".\\gdipp.log",L"a,ccs=UNICODE"); fputws(Msg, f); fclose(f); } class CAlphaBlend { private: int alphatbl[256]; int tbl1[257]; BYTE tbl2[256 * 16 + 1]; // 通常のアルファ値補正 int tunetbl[256]; int tunetblR[256]; int tunetblG[256]; int tunetblB[256]; // 影文字用のアルファ値補正 int tunetblS[256]; int tunetblRS[256]; int tunetblGS[256]; int tunetblBS[256]; int tunetblLS[256]; int tunetblLRS[256]; int tunetblLGS[256]; int tunetblLBS[256]; //Snowie!! double RGB2CRT[256]; //table used for RGB<->Lab public: static const int BASE; public: CAlphaBlend() { } ~CAlphaBlend() {} void init(); void initRGB(); double* GetRGBTable() { return RGB2CRT; } BYTE doAB(BYTE fg, BYTE bg, int alpha); void gettunetbl(int paramalpha, BOOL lcd, BOOL dark, const int * &tblR, const int * &tblG, const int * &tblB) const; inline int conv1(BYTE n) { return tbl1[n]; } inline BYTE conv2(int n) { return tbl2[n / (BASE * BASE / (sizeof tbl2 - 1))]; } private: inline int convalpha(int alpha) { return alphatbl[alpha]; } inline BYTE rconv1(int n); }; const int CAlphaBlend::BASE = 0x4000; static CAlphaBlend s_AlphaBlendTable; void CAlphaBlend::gettunetbl(int paramalpha, BOOL lcd, BOOL dark, const int * &tblR, const int * &tblG, const int * &tblB) const { if (paramalpha == 1) { //获取文字混合表 if (lcd) { tblR = tunetblR; tblG = tunetblG; tblB = tunetblB; } else { tblR = tblG = tblB = tunetbl; } } else { //获取阴影混合表 if (dark) { if (lcd) { tblR = tunetblRS; tblG = tunetblGS; tblB = tunetblBS; } else { tblR = tblG = tblB = tunetblS; } } else { if (lcd) { tblR = tunetblLRS; tblG = tunetblLGS; tblB = tunetblLBS; } else { tblR = tblG = tblB = tunetblLS; } } } } void CAlphaBlend::initRGB() { for (int i=0; i<256; i++) RGB2CRT[i] = pow(i/255.0, 2.2); } void CAlphaBlend::init() { const CGdippSettings* pSettings = CGdippSettings::GetInstance(); const float gamma = pSettings->GammaValue(); const float weight = pSettings->RenderWeight(); const float contrast = pSettings->Contrast(); const int mode = pSettings->GammaMode(); int i; float temp, alpha; for (i = 0; i < 256; ++i) { temp = pow((1.0f / 255.0f) * i, 1.0f / weight); if (temp < 0.5f) { alpha = pow(temp * 2, contrast) / 2.0f; } else { alpha = 1.0f - pow((1.0f - temp) * 2, contrast) / 2.0f; } alphatbl[i] = (int)(alpha * BASE); if (mode < 0) { temp = (1.0f / 255.0f) * i; } else { if (mode == 1) { if (i <= 10) { temp = (float)i / (12.92f * 255.0f); } else { temp = pow(((1.0f / 255.0f) * i + 0.055f) / 1.055f, 2.4f); } } else if (mode == 2) { if (i <= 10) { temp = ((float)i / (12.92f * 255.0f) + (float)i / 255.0f) / 2; } else { temp = (pow(((1.0f / 255.0f) * i + 0.055f) / 1.055f, 2.4f) + (float)i / 255.0f) / 2; } } else { temp = pow((1.0f / 255.0f) * i, gamma); } } tbl1[i] = (int)(temp * BASE); } tbl1[i] = BASE; for (i = 0; i <= sizeof tbl2 - 1; ++i) { tbl2[i] = rconv1(i * (BASE / (sizeof tbl2 - 1))); } const int* table = pSettings->GetTuneTable(); const int* tableR = pSettings->GetTuneTableR(); const int* tableG = pSettings->GetTuneTableG(); const int* tableB = pSettings->GetTuneTableB(); const int* shadow = pSettings->GetShadowParams(); const int paramalpha = Max(shadow[2], 1); const int lightparamalpha = Max(shadow[3], 1); for (i = 0; i < 256; ++i) { tunetbl[i] = Bound(0, alphatbl[Bound(table[i], 0, 255)], CAlphaBlend::BASE); tunetblR[i] = Bound(0, alphatbl[Bound(tableR[i], 0, 255)], CAlphaBlend::BASE); tunetblG[i] = Bound(0, alphatbl[Bound(tableG[i], 0, 255)], CAlphaBlend::BASE); tunetblB[i] = Bound(0, alphatbl[Bound(tableB[i], 0, 255)], CAlphaBlend::BASE); tunetblS[i] = Bound(0, alphatbl[Bound(table[i] * paramalpha /100, 0, 255)], CAlphaBlend::BASE); tunetblRS[i] = Bound(0, alphatbl[Bound(tableR[i] * paramalpha/100, 0, 255)], CAlphaBlend::BASE); tunetblGS[i] = Bound(0, alphatbl[Bound(tableG[i] * paramalpha/100, 0, 255)], CAlphaBlend::BASE); tunetblBS[i] =Bound(0, alphatbl[Bound(tableB[i] * paramalpha/100, 0, 255)], CAlphaBlend::BASE); //浅色混合表 tunetblLS[i] = Bound(0, alphatbl[Bound(table[i] * lightparamalpha/100, 0, 255)], CAlphaBlend::BASE); tunetblLRS[i] = Bound(0, alphatbl[Bound(tableR[i] * lightparamalpha/100, 0, 255)], CAlphaBlend::BASE); tunetblLGS[i] = Bound(0, alphatbl[Bound(tableG[i] * lightparamalpha/100, 0, 255)], CAlphaBlend::BASE); tunetblLBS[i] =Bound(0, alphatbl[Bound(tableB[i] * lightparamalpha/100, 0, 255)], CAlphaBlend::BASE); //深色混合表 } } BYTE CAlphaBlend::rconv1(int n) { int pos = 0x80; int i = pos >> 1; while (i > 0) { if (n >= tbl1[pos]) { pos += i; } else { pos -= i; } i >>= 1; } if (n >= tbl1[pos]) { ++pos; } return (BYTE)(pos - 1); } class CAlphaBlendColorOne { private: BYTE fg; int temp_fg; const int *tunetbl; BYTE bg0; int alpha0; BYTE c0; public: CAlphaBlendColorOne() : fg(0), temp_fg(0), tunetbl(NULL), bg0(0), alpha0(0), c0(0) {} void init(BYTE f, const int *tbl); ~CAlphaBlendColorOne() {}; BYTE doAB(BYTE bg, int alpha); }; FORCEINLINE void CAlphaBlendColorOne::init(BYTE f, const int *tbl) { fg = f; temp_fg = s_AlphaBlendTable.conv1(fg); tunetbl = tbl; } FORCEINLINE BYTE CAlphaBlendColorOne::doAB(BYTE bg, int alpha) { int temp_alpha = tunetbl[alpha]; return temp_alpha ? s_AlphaBlendTable.conv2(s_AlphaBlendTable.conv1(bg) * (s_AlphaBlendTable.BASE - tunetbl[alpha]) + temp_fg * tunetbl[alpha]) : bg; } class CAlphaBlendColor { private: CAlphaBlendColorOne r; CAlphaBlendColorOne g; CAlphaBlendColorOne b; public: CAlphaBlendColor( COLORREF newColor, int paramalpha, BOOL lcd, BOOL dark, bool gbr = false); ~CAlphaBlendColor() { } BYTE doABsub(BYTE fg, int temp_fg, BYTE bg, int temp_alpha) const; COLORREF doAB(COLORREF baseColor, int alphaR, int alphaG, int alphaB, BOOL bClearAlpha); COLORREF doAB(COLORREF baseColor, int alpha, BOOL bClearAlpha) { return doAB(baseColor, alpha, alpha, alpha, bClearAlpha); } private: CAlphaBlendColor() { } }; FORCEINLINE CAlphaBlendColor::CAlphaBlendColor( COLORREF newColor, int paramalpha, BOOL lcd, BOOL dark, bool gbr) { const int *tblR; const int *tblG; const int *tblB; s_AlphaBlendTable.gettunetbl(paramalpha, lcd, dark, tblR, tblG, tblB); if (!gbr) { r.init(GetRValue(newColor), tblR); b.init(GetBValue(newColor), tblB); } else { r.init(GetBValue(newColor), tblB); b.init(GetRValue(newColor), tblR); } g.init(GetGValue(newColor), tblG); } FORCEINLINE COLORREF CAlphaBlendColor::doAB(COLORREF baseColor, int alphaR, int alphaG, int alphaB, BOOL bClearAlpha) { if (alphaB | alphaG | alphaR) { if (bClearAlpha) return RGB(r.doAB(GetRValue(baseColor), alphaR), g.doAB(GetGValue(baseColor), alphaG), b.doAB(GetBValue(baseColor), alphaB)); else return RGBA(r.doAB(GetRValue(baseColor), alphaR), g.doAB(GetGValue(baseColor), alphaG), b.doAB(GetBValue(baseColor), alphaB), baseColor>>24); } else return baseColor; } FORCEINLINE BYTE CAlphaBlend::doAB(BYTE fg, BYTE bg, int alpha) { if (fg == bg || alpha <= 0) return bg; if (alpha >= 255) return fg; int temp_alpha = convalpha(alpha); int temp_bg = conv1(bg); int temp_fg = conv1(fg); int temp = temp_bg * (BASE - temp_alpha) + temp_fg * temp_alpha; return conv2(temp); } FORCEINLINE BYTE DoAlphaBlend(BYTE fg, BYTE bg, int alpha) { return s_AlphaBlendTable.doAB(fg, bg, alpha); } // LCD(液晶)用のアルファブレンド(サブピクセルレンダリング) static FORCEINLINE COLORREF AlphaBlendColorLCD( COLORREF baseColor, COLORREF newColor, int alphaR, int alphaG, int alphaB, const int* tableR, const int* tableG, const int* tableB, const FreeTypeDrawInfo& ftdi) { const BYTE rs = GetRValue(baseColor); const BYTE gs = GetGValue(baseColor); const BYTE bs = GetBValue(baseColor); BYTE rd = GetRValue(newColor); BYTE gd = GetGValue(newColor); BYTE bd = GetBValue(newColor); // アルファ値を補正 alphaR = tableR[alphaR] / ftdi.params->alpha; alphaG = tableG[alphaG] / ftdi.params->alpha; alphaB = tableB[alphaB] / ftdi.params->alpha; // rd = (((rd - rs) * alphaR) / 255) + rs; // gd = (((gd - gs) * alphaG) / 255) + gs; // bd = (((bd - bs) * alphaB) / 255) + bs; rd = DoAlphaBlend(rd, rs, alphaR); gd = DoAlphaBlend(gd, gs, alphaG); bd = DoAlphaBlend(bd, bs, alphaB); return RGB(rd, gd, bd); } // アルファブレンド(256階調) static FORCEINLINE COLORREF AlphaBlendColor( COLORREF baseColor, COLORREF newColor, int alpha, const int* table, const FreeTypeDrawInfo& ftdi) { const BYTE rs = GetRValue(baseColor); const BYTE gs = GetGValue(baseColor); const BYTE bs = GetBValue(baseColor); BYTE rd = GetRValue(newColor); BYTE gd = GetGValue(newColor); BYTE bd = GetBValue(newColor); // アルファ値を補正 alpha = table[alpha] / ftdi.params->alpha; // rd = (rs * (255 - alpha) + rd * alpha) / 255; // gd = (gs * (255 - alpha) + gd * alpha) / 255; // bd = (bs * (255 - alpha) + bd * alpha) / 255; // rd = (((rd - rs) * alpha) / 255) + rs; // gd = (((gd - gs) * alpha) / 255) + gs; // bd = (((bd - bs) * alpha) / 255) + bs; rd = DoAlphaBlend(rd, rs, alpha); gd = DoAlphaBlend(gd, gs, alpha); bd = DoAlphaBlend(bd, bs, alpha); return RGB(rd, gd, bd); } typedef struct { FreeTypeDrawInfo* FTInfo; //orignal draw information WCHAR wch; //text to draw FT_BitmapGlyph FTGlyph; //glyph int AAMode; //antialiased mode for every char CAlphaBlendColor* solid; CAlphaBlendColor* shadow; //alpha blender } FreeTypeGlyphInfo, *PFreeTypeGlyphInfo; // 2階調 static void FreeTypeDrawBitmapPixelModeMono(FreeTypeGlyphInfo& FTGInfo, CAlphaBlendColor& ab, int x, int y) { CBitmapCache& cache = *FTGInfo.FTInfo->pCache; const FT_Bitmap *bitmap = &FTGInfo.FTGlyph->bitmap; BYTE alphatuner = FTGInfo.FTInfo->params->alphatuner; int i, j; int dx, dy; // display FT_Bytes p; if(bitmap->pixel_mode != FT_PIXEL_MODE_MONO){ return; } const COLORREF color = RGB2DIB(FTGInfo.FTInfo->Color()); const SIZE cachebufsize = cache.Size(); DWORD * const cachebufp = (DWORD *)cache.GetPixels(); DWORD * cachebufrowp; int left, top, width, height; if (x < 0) { left = -x; x = 0; } else { left = 0; } width = Min((int)bitmap->width, (int)(cachebufsize.cx - x)); top = 0; height = bitmap->rows; for(j = top, dy = y; j < height; ++j, ++dy){ if ((unsigned int)dy >= (unsigned int)cachebufsize.cy) continue; p = bitmap->pitch < 0 ? &bitmap->buffer[(-bitmap->pitch * bitmap->rows) - bitmap->pitch * j] : // up-flow &bitmap->buffer[bitmap->pitch * j]; // down-flow cachebufrowp = &cachebufp[dy * cachebufsize.cx]; for(i = left, dx = x; i < width; ++i, ++dx){ if((p[i / 8] & (1 << (7 - (i % 8)))) != 0){ cachebufrowp[dx] = color; } } } } // LCD(液晶)用描画(サブピクセルレンダリング) // RGB順(のはず) static void FreeTypeDrawBitmapPixelModeLCD(FreeTypeGlyphInfo& FTGInfo, CAlphaBlendColor& ab, int x, int y) { CBitmapCache& cache = *FTGInfo.FTInfo->pCache; const FT_Bitmap *bitmap = &FTGInfo.FTGlyph->bitmap; BYTE alphatuner = FTGInfo.FTInfo->params->alphatuner; int AAMode = FTGInfo.AAMode; int i, j; int dx, dy; // display FT_Bytes p; if(bitmap->pixel_mode != FT_PIXEL_MODE_LCD){ return; } const COLORREF color = FTGInfo.FTInfo->Color(); const SIZE cachebufsize = cache.Size(); DWORD * const cachebufp = (DWORD *)cache.GetPixels(); DWORD * cachebufrowp; // LCDは3サブピクセル分ある int left, top, width, height; if (x < 0) { left = -x * 3; x = 0; } else { left = 0; } width = Min((int)bitmap->width, (int)(cachebufsize.cx - x) * 3); top = 0; height = bitmap->rows; //CAlphaBlendColor ab(color, ftdi.params->alpha, true, true); COLORREF backColor, newColor; unsigned int alphaR, alphaG, alphaB; BOOL bAlphaDraw = FTGInfo.FTInfo->params->alpha!=1; if (bAlphaDraw) for(j = 0, dy = y; j < height; ++j, ++dy){ if ((unsigned int)dy >= (unsigned int)cachebufsize.cy) continue; p = bitmap->pitch < 0 ? &bitmap->buffer[(-bitmap->pitch * bitmap->rows) - bitmap->pitch * j] : // up-flow &bitmap->buffer[bitmap->pitch * j]; // down-flow cachebufrowp = &cachebufp[dy * cachebufsize.cx]; for(i = left, dx = x; i < width; i += 3, ++dx){ backColor = cachebufrowp[dx]; COLORREF last=0xFFFFFFFF; if(AAMode == 2 || AAMode == 4){ // これはRGBの順にサブピクセルがあるディスプレイ用 // これはRGBの順にサブピクセルがあるディスプレイ用 alphaR = p[i + 0] / alphatuner; alphaG = p[i + 1] / alphatuner; alphaB = p[i + 2] / alphatuner; }else{ // BGR alphaR = p[i + 2] / alphatuner; alphaG = p[i + 1] / alphatuner; alphaB = p[i + 0] / alphatuner; } /* if (bAlphaDraw) { if (alphaB && alphaG && alphaR) backColor &= 0x00ffffff; } else*/ //if ((alphaB || alphaG || alphaR)) // backColor &= 0x00ffffff; newColor = ab.doAB(backColor, alphaB, alphaG, alphaR, !bAlphaDraw); cachebufrowp[dx] = newColor; } } else for(j = 0, dy = y; j < height; ++j, ++dy){ if ((unsigned int)dy >= (unsigned int)cachebufsize.cy) continue; p = bitmap->pitch < 0 ? &bitmap->buffer[(-bitmap->pitch * bitmap->rows) - bitmap->pitch * j] : // up-flow &bitmap->buffer[bitmap->pitch * j]; // down-flow cachebufrowp = &cachebufp[dy * cachebufsize.cx]; for(i = left, dx = x; i < width; i += 3, ++dx){ backColor = cachebufrowp[dx]; COLORREF last=0xFFFFFFFF; if(AAMode == 2 || AAMode == 4){ // これはRGBの順にサブピクセルがあるディスプレイ用 // これはRGBの順にサブピクセルがあるディスプレイ用 alphaR = p[i + 0]; alphaG = p[i + 1]; alphaB = p[i + 2]; }else{ // BGR alphaR = p[i + 2]; alphaG = p[i + 1]; alphaB = p[i + 0]; } /* if (bAlphaDraw) { if (alphaB && alphaG && alphaR) backColor &= 0x00ffffff; } else*/ //if ((alphaB || alphaG || alphaR)) // backColor &= 0x00ffffff; newColor = ab.doAB(backColor, alphaB, alphaG, alphaR, !bAlphaDraw); cachebufrowp[dx] = newColor; } } } static void FreeTypeDrawBitmapGray(FreeTypeGlyphInfo& FTGInfo, CAlphaBlendColor& ab, int x, int y) { int i, j; int dx, dy; // display COLORREF c; FT_Bytes p; CBitmapCache& cache = *FTGInfo.FTInfo->pCache; const FT_Bitmap *bitmap = &FTGInfo.FTGlyph->bitmap; BYTE alphatuner = FTGInfo.FTInfo->params->alphatuner; BOOL bAlphaDraw = FTGInfo.FTInfo->params->alpha!=1; const COLORREF color = FTGInfo.FTInfo->Color(); const SIZE cachebufsize = cache.Size(); DWORD * const cachebufp = (DWORD *)cache.GetPixels(); DWORD * cachebufrowp; int left, top, width, height; if (x < 0) { left = -x; x = 0; } else { left = 0; } width = Min((int)bitmap->width, (int)(cachebufsize.cx - x)); top = 0; height = bitmap->rows; // CAlphaBlendColor ab(color, ftdi.params->alpha, false, true); COLORREF backColor; int alpha; for(j = top, dy = y; j < height; ++j, ++dy){ if ((unsigned int)dy >= (unsigned int)cachebufsize.cy) continue; p = bitmap->pitch < 0 ? &bitmap->buffer[(-bitmap->pitch * bitmap->rows) - bitmap->pitch * j] : // up-flow &bitmap->buffer[bitmap->pitch * j]; // down-flow cachebufrowp = &cachebufp[dy * cachebufsize.cx]; for(i = left, dx = x; i < width; ++i, ++dx){ alpha = p[i]; backColor = cachebufrowp[dx]; c = ab.doAB(backColor, alpha, !bAlphaDraw); cachebufrowp[dx] = c; } } } // グリフビットマップのレンダリング static void FreeTypeDrawBitmap( FreeTypeGlyphInfo& FTGInfo, CAlphaBlendColor& ab, int x, int y) { if(FTGInfo.FTGlyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY){ // この関数自体はFT_PIXEL_MODE_GRAYにのみ対応し他に委譲する switch(FTGInfo.FTGlyph->bitmap.pixel_mode){ case FT_PIXEL_MODE_MONO: FreeTypeDrawBitmapPixelModeMono(FTGInfo, ab, x, y); break; case FT_PIXEL_MODE_LCD: FreeTypeDrawBitmapPixelModeLCD(FTGInfo, ab, x, y); break; default: return; // 未対応 } return; } FreeTypeDrawBitmapGray(FTGInfo, ab, x, y); } // 縦書き用のレンダリング(コピペ手抜き) // 2階調 static void FreeTypeDrawBitmapPixelModeMonoV(FreeTypeGlyphInfo& FTGInfo, CAlphaBlendColor& ab, int x, int y) { CBitmapCache& cache = *FTGInfo.FTInfo->pCache; FT_Bitmap *bitmap = &FTGInfo.FTGlyph->bitmap; int i, j; int dx, dy; // display FT_Bytes p; if(bitmap->pixel_mode != FT_PIXEL_MODE_MONO){ return; } const COLORREF color = FTGInfo.FTInfo->Color(); const int width = bitmap->width; const int height = bitmap->rows; for(j = 0, dy = x; j < height; ++j, ++dy){ p = bitmap->pitch < 0 ? &bitmap->buffer[(-bitmap->pitch * bitmap->rows) - bitmap->pitch * j] : // up-flow &bitmap->buffer[bitmap->pitch * j]; // down-flow for(i = 0, dx = y+width; i < width; ++i, --dx){ if((p[i / 8] & (1 << (7 - (i % 8)))) != 0){ if (cache.GetPixel(dx, dy) != CLR_INVALID) { // dx dy エラーチェック cache.SetCurrentPixel(color); } } } } } // LCD(液晶)用描画(サブピクセルレンダリング) // RGB順(のはず) static void FreeTypeDrawBitmapPixelModeLCDV(FreeTypeGlyphInfo& FTGInfo, CAlphaBlendColor& ab, int x, int y) { CBitmapCache& cache = *FTGInfo.FTInfo->pCache; const FT_Bitmap *bitmap = &FTGInfo.FTGlyph->bitmap; BYTE alphatuner = FTGInfo.FTInfo->params->alphatuner; int AAMode = FTGInfo.AAMode; int i, j; int dx, dy; // display COLORREF c; FT_Bytes p; if(bitmap->pixel_mode != FT_PIXEL_MODE_LCD_V){ return; } const COLORREF color = FTGInfo.FTInfo->Color(); // LCDは3サブピクセル分ある const int width = bitmap->width; const int height = bitmap->rows; const int pitch = bitmap->pitch; const int pitchabs = pitch < 0 ? -pitch : pitch; BOOL bAlphaDraw = FTGInfo.FTInfo->params->alpha!=1; //CAlphaBlendColor ab(color, ftdi.params->alpha, true); if (bAlphaDraw) for(j = 0, dy = x; j < height; j += 3, ++dy){ p = pitch < 0 ? &bitmap->buffer[(pitchabs * bitmap->rows) + pitchabs * j] : // up-flow &bitmap->buffer[pitchabs * j]; // down-flow int alphaR, alphaG, alphaB; for(i = 0, dx = y+width; i < width; ++i, --dx){ COLORREF backColor = cache.GetPixel(dy, dx); if (backColor == color || backColor == CLR_INVALID) continue; if(AAMode == 2 || AAMode == 4){ // これはRGBの順にサブピクセルがあるディスプレイ用 alphaR = p[i + 0] / alphatuner; alphaG = p[i + pitch] / alphatuner; alphaB = p[i + pitch * 2] / alphatuner; }else{ // BGR alphaR = p[i + pitch * 2]/ alphatuner; alphaG = p[i + pitch]/ alphatuner; alphaB = p[i + 0]/ alphatuner; } c = ab.doAB(backColor, alphaR, alphaG, alphaB, !bAlphaDraw); cache.SetCurrentPixel(c); } if (i >= width) continue; } else for(j = 0, dy = x; j < height; j += 3, ++dy){ p = pitch < 0 ? &bitmap->buffer[(pitchabs * bitmap->rows) + pitchabs * j] : // up-flow &bitmap->buffer[pitchabs * j]; // down-flow int alphaR, alphaG, alphaB; for(i = 0, dx = y+width; i < width; ++i, --dx){ COLORREF backColor = cache.GetPixel(dy, dx); if (backColor == color || backColor == CLR_INVALID) continue; if(AAMode == 2 || AAMode == 4){ // これはRGBの順にサブピクセルがあるディスプレイ用 alphaR = p[i + 0]; alphaG = p[i + pitch]; alphaB = p[i + pitch * 2]; }else{ // BGR alphaR = p[i + pitch * 2]; alphaG = p[i + pitch]; alphaB = p[i + 0]; } c = ab.doAB(backColor, alphaR, alphaG, alphaB, !bAlphaDraw); cache.SetCurrentPixel(c); } if (i >= width) continue; } } void FreeTypeDrawBitmapGrayV(FreeTypeGlyphInfo& FTGInfo, CAlphaBlendColor& ab, int x, int y) { CBitmapCache& cache = *FTGInfo.FTInfo->pCache; const FT_Bitmap *bitmap = &FTGInfo.FTGlyph->bitmap; BYTE alphatuner = FTGInfo.FTInfo->params->alphatuner; int i, j; int dx, dy; // display int width, height; COLORREF c; FT_Bytes p; const COLORREF color = FTGInfo.FTInfo->Color(); //const CGdippSettings* pSettings = CGdippSettings::GetInstance(); //const int* table = pSettings->GetTuneTable(); width = bitmap->width; height = bitmap->rows; // CAlphaBlendColor ab(color, ftdi.params->alpha, false); for(j = 0, dy = x; j < height; ++j, ++dy){ p = bitmap->pitch < 0 ? &bitmap->buffer[(-bitmap->pitch * bitmap->rows) - bitmap->pitch * j] : // up-flow &bitmap->buffer[bitmap->pitch * j]; // down-flow for(i = 0, dx = y+width; i < width; ++i, --dx){ const COLORREF backColor = cache.GetPixel(dy, dx); if (backColor == color || backColor == CLR_INVALID) continue; c = ab.doAB(backColor, p[i], true); cache.SetPixelV(dy, dx, c); } } } static void FreeTypeDrawBitmapV(FreeTypeGlyphInfo& FTGInfo, CAlphaBlendColor& ab, const int x, const int y) { if(FTGInfo.FTGlyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY){ // この関数自体はFT_PIXEL_MODE_GRAYにのみ対応し他に委譲する switch(FTGInfo.FTGlyph->bitmap.pixel_mode){ case FT_PIXEL_MODE_MONO: FreeTypeDrawBitmapPixelModeMonoV(FTGInfo, ab, x, y); break; case FT_PIXEL_MODE_LCD_V: FreeTypeDrawBitmapPixelModeLCDV(FTGInfo, ab, x, y); break; default: return; // 未対応 } return; } } class CGGOGlyphLoader { private: FT_Library m_lib; const FT_Glyph_Class *m_clazz; BYTE bgtbl[0x41]; static int CALLBACK EnumFontFamProc(const LOGFONT* lplf, const TEXTMETRIC* lptm, DWORD FontType, LPARAM lParam); public: CGGOGlyphLoader() : m_lib(NULL), m_clazz(NULL) {} ~CGGOGlyphLoader() {} bool init(FT_Library freetype_library); FT_Library getlib() { return m_lib; } const FT_Glyph_Class * getclazz() { return m_clazz; } BYTE convbgpixel(BYTE val) { return bgtbl[val]; } }; static CGGOGlyphLoader s_GGOGlyphLoader; int CALLBACK CGGOGlyphLoader::EnumFontFamProc(const LOGFONT* lplf, const TEXTMETRIC* lptm, DWORD FontType, LPARAM lParam) { CGGOGlyphLoader* pThis = reinterpret_cast(lParam); if (FontType != TRUETYPE_FONTTYPE || lplf->lfCharSet == SYMBOL_CHARSET) { return TRUE; } TRACE(_T("Face: %s\n"), lplf->lfFaceName); FreeTypeSysFontData* pFont = FreeTypeSysFontData::CreateInstance(lplf->lfFaceName, 0, false); if (!pFont) { return TRUE; } const FT_Glyph_Class *clazz = NULL; FT_Face face = pFont->GetFace(); FT_Error err = FT_Set_Pixel_Sizes(face, 0, 12);//optimized if (!err) { err = FT_Load_Char(face, lptm->tmDefaultChar, FT_LOAD_NO_BITMAP); if (!err) { FT_Glyph glyph; err = FT_Get_Glyph(face->glyph, &glyph); if (!err) { if (glyph->format == FT_GLYPH_FORMAT_OUTLINE) { clazz = glyph->clazz; } FT_Done_Glyph(glyph); } } } FT_Done_Face(face); if (clazz) { pThis->m_clazz = clazz; //列挙中止 return FALSE; } return TRUE; } bool CGGOGlyphLoader::init(FT_Library freetype_library) { if (m_lib) { return true; } if (!freetype_library) { return false; } for (BYTE val = 0; val <= 0x40; ++val) { BYTE t = (BYTE)(((DWORD)val * 256) / 65); bgtbl[val] = t + (t >> 6); } m_lib = freetype_library; m_clazz = NULL; //前の方法だと、arial.ttfが無いとまずそうなので //適当に使えるアウトラインフォントを探す HDC hdc = CreateCompatibleDC(NULL); EnumFontFamilies(hdc, NULL, EnumFontFamProc, reinterpret_cast(this)); DeleteDC(hdc); if (m_clazz != NULL) { return true; } m_lib = NULL; return false; } class CGGOOutlineGlyph { private: FT_OutlineGlyph m_ptr; static FT_F26Dot6 toF26Dot6(const FIXED& fx) { return *(LONG *)(&fx) >> 10; } static FT_Fixed toFixed(const short n) { return (FT_Fixed)n << 16; } static char getTag(char tag, const FT_Vector& point) { if ((point.x & 0x0f) != 0) { tag |= FT_CURVE_TAG_TOUCH_X; } if ((point.y & 0x0f) != 0) { tag |= FT_CURVE_TAG_TOUCH_Y; } return tag; } public: CGGOOutlineGlyph() : m_ptr(NULL) { _ASSERTE(s_GGOGlyphLoader.getlib()); } ~CGGOOutlineGlyph() { done(); }; bool init(DWORD bufsize, PVOID bufp, const GLYPHMETRICS& gm); void done(); operator FT_Glyph () { return (FT_Glyph)m_ptr; } }; void CGGOOutlineGlyph::done() { if (m_ptr) { free(m_ptr->outline.points); free(m_ptr->outline.tags); free(m_ptr->outline.contours); } free(m_ptr); m_ptr = NULL; } bool CGGOOutlineGlyph::init(DWORD bufsize, PVOID bufp, const GLYPHMETRICS& gm) { done(); m_ptr = (FT_OutlineGlyph)calloc(1, sizeof *m_ptr); if (!m_ptr) { return false; } FT_GlyphRec& root = m_ptr->root; FT_Outline& outline = m_ptr->outline; root.library = s_GGOGlyphLoader.getlib(); root.clazz = s_GGOGlyphLoader.getclazz(); root.format = FT_GLYPH_FORMAT_OUTLINE; root.advance.x = toFixed(gm.gmCellIncX); root.advance.y = toFixed(gm.gmCellIncY); outline.n_contours = 0; outline.n_points = 0; outline.flags = 0; //FT_OUTLINE_HIGH_PRECISION; LPTTPOLYGONHEADER ttphp = (LPTTPOLYGONHEADER)bufp; LPTTPOLYGONHEADER ttphpend = (LPTTPOLYGONHEADER)((PBYTE)ttphp + bufsize); while (ttphp < ttphpend) { LPTTPOLYCURVE ttpcp = (LPTTPOLYCURVE)(ttphp + 1); LPTTPOLYCURVE ttpcpend = (LPTTPOLYCURVE)((PBYTE)ttphp + ttphp->cb); if ((PVOID)ttpcpend > (PVOID)ttphpend) { break; } ++outline.n_points; ++outline.n_contours; while (ttpcp < ttpcpend) { LPPOINTFX pfxp = &ttpcp->apfx[0]; outline.n_points += ttpcp->cpfx; ttpcp = (LPTTPOLYCURVE)(pfxp + ttpcp->cpfx); } ttphp = (LPTTPOLYGONHEADER)ttpcp; } if (ttphp != ttphpend) { return false; } outline.points = (FT_Vector *)calloc(outline.n_points, sizeof *outline.points); outline.tags = (char *)calloc(outline.n_points, sizeof *outline.tags); outline.contours = (short *)calloc(outline.n_contours, sizeof *outline.contours); if (!outline.points || !outline.tags || !outline.contours) { done(); return false; } short *cp = outline.contours; short ppos = 0; ttphp = (LPTTPOLYGONHEADER)bufp; while (ttphp < ttphpend) { LPTTPOLYCURVE ttpcp = (LPTTPOLYCURVE)(ttphp + 1); LPTTPOLYCURVE ttpcpend = (LPTTPOLYCURVE)((PBYTE)ttphp + ttphp->cb); LPPOINTFX pfxp0 = &ttpcp->apfx[0]; while (ttpcp < ttpcpend) { LPPOINTFX pfxp = &ttpcp->apfx[0]; pfxp0 = pfxp + (ttpcp->cpfx - 1); ttpcp = (LPTTPOLYCURVE)(pfxp + ttpcp->cpfx); } ttpcp = (LPTTPOLYCURVE)(ttphp + 1); if (pfxp0->x.value != ttphp->pfxStart.x.value || pfxp0->x.fract != ttphp->pfxStart.x.fract || pfxp0->y.value != ttphp->pfxStart.y.value || pfxp0->y.fract != ttphp->pfxStart.y.fract) { outline.points[ppos].x = toF26Dot6(ttphp->pfxStart.x); outline.points[ppos].y = toF26Dot6(ttphp->pfxStart.y); outline.tags[ppos] = getTag(FT_CURVE_TAG_ON, outline.points[ppos]); ++ppos; } while (ttpcp < ttpcpend) { char tag; switch (ttpcp->wType) { case TT_PRIM_LINE: tag = FT_CURVE_TAG_ON; break; case TT_PRIM_QSPLINE: tag = FT_CURVE_TAG_CONIC; break; case TT_PRIM_CSPLINE: tag = FT_CURVE_TAG_CONIC; break; default: tag = 0; } LPPOINTFX pfxp = &ttpcp->apfx[0]; for (WORD cnt = 0; cnt < ttpcp->cpfx; ++cnt) { outline.points[ppos].x = toF26Dot6(pfxp->x); outline.points[ppos].y = toF26Dot6(pfxp->y); outline.tags[ppos] = tag; ++ppos; ++pfxp; } outline.tags[ppos - 1] = getTag(FT_CURVE_TAG_ON, outline.points[ppos - 1]); ttpcp = (LPTTPOLYCURVE)pfxp; } *cp++ = ppos - 1; ttphp = (LPTTPOLYGONHEADER)ttpcp; } outline.n_points = ppos; return true; } template class CTempMem { private: char m_localbuf[0x0f80]; DWORD m_size; T m_ptr; public: CTempMem() : m_size(sizeof m_localbuf), m_ptr((T)m_localbuf) { } ~CTempMem() { done(); } T init(DWORD size) { done(); if (m_size > size) { m_size = size; m_ptr = (T)malloc(m_size); } return m_ptr; } void done() { if (m_ptr != (T)m_localbuf) { free(m_ptr); } m_size = sizeof m_localbuf; m_ptr = (T)m_localbuf; } operator T () { return m_ptr; } bool operator ! () { return !m_ptr; } DWORD getsize() { return m_size; } }; BOOL FreeTypePrepare(FreeTypeDrawInfo& FTInfo) { //CDebugElapsedCounter cntr("FreeTypePrepare"); #ifdef _DEBUG FTInfo.Validate(); #endif FT_Face& freetype_face = FTInfo.freetype_face; FT_Int& cmap_index = FTInfo.cmap_index; FT_Render_Mode& render_mode = FTInfo.render_mode; FTC_ImageTypeRec& font_type = FTInfo.font_type; FreeTypeFontInfo*& pfi = FTInfo.pfi; const CFontSettings*& pfs = FTInfo.pfs; FreeTypeFontCache*& pftCache = FTInfo.pftCache; FTC_ScalerRec& scaler = FTInfo.scaler; TEXTMETRIC& tm = FTInfo.params->otm->otmTextMetrics; FTC_FaceID face_id = NULL; int height = 0; const LOGFONTW& lf = FTInfo.LogFont(); render_mode = FT_RENDER_MODE_NORMAL; if (FTInfo.params->alpha < 1) FTInfo.params->alpha = 1; if (lf.lfFaceName == NULL) return FALSE; //optimized FTInfo.face_id_list_num = 0; //Assert(_tcsicmp(lf.lfFaceName, _T("@Arial Unicode MS")) != 0); pfi = NULL; CGdippSettings* pSettings = CGdippSettings::GetInstance(); const bool bVertical = pSettings->FontLoader()==SETTING_FONTLOADER_FREETYPE? lf.lfFaceName[0] == _T('@'):false; FreeTypeFontInfo* pfitemp = g_pFTEngine->FindFont(FTInfo.params); if (pfitemp) { if (!pfi) pfi = pfitemp; FTInfo.face_id_list_num = pfi->GetFTLink(&FTInfo.face_id_list); pfi->GetGGOLink(&FTInfo.ggo_font_list); FTInfo.face_id_simsun = pfi->GetSimSunID(); } if (!(freetype_face = FTInfo.GetFace(0))) { pSettings->AddFontExclude(lf.lfFaceName); return FALSE; } if (!pfi) { return FALSE; } FTInfo.params->lplf->lfWeight = FTInfo.params->otm->otmTextMetrics.tmWeight; //更新到标准weight pfs = &pfi->GetFontSettings(); cmap_index = -1; switch (pSettings->FontLoader()) { case SETTING_FONTLOADER_FREETYPE: { face_id = (FTC_FaceID)pfi->GetId(); scaler.face_id = face_id; height = FTInfo.params->otm->otmTextMetrics.tmHeight - FTInfo.params->otm->otmTextMetrics.tmInternalLeading; //Snowie!!剪掉空白高度,bugfix。 // if(lf.lfHeight > 0){ // scaler.height = height; // } // else{ scaler.height = height; // } //Snowie!! TT_OS2* os2_table = pfitemp->GetOS2Table(); if (lf.lfQuality && os2_table->xAvgCharWidth) { if (!(freetype_face->style_flags & FT_STYLE_FLAG_BOLD) && tm.tmWeight>= FW_BOLD) --FTInfo.params->otm->otmTextMetrics.tmAveCharWidth; scaler.width = MulDiv(FTInfo.params->otm->otmTextMetrics.tmAveCharWidth, FTInfo.params->otm->otmEMSquare, os2_table->xAvgCharWidth); } else scaler.width = scaler.height; if (bVertical) swap(scaler.width, scaler.height);//如果是竖向字体,交换宽高 //!!Snowie scaler.pixel = 1; scaler.x_res = 0; scaler.y_res = 0; /* FT_Size font_size; { CCriticalSectionLock __lock(CCriticalSectionLock::CS_MANAGER); if(FTC_Manager_LookupSize(cache_man, &scaler, &font_size)) return FALSE; }*/ height = scaler.height; break; } case SETTING_FONTLOADER_WIN32: { /* OUTLINETEXTMETRIC otm; if (GetOutlineTextMetrics(FTInfo.hdc, sizeof otm, &otm) != sizeof otm) { return FALSE; }*/ height = -lf.lfHeight; scaler.height = height; scaler.width = lf.lfWidth; } break; default: return FALSE; } // if (!(freetype_face = FTInfo.GetFace(0))) // { // pSettings->AddFontExclude(lf.lfFaceName); // return FALSE; // } pftCache = pfi->GetCache(scaler, lf); if(!pftCache) return FALSE; /*FT_Size_RequestRec size_request; size_request.width = lf.lfWidth; size_request.horiResolution = 0; size_request.vertResolution = 0; if(lf.lfHeight > 0){ // セル高さ size_request.type = FT_SIZE_REQUEST_TYPE_CELL; size_request.height = lf.lfHeight * 64; } else{ // 文字高さ size_request.type = FT_SIZE_REQUEST_TYPE_NOMINAL; size_request.height = (-lf.lfHeight) * 64; } if(FT_Request_Size(freetype_face, &size_request)) goto Exit2;*/ switch (pSettings->FontLoader()) { case SETTING_FONTLOADER_FREETYPE: // font_typeを設定 font_type.face_id = face_id; font_type.width = scaler.width;//freetype_face->size->metrics.x_ppem; font_type.height = scaler.height;//freetype_face->size->metrics.y_ppem; //Snowie!! FTInfo.height = font_type.height; FTInfo.width = font_type.width; /* ビットマップまでキャッシュする場合はFT_LOAD_RENDER | FT_LOAD_TARGET_* * とする。ただし途中でTARGETを変更した場合等はキャッシュが邪魔する。 * そういう時はFT_LOAD_DEFAULTにしてFTC_ImageCache_Lookup後に * FT_Glyph_To_Bitmapしたほうが都合がいいと思う。 */ // Boldは太り具合というものがあるので本当はこれだけでは足りない気がする。 /*if(IsFontBold(lf) && !(freetype_face->style_flags & FT_STYLE_FLAG_BOLD) || lf.lfItalic && !(freetype_face->style_flags & FT_STYLE_FLAG_ITALIC)){ // ボールド、イタリックは後でレンダリングする // 多少速度は劣化するだろうけど仕方ない。 font_type.flags = FT_LOAD_NO_BITMAP; } else{ font_type.flags = FT_LOAD_RENDER | FT_LOAD_NO_BITMAP; }*/ break; case SETTING_FONTLOADER_WIN32: font_type.face_id = face_id; font_type.width = -1; font_type.height = -1; break; DEFAULT_UNREACHABLE; } font_type.flags = FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH; // ヒンティング switch (pfs->GetHintingMode()) { case 0: // ignore. break; case 1: font_type.flags |= FT_LOAD_NO_HINTING; break; case 2: font_type.flags |= FT_LOAD_FORCE_AUTOHINT; break; } //如果含有内置hinting则启用default模式,否则使用autohint模式,以保证效果 // アンチエイリアス if (FTInfo.IsMono()) { font_type.flags |= FT_LOAD_TARGET_MONO; render_mode = FT_RENDER_MODE_MONO; } else { switch (pfs->GetAntiAliasMode()) { case -1: font_type.flags |= FT_LOAD_TARGET_MONO; render_mode = FT_RENDER_MODE_MONO; break; case 0: font_type.flags |= FT_LOAD_TARGET_NORMAL; render_mode = FT_RENDER_MODE_NORMAL; break; case 1: font_type.flags |= FT_LOAD_TARGET_LIGHT; render_mode = FT_RENDER_MODE_LIGHT; break; case 2: case 3: font_type.flags |= FT_LOAD_TARGET_LCD; render_mode = FT_RENDER_MODE_LCD; break; case 4: case 5: font_type.flags |= FT_LOAD_TARGET_LIGHT; render_mode = FT_RENDER_MODE_LCD; break; } } if (pSettings->HintSmallFont() && font_type.flags & FT_LOAD_TARGET_LIGHT && font_type.height!=-1 && font_type.height<12) //通用设置不使用hinting,但是打开了小字体hinting开关 { /* if (!(freetype_face->face_flags & FT_FACE_FLAG_TRICKY)) //如果不是tricky字体 font_type.flags = font_type.flags & (~FT_LOAD_NO_HINTING) | (pfi->FontHasHinting() ? FT_LOAD_NO_AUTOHINT : FT_LOAD_FORCE_AUTOHINT); else*/ font_type.flags = font_type.flags & (~FT_LOAD_NO_HINTING)/* | (pfi->FontHasHinting() ? FT_LOAD_DEFAULT : FT_LOAD_FORCE_AUTOHINT)*/; } FTInfo.useKerning = FALSE; if (pfs->GetKerning()) { switch (pSettings->FontLoader()) { case SETTING_FONTLOADER_FREETYPE: FTInfo.useKerning = !!FT_HAS_KERNING(freetype_face); break; case SETTING_FONTLOADER_WIN32: { DWORD rc = GetFontLanguageInfo(FTInfo.hdc); if (rc != GCP_ERROR) { FTInfo.useKerning = !!(rc & GCP_USEKERNING); FTInfo.ggokerning.init(FTInfo.hdc); } } break; DEFAULT_UNREACHABLE; } } return TRUE; } // 縦にするやつはtrue(ASCIIと半角カナはfalse) inline bool IsVerticalChar(WCHAR wch){ if(wch < 0x80) return false; if(0xFF61 <= wch && wch <= 0xFF9F) return false; // 本当はもっと真面目にやらないとまずいが。 return true; } struct CGGOFont { HDC m_hdc; HFONT m_hfont; HFONT m_hprevfont; CGGOFont(HDC hdc, const LOGFONT& olf) : m_hdc(hdc), m_hfont(NULL), m_hprevfont(NULL) { LOGFONT lf = olf; lf.lfWeight = FW_REGULAR; lf.lfItalic = FALSE; lf.lfStrikeOut = FALSE; m_hfont = CreateFontIndirect(&lf); } ~CGGOFont() { if (m_hprevfont) { SelectFont(m_hdc, m_hprevfont); } DeleteFont(m_hfont); } void change() { m_hprevfont = SelectFont(m_hdc, m_hfont); } void restore() { SelectFont(m_hdc, m_hprevfont); m_hprevfont = NULL; } operator HFONT () { return m_hfont; } }; class ClpDx { private: const INT *p; const INT step; public: ClpDx(const INT *lpDx, UINT etoOptions) : p(lpDx), step((etoOptions & ETO_PDY) ? 2 : 1) { } ~ClpDx() { } int get(int val) { int result; if (p) { result = *p; p += step; } else { result = val; } return result; } }; /* FT_UInt FTC_CMapCache_Lookup2( FTC_CMapCache cache, FTC_FaceID face_id, FT_Int cmap_index, FT_UInt32 char_code, FT_Face freetype_face) { if ((int)face_id >= charmapCacheSize) { int oldsize = charmapCacheSize; charmapCacheSize = ((int)face_id / 100 + 1)*100; g_charmapCache = (FT_Int*)realloc(g_charmapCache, charmapCacheSize*sizeof(FT_Int)); memset(&g_charmapCache[oldsize], 0xff, (charmapCacheSize-oldsize)*sizeof(FT_Int)); } if (g_charmapCache[(int)face_id]==-1) if (!FTC_Manager_LookupFace(cache_man, face_id, &freetype_face)) { g_charmapCache[(int)face_id] = FT_Get_Charmap_Index(freetype_face->charmap); cmap_index = g_charmapCache[(int)face_id]; } else cmap_index = 0; return FTC_CMapCache_Lookup(cache, face_id, cmap_index, char_code); }*/ BOOL ForEachGetGlyphFT(FreeTypeDrawInfo& FTInfo, LPCTSTR lpString, int cbString, FT_Glyph* GlyphArray, FT_DRAW_STATE* drState) { const CGdippSettings* pSettings = CGdippSettings::GetInstance(); //Snowie!! BOOL bIsSymbol = GetTextCharsetInfo(FTInfo.hdc, NULL, 0) == SYMBOL_CHARSET; BOOL bAllowDefaultLink = pSettings->GetFontLinkInfo().IsAllowFontLink((BYTE)GetTextCharsetInfo(FTInfo.hdc, NULL, 0)); //是否为符号 BOOL nRet = true; BOOL bWindowsLink = pSettings->FontLink()==2; //!!Snowie /*const*/ FT_Face freetype_face = FTInfo.freetype_face; //去掉常量属性,下面要改他 const FT_Int cmap_index = FTInfo.cmap_index; const FT_Bool useKerning = FTInfo.useKerning; FT_Render_Mode render_mode = FTInfo.render_mode; const int LinkNum = FTInfo.face_id_list_num; int AAMode = FTInfo.pfs->GetAntiAliasMode(); int* AAList = FTInfo.AAModes; const LOGFONTW& lf = FTInfo.LogFont(); FreeTypeFontCache* pftCache = FTInfo.pftCache; const CFontSettings*& pfs = FTInfo.pfs; FreeTypeFontInfo*& pfi = FTInfo.pfi; const bool bGlyphIndex = FTInfo.IsGlyphIndex(); //const bool bSizeOnly = FTInfo.IsSizeOnly(); //const bool bOwnCache = !(FTInfo.font_type.flags & FT_LOAD_RENDER); const LPCTSTR lpStart = lpString; const LPCTSTR lpEnd = lpString + cbString; FT_UInt previous = 0; WCHAR previouswch = 0; const bool bVertical = lf.lfFaceName[0] == _T('@'); bool bLcdMode = render_mode == FT_RENDER_MODE_LCD; bool bLightLcdMode = (AAMode == 4) || (AAMode == 5); ClpDx clpdx(FTInfo.lpDx, FTInfo.params->etoOptions); const bool bWidthGDI32 = true; const int ggoformatbase = (FTInfo.font_type.flags & FT_LOAD_NO_HINTING) ? GGO_UNHINTED | GGO_NATIVE : GGO_NATIVE; if (!s_GGOGlyphLoader.init(freetype_library)) { return FALSE; } WORD * gi = new WORD[cbString]; WORD * ggi=gi; //Snowie!! //Fast fontlink WORD ** lpfontlink = NULL; HFONT hOldFont = NULL; if (!bGlyphIndex && bWindowsLink) //使用Windows fontlink { lpfontlink = (WORD**)new LPVOID[FTInfo.face_id_list_num]; for (int i=0;i 1) FTInfo.face_id_list_num--; //如果是symbol页那就不链接到宋体 bool bUnicodePlane = false; for (int i=0 ; lpString < lpEnd; ++lpString, ++gi, ++GlyphArray, ++drState, ++AAList, /*ggdi32++,*/ i++){ if (bUnicodePlane) { *drState = FT_DRAW_NOTFOUND; bUnicodePlane = false; clpdx.get(0); FTInfo.px = FTInfo.x; goto cont; } WCHAR wch = *lpString; if (!bGlyphIndex && bIsSymbol && !bWindowsLink) wch |= 0xF000; FT_Glyph* glyph_bitmap = GlyphArray; int gdi32x = 0;// = *ggdi32; FTInfo.font_type.face_id = FTInfo.face_id_list[0]; FreeTypeCharData* chData = NULL; FT_UInt glyph_index = 0; BOOL bIsBold = false, bIsIndivBold = false; { chData = bGlyphIndex ? pftCache->FindGlyphIndex(wch) : pftCache->FindChar(wch); if (chData/* && FTInfo.width==chData->GetWidth()*/) { gdi32x = chData->GetGDIWidth(); *AAList = chData->GetAAMode(); CCriticalSectionLock __lock(CCriticalSectionLock::CS_LIBRARY); FT_Glyph_Copy((FT_Glyph)chData->GetGlyph(render_mode), glyph_bitmap); //TRACE(_T("Cache Hit: %wc, size:%d, 0x%8.8X\n"), wch, chData->GetWidth(), glyph_bitmap); } } if (!*glyph_bitmap) { FT_Glyph glyph = NULL; bool f_glyph = false; //GLYPHMETRICS gm; const MAT2 mat2 = {{0, 1}, {0, 0}, {0, 0}, {0, 1}}; UINT ggoformat = ggoformatbase; CTempMem ggobuf; DWORD outlinesize = 0; if (bGlyphIndex) { f_glyph = !!wch; glyph_index = wch; *AAList = AAMode; GetCharWidthI(FTInfo.hdc, wch, 1, (LPWORD)&wch, &gdi32x); //index的文字必须计算宽度 if (FTInfo.font_type.height<=pSettings->BitmapHeight() && pfi->EmbeddedBmpExist(FTInfo.font_type.height)) { f_glyph=false; //使用点阵,不绘图 *drState=FT_DRAW_EMBEDDED_BITMAP; //设置为点阵绘图方式 } } else if (wch && !CID.myiswcntrl(lpString[0])) { for (int j = 0; j < FTInfo.face_id_list_num; ++j) { if (bWindowsLink) //使用Windows函数进行fontlink { if (!lpfontlink[j][i]) //还没初始化该字体的fontlink { SelectFont(FTInfo.hdc, FTInfo.ggo_font_list[j]); //加载ggo字体 GetGlyphIndices(FTInfo.hdc, lpString, cbString-i, &lpfontlink[j][i], GGI_MARK_NONEXISTING_GLYPHS); //进行fontlink SelectFont(FTInfo.hdc, hOldFont); } glyph_index = lpfontlink[j][i]; if (glyph_index==0xffff) glyph_index = 0; } else //使用freetype进行fontlink { CCriticalSectionLock __lock(CCriticalSectionLock::CS_MANAGER); glyph_index = FTC_CMapCache_Lookup(cmap_cache,FTInfo.face_id_list[j],-1,wch); } if (glyph_index) { GetCharWidth32W(FTInfo.hdc, wch, wch, &gdi32x); //有效文字,计算宽度 f_glyph = true; FTInfo.font_type.face_id = FTInfo.face_id_list[j]; freetype_face = FTInfo.GetFace(j); //同时更新对应faceid的实际face //接下来更新对应的fontsetting FTInfo.font_type.flags = FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH; // ヒンティング //extern CFontSetCache g_fsetcache; //pfs = g_fsetcache.Get(FTInfo.font_type.face_id); if (FTInfo.font_type.face_id==FTInfo.face_id_simsun && j>0) { switch (FTInfo.font_type.height) { case 11:{FTInfo.font_type.height=12; FTInfo.font_type.width++; break;} //对宋体进行特殊处理 case 13:{FTInfo.font_type.height=15; FTInfo.font_type.width+=2; break;} } } pfi = g_pFTEngine->FindFont((int)FTInfo.font_type.face_id); if (pfi) { pfs = &pfi->GetFontSettings(); switch (pfs->GetHintingMode()) { case 0: // ignore. break; case 1: FTInfo.font_type.flags |= FT_LOAD_NO_HINTING; break; case 2: FTInfo.font_type.flags |= FT_LOAD_FORCE_AUTOHINT; break; } // アンチエイリアス if (FTInfo.IsMono()) { FTInfo.font_type.flags |= FT_LOAD_TARGET_MONO; render_mode = FT_RENDER_MODE_MONO; } else { switch (*AAList = pfs->GetAntiAliasMode()) { case -1: FTInfo.font_type.flags |= FT_LOAD_TARGET_MONO; render_mode = FT_RENDER_MODE_MONO; break; case 0: FTInfo.font_type.flags |= FT_LOAD_TARGET_NORMAL; render_mode = FT_RENDER_MODE_NORMAL; break; case 1: FTInfo.font_type.flags |= FT_LOAD_TARGET_LIGHT; render_mode = FT_RENDER_MODE_LIGHT; break; case 2: case 3: FTInfo.font_type.flags |= FT_LOAD_TARGET_LCD; render_mode = FT_RENDER_MODE_LCD; break; case 4: case 5: FTInfo.font_type.flags |= FT_LOAD_TARGET_LIGHT; render_mode = FT_RENDER_MODE_LCD; break; } } if (pSettings->HintSmallFont() && FTInfo.font_type.flags & FT_LOAD_TARGET_LIGHT && FTInfo.font_type.height!=-1 && FTInfo.font_type.height<12) //通用设置不使用hinting,但是打开了小字体hinting开关 FTInfo.font_type.flags = FTInfo.font_type.flags & (~FT_LOAD_NO_HINTING)/* | (pfi->FontHasHinting() ? FT_LOAD_DEFAULT : FT_LOAD_FORCE_AUTOHINT)*/; AAMode = *AAList/*pfs->GetAntiAliasMode()*/; bLcdMode = render_mode == FT_RENDER_MODE_LCD; bLightLcdMode = (AAMode == 4) || (AAMode == 5); //更新完成 } if (FTInfo.font_type.height<=pSettings->BitmapHeight() && pfi->EmbeddedBmpExist(FTInfo.font_type.height)) { f_glyph=false; //使用点阵,不绘图 *drState=FT_DRAW_EMBEDDED_BITMAP; //设置为点阵绘图方式 } break; } } } if (!f_glyph) { //glyphindex的文字上面已经计算过了 #ifdef _DEBUG GdiSetBatchLimit(0); #endif if (*drState==FT_DRAW_NORMAL || bGlyphIndex) *drState = FT_DRAW_NOTFOUND; //找不到文字 if ((!FTInfo.lpDx || lpString == lpEnd - 1) && !bGlyphIndex) //无效文字,而且没有事先排版或者是排版的最后一个字符了 { GetCharWidth32W(FTInfo.hdc, wch, wch, &gdi32x); } int cx = gdi32x; /* if (bSizeOnly) { FTInfo.x += cx; } else*/ { if (wch) { *glyph_bitmap = NULL; //无效文字 //ORIG_ExtTextOutW(FTInfo.hdc, FTInfo.x, FTInfo.yTop, FTInfo.GetETO(), NULL, &wch, 1, NULL); } BOOL isc = bGlyphIndex ? false : (CID.myiswcntrl(*lpString)); if (isc == CNTRL_UNICODE_PLANE) bUnicodePlane = true; // else // if (isc == CNTRL_ZERO_WIDTH) //预计算的无宽度控制字 // cx = 0; int dxWidth = clpdx.get(cx); if (isc == CNTRL_COMPLEX_TEXT) //控制字 { cx = dxWidth; //服从windows的宽度调度 //if (!dxWidth) // CID.setcntrlAttribute(wch, CNTRL_ZERO_WIDTH); } if (lpString < lpEnd - 1) { FTInfo.x += dxWidth; } else { //if (gdi32x) //{ /* ABC abc = {0, cx, 0}; if (bGlyphIndex) GetCharABCWidthsI(FTInfo.hdc, wch, 1, NULL, &abc); else GetCharABCWidths(FTInfo.hdc, wch, wch, &abc);*/ //FTInfo.px = FTInfo.x+Max(clpdx.get(cx), abc.abcA+(int)abc.abcB+abc.abcC); //无效文字的情况下,绘图宽度=鼠标位置 FTInfo.px = FTInfo.x + cx; FTInfo.x += dxWidth;//Max(clpdx.get(cx), cx);/*(int)abc.abcB+abc.abcC*///Max(clpdx.get(cx), abc.abcB? abc.abcA:0); //} } if (!isc) FTInfo.x += FTInfo.params->charExtra; } goto cont; } // 縦書き if(bVertical){ glyph_index = ft2vert_get_gid( (struct ft2vert_st *)freetype_face->generic.data, glyph_index); } // カーニング if(useKerning){ if(previous != 0 && glyph_index){ FT_Vector delta; FT_Get_Kerning(freetype_face, previous, glyph_index, ft_kerning_default, &delta); FTInfo.x += FT_PosToInt(delta.x); } previous = glyph_index; } // 縦横 if(bVertical && IsVerticalChar(wch)){ FTInfo.font_type.flags |= FT_LOAD_VERTICAL_LAYOUT; if(bLcdMode){ if(!bLightLcdMode){ FTInfo.font_type.flags &= ~FT_LOAD_TARGET_LCD; FTInfo.font_type.flags |= FT_LOAD_TARGET_LCD_V; } render_mode = FT_RENDER_MODE_LCD_V; } }else{ if (bVertical) swap(FTInfo.font_type.height, FTInfo.font_type.width); //交换无法旋转的文字宽高 FTInfo.font_type.flags &=~FT_LOAD_VERTICAL_LAYOUT; if(bLcdMode){ if(!bLightLcdMode){ FTInfo.font_type.flags &= ~FT_LOAD_TARGET_LCD_V; FTInfo.font_type.flags |= FT_LOAD_TARGET_LCD; } render_mode = FT_RENDER_MODE_LCD; } } { bool bRequiredownsize; bIsIndivBold = freetype_face->style_flags & FT_STYLE_FLAG_BOLD; //是独立粗体 bIsBold = (IsFontBold(lf) && !bIsIndivBold); //是仿粗体 bRequiredownsize = bIsBold && /*(pSettings->BolderMode()==2 || (*/pSettings->BolderMode()!=1 /*&& FTInfo.height>FT_BOLD_LOW))*/; if (bRequiredownsize) { FTInfo.font_type.width -= (FTInfo.font_type.width)/36; FTInfo.font_type.height -= (FTInfo.font_type.height)/36; } { CCriticalSectionLock __lock(CCriticalSectionLock::CS_MANAGER); if(FTC_ImageCache_Lookup( image_cache, &FTInfo.font_type, glyph_index, &glyph, NULL)) { nRet= false; goto gdiexit; } //glyph = New_FT_Glyph(); } FTInfo.font_type.height = FTInfo.height; FTInfo.font_type.width = FTInfo.width; } { CCriticalSectionLock __lock(CCriticalSectionLock::CS_LIBRARY); if (FT_Glyph_Copy(glyph, glyph_bitmap)) { //FT_Done_Glyph(glyph); nRet = FALSE; goto gdiexit; } //FT_Done_Glyph(glyph); } if((*glyph_bitmap)->format != FT_GLYPH_FORMAT_BITMAP){ int str_h; int str_v; bool fbold = false; str_h = str_v = FTInfo.pfi->CalcNormalWeight(); if (bIsIndivBold) str_h = str_v = FTInfo.pfi->GetExactBoldWeight()<<2; if (bIsBold) { fbold = true; str_h += FTInfo.font_type.height<24 ? FTInfo.pfi->GetFTWeight(): (FTInfo.pfi->GetFTWeight()*FTInfo.font_type.height/24); str_v = str_h; } if((str_h || str_v) && New_FT_Outline_Embolden( &((FT_OutlineGlyph)(*glyph_bitmap))->outline, str_h, str_v, FTInfo.height)) { FT_Done_Glyph(*glyph_bitmap); nRet= false; goto gdiexit; } if (fbold) { ((FT_BitmapGlyph)(*glyph_bitmap))->root.advance.x += 0x10000; } if(lf.lfItalic && !(freetype_face->style_flags & FT_STYLE_FLAG_ITALIC)){ FT_Matrix matrix; FTInfo.pfi->CalcItalicSlant(matrix); FT_Outline_Transform( &((FT_OutlineGlyph)((*glyph_bitmap)))->outline, &matrix); } { CCriticalSectionLock __lock(CCriticalSectionLock::CS_LIBRARY); if(FT_Glyph_To_Bitmap(&((*glyph_bitmap)), render_mode, 0, 1)){ FT_Done_Glyph(*glyph_bitmap); nRet= false; goto gdiexit; } } } } int cx = (bVertical && IsVerticalChar(wch)) ? FT_FixedToInt(FT_BitmapGlyph((*glyph_bitmap))->root.advance.y) : FT_FixedToInt(FT_BitmapGlyph((*glyph_bitmap))->root.advance.x); { int dx = clpdx.get(bWidthGDI32 ? gdi32x : cx); //获得宽度 int left = FT_BitmapGlyph((*glyph_bitmap))->left; if (FTInfo.x + left< FTInfo.xBase) FTInfo.xBase = FTInfo.x + left; //如果有字符是负数起始位置的(合成符号), 调整文字的起始位置 if (lpString < lpEnd - 1) { FTInfo.x += dx; } else { int bx = FT_BitmapGlyph((*glyph_bitmap))->bitmap.width; if (render_mode == FT_RENDER_MODE_LCD) bx /= 3; bx += left; FTInfo.px = FTInfo.x + Max(Max(dx, bx), cx); //有文字的情况下,绘图宽度=ft计算的宽度,鼠标位置=win宽度 FTInfo.x += dx;//Max(dx, gdi32x);//Max(Max(dx, bx), cx); } } FTInfo.x += FTInfo.params->charExtra; //if (bSizeOnly || bOwnCache) { //キャッシュ化 if (glyph_index) { if (bGlyphIndex) { pftCache->AddGlyphData(glyph_index, /*cx*/FTInfo.width, gdi32x, (FT_BitmapGlyph)*glyph_bitmap, render_mode, AAMode); } else { pftCache->AddCharData(wch, glyph_index, /*cx*/FTInfo.width, gdi32x, (FT_BitmapGlyph)*glyph_bitmap, render_mode, AAMode); } } cont: *Dx = FTInfo.x; //Dx的位置是下一个字符开始的基准位置,并不是下一个字符开始画的位置 ++Dx; } gdiexit: delete[] ggi; // delete[] gdi32w; if (!bGlyphIndex && bWindowsLink) { for (int i=0;iGetFontLinkInfo().IsAllowFontLink((BYTE)GetTextCharsetInfo(FTInfo.hdc, NULL, 0)); //是否为符号 BOOL nRet = true; BOOL bWindowsLink = pSettings->FontLink()==2; //!!Snowie /*const*/ FT_Face freetype_face = FTInfo.freetype_face; //去掉常量属性,下面要改他 const FT_Int cmap_index = FTInfo.cmap_index; const FT_Bool useKerning = FTInfo.useKerning; FT_Render_Mode render_mode = FTInfo.render_mode; const int LinkNum = FTInfo.face_id_list_num; int AAMode = FTInfo.pfs->GetAntiAliasMode(); int* AAList = FTInfo.AAModes; const LOGFONTW& lf = FTInfo.LogFont(); FreeTypeFontCache* pftCache = FTInfo.pftCache; const CFontSettings*& pfs = FTInfo.pfs; FreeTypeFontInfo*& pfi = FTInfo.pfi; const bool bGlyphIndex = FTInfo.IsGlyphIndex(); //const bool bSizeOnly = FTInfo.IsSizeOnly(); //const bool bOwnCache = !(FTInfo.font_type.flags & FT_LOAD_RENDER); const LPCTSTR lpStart = lpString; const LPCTSTR lpEnd = lpString + cbString; FT_UInt previous = 0; WCHAR previouswch = 0; const bool bVertical = false; bool bLcdMode = render_mode == FT_RENDER_MODE_LCD; bool bLightLcdMode = (AAMode == 4) || (AAMode == 5); ClpDx clpdx(FTInfo.lpDx, FTInfo.params->etoOptions); const bool bWidthGDI32 = pSettings->WidthMode() == SETTING_WIDTHMODE_GDI32; const int ggoformatbase = (FTInfo.font_type.flags & FT_LOAD_NO_HINTING) ? GGO_UNHINTED | GGO_NATIVE : GGO_NATIVE; if (!s_GGOGlyphLoader.init(freetype_library)) { return FALSE; } // LPCTSTR dumy = lpString; // if (!bGlyphIndex) // for (; dumy 1) FTInfo.face_id_list_num--; //如果是symbol页那就不链接到宋体 for (int i=0 ; lpString < lpEnd; ++lpString, gi++, GlyphArray++, drState++, ++AAList,/*ggdi32++,*/ i++){ WCHAR wch = *lpString; if (!bGlyphIndex && bIsSymbol && !bWindowsLink) wch |= 0xF000; FT_Glyph* glyph_bitmap = GlyphArray; int gdi32x = 0;// = *ggdi32; FTInfo.font_type.face_id = FTInfo.face_id_list[0]; FreeTypeCharData* chData = NULL; FT_UInt glyph_index = 0; BOOL bIsBold = false, bIsIndivBold = false; { chData = bGlyphIndex ? pftCache->FindGlyphIndex(wch) : pftCache->FindChar(wch); if (chData && FTInfo.width==chData->GetWidth()) { /* if (bSizeOnly) { //TRACE(_T("Cache hit: GetCharWidth [%c]\n"), *lpString); int cx = chData->GetWidth(); FTInfo.x += (bWidthGDI32 ? gdi32x : cx) + FTInfo.params->charExtra; goto cont; }*/ gdi32x = chData->GetGDIWidth(); *AAList = chData->GetAAMode(); CCriticalSectionLock __lock(CCriticalSectionLock::CS_LIBRARY); FT_Glyph_Copy((FT_Glyph)chData->GetGlyph(render_mode), glyph_bitmap); //TRACE(_T("Cache Hit: %wc, size:%d, 0x%8.8X\n"), wch, chData->GetWidth(), glyph_bitmap); } } if (!*glyph_bitmap) { FT_Glyph glyph = NULL; bool f_glyph = false; GLYPHMETRICS gm; const MAT2 mat2 = {{0, 1}, {0, 0}, {0, 0}, {0, 1}}; UINT ggoformat = ggoformatbase; CTempMem ggobuf; DWORD outlinesize = 0; if (bGlyphIndex) { f_glyph = true; *AAList = AAMode; glyph_index = wch; ggoformat |= GGO_GLYPH_INDEX; GetCharWidthI(FTInfo.hdc, wch, 1, (LPWORD)&wch, &gdi32x); //index的文字必须计算宽度 } else { if (*(gi) != 0xffff) { glyph_index = *(gi); f_glyph = true; *AAList = AAMode; } GetCharWidth32W(FTInfo.hdc, wch, wch, &gdi32x); //有效文字,计算宽度 } if (lpString == lpStart && FTInfo.font_type.flags & FT_LOAD_FORCE_AUTOHINT) { // FORCE_AUTOHINT GetGlyphOutlineW(FTInfo.hdc, 0, GGO_METRICS | GGO_GLYPH_INDEX | GGO_NATIVE | GGO_UNHINTED, &gm, 0, NULL, &mat2); } outlinesize = GetGlyphOutlineW(FTInfo.hdc, wch, ggoformat, &gm, ggobuf.getsize(), ggobuf, &mat2); if (outlinesize == GDI_ERROR || outlinesize == 0){ glyph_index = 0; f_glyph = false; } else { glyph_index = wch; f_glyph = true; } if (!f_glyph) { //glyphindex的文字上面已经计算过了 #ifdef _DEBUG GdiSetBatchLimit(0); #endif if (*drState==FT_DRAW_NORMAL || bGlyphIndex) *drState = FT_DRAW_NOTFOUND; //找不到文字 if ((!FTInfo.lpDx || lpString == lpEnd - 1) && !bGlyphIndex) //无效文字,而且没有事先排版或者是排版的最后一个字符了 { GetCharWidth32W(FTInfo.hdc, wch, wch, &gdi32x); } int cx = gdi32x; /* if (bSizeOnly) { FTInfo.x += cx; } else*/ { if (wch) { *glyph_bitmap = NULL; //无效文字 //ORIG_ExtTextOutW(FTInfo.hdc, FTInfo.x, FTInfo.yTop, FTInfo.GetETO(), NULL, &wch, 1, NULL); } BOOL isc = bGlyphIndex ? false : (CID.myiswcntrl(*lpString)); if (isc) cx = 0; if (lpString < lpEnd - 1) { FTInfo.x += clpdx.get(cx); } else { //if (gdi32x) { /* ABC abc = {0, cx, 0}; if (bGlyphIndex) GetCharABCWidthsI(FTInfo.hdc, wch, 1, NULL, &abc); else GetCharABCWidths(FTInfo.hdc, wch, wch, &abc);*/ //FTInfo.px = FTInfo.x+Max(clpdx.get(cx), abc.abcA+(int)abc.abcB+abc.abcC); //无效文字的情况下,绘图宽度=鼠标位置 FTInfo.px = FTInfo.x + cx; FTInfo.x += clpdx.get(cx); } } if (!isc) FTInfo.x += FTInfo.params->charExtra; } goto cont; } if(useKerning && !bGlyphIndex){ if (previouswch && wch) { FTInfo.x += FTInfo.ggokerning.get(previouswch, wch); } previouswch = wch; } // 縦横 if(bVertical && IsVerticalChar(wch)){ FTInfo.font_type.flags |= FT_LOAD_VERTICAL_LAYOUT; if(bLcdMode){ if(!bLightLcdMode){ FTInfo.font_type.flags &= ~FT_LOAD_TARGET_LCD; FTInfo.font_type.flags |= FT_LOAD_TARGET_LCD_V; } render_mode = FT_RENDER_MODE_LCD_V; } }else{ if (bVertical) swap(FTInfo.font_type.height, FTInfo.font_type.width); //交换无法旋转的文字宽高 FTInfo.font_type.flags &=~FT_LOAD_VERTICAL_LAYOUT; if(bLcdMode){ if(!bLightLcdMode){ FTInfo.font_type.flags &= ~FT_LOAD_TARGET_LCD_V; FTInfo.font_type.flags |= FT_LOAD_TARGET_LCD; } render_mode = FT_RENDER_MODE_LCD; } } CGGOOutlineGlyph ggoog; { if (outlinesize > ggobuf.getsize()) { if (!ggobuf.init(outlinesize)) { nRet= false; goto gdiexit; } //ggofont.change(); outlinesize = GetGlyphOutlineW(FTInfo.hdc, wch, ggoformat, &gm, ggobuf.getsize(), ggobuf, &mat2); //ggofont.restore(); } if (outlinesize > ggobuf.getsize()) { nRet= false; goto gdiexit; } if (!ggoog.init(outlinesize, ggobuf, gm)) { nRet= false; goto gdiexit; } //glyph = New_FT_Ref_Glyph(); //FT_Glyph_Copy((FT_Glyph)ggoog, &glyph); glyph = ggoog; } { CCriticalSectionLock __lock(CCriticalSectionLock::CS_LIBRARY); if (FT_Glyph_Copy(glyph, glyph_bitmap)) { //FT_Done_Glyph(glyph); nRet = FALSE; goto gdiexit; } //FT_Done_Glyph(glyph); } if((*glyph_bitmap)->format != FT_GLYPH_FORMAT_BITMAP){ int str_h; int str_v; bool fbold = false; str_h = str_v = FTInfo.pfi->CalcNormalWeight(); if (bIsIndivBold) str_h = str_v = FTInfo.pfi->GetExactBoldWeight()<<2; if (bIsBold) { fbold = true; str_h += FTInfo.font_type.height<24 ? FTInfo.pfi->GetFTWeight(): (FTInfo.pfi->GetFTWeight()*FTInfo.font_type.height/24); str_v = str_h; } if((str_h || str_v) && New_FT_Outline_Embolden( &((FT_OutlineGlyph)((*glyph_bitmap)))->outline, str_h, str_v, FTInfo.height)) { FT_Done_Glyph(*glyph_bitmap); nRet= false; goto gdiexit; } if (fbold) { ((FT_BitmapGlyph)((*glyph_bitmap)))->root.advance.x += 0x10000; } { CCriticalSectionLock __lock(CCriticalSectionLock::CS_LIBRARY); if(FT_Glyph_To_Bitmap(&((*glyph_bitmap)), render_mode, 0, 1)){ FT_Done_Glyph(*glyph_bitmap); nRet= false; goto gdiexit; } } } } int cx = (bVertical && IsVerticalChar(wch)) ? FT_FixedToInt(FT_BitmapGlyph((*glyph_bitmap))->root.advance.y) : FT_FixedToInt(FT_BitmapGlyph((*glyph_bitmap))->root.advance.x); //done /* if (bSizeOnly) { FTInfo.x += bWidthGDI32 ? gdi32x : cx; } else */ { int dx = clpdx.get(bWidthGDI32 ? gdi32x : cx); //获得宽度 int left = FT_BitmapGlyph((*glyph_bitmap))->left; if (FTInfo.x + left< FTInfo.xBase) FTInfo.xBase = FTInfo.x + left; //如果有字符是负数起始位置的(合成符号), 调整文字的起始位置 if (lpString < lpEnd - 1) { FTInfo.x += dx; } else { int bx = FT_BitmapGlyph((*glyph_bitmap))->bitmap.width; if (render_mode == FT_RENDER_MODE_LCD) bx /= 3; bx += left; FTInfo.px = FTInfo.x + Max(Max(dx, bx), cx); //有文字的情况下,绘图宽度=ft计算的宽度,鼠标位置=win宽度 FTInfo.x += dx;//Max(dx, gdi32x);//Max(Max(dx, bx), cx); } } FTInfo.x += FTInfo.params->charExtra; //if (bSizeOnly || bOwnCache) { //キャッシュ化 if (glyph_index) { if (bGlyphIndex) { pftCache->AddGlyphData(glyph_index, /*cx*/FTInfo.width, gdi32x, (FT_BitmapGlyph)*glyph_bitmap, render_mode, AAMode); } else { pftCache->AddCharData(wch, glyph_index, /*cx*/FTInfo.width, gdi32x, (FT_BitmapGlyph)*glyph_bitmap, render_mode, AAMode); } } //} // if (!bGlyphIndex && iswcntrl(wch) && *glyph_bitmap) // { // // FT_Done_Glyph(*glyph_bitmap); // *glyph_bitmap = NULL; // } cont: *Dx = FTInfo.x; Dx++; } gdiexit: delete[] ggi; // delete[] gdi32w; if (!bGlyphIndex && bWindowsLink) { for (int i=0;iCopyForceFont(lfForce, lf)) // lf = lfForce; if(pSettings->LoadOnDemand()) { //AddFontToFT(lf.lfFaceName, lf.lfWeight, !!lf.lfItalic); } return TRUE; } BOOL CALLBACK TextOutCallback(FreeTypeGlyphInfo& FTGInfo) { FreeTypeDrawInfo* FTInfo = FTGInfo.FTInfo; FT_BitmapGlyph& glyph_bitmap = FTGInfo.FTGlyph; const bool bVertical = FTInfo->LogFont().lfFaceName[0] == _T('@'); int nOldAlpha = FTInfo->params->alpha; if (!FTGInfo.FTGlyph->bitmap.buffer) { //if (FTInfo->params->alpha == 1) { // if (!(FTInfo->GetETO() & ETO_GLYPH_INDEX) && wch==32) //空格 // ORIG_ExtTextOutW(FTInfo->hdc, FTInfo->x, FTInfo->yTop, FTInfo->GetETO() & ETO_IGNORELANGUAGE, NULL, &wch, 1, NULL); // else ORIG_ExtTextOutW(FTInfo->hdc, FTInfo->x, FTInfo->yTop, FTInfo->GetETO(), NULL, &FTGInfo.wch, 1, NULL); //} } else { const CGdippSettings* pSettings = CGdippSettings::GetInstance(); if (bVertical && IsVerticalChar(FTGInfo.wch) && pSettings->FontLoader() == SETTING_FONTLOADER_FREETYPE) { if (FTInfo->params->alpha>1) { FreeTypeDrawBitmapV(FTGInfo, *FTGInfo.shadow, FTInfo->x + FTInfo->sx, FTInfo->params->otm->otmTextMetrics.tmHeight - (glyph_bitmap->left+glyph_bitmap->bitmap.width) -1 + FTInfo->sy);//画阴影 FTInfo->params->alpha = 1; } FreeTypeDrawBitmapV(FTGInfo,*FTGInfo.solid, FTInfo->x, FTInfo->params->otm->otmTextMetrics.tmHeight - (glyph_bitmap->left+glyph_bitmap->bitmap.width) -1); //画文字 }else{ if (FTInfo->params->alpha>1) { FreeTypeDrawBitmap(FTGInfo,*FTGInfo.shadow, FTInfo->x + glyph_bitmap->left + FTInfo->sx, FTInfo->yBase - glyph_bitmap->top + FTInfo->sy); //画阴影 FTInfo->params->alpha = 1; } FreeTypeDrawBitmap(FTGInfo,*FTGInfo.solid, FTInfo->x + glyph_bitmap->left, FTInfo->yBase - glyph_bitmap->top); //画文字 } } FTInfo->params->alpha = nOldAlpha; return TRUE; } int IsColorDark(DWORD Color, double Gamma) { //return (GetRValue(Color)*0.299 + GetGValue(Color)*0.587 + GetBValue(Color)*0.114); //原始算法 //=============================================================== //采用Photoshop sRGB的RGB->Lab算法进行换算,L为色彩视觉亮度 //感谢 西安理工大学 贾婉丽 的分析 //=============================================================== static double s_multipler = 116/pow(100,(double)1.0/3.0); //预计算常数,强制使用double版本 double* RGBTable = s_AlphaBlendTable.GetRGBTable(); //获得显示器转换表 double ret = pow(23.9746*RGBTable[GetRValue(Color)] + 73.0653*RGBTable[GetGValue(Color)] + 6.13799*RGBTable[GetBValue(Color)] , 1.0/3.0)*s_multipler-16; return max(int(ret + 0.499),0); /*double r = GetRValue(Color)/255.0; double g = GetGValue(Color)/255.0; double b = GetBValue(Color)/255.0; double v; double m; double vm; double r2, g2, b2; double h = 0; // default to black double s = 0; double l = 0; v = Max(r,g); v = Max(v,b); m = Min(r,g); m = Min(m,b); l = (m + v) / 2.0; if (l <= 0.0) { return 0; } vm = v - m; s = vm; if (s > 0.0) { s /= (l <= 0.5) ? (v + m ) : (2.0 - v - m) ; } else { return l; } r2 = (v - r) / vm; g2 = (v - g) / vm; b2 = (v - b) / vm; if (r == v) { h = (g == m ? 5.0 + b2 : 1.0 - g2); } else if (g == v) { h = (b == m ? 1.0 + r2 : 3.0 - b2); } else { h = (r == m ? 3.0 + g2 : 5.0 - r2); } h /= 6.0; return l;*/ } /* BOOL GetColorDiff(DWORD Color) { / *const CGdippSettings* pSettings = CGdippSettings::GetInstance(); DWORD ShadowColorD = pSettings->ShadowDarkColor(); DWORD ShadowColorL = pSettings->ShadowLightColor(); DWORD ColorDiffD = RGBA(abs(GetRValue(Color)-GetRValue(ShadowColorD)),abs(GetGValue(Color)-GetGValue(ShadowColorD)),abs(GetBValue(Color)-GetBValue(ShadowColorD)),0); DWORD ColorDiffL = RGBA(abs(GetRValue(Color)-GetRValue(ShadowColorL)),abs(GetGValue(Color)-GetGValue(ShadowColorL)),abs(GetBValue(Color)-GetBValue(ShadowColorL)),0); double cd = IsColorDark(ColorDiffD), cl = IsColorDark(ColorDiffL); return cd==cl ? IsColorDark(Color)<0.7 : cd>cl;* / }*/ BOOL FreeTypeTextOut( const HDC hdc, // デバイスコンテキストのハンドル CBitmapCache& cache, LPCWSTR lpString, // 文字列 int cbString, // 文字数 FreeTypeDrawInfo& FTInfo, FT_Glyph * Glyphs, FT_DRAW_STATE* drState ) { if(cbString <= 0 || lpString == NULL) return FALSE; CAlphaBlendColor * solid = NULL; CAlphaBlendColor * shadow = NULL; //CCriticalSectionLock __lock; FT_Face freetype_face = FTInfo.freetype_face; const LOGFONT& lf = FTInfo.LogFont(); FTInfo.x = -FTInfo.xBase; FTInfo.yTop = 0; const TEXTMETRIC& tm = FTInfo.params->otm->otmTextMetrics; FTInfo.yBase = tm.tmAscent; //===============计算颜色缓存====================== const CGdippSettings* pSettings = CGdippSettings::GetInstance(); int lightdiff, darkdiff, bDarkColor=0, ShadowColor=0; if (FTInfo.params->alpha!=1) { float Gamma = pSettings->GammaValue(); bDarkColor = IsColorDark(FTInfo.params->color, Gamma); int diff = max(darkdiff=abs(IsColorDark(pSettings->ShadowDarkColor(), Gamma)-bDarkColor), lightdiff=abs(IsColorDark(pSettings->ShadowLightColor(), Gamma)-bDarkColor)); ShadowColor = lightdiff<=darkdiff ? pSettings->ShadowDarkColor() : pSettings->ShadowLightColor(); bDarkColor = lightdiff<=darkdiff; if (/*diff<10 || abs(lightdiff-darkdiff)<20 &&*/ pSettings->ShadowDarkColor()==pSettings->ShadowLightColor()) { //无视底色问题,强制开启阴影 FTInfo.params->alphatuner = 1; } else { diff = abs(lightdiff-darkdiff); if (diff<10) FTInfo.params->alpha = 1; else FTInfo.params->alphatuner = max(1, 100/diff); //根据色差调整阴影浓度 } } char mode = (*Glyphs)? FT_BitmapGlyph((*Glyphs))->bitmap.pixel_mode:FT_PIXEL_MODE_LCD; switch(mode){ case FT_PIXEL_MODE_MONO: return false; //break; case FT_PIXEL_MODE_LCD: solid = new CAlphaBlendColor( FTInfo.params->color, 1, true, true,true); shadow = new CAlphaBlendColor( /*FTInfo.params->color*/ShadowColor, FTInfo.params->alpha, true, bDarkColor, true); break; case FT_PIXEL_MODE_LCD_V: solid = new CAlphaBlendColor( FTInfo.params->color, 1, true, true,false); shadow = new CAlphaBlendColor( /*FTInfo.params->color*/ShadowColor, FTInfo.params->alpha, true, bDarkColor, false); break; case FT_PIXEL_MODE_GRAY: solid = new CAlphaBlendColor( FTInfo.params->color, 1, false,true, true); shadow = new CAlphaBlendColor( /*FTInfo.params->color*/ShadowColor, FTInfo.params->alpha, false, bDarkColor, true); break; default: solid = new CAlphaBlendColor( FTInfo.params->color, 1, pSettings->LcdFilter(),true); shadow = new CAlphaBlendColor( /*FTInfo.params->color*/ShadowColor, FTInfo.params->alpha, pSettings->LcdFilter(), bDarkColor); break; } //===============计算完成========================== FreeTypeGlyphInfo FTGInfo = {&FTInfo, 0, 0, 0, solid, shadow}; for (int i=0; iotm; if(lf.lfUnderline){ int yPos = 0; //下線の位置 int height = 0; int thickness = 0; // 適当な太さ switch (pSettings->FontLoader()) { case SETTING_FONTLOADER_FREETYPE: yPos = y - otm.otmsUnderscorePosition; height = otm.otmTextMetrics.tmHeight; //FT_PosToInt(freetype_face->size->metrics.height); thickness = MulDiv(freetype_face->underline_thickness, FTInfo.font_type.height/*freetype_face->size->metrics.y_ppem*/, freetype_face->units_per_EM); break; case SETTING_FONTLOADER_WIN32: yPos = y - otm.otmsUnderscorePosition; height = otm.otmTextMetrics.tmHeight; thickness = otm.otmsUnderscoreSize; break; } if (yPos >= height) { yPos = height - 1; } cache.DrawHorizontalLine(0, yPos, x, FTInfo.Color(), thickness); } if(lf.lfStrikeOut){ int yPos = y - otm.otmsStrikeoutPosition; int thickness = 0; switch (pSettings->FontLoader()) { case SETTING_FONTLOADER_FREETYPE: thickness = MulDiv(freetype_face->underline_thickness, FTInfo.font_type.height,// freetype_face->size->metrics.y_ppem, freetype_face->units_per_EM); break; case SETTING_FONTLOADER_WIN32: thickness = otm.otmsStrikeoutSize; break; } cache.DrawHorizontalLine(0, yPos, x, FTInfo.Color(), thickness); } } return TRUE; } BOOL FreeTypeGetGlyph( //获得所有图形和需要的宽度 FreeTypeDrawInfo& FTInfo, LPCWSTR lpString, int cbString, int& width, FT_Glyph* Glyphs, FT_DRAW_STATE* drState ) { COwnedCriticalSectionLock __lock(1); { //CCriticalSectionLock __lock; if (!FreeTypePrepare(FTInfo)) return false; } const CGdippSettings* pSettings = CGdippSettings::GetInstance(); BOOL nRet = false; switch (pSettings->FontLoader()) { case SETTING_FONTLOADER_FREETYPE: nRet = ForEachGetGlyphFT(FTInfo,lpString,cbString,Glyphs,drState); break; case SETTING_FONTLOADER_WIN32: nRet = ForEachGetGlyphGGO(FTInfo,lpString,cbString,Glyphs,drState); break; } width = FTInfo.px; //获得了宽度 return nRet; } void VertFinalizer(void *object){ FT_Face face = (FT_Face)object; ft2vert_final(face, (struct ft2vert_st *)face->generic.data); } // // グリフをIVSで指定された字形をサポートするかどうか調べ、 // サポートしている場合はグリフを置換する。 // サポートしていなければ何もしない。 // /* void FreeTypeSubstGlyph(const HDC hdc, const WORD vsindex, const int baseChar, int cChars, SCRIPT_ANALYSIS* psa, WORD* pwOutGlyphs, WORD* pwLogClust, SCRIPT_VISATTR* psva, int* pcGlyphs ) { CThreadLocalInfo* pTLInfo = g_TLInfo.GetPtr(); CBitmapCache& cache = pTLInfo->BitmapCache(); CCriticalSectionLock __lock; LOGFONT lf; if (!GetLogFontFromDC(hdc, lf)) return; FREETYPE_PARAMS params(0, hdc); FreeTypeDrawInfo FTInfo(params, hdc, &lf, &cache); if(!FreeTypePrepare(FTInfo)) return; FT_UInt glyph_index = ft2_subst_uvs(FTInfo.freetype_face, pwOutGlyphs[*pcGlyphs - 1], vsindex, baseChar); TRACE(_T("FreeTypeSubstGlyph: %04X->%04X\n"), pwOutGlyphs[*pcGlyphs - 1], glyph_index); if (glyph_index) { pwOutGlyphs[*pcGlyphs - 1] = glyph_index; // 置換を実行 // ASCII空白のグリフを取得 glyph_index = FTC_CMapCache_Lookup( cmap_cache, FTInfo.font_type.face_id, FTInfo.cmap_index, ' '); // ゼロ幅グリフにする pwOutGlyphs[*pcGlyphs] = glyph_index; psva[*pcGlyphs].uJustification = SCRIPT_JUSTIFY_NONE; psva[*pcGlyphs].fClusterStart = 0; psva[*pcGlyphs].fDiacritic = 0; psva[*pcGlyphs].fZeroWidth = 1; psva[*pcGlyphs].fReserved = 0; psva[*pcGlyphs].fShapeReserved = 0; } else { // フォントは指定された字形を持たない。IVSのグリフを取得 glyph_index = FTC_CMapCache_Lookup( cmap_cache, FTInfo.font_type.face_id, FTInfo.cmap_index, vsindex + 0xE0100); // IVSをサポートしていないフォントはIVSのグリフを持っている可能性もほとんどない。 // missing glyphを返すとフォールバックされてしまうため確実に持っていそうなグリフを拾う if (!glyph_index) glyph_index = FTC_CMapCache_Lookup( cmap_cache, FTInfo.font_type.face_id, FTInfo.cmap_index, 0x30FB); pwOutGlyphs[*pcGlyphs] = glyph_index; psva[*pcGlyphs] = psva[*pcGlyphs - 1]; psva[*pcGlyphs].fClusterStart = 0; } pwLogClust[cChars - 2] = *pcGlyphs; pwLogClust[cChars - 1] = *pcGlyphs; ++*pcGlyphs; }*/ FT_Error face_requester( FTC_FaceID face_id, FT_Library /*library*/, FT_Pointer /*request_data*/, FT_Face* aface) { FT_Error ret; FT_Face face; FreeTypeFontInfo* pfi = g_pFTEngine->FindFont((int)face_id); Assert(pfi); if (!pfi) { return FT_Err_Invalid_Argument; } LPCTSTR fontname = pfi->GetName(); // 名称を指定してフォントを取得 FreeTypeSysFontData* pData = FreeTypeSysFontData::CreateInstance(fontname, pfi->GetFontWeight(), pfi->IsItalic()); if(pData == NULL){ return FT_Err_Cannot_Open_Resource; } face = pData->GetFace(); Assert(face != NULL); // Charmapを設定しておく ret = FT_Select_Charmap(face, FT_ENCODING_UNICODE); if(ret != FT_Err_Ok) ret = FT_Select_Charmap(face, FT_ENCODING_MS_SYMBOL); /* if(ret != FT_Err_Ok) ret = FT_Select_Charmap(face, FT_ENCODING_SJIS); if(ret != FT_Err_Ok) ret = FT_Select_Charmap(face, FT_ENCODING_GB2312); if(ret != FT_Err_Ok) ret = FT_Select_Charmap(face, FT_ENCODING_BIG5); if(ret != FT_Err_Ok) ret = FT_Select_Charmap(face, FT_ENCODING_WANSUNG); if(ret != FT_Err_Ok) ret = FT_Select_Charmap(face, FT_ENCODING_JOHAB); if(ret != FT_Err_Ok) ret = FT_Select_Charmap(face, FT_ENCODING_ADOBE_STANDARD); if(ret != FT_Err_Ok) ret = FT_Select_Charmap(face, FT_ENCODING_ADOBE_EXPERT); if(ret != FT_Err_Ok) ret = FT_Select_Charmap(face, FT_ENCODING_ADOBE_CUSTOM); if(ret != FT_Err_Ok) ret = FT_Select_Charmap(face, FT_ENCODING_ADOBE_LATIN_1); if(ret != FT_Err_Ok) ret = FT_Select_Charmap(face, FT_ENCODING_OLD_LATIN_2); if(ret != FT_Err_Ok) ret = FT_Select_Charmap(face, FT_ENCODING_APPLE_ROMAN); */ if(ret != FT_Err_Ok) { FT_Done_Face(face); return ret; } struct ft2vert_st *vert = ft2vert_init(face); face->generic.data = vert; face->generic.finalizer = VertFinalizer; *aface = face; return 0; } /* DWORD FreeTypeGetVersion() { int major = 0, minor = 0, patch = 0; FT_Library_Version(freetype_library, &major, &minor, &patch); //面倒なのでRGBマクロ使用 return RGB(major, minor, patch); }*/ //新太字アルゴリズム FT_Error New_FT_Outline_Embolden( FT_Outline* outline, FT_Pos str_h, FT_Pos str_v, FT_Int font_size ) { const CGdippSettings* pSettings = CGdippSettings::GetInstance(); int orientation = 0; switch (pSettings->BolderMode()) { case 1: return FT_Outline_EmboldenXY( outline, str_h, 0); case 2: return FT_Outline_Embolden( outline, str_h ); default: { if ( !outline ) return FT_Err_Invalid_Argument; //orientation = FT_Outline_Get_Orientation( outline ); //if ( orientation == FT_ORIENTATION_NONE ) // if ( outline->n_contours ) return FT_Err_Invalid_Argument; /* if (font_size>FT_BOLD_LOW || str_h<16) Vert_FT_Outline_Embolden( outline, str_v ); Old_FT_Outline_Embolden( outline, str_h );*/ if (font_size32) { FT_Outline_EmboldenXY(outline, str_h, Min(long(32), str_v)); } else FT_Outline_Embolden(outline, str_h); return FT_Err_Ok; } } } //横方向だけ太らせるFT_Outline_Embolden FT_Error Old_FT_Outline_Embolden( FT_Outline* outline, FT_Pos strength ) { FT_Vector* points; FT_Vector v_prev, v_first, v_next, v_cur; FT_Angle rotate, angle_in, angle_out; FT_Int c, n, first; FT_Int orientation; if ( !outline ) return FT_Err_Invalid_Argument; strength /= 2; if ( strength == 0 ) return FT_Err_Ok; orientation = FT_Outline_Get_Orientation( outline ); if ( orientation == FT_ORIENTATION_NONE ) { if ( outline->n_contours ) return FT_Err_Invalid_Argument; else return FT_Err_Ok; } if ( orientation == FT_ORIENTATION_TRUETYPE ) rotate = -FT_ANGLE_PI2; else rotate = FT_ANGLE_PI2; points = outline->points; first = 0; for ( c = 0; c < outline->n_contours; c++ ) { int last = outline->contours[c]; v_first = points[first]; v_prev = points[last]; v_cur = v_first; for ( n = first; n <= last; n++ ) { FT_Vector in, out; FT_Angle angle_diff; FT_Pos d; FT_Fixed scale; if ( n < last ) v_next = points[n + 1]; else v_next = v_first; /* compute the in and out vectors */ in.x = v_cur.x - v_prev.x; in.y = v_cur.y - v_prev.y; out.x = v_next.x - v_cur.x; out.y = v_next.y - v_cur.y; angle_in = FT_Atan2( in.x, in.y ); angle_out = FT_Atan2( out.x, out.y ); angle_diff = FT_Angle_Diff( angle_in, angle_out ); scale = FT_Cos( angle_diff / 2 ); if ( scale < 0x4000L && scale > -0x4000L ) in.x = in.y = 0; else { d = FT_DivFix( strength, scale ); FT_Vector_From_Polar( &in, d, angle_in + angle_diff / 2 - rotate ); } outline->points[n].x = v_cur.x + strength + in.x; //↓これをコメントアウトしただけ //outline->points[n].y = v_cur.y + strength + in.y; v_prev = v_cur; v_cur = v_next; } first = last + 1; } return FT_Err_Ok; } //こっちは縦方向 FT_Error Vert_FT_Outline_Embolden( FT_Outline* outline, FT_Pos strength ) { FT_Vector* points; FT_Vector v_prev, v_first, v_next, v_cur; FT_Angle rotate, angle_in, angle_out; FT_Int c, n, first; FT_Int orientation; if ( !outline ) return FT_Err_Invalid_Argument; strength /= 2; if ( strength == 0 ) return FT_Err_Ok; orientation = FT_Outline_Get_Orientation( outline ); if ( orientation == FT_ORIENTATION_NONE ) { if ( outline->n_contours ) return FT_Err_Invalid_Argument; else return FT_Err_Ok; } if ( orientation == FT_ORIENTATION_TRUETYPE ) rotate = -FT_ANGLE_PI2; else rotate = FT_ANGLE_PI2; points = outline->points; first = 0; for ( c = 0; c < outline->n_contours; c++ ) { int last = outline->contours[c]; v_first = points[first]; v_prev = points[last]; v_cur = v_first; for ( n = first; n <= last; n++ ) { FT_Vector in, out; FT_Angle angle_diff; FT_Pos d; FT_Fixed scale; if ( n < last ) v_next = points[n + 1]; else v_next = v_first; /* compute the in and out vectors */ in.x = v_cur.x - v_prev.x; in.y = v_cur.y - v_prev.y; out.x = v_next.x - v_cur.x; out.y = v_next.y - v_cur.y; angle_in = FT_Atan2( in.x, in.y ); angle_out = FT_Atan2( out.x, out.y ); angle_diff = FT_Angle_Diff( angle_in, angle_out ); scale = FT_Cos( angle_diff / 2 ); if ( scale < 0x4000L && scale > -0x4000L ) in.x = in.y = 0; else { d = FT_DivFix( strength, scale ); FT_Vector_From_Polar( &in, d, angle_in + angle_diff / 2 - rotate ); } //outline->points[n].x = v_cur.x + strength + in.x; //↑これをコメントアウトしただけ outline->points[n].y = v_cur.y + strength + in.y; v_prev = v_cur; v_cur = v_next; } first = last + 1; } return FT_Err_Ok; } //ダミー FT_EXPORT( FT_Error ) FT_Library_SetLcdFilter_Dummy( FT_Library /*library*/, FT_LcdFilter /*filter*/ ) { return 0; } BOOL FontLInit(void){ CCriticalSectionLock __lock; if(FT_Init_FreeType(&freetype_library)){ return FALSE; } const CGdippSettings* pSettings = CGdippSettings::GetInstance(); if(FTC_Manager_New(freetype_library, pSettings->CacheMaxFaces(), pSettings->CacheMaxSizes(), pSettings->CacheMaxBytes(), face_requester, NULL, &cache_man)) { FontLFree(); return FALSE; } if(FTC_CMapCache_New(cache_man, &cmap_cache)){ FontLFree(); return FALSE; } if(FTC_ImageCache_New(cache_man, &image_cache)){ FontLFree(); return FALSE; } const int nLcdFilter = pSettings->LcdFilter(); if ((int)FT_LCD_FILTER_NONE < nLcdFilter && nLcdFilter < (int)FT_LCD_FILTER_MAX) { FT_Library_SetLcdFilter(freetype_library, (FT_LcdFilter)nLcdFilter); if (pSettings->UseCustomLcdFilter()) { unsigned char buff[5]; memcpy(buff, pSettings->LcdFilterWeights(), sizeof(buff)); FT_Library_SetLcdFilterWeights(freetype_library, buff); } else switch (nLcdFilter) { case FT_LCD_FILTER_NONE: case FT_LCD_FILTER_DEFAULT: case FT_LCD_FILTER_LEGACY: { FT_Library_SetLcdFilterWeights(freetype_library, (unsigned char*)"\x00\x55\x56\x55\x00" ); break; } case FT_LCD_FILTER_LIGHT: default: FT_Library_SetLcdFilterWeights(freetype_library, (unsigned char*)"\x10\x40\x70\x40\x10" ); } } s_AlphaBlendTable.init(); s_AlphaBlendTable.initRGB(); return TRUE; } void FontLFree(void){ CCriticalSectionLock __lock; if(cache_man != NULL) FTC_Manager_Done(cache_man); if(freetype_library != NULL) FT_Done_FreeType(freetype_library); cache_man = NULL; freetype_library = NULL; } //Snowie void RefreshAlphaTable() { s_AlphaBlendTable.init(); } void UpdateLcdFilter() { const CGdippSettings* pSettings = CGdippSettings::GetInstance(); const int nLcdFilter = pSettings->LcdFilter(); if ((int)FT_LCD_FILTER_NONE < nLcdFilter && nLcdFilter < (int)FT_LCD_FILTER_MAX) { FT_Library_SetLcdFilter(freetype_library, (FT_LcdFilter)nLcdFilter); if (pSettings->UseCustomLcdFilter()) { unsigned char buff[5]; memcpy(buff, pSettings->LcdFilterWeights(), sizeof(buff)); FT_Library_SetLcdFilterWeights(freetype_library, buff); } /* else switch (nLcdFilter) { case FT_LCD_FILTER_NONE: case FT_LCD_FILTER_DEFAULT: case FT_LCD_FILTER_LEGACY: { FT_Library_SetLcdFilterWeights(freetype_library, (unsigned char*)"\x10\x40\x70\x40\x10" ); break; } case FT_LCD_FILTER_LIGHT: default: FT_Library_SetLcdFilterWeights(freetype_library, (unsigned char*)"\x00\x55\x56\x55\x00" ); }*/ } } ================================================ FILE: ft.cpp ================================================ /* 2006-10-23(by 555) * http://hp.vector.co.jp/authors/VA028002/winfreetype.c (higambana(菅野友紀)) * を丸写し */ /* 2006-10-27(by 555) * http://hp.vector.co.jp/authors/VA028002/freetype.html (higambana(菅野友紀)) * を参考にしてやり直し */ /* 2006-10-29(by 555) * 693氏(と呼ぶことにする)の精力的な活動によって出来上がったウハウハソースと * 上記サイトの変更点を元にみみっちい修正。(ベースgdi0164) */ /* (by 555) * さらに線引きもウハウハにしてもらったgdi0168を元に * イタリックとボールドを追加。 */ /* (by sy567) * 太字のアルゴリズムを変更。 * ガンマ補正を実装してみる。 */ #include "override.h" #include "ft.h" #include //#include #include #include #include #include #include #include /* FT_FREETYPE_H */ #include /* FT_CACHE_H */ //#include // FT_TRUETYPE_TAGS_H //#include // FT_TRUETYPE_TABLES_H #include // FT_OUTLINE_H #include //FT_TRIGONOMETRY_H #include FT_MULTIPLE_MASTERS_H #include FT_SFNT_NAMES_H #ifdef FT_LCD_FILTER_H #include // FT_LCD_FILTER_H #endif #include "fteng.h" #include "ft2vert.h" #include "colorinvert.h" FT_BitmapGlyphRec empty_glyph = {};//优化控制字 #define FT_BOLD_LOW 15 #define IsFontBold(lf) ((lf).lfWeight >= FW_BOLD) #define FT_FixedToInt(x) (FT_RoundFix(x) >> 16) #define FT_PosToInt(x) (((x) + (1 << 5)) >> 6) #define RESOLUTION_X 72 #define RESOLUTION_Y 72 FT_Error New_FT_Outline_Embolden(FT_Outline* outline, FT_Pos str_h, FT_Pos str_v, FT_Int font_size); FT_Error Old_FT_Outline_Embolden(FT_Outline* outline, FT_Pos strength); FT_Error Vert_FT_Outline_Embolden(FT_Outline* outline, FT_Pos strength); ControlIder CID; #if _MSC_VER <= 1200 #pragma warning(disable: 4786) #endif //更新 #define RGBA(r,g,b,a) ((COLORREF)(((BYTE)(r)|((WORD)((BYTE)(g))<<8))|(((DWORD)(BYTE)(b))<<16)|(((DWORD)(BYTE)(a))<<24))) //!!Snowie COLORREF GetPaletteColor(HDC hdc, UINT paletteindex) { //if ((paletteindex>>28)%2) return 0; HPALETTE hpal = (HPALETTE)GetCurrentObject(hdc, OBJ_PAL); PALETTEENTRY lppe = {}; memset(&lppe, 0, sizeof(lppe)); GetPaletteEntries(hpal, paletteindex & 0xffff, 1, &lppe); return RGB(lppe.peRed, lppe.peGreen, lppe.peBlue); } bool EmBoldVariableFont(const FT_Face face, int boldWeight) { FT_MM_Var* mm_var = nullptr; auto error = FT_Get_MM_Var(face, &mm_var); if (error) { return false; // not a varaible font } auto num_axes = mm_var->num_axis; auto coords = new FT_Fixed[num_axes]; bool axisFound = false; // Find 'wght' axis and set coordinates for (unsigned int i = 0; i < num_axes; ++i) { FT_Var_Axis* axis = &mm_var->axis[i]; if (axis->tag == FT_MAKE_TAG('w', 'g', 'h', 't')) { axisFound = true; // fix out-of-range bold weight if (boldWeight < axis->minimum) { boldWeight = axis->minimum; } if (boldWeight > axis->maximum) { boldWeight = axis->maximum; } coords[i] = boldWeight; } else { // Set other axes to their default values coords[i] = axis->def; } } if (!axisFound) { return false; // no "wght" axis found } // Apply the design coordinates FT_Set_Var_Design_Coordinates(face, num_axes, coords); // we will continue whatsoever // Free the MM_Var structure (we've copied the data we need) FT_Done_MM_Var(freetype_library, mm_var); mm_var = nullptr; // Avoid double free later return true; } void Log(char* Msg) { #ifndef _DEBUG return; #endif FILE* f = fopen(".\\gdipp.log", "a"); fputs(Msg, f); fclose(f); } void Log(wchar_t* Msg) { #ifndef _DEBUG return; #endif FILE* f = _wfopen(L".\\gdipp.log", L"a,ccs=UNICODE"); fputws(Msg, f); fclose(f); } extern "C" FT_Error FT_Glyph_To_BitmapEx(FT_Glyph * the_glyph, FT_Render_Mode render_mode, FT_Vector * origin, FT_Bool destroy, FT_Bool loadcolor, FT_UInt glyphindex, FT_Face face); class CAlphaBlend { private: std::vector alphatbl; std::vector tbl1; std::vector tbl2; // 通常のアルファ値補正 std::vector tunetbl; std::vector tunetblR; std::vector tunetblG; std::vector tunetblB; // 影文字用のアルファ値補正 std::vector tunetblS; std::vector tunetblRS; std::vector tunetblGS; std::vector tunetblBS; std::vector tunetblLS; std::vector tunetblLRS; std::vector tunetblLGS; std::vector tunetblLBS; //Snowie!! std::vector RGB2CRT; //table used for RGB<->Lab public: static const int BASE; public: CAlphaBlend() : alphatbl(256), tbl1(257), tbl2(256 * 16 + 1), tunetbl(256), tunetblR(256), tunetblG(256), tunetblB(256), tunetblS(256), tunetblRS(256), tunetblGS(256), tunetblBS(256), tunetblLS(256), tunetblLRS(256), tunetblLGS(256), tunetblLBS(256), RGB2CRT(256) {} ~CAlphaBlend() {} void init(); void initRGB(); double* GetRGBTable() { return RGB2CRT.data(); } BYTE doAB(BYTE fg, BYTE bg, int alpha); void gettunetbl(int paramalpha, BOOL lcd, BOOL dark, const int*& tblR, const int*& tblG, const int*& tblB) const; inline int conv1(BYTE n) { return tbl1[n]; } inline BYTE conv2(int n) { return tbl2[n / (BASE * BASE / (tbl2.size() - 1))]; } private: inline int convalpha(int alpha) { return alphatbl[alpha]; } inline BYTE rconv1(int n); }; const int CAlphaBlend::BASE = 0x4000; static CAlphaBlend s_AlphaBlendTable; void CAlphaBlend::gettunetbl(int paramalpha, BOOL lcd, BOOL dark, const int*& tblR, const int*& tblG, const int*& tblB) const { if (paramalpha == 1) { //获取文字混合表 if (lcd) { tblR = tunetblR.data(); tblG = tunetblG.data(); tblB = tunetblB.data(); } else { tblR = tblG = tblB = tunetbl.data(); } } else { //获取阴影混合表 if (dark) { if (lcd) { tblR = tunetblRS.data(); tblG = tunetblGS.data(); tblB = tunetblBS.data(); } else { tblR = tblG = tblB = tunetblS.data(); } } else { if (lcd) { tblR = tunetblLRS.data(); tblG = tunetblLGS.data(); tblB = tunetblLBS.data(); } else { tblR = tblG = tblB = tunetblLS.data(); } } } } void CAlphaBlend::initRGB() { for (int i = 0; i < 256; i++) RGB2CRT[i] = pow(i / 255.0, 2.2); } void CAlphaBlend::init() { const CGdippSettings* pSettings = CGdippSettings::GetInstance(); const float gamma = pSettings->GammaValue(); const float weight = pSettings->RenderWeight(); const float contrast = pSettings->Contrast(); const int mode = pSettings->GammaMode(); int i; float temp, alpha; for (i = 0; i < 256; ++i) { temp = pow((1.0f / 255.0f) * i, 1.0f / weight); if (temp < 0.5f) { alpha = pow(temp * 2, contrast) / 2.0f; } else { alpha = 1.0f - pow((1.0f - temp) * 2, contrast) / 2.0f; } alphatbl[i] = (int)(alpha * BASE); if (mode < 0) { temp = (1.0f / 255.0f) * i; } else { if (mode == 1) { if (i <= 10) { temp = (float)i / (12.92f * 255.0f); } else { temp = pow(((1.0f / 255.0f) * i + 0.055f) / 1.055f, 2.4f); } } else if (mode == 2) { if (i <= 10) { temp = ((float)i / (12.92f * 255.0f) + (float)i / 255.0f) / 2; } else { temp = (pow(((1.0f / 255.0f) * i + 0.055f) / 1.055f, 2.4f) + (float)i / 255.0f) / 2; } } else { temp = pow((1.0f / 255.0f) * i, gamma); } } tbl1[i] = (int)(temp * BASE); } tbl1[i] = BASE; for (i = 0; i <= tbl2.size() - 1; ++i) { tbl2[i] = rconv1(i * (BASE / (tbl2.size() - 1))); } const int* table = pSettings->GetTuneTable(); const int* tableR = pSettings->GetTuneTableR(); const int* tableG = pSettings->GetTuneTableG(); const int* tableB = pSettings->GetTuneTableB(); const int* shadow = pSettings->GetShadowParams(); const int paramalpha = Max(shadow[2], 1); const int lightparamalpha = Max(shadow[3], 1); for (i = 0; i < 256; ++i) { tunetbl[i] = Bound(0, alphatbl[Bound(table[i], 0, 255)], CAlphaBlend::BASE); tunetblR[i] = Bound(0, alphatbl[Bound(tableR[i], 0, 255)], CAlphaBlend::BASE); tunetblG[i] = Bound(0, alphatbl[Bound(tableG[i], 0, 255)], CAlphaBlend::BASE); tunetblB[i] = Bound(0, alphatbl[Bound(tableB[i], 0, 255)], CAlphaBlend::BASE); tunetblS[i] = Bound(0, alphatbl[Bound(table[i] * paramalpha / 100, 0, 255)], CAlphaBlend::BASE); tunetblRS[i] = Bound(0, alphatbl[Bound(tableR[i] * paramalpha / 100, 0, 255)], CAlphaBlend::BASE); tunetblGS[i] = Bound(0, alphatbl[Bound(tableG[i] * paramalpha / 100, 0, 255)], CAlphaBlend::BASE); tunetblBS[i] = Bound(0, alphatbl[Bound(tableB[i] * paramalpha / 100, 0, 255)], CAlphaBlend::BASE); //浅色混合表 tunetblLS[i] = Bound(0, alphatbl[Bound(table[i] * lightparamalpha / 100, 0, 255)], CAlphaBlend::BASE); tunetblLRS[i] = Bound(0, alphatbl[Bound(tableR[i] * lightparamalpha / 100, 0, 255)], CAlphaBlend::BASE); tunetblLGS[i] = Bound(0, alphatbl[Bound(tableG[i] * lightparamalpha / 100, 0, 255)], CAlphaBlend::BASE); tunetblLBS[i] = Bound(0, alphatbl[Bound(tableB[i] * lightparamalpha / 100, 0, 255)], CAlphaBlend::BASE); //深色混合表 } } BYTE CAlphaBlend::rconv1(int n) { int pos = 0x80; int i = pos >> 1; while (i > 0) { if (n >= tbl1[pos]) { pos += i; } else { pos -= i; } i >>= 1; } if (n >= tbl1[pos]) { ++pos; } return (BYTE)(pos - 1); } class CAlphaBlendColorOne { private: BYTE fg; int temp_fg; const int* tunetbl; BYTE bg0; int alpha0; BYTE c0; public: CAlphaBlendColorOne() : fg(0), temp_fg(0), tunetbl(NULL), bg0(0), alpha0(0), c0(0) {} void init(BYTE f, const int* tbl); ~CAlphaBlendColorOne() {}; BYTE doAB(BYTE bg, int alpha); }; FORCEINLINE void CAlphaBlendColorOne::init(BYTE f, const int* tbl) { fg = f; temp_fg = s_AlphaBlendTable.conv1(fg); tunetbl = tbl; } FORCEINLINE BYTE CAlphaBlendColorOne::doAB(BYTE bg, int alpha) { int temp_alpha = tunetbl[alpha]; return temp_alpha ? s_AlphaBlendTable.conv2(s_AlphaBlendTable.conv1(bg) * (s_AlphaBlendTable.BASE - tunetbl[alpha]) + temp_fg * tunetbl[alpha]) : bg; } class CAlphaBlendColor { private: CAlphaBlendColorOne r; CAlphaBlendColorOne g; CAlphaBlendColorOne b; public: CAlphaBlendColor(COLORREF newColor, int paramalpha, BOOL lcd, BOOL dark, BOOL gbr = false); ~CAlphaBlendColor() { } BYTE doABsub(BYTE fg, int temp_fg, BYTE bg, int temp_alpha) const; COLORREF doAB(COLORREF baseColor, int alphaR, int alphaG, int alphaB, BOOL bClearAlpha); COLORREF doAB(COLORREF baseColor, int alpha, BOOL bClearAlpha) { return doAB(baseColor, alpha, alpha, alpha, bClearAlpha); } private: CAlphaBlendColor() { } }; FORCEINLINE CAlphaBlendColor::CAlphaBlendColor(COLORREF newColor, int paramalpha, BOOL lcd, BOOL dark, BOOL gbr) { const int* tblR; const int* tblG; const int* tblB; s_AlphaBlendTable.gettunetbl(paramalpha, lcd, dark, tblR, tblG, tblB); if (!gbr) { r.init(GetRValue(newColor), tblR); b.init(GetBValue(newColor), tblB); } else { r.init(GetBValue(newColor), tblB); b.init(GetRValue(newColor), tblR); } g.init(GetGValue(newColor), tblG); } FORCEINLINE COLORREF CAlphaBlendColor::doAB(COLORREF baseColor, int alphaR, int alphaG, int alphaB, BOOL bClearAlpha) { if (alphaB | alphaG | alphaR) { if (bClearAlpha) return RGB(r.doAB(GetRValue(baseColor), alphaR), g.doAB(GetGValue(baseColor), alphaG), b.doAB(GetBValue(baseColor), alphaB)); else return RGBA(r.doAB(GetRValue(baseColor), alphaR), g.doAB(GetGValue(baseColor), alphaG), b.doAB(GetBValue(baseColor), alphaB), baseColor >> 24); } else return baseColor; } FORCEINLINE BYTE CAlphaBlend::doAB(BYTE fg, BYTE bg, int alpha) { if (fg == bg || alpha <= 0) return bg; if (alpha >= 255) return fg; int temp_alpha = convalpha(alpha); int temp_bg = conv1(bg); int temp_fg = conv1(fg); int temp = temp_bg * (BASE - temp_alpha) + temp_fg * temp_alpha; return conv2(temp); } FORCEINLINE BYTE DoAlphaBlend(BYTE fg, BYTE bg, int alpha) { return s_AlphaBlendTable.doAB(fg, bg, alpha); } // LCD(液晶)用のアルファブレンド(サブピクセルレンダリング) static FORCEINLINE COLORREF AlphaBlendColorLCD( COLORREF baseColor, COLORREF newColor, int alphaR, int alphaG, int alphaB, const int* tableR, const int* tableG, const int* tableB, const FreeTypeDrawInfo& ftdi) { const BYTE rs = GetRValue(baseColor); const BYTE gs = GetGValue(baseColor); const BYTE bs = GetBValue(baseColor); BYTE rd = GetRValue(newColor); BYTE gd = GetGValue(newColor); BYTE bd = GetBValue(newColor); // アルファ値を補正 alphaR = tableR[alphaR] / ftdi.params->alpha; alphaG = tableG[alphaG] / ftdi.params->alpha; alphaB = tableB[alphaB] / ftdi.params->alpha; // rd = (((rd - rs) * alphaR) / 255) + rs; // gd = (((gd - gs) * alphaG) / 255) + gs; // bd = (((bd - bs) * alphaB) / 255) + bs; rd = DoAlphaBlend(rd, rs, alphaR); gd = DoAlphaBlend(gd, gs, alphaG); bd = DoAlphaBlend(bd, bs, alphaB); return RGB(rd, gd, bd); } // アルファブレンド(256階調) static FORCEINLINE COLORREF AlphaBlendColor( COLORREF baseColor, COLORREF newColor, int alpha, const int* table, const FreeTypeDrawInfo& ftdi) { const BYTE rs = GetRValue(baseColor); const BYTE gs = GetGValue(baseColor); const BYTE bs = GetBValue(baseColor); BYTE rd = GetRValue(newColor); BYTE gd = GetGValue(newColor); BYTE bd = GetBValue(newColor); // アルファ値を補正 alpha = table[alpha] / ftdi.params->alpha; // rd = (rs * (255 - alpha) + rd * alpha) / 255; // gd = (gs * (255 - alpha) + gd * alpha) / 255; // bd = (bs * (255 - alpha) + bd * alpha) / 255; // rd = (((rd - rs) * alpha) / 255) + rs; // gd = (((gd - gs) * alpha) / 255) + gs; // bd = (((bd - bs) * alpha) / 255) + bs; rd = DoAlphaBlend(rd, rs, alpha); gd = DoAlphaBlend(gd, gs, alpha); bd = DoAlphaBlend(bd, bs, alpha); return RGB(rd, gd, bd); } typedef struct { FreeTypeDrawInfo* FTInfo; //orignal draw information WCHAR wch; //text to draw FT_BitmapGlyph FTGlyph; //glyph int AAMode; //antialiased mode for every char CAlphaBlendColor* solid; CAlphaBlendColor* shadow; //alpha blender bool bInvertColor; // invert color for chrome/skia } FreeTypeGlyphInfo, * PFreeTypeGlyphInfo; // 2階調 static void FreeTypeDrawBitmapPixelModeMono(FreeTypeGlyphInfo& FTGInfo, CAlphaBlendColor& ab, int x, int y) { CBitmapCache& cache = *FTGInfo.FTInfo->pCache; const FT_Bitmap* bitmap = &FTGInfo.FTGlyph->bitmap; BYTE alphatuner = FTGInfo.FTInfo->params->alphatuner; int i, j; int dx, dy; // display FT_Bytes p; if (bitmap->pixel_mode != FT_PIXEL_MODE_MONO) { return; } const COLORREF color = RGB2DIB(FTGInfo.FTInfo->Color()); const SIZE cachebufsize = cache.Size(); DWORD* const cachebufp = (DWORD*)cache.GetPixels(); DWORD* cachebufrowp; int left, top, width, height; if (x < 0) { left = -x; x = 0; } else { left = 0; } width = Min((int)bitmap->width, (int)(cachebufsize.cx - x)); top = 0; height = bitmap->rows; for (j = top, dy = y; j < height; ++j, ++dy) { if ((unsigned int)dy >= (unsigned int)cachebufsize.cy) continue; p = bitmap->pitch < 0 ? &bitmap->buffer[(-bitmap->pitch * bitmap->rows) - bitmap->pitch * j] : // up-flow &bitmap->buffer[bitmap->pitch * j]; // down-flow cachebufrowp = &cachebufp[dy * cachebufsize.cx]; for (i = left, dx = x; i < width; ++i, ++dx) { if ((p[i / 8] & (1 << (7 - (i % 8)))) != 0) { cachebufrowp[dx] = color; } } } } // LCD(液晶)用描画(サブピクセルレンダリング) // RGB順(のはず) static void FreeTypeDrawBitmapPixelModeLCD(FreeTypeGlyphInfo& FTGInfo, CAlphaBlendColor& ab, int x, int y) { CBitmapCache& cache = *FTGInfo.FTInfo->pCache; const FT_Bitmap* bitmap = &FTGInfo.FTGlyph->bitmap; BYTE alphatuner = FTGInfo.FTInfo->params->alphatuner; int AAMode = FTGInfo.AAMode; int i, j; int dx, dy; // display FT_Bytes p; if (bitmap->pixel_mode != FT_PIXEL_MODE_LCD) { return; } const COLORREF color = FTGInfo.FTInfo->Color(); const SIZE cachebufsize = cache.Size(); DWORD* const cachebufp = (DWORD*)cache.GetPixels(); DWORD* cachebufrowp; // LCDは3サブピクセル分ある int left, top, width, height; if (x < 0) { left = -x * 3; x = 0; } else { left = 0; } width = Min((int)bitmap->width, (int)(cachebufsize.cx - x) * 3); top = 0; height = bitmap->rows; //CAlphaBlendColor ab(color, ftdi.params->alpha, true, true); COLORREF backColor, newColor; unsigned int alphaR, alphaG, alphaB; BOOL bAlphaDraw = FTGInfo.FTInfo->params->alpha != 1; if (bAlphaDraw) for (j = 0, dy = y; j < height; ++j, ++dy) { if ((unsigned int)dy >= (unsigned int)cachebufsize.cy) continue; p = bitmap->pitch < 0 ? &bitmap->buffer[(-bitmap->pitch * bitmap->rows) - bitmap->pitch * j] : // up-flow &bitmap->buffer[bitmap->pitch * j]; // down-flow cachebufrowp = &cachebufp[dy * cachebufsize.cx]; for (i = left, dx = x; i < width; i += 3, ++dx) { backColor = cachebufrowp[dx]; COLORREF last = 0xFFFFFFFF; if (AAMode == 2 || AAMode == 4) { // This is for displays with subpixels in RGB order alphaR = p[i + 0] / alphatuner; alphaG = p[i + 1] / alphatuner; alphaB = p[i + 2] / alphatuner; } else { // BGR alphaR = p[i + 2] / alphatuner; alphaG = p[i + 1] / alphatuner; alphaB = p[i + 0] / alphatuner; } /* if (bAlphaDraw) { if (alphaB && alphaG && alphaR) backColor &= 0x00ffffff; } else*/ //if ((alphaB || alphaG || alphaR)) // backColor &= 0x00ffffff; newColor = ab.doAB(backColor, alphaB, alphaG, alphaR, !bAlphaDraw); cachebufrowp[dx] = newColor; } } else for (j = 0, dy = y; j < height; ++j, ++dy) { if ((unsigned int)dy >= (unsigned int)cachebufsize.cy) continue; p = bitmap->pitch < 0 ? &bitmap->buffer[(-bitmap->pitch * bitmap->rows) - bitmap->pitch * j] : // up-flow &bitmap->buffer[bitmap->pitch * j]; // down-flow cachebufrowp = &cachebufp[dy * cachebufsize.cx]; for (i = left, dx = x; i < width; i += 3, ++dx) { backColor = cachebufrowp[dx]; COLORREF last = 0xFFFFFFFF; if (AAMode == 2 || AAMode == 4) { // これはRGBの順にサブピクセルがあるディスプレイ用 // これはRGBの順にサブピクセルがあるディスプレイ用 alphaR = p[i + 0]; alphaG = p[i + 1]; alphaB = p[i + 2]; } else { // BGR alphaR = p[i + 2]; alphaG = p[i + 1]; alphaB = p[i + 0]; } /* if (bAlphaDraw) { if (alphaB && alphaG && alphaR) backColor &= 0x00ffffff; } else*/ //if ((alphaB || alphaG || alphaR)) // backColor &= 0x00ffffff; newColor = ab.doAB(backColor, alphaB, alphaG, alphaR, !bAlphaDraw); cachebufrowp[dx] = newColor; } } } COLORREF _rgbamixer(COLORREF bkColor, int b, int g, int r, int a) { int bkr = GetRValue(bkColor), bkg = GetGValue(bkColor), bkb = GetBValue(bkColor); return a << 24 | (bkb - a * bkb / 255 + b) << 16 | (bkg - a * bkg / 255 + g) << 8 | (bkr - a * bkr / 255 + r); } // color blender for color font COLORREF _invert_rgbamixer(COLORREF bkColor, int b, int g, int r, int a) { if (!a) return bkColor; int invertr, invertg, invertb; if (a == 255) { invertr = InvertTable[r]; invertg = InvertTable[g]; invertb = InvertTable[b]; } else { invertr = InvertTable[r * 255 / a] * a / 255; invertg = InvertTable[g * 255 / a] * a / 255; invertb = InvertTable[b * 255 / a] * a / 255; } return _rgbamixer(bkColor, invertb, invertg, invertr, a); } // draw color emoji static void FreeTypeDrawBitmapPixelModeBGRA(FreeTypeGlyphInfo& FTGInfo, int x, int y) { CBitmapCache& cache = *FTGInfo.FTInfo->pCache; const FT_Bitmap* bitmap = &FTGInfo.FTGlyph->bitmap; BYTE alphatuner = FTGInfo.FTInfo->params->alphatuner; BOOL bAlphaDraw = FTGInfo.FTInfo->params->alpha != 1; int AAMode = FTGInfo.AAMode; int i, j; int dx, dy; // display FT_Bytes p; if (bAlphaDraw) { // no shadow for color font return; } if (bitmap->pixel_mode != FT_PIXEL_MODE_BGRA) { return; } const COLORREF color = FTGInfo.FTInfo->Color(); const SIZE cachebufsize = cache.Size(); DWORD* const cachebufp = (DWORD*)cache.GetPixels(); DWORD* cachebufrowp; typedef COLORREF(*pfnmixer) (COLORREF bkColor, int b, int g, int r, int a); pfnmixer mixer = FTGInfo.bInvertColor ? _invert_rgbamixer : _rgbamixer; int left, top, width, height; if (x < 0) { left = -x * 4; x = 0; } else { left = 0; } width = Min((int)bitmap->width * 4, (int)(cachebufsize.cx - x) * 4); top = 0; height = bitmap->rows; COLORREF backColor, newColor; unsigned int alphaR, alphaG, alphaB, alpha; for (j = 0, dy = y; j < height; ++j, ++dy) { if ((unsigned int)dy >= (unsigned int)cachebufsize.cy) continue; p = bitmap->pitch < 0 ? &bitmap->buffer[(-bitmap->pitch * bitmap->rows) - bitmap->pitch * j] : // up-flow &bitmap->buffer[bitmap->pitch * j]; // down-flow cachebufrowp = &cachebufp[dy * cachebufsize.cx]; for (i = left, dx = x; i < width; i += 4, ++dx) { backColor = cachebufrowp[dx]; COLORREF last = 0xFFFFFFFF; // always RGB alphaR = p[i + 0]; alphaG = p[i + 1]; alphaB = p[i + 2]; alpha = p[i + 3]; newColor = mixer(backColor, alphaB, alphaG, alphaR, alpha); cachebufrowp[dx] = newColor; } } } static void FreeTypeDrawBitmapGray(FreeTypeGlyphInfo& FTGInfo, CAlphaBlendColor& ab, int x, int y) { int i, j; int dx, dy; // display COLORREF c; FT_Bytes p; CBitmapCache& cache = *FTGInfo.FTInfo->pCache; const FT_Bitmap* bitmap = &FTGInfo.FTGlyph->bitmap; BYTE alphatuner = FTGInfo.FTInfo->params->alphatuner; BOOL bAlphaDraw = FTGInfo.FTInfo->params->alpha != 1; const COLORREF color = FTGInfo.FTInfo->Color(); const SIZE cachebufsize = cache.Size(); DWORD* const cachebufp = (DWORD*)cache.GetPixels(); DWORD* cachebufrowp; int left, top, width, height; if (x < 0) { left = -x; x = 0; } else { left = 0; } width = Min((int)bitmap->width, (int)(cachebufsize.cx - x)); top = 0; height = bitmap->rows; // CAlphaBlendColor ab(color, ftdi.params->alpha, false, true); COLORREF backColor; int alpha; for (j = top, dy = y; j < height; ++j, ++dy) { if ((unsigned int)dy >= (unsigned int)cachebufsize.cy) continue; p = bitmap->pitch < 0 ? &bitmap->buffer[(-bitmap->pitch * bitmap->rows) - bitmap->pitch * j] : // up-flow &bitmap->buffer[bitmap->pitch * j]; // down-flow cachebufrowp = &cachebufp[dy * cachebufsize.cx]; for (i = left, dx = x; i < width; ++i, ++dx) { alpha = p[i]; backColor = cachebufrowp[dx]; c = ab.doAB(backColor, alpha, !bAlphaDraw); cachebufrowp[dx] = c; } } } // グリフビットマップのレンダリング static bool FreeTypeDrawBitmap( FreeTypeGlyphInfo& FTGInfo, CAlphaBlendColor& ab, int x, int y) { if (FTGInfo.FTGlyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY) { // この関数自体はFT_PIXEL_MODE_GRAYにのみ対応し他に委譲する switch (FTGInfo.FTGlyph->bitmap.pixel_mode) { case FT_PIXEL_MODE_MONO: FreeTypeDrawBitmapPixelModeMono(FTGInfo, ab, x, y); break; case FT_PIXEL_MODE_LCD: FreeTypeDrawBitmapPixelModeLCD(FTGInfo, ab, x, y); break; case FT_PIXEL_MODE_BGRA: FreeTypeDrawBitmapPixelModeBGRA(FTGInfo, x, y); break; default: return false; // 未対応 } return true; } FreeTypeDrawBitmapGray(FTGInfo, ab, x, y); return true; } // 縦書き用のレンダリング(コピペ手抜き) // 2階調 static void FreeTypeDrawBitmapPixelModeMonoV(FreeTypeGlyphInfo& FTGInfo, CAlphaBlendColor& ab, int x, int y) { CBitmapCache& cache = *FTGInfo.FTInfo->pCache; FT_Bitmap* bitmap = &FTGInfo.FTGlyph->bitmap; int i, j; int dx, dy; // display FT_Bytes p; if (bitmap->pixel_mode != FT_PIXEL_MODE_MONO) { return; } const COLORREF color = FTGInfo.FTInfo->Color(); const int width = bitmap->width; const int height = bitmap->rows; for (j = 0, dy = x; j < height; ++j, ++dy) { p = bitmap->pitch < 0 ? &bitmap->buffer[(-bitmap->pitch * bitmap->rows) - bitmap->pitch * j] : // up-flow &bitmap->buffer[bitmap->pitch * j]; // down-flow for (i = 0, dx = y + width; i < width; ++i, --dx) { if ((p[i / 8] & (1 << (7 - (i % 8)))) != 0) { if (cache.GetPixel(dx, dy) != CLR_INVALID) { // dx dy エラーチェック cache.SetCurrentPixel(color); } } } } } // LCD(液晶)用描画(サブピクセルレンダリング) // RGB順(のはず) static void FreeTypeDrawBitmapPixelModeLCDV(FreeTypeGlyphInfo& FTGInfo, CAlphaBlendColor& ab, int x, int y) { CBitmapCache& cache = *FTGInfo.FTInfo->pCache; const FT_Bitmap* bitmap = &FTGInfo.FTGlyph->bitmap; BYTE alphatuner = FTGInfo.FTInfo->params->alphatuner; int AAMode = FTGInfo.AAMode; int i, j; int dx, dy; // display COLORREF c; FT_Bytes p; if (bitmap->pixel_mode != FT_PIXEL_MODE_LCD_V) { return; } const COLORREF color = FTGInfo.FTInfo->Color(); // LCDは3サブピクセル分ある const int width = bitmap->width; const int height = bitmap->rows; const int pitch = bitmap->pitch; const int pitchabs = pitch < 0 ? -pitch : pitch; BOOL bAlphaDraw = FTGInfo.FTInfo->params->alpha != 1; //CAlphaBlendColor ab(color, ftdi.params->alpha, true); if (bAlphaDraw) for (j = 0, dy = x; j < height; j += 3, ++dy) { p = pitch < 0 ? &bitmap->buffer[(pitchabs * bitmap->rows) + pitchabs * j] : // up-flow &bitmap->buffer[pitchabs * j]; // down-flow int alphaR, alphaG, alphaB; for (i = 0, dx = y + width; i < width; ++i, --dx) { COLORREF backColor = cache.GetPixel(dy, dx); if (backColor == color || backColor == CLR_INVALID) continue; if (AAMode == 2 || AAMode == 4) { // これはRGBの順にサブピクセルがあるディスプレイ用 alphaR = p[i + 0] / alphatuner; alphaG = p[i + pitch] / alphatuner; alphaB = p[i + pitch * 2] / alphatuner; } else { // BGR alphaR = p[i + pitch * 2] / alphatuner; alphaG = p[i + pitch] / alphatuner; alphaB = p[i + 0] / alphatuner; } c = ab.doAB(backColor, alphaR, alphaG, alphaB, !bAlphaDraw); cache.SetCurrentPixel(c); } if (i >= width) continue; } else for (j = 0, dy = x; j < height; j += 3, ++dy) { p = pitch < 0 ? &bitmap->buffer[(pitchabs * bitmap->rows) + pitchabs * j] : // up-flow &bitmap->buffer[pitchabs * j]; // down-flow int alphaR, alphaG, alphaB; for (i = 0, dx = y + width; i < width; ++i, --dx) { COLORREF backColor = cache.GetPixel(dy, dx); if (backColor == color || backColor == CLR_INVALID) continue; if (AAMode == 2 || AAMode == 4) { // これはRGBの順にサブピクセルがあるディスプレイ用 alphaR = p[i + 0]; alphaG = p[i + pitch]; alphaB = p[i + pitch * 2]; } else { // BGR alphaR = p[i + pitch * 2]; alphaG = p[i + pitch]; alphaB = p[i + 0]; } c = ab.doAB(backColor, alphaR, alphaG, alphaB, !bAlphaDraw); cache.SetCurrentPixel(c); } if (i >= width) continue; } } void FreeTypeDrawBitmapGrayV(FreeTypeGlyphInfo& FTGInfo, CAlphaBlendColor& ab, int x, int y) { CBitmapCache& cache = *FTGInfo.FTInfo->pCache; const FT_Bitmap* bitmap = &FTGInfo.FTGlyph->bitmap; BYTE alphatuner = FTGInfo.FTInfo->params->alphatuner; int i, j; int dx, dy; // display int width, height; COLORREF c; FT_Bytes p; const COLORREF color = FTGInfo.FTInfo->Color(); //const CGdippSettings* pSettings = CGdippSettings::GetInstance(); //const int* table = pSettings->GetTuneTable(); width = bitmap->width; height = bitmap->rows; // CAlphaBlendColor ab(color, ftdi.params->alpha, false); for (j = 0, dy = x; j < height; ++j, ++dy) { p = bitmap->pitch < 0 ? &bitmap->buffer[(-bitmap->pitch * bitmap->rows) - bitmap->pitch * j] : // up-flow &bitmap->buffer[bitmap->pitch * j]; // down-flow for (i = 0, dx = y + width; i < width; ++i, --dx) { const COLORREF backColor = cache.GetPixel(dy, dx); if (backColor == color || backColor == CLR_INVALID) continue; c = ab.doAB(backColor, p[i], true); cache.SetPixelV(dy, dx, c); } } } static bool FreeTypeDrawBitmapV(FreeTypeGlyphInfo& FTGInfo, CAlphaBlendColor& ab, const int x, const int y) { if (FTGInfo.FTGlyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY) { // この関数自体はFT_PIXEL_MODE_GRAYにのみ対応し他に委譲する switch (FTGInfo.FTGlyph->bitmap.pixel_mode) { case FT_PIXEL_MODE_MONO: FreeTypeDrawBitmapPixelModeMonoV(FTGInfo, ab, x, y); break; case FT_PIXEL_MODE_LCD_V: FreeTypeDrawBitmapPixelModeLCDV(FTGInfo, ab, x, y); break; case FT_PIXEL_MODE_BGRA: FreeTypeDrawBitmapPixelModeBGRA(FTGInfo, x, y); break; default: return false; // 未対応 } return true; } FreeTypeDrawBitmapGrayV(FTGInfo, ab, x, y); return true; } class CGGOGlyphLoader { private: FT_Library m_lib; const FT_Glyph_Class* m_clazz; BYTE bgtbl[0x41]; static int CALLBACK EnumFontFamProc(const LOGFONT* lplf, const TEXTMETRIC* lptm, DWORD FontType, LPARAM lParam); public: CGGOGlyphLoader() : m_lib(NULL), m_clazz(NULL) {} ~CGGOGlyphLoader() {} bool init(FT_Library freetype_library); FT_Library getlib() { return m_lib; } const FT_Glyph_Class* getclazz() { return m_clazz; } BYTE convbgpixel(BYTE val) { return bgtbl[val]; } }; static CGGOGlyphLoader s_GGOGlyphLoader; int CALLBACK CGGOGlyphLoader::EnumFontFamProc(const LOGFONT* lplf, const TEXTMETRIC* lptm, DWORD FontType, LPARAM lParam) { CGGOGlyphLoader* pThis = reinterpret_cast(lParam); if (FontType != TRUETYPE_FONTTYPE || lplf->lfCharSet == SYMBOL_CHARSET) { return TRUE; } TRACE(_T("Face: %s\n"), lplf->lfFaceName); FreeTypeSysFontData* pFont = FreeTypeSysFontData::CreateInstance(lplf->lfFaceName, 0, false); if (!pFont) { return TRUE; } const FT_Glyph_Class* clazz = NULL; FT_Face face = pFont->GetFace(); FT_Error err = FT_Set_Pixel_Sizes(face, 0, 12);//optimized if (!err) { err = FT_Load_Char(face, lptm->tmDefaultChar, FT_LOAD_NO_BITMAP); if (!err) { FT_Glyph glyph; err = FT_Get_Glyph(face->glyph, &glyph); if (!err) { if (glyph->format == FT_GLYPH_FORMAT_OUTLINE) { clazz = glyph->clazz; } FT_Done_Glyph(glyph); } } } FT_Done_Face(face); if (clazz) { pThis->m_clazz = clazz; //列挙中止 return FALSE; } return TRUE; } bool CGGOGlyphLoader::init(FT_Library freetype_library) { if (m_lib) { return true; } if (!freetype_library) { return false; } for (BYTE val = 0; val <= 0x40; ++val) { BYTE t = (BYTE)(((DWORD)val * 256) / 65); bgtbl[val] = t + (t >> 6); } m_lib = freetype_library; m_clazz = NULL; //前の方法だと、arial.ttfが無いとまずそうなので //適当に使えるアウトラインフォントを探す HDC hdc = CreateCompatibleDC(NULL); EnumFontFamilies(hdc, NULL, EnumFontFamProc, reinterpret_cast(this)); DeleteDC(hdc); if (m_clazz != NULL) { return true; } m_lib = NULL; return false; } class CGGOOutlineGlyph { private: FT_OutlineGlyph m_ptr; static FT_F26Dot6 toF26Dot6(const FIXED& fx) { return *(LONG*)(&fx) >> 10; } static FT_Fixed toFixed(const short n) { return (FT_Fixed)n << 16; } static char getTag(char tag, const FT_Vector& point) { if ((point.x & 0x0f) != 0) { tag |= FT_CURVE_TAG_TOUCH_X; } if ((point.y & 0x0f) != 0) { tag |= FT_CURVE_TAG_TOUCH_Y; } return tag; } public: CGGOOutlineGlyph() : m_ptr(NULL) { _ASSERTE(s_GGOGlyphLoader.getlib()); } ~CGGOOutlineGlyph() { done(); }; bool init(DWORD bufsize, PVOID bufp, const GLYPHMETRICS& gm); void done(); operator FT_Glyph () { return (FT_Glyph)m_ptr; } }; void CGGOOutlineGlyph::done() { if (m_ptr) { free(m_ptr->outline.points); free(m_ptr->outline.tags); free(m_ptr->outline.contours); } free(m_ptr); m_ptr = NULL; } bool CGGOOutlineGlyph::init(DWORD bufsize, PVOID bufp, const GLYPHMETRICS& gm) { done(); m_ptr = (FT_OutlineGlyph)calloc(1, sizeof * m_ptr); if (!m_ptr) { return false; } FT_GlyphRec& root = m_ptr->root; FT_Outline& outline = m_ptr->outline; root.library = s_GGOGlyphLoader.getlib(); root.clazz = s_GGOGlyphLoader.getclazz(); root.format = FT_GLYPH_FORMAT_OUTLINE; root.advance.x = toFixed(gm.gmCellIncX); root.advance.y = toFixed(gm.gmCellIncY); outline.n_contours = 0; outline.n_points = 0; outline.flags = 0; //FT_OUTLINE_HIGH_PRECISION; LPTTPOLYGONHEADER ttphp = (LPTTPOLYGONHEADER)bufp; LPTTPOLYGONHEADER ttphpend = (LPTTPOLYGONHEADER)((PBYTE)ttphp + bufsize); while (ttphp < ttphpend) { LPTTPOLYCURVE ttpcp = (LPTTPOLYCURVE)(ttphp + 1); LPTTPOLYCURVE ttpcpend = (LPTTPOLYCURVE)((PBYTE)ttphp + ttphp->cb); if ((PVOID)ttpcpend > (PVOID)ttphpend) { break; } ++outline.n_points; ++outline.n_contours; while (ttpcp < ttpcpend) { LPPOINTFX pfxp = &ttpcp->apfx[0]; outline.n_points += ttpcp->cpfx; ttpcp = (LPTTPOLYCURVE)(pfxp + ttpcp->cpfx); } ttphp = (LPTTPOLYGONHEADER)ttpcp; } if (ttphp != ttphpend) { return false; } outline.points = (FT_Vector*)calloc(outline.n_points, sizeof * outline.points); outline.tags = (unsigned char*)calloc(outline.n_points, sizeof * outline.tags); outline.contours = (unsigned short*)calloc(outline.n_contours, sizeof * outline.contours); if (!outline.points || !outline.tags || !outline.contours) { done(); return false; } unsigned short* cp = outline.contours; short ppos = 0; ttphp = (LPTTPOLYGONHEADER)bufp; while (ttphp < ttphpend) { LPTTPOLYCURVE ttpcp = (LPTTPOLYCURVE)(ttphp + 1); LPTTPOLYCURVE ttpcpend = (LPTTPOLYCURVE)((PBYTE)ttphp + ttphp->cb); LPPOINTFX pfxp0 = &ttpcp->apfx[0]; while (ttpcp < ttpcpend) { LPPOINTFX pfxp = &ttpcp->apfx[0]; pfxp0 = pfxp + (ttpcp->cpfx - 1); ttpcp = (LPTTPOLYCURVE)(pfxp + ttpcp->cpfx); } ttpcp = (LPTTPOLYCURVE)(ttphp + 1); if (pfxp0->x.value != ttphp->pfxStart.x.value || pfxp0->x.fract != ttphp->pfxStart.x.fract || pfxp0->y.value != ttphp->pfxStart.y.value || pfxp0->y.fract != ttphp->pfxStart.y.fract) { outline.points[ppos].x = toF26Dot6(ttphp->pfxStart.x); outline.points[ppos].y = toF26Dot6(ttphp->pfxStart.y); outline.tags[ppos] = getTag(FT_CURVE_TAG_ON, outline.points[ppos]); ++ppos; } while (ttpcp < ttpcpend) { char tag; switch (ttpcp->wType) { case TT_PRIM_LINE: tag = FT_CURVE_TAG_ON; break; case TT_PRIM_QSPLINE: tag = FT_CURVE_TAG_CONIC; break; case TT_PRIM_CSPLINE: tag = FT_CURVE_TAG_CONIC; break; default: tag = 0; } LPPOINTFX pfxp = &ttpcp->apfx[0]; for (WORD cnt = 0; cnt < ttpcp->cpfx; ++cnt) { outline.points[ppos].x = toF26Dot6(pfxp->x); outline.points[ppos].y = toF26Dot6(pfxp->y); outline.tags[ppos] = tag; ++ppos; ++pfxp; } outline.tags[ppos - 1] = getTag(FT_CURVE_TAG_ON, outline.points[ppos - 1]); ttpcp = (LPTTPOLYCURVE)pfxp; } *cp++ = ppos - 1; ttphp = (LPTTPOLYGONHEADER)ttpcp; } outline.n_points = ppos; return true; } template class CTempMem { private: char m_localbuf[0x0f80]; DWORD m_size; T m_ptr; public: CTempMem() : m_size(sizeof m_localbuf), m_ptr((T)m_localbuf) { } ~CTempMem() { done(); } T init(DWORD size) { done(); if (m_size > size) { m_size = size; m_ptr = (T)malloc(m_size); } return m_ptr; } void done() { if (m_ptr != (T)m_localbuf) { free(m_ptr); } m_size = sizeof m_localbuf; m_ptr = (T)m_localbuf; } operator T () { return m_ptr; } bool operator ! () { return !m_ptr; } DWORD getsize() { return m_size; } }; bool IsSFNTNameMatch(const FT_Face& face, FT_UInt nameID, wstring name) { // get sfnt name by platform id auto getSfntName = [](FT_SfntName& fn)->wstring { switch (fn.platform_id) { case 0: { return wstring(reinterpret_cast(fn.string), fn.string_len); } case 1: { // macintosh return to_wide_string(string(reinterpret_cast(fn.string), fn.string_len)); } case 3: { // Windows switch (fn.encoding_id) { case 0: case 1: { return to_utf16le(wstring(reinterpret_cast(fn.string), fn.string_len)); } default: return to_wide_string(string(reinterpret_cast(fn.string), fn.string_len)); } } } return L""; }; auto getWordSet = [](const wstring& str) { set words; wstringstream ss(to_lower_case(str)); wstring word; while (ss >> word) { if (word != L"regular") // drop the regular style as it can be omitted words.insert(word); } return words; }; auto compareStyle = [&](const wstring nameA, const wstring nameB)->bool { auto setA = getWordSet(nameA); auto setB = getWordSet(nameB); return setA == setB; }; FT_SfntName sfntName; FT_UInt nameCount = FT_Get_Sfnt_Name_Count(face); for (FT_UInt i = 0; i < nameCount; ++i) { if (FT_Get_Sfnt_Name(face, i, &sfntName) == 0) { if (sfntName.name_id == nameID) { if (sfntName.string_len > 0 && sfntName.string) { wstring fontName = getSfntName(sfntName); if (compareStyle(fontName, name)) { return true; } } } } } return false; } void VarFontByAlias(const FT_Face& face, const wstring& lfStyleName) { FT_MM_Var* mm_var = nullptr; auto error = FT_Get_MM_Var(face, &mm_var); if (error) { return; // not a varaible font } if (!mm_var->num_namedstyles) return; // no named instance, nothing to adjust. for (unsigned int i = 0; i < mm_var->num_namedstyles; ++i) { auto& style = mm_var->namedstyle[i]; if (IsSFNTNameMatch(face, style.strid, lfStyleName)) { // found it FT_Set_Named_Instance(face, i+1); break; } } // Free the MM_Var structure FT_Done_MM_Var(freetype_library, mm_var); mm_var = nullptr; // Avoid double free later } BOOL FreeTypePrepare(FreeTypeDrawInfo& FTInfo) { //CDebugElapsedCounter cntr("FreeTypePrepare"); #ifdef _DEBUG FTInfo.Validate(); #endif FT_Face& freetype_face = FTInfo.freetype_face; FT_Int& cmap_index = FTInfo.cmap_index; FT_Render_Mode& render_mode = FTInfo.render_mode; FTC_ImageTypeRec& font_type = FTInfo.font_type; FreeTypeFontInfo*& pfi = FTInfo.pfi; const CFontSettings*& pfs = FTInfo.pfs; FreeTypeFontCache*& pftCache = FTInfo.pftCache; FTC_ScalerRec& scaler = FTInfo.scaler; TEXTMETRIC& tm = FTInfo.params->otm->otmTextMetrics; FTC_FaceID face_id = NULL; int height = 0; const LOGFONTW& lf = FTInfo.LogFont(); render_mode = FT_RENDER_MODE_NORMAL; if (FTInfo.params->alpha < 1) FTInfo.params->alpha = 1; if (!*lf.lfFaceName) return FALSE; //optimized FTInfo.face_id_list_num = 0; //Assert(_tcsicmp(lf.lfFaceName, _T("@Arial Unicode MS")) != 0); pfi = NULL; CGdippSettings* pSettings = CGdippSettings::GetInstance(); const bool bVertical = pSettings->FontLoader() == SETTING_FONTLOADER_FREETYPE ? lf.lfFaceName[0] == _T('@') : false; FreeTypeFontInfo* pfitemp = g_pFTEngine->FindFont(FTInfo.params); if (pfitemp) { if (!pfi) pfi = pfitemp; FTInfo.face_id_list_num = pfi->GetFTLink(&FTInfo.face_id_list); pfi->GetGGOLink(&FTInfo.ggo_font_list); FTInfo.face_id_simsun = pfi->GetSimSunID(); } else return FALSE; if (!(freetype_face = FTInfo.GetFace(0))) { pSettings->AddFontExclude(lf.lfFaceName); return FALSE; } if (!pfi) { return FALSE; } FTInfo.params->lplf->lfWeight = FTInfo.params->otm->otmTextMetrics.tmWeight; //更新到标准weight pfs = &pfi->GetFontSettings(); cmap_index = -1; switch (pSettings->FontLoader()) { case SETTING_FONTLOADER_FREETYPE: { face_id = (FTC_FaceID)pfi->GetId(); scaler.face_id = face_id; height = FTInfo.params->otm->otmTextMetrics.tmHeight - FTInfo.params->otm->otmTextMetrics.tmInternalLeading; //Snowie!!剪掉空白高度,bugfix。 // if(lf.lfHeight > 0){ // scaler.height = height; // } // else{ scaler.height = height; // } //Snowie!! TT_OS2* os2_table = pfitemp->GetOS2Table(); if (lf.lfQuality && os2_table->xAvgCharWidth) { if (!(freetype_face->style_flags & FT_STYLE_FLAG_BOLD) && tm.tmWeight >= FW_BOLD) --FTInfo.params->otm->otmTextMetrics.tmAveCharWidth; scaler.width = MulDiv(FTInfo.params->otm->otmTextMetrics.tmAveCharWidth, FTInfo.params->otm->otmEMSquare, os2_table->xAvgCharWidth); } else scaler.width = scaler.height; if (bVertical) swap(scaler.width, scaler.height);//如果是竖向字体,交换宽高 //!!Snowie scaler.pixel = 1; scaler.x_res = 0; scaler.y_res = 0; /* FT_Size font_size; { CCriticalSectionLock __lock(CCriticalSectionLock::CS_MANAGER); if(FTC_Manager_LookupSize(cache_man, &scaler, &font_size)) return FALSE; }*/ height = scaler.height; break; } case SETTING_FONTLOADER_WIN32: { /* OUTLINETEXTMETRIC otm; if (GetOutlineTextMetrics(FTInfo.hdc, sizeof otm, &otm) != sizeof otm) { return FALSE; }*/ height = -lf.lfHeight; scaler.height = height; scaler.width = lf.lfWidth; } break; default: return FALSE; } // fetch face again to get the correct one. if (!(freetype_face = FTInfo.GetFace(0))) { pSettings->AddFontExclude(lf.lfFaceName); return FALSE; } pftCache = pfi->GetCache(scaler, lf); if (!pftCache) return FALSE; /*FT_Size_RequestRec size_request; size_request.width = lf.lfWidth; size_request.horiResolution = 0; size_request.vertResolution = 0; if(lf.lfHeight > 0){ // セル高さ size_request.type = FT_SIZE_REQUEST_TYPE_CELL; size_request.height = lf.lfHeight * 64; } else{ // 文字高さ size_request.type = FT_SIZE_REQUEST_TYPE_NOMINAL; size_request.height = (-lf.lfHeight) * 64; } if(FT_Request_Size(freetype_face, &size_request)) goto Exit2;*/ switch (pSettings->FontLoader()) { case SETTING_FONTLOADER_FREETYPE: // font_typeを設定 font_type.face_id = face_id; font_type.width = scaler.width;//freetype_face->size->metrics.x_ppem; font_type.height = scaler.height;//freetype_face->size->metrics.y_ppem; //Snowie!! FTInfo.height = font_type.height; FTInfo.width = font_type.width; /* ビットマップまでキャッシュする場合はFT_LOAD_RENDER | FT_LOAD_TARGET_* * とする。ただし途中でTARGETを変更した場合等はキャッシュが邪魔する。 * そういう時はFT_LOAD_DEFAULTにしてFTC_ImageCache_Lookup後に * FT_Glyph_To_Bitmapしたほうが都合がいいと思う。 */ // Boldは太り具合というものがあるので本当はこれだけでは足りない気がする。 /*if(IsFontBold(lf) && !(freetype_face->style_flags & FT_STYLE_FLAG_BOLD) || lf.lfItalic && !(freetype_face->style_flags & FT_STYLE_FLAG_ITALIC)){ // ボールド、イタリックは後でレンダリングする // 多少速度は劣化するだろうけど仕方ない。 font_type.flags = FT_LOAD_NO_BITMAP; } else{ font_type.flags = FT_LOAD_RENDER | FT_LOAD_NO_BITMAP; }*/ break; case SETTING_FONTLOADER_WIN32: font_type.face_id = face_id; font_type.width = -1; font_type.height = -1; break; DEFAULT_UNREACHABLE; } font_type.flags = FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH; // ヒンティング switch (pfs->GetHintingMode()) { case 0: // ignore. break; case 1: font_type.flags |= FT_LOAD_NO_HINTING; break; case 2: font_type.flags |= FT_LOAD_FORCE_AUTOHINT; break; } //如果含有内置hinting则启用default模式,否则使用autohint模式,以保证效果 // アンチエイリアス if (FTInfo.IsMono()) { font_type.flags |= FT_LOAD_TARGET_MONO; render_mode = FT_RENDER_MODE_MONO; } else { switch (pfs->GetAntiAliasMode()) { case -1: font_type.flags |= FT_LOAD_TARGET_MONO; render_mode = FT_RENDER_MODE_MONO; break; case 0: font_type.flags |= FT_LOAD_TARGET_NORMAL; render_mode = FT_RENDER_MODE_NORMAL; break; case 1: font_type.flags |= FT_LOAD_TARGET_LIGHT; render_mode = FT_RENDER_MODE_LIGHT; break; case 2: case 3: font_type.flags |= FT_LOAD_TARGET_LCD; render_mode = FT_RENDER_MODE_LCD; break; case 4: case 5: font_type.flags |= FT_LOAD_TARGET_LIGHT; render_mode = FT_RENDER_MODE_LCD; break; } } if (pSettings->HintSmallFont() /*&& font_type.flags & FT_LOAD_TARGET_LIGHT*/ && font_type.height != -1 && font_type.height < 12) //通用设置不使用hinting,但是打开了小字体hinting开关 { /* if (!(freetype_face->face_flags & FT_FACE_FLAG_TRICKY)) //如果不是tricky字体 font_type.flags = font_type.flags & (~FT_LOAD_NO_HINTING) | (pfi->FontHasHinting() ? FT_LOAD_NO_AUTOHINT : FT_LOAD_FORCE_AUTOHINT); else*/ font_type.flags = font_type.flags & (~FT_LOAD_NO_HINTING)/* | (pfi->FontHasHinting() ? FT_LOAD_DEFAULT : FT_LOAD_FORCE_AUTOHINT)*/; } FTInfo.useKerning = FALSE; if (pfs->GetKerning()) { switch (pSettings->FontLoader()) { case SETTING_FONTLOADER_FREETYPE: FTInfo.useKerning = !!FT_HAS_KERNING(freetype_face); break; case SETTING_FONTLOADER_WIN32: { DWORD rc = GetFontLanguageInfo(FTInfo.hdc); if (rc != GCP_ERROR) { FTInfo.useKerning = !!(rc & GCP_USEKERNING); FTInfo.ggokerning.init(FTInfo.hdc); } } break; DEFAULT_UNREACHABLE; } } return TRUE; } // 縦にするやつはtrue(ASCIIと半角カナはfalse) inline bool IsVerticalChar(WCHAR wch) { if (wch < 0x80) return false; if (0xFF61 <= wch && wch <= 0xFF9F) return false; // 本当はもっと真面目にやらないとまずいが。 return true; } struct CGGOFont { HDC m_hdc; HFONT m_hfont; HFONT m_hprevfont; CGGOFont(HDC hdc, const LOGFONT& olf) : m_hdc(hdc), m_hfont(NULL), m_hprevfont(NULL) { LOGFONT lf = olf; lf.lfWeight = FW_REGULAR; lf.lfItalic = FALSE; lf.lfStrikeOut = FALSE; m_hfont = CreateFontIndirect(&lf); } ~CGGOFont() { if (m_hprevfont) { SelectFont(m_hdc, m_hprevfont); } DeleteFont(m_hfont); } void change() { m_hprevfont = SelectFont(m_hdc, m_hfont); } void restore() { SelectFont(m_hdc, m_hprevfont); m_hprevfont = NULL; } operator HFONT () { return m_hfont; } }; class ClpDx { private: const INT* p; const INT step; public: ClpDx(const INT* lpDx, UINT etoOptions) : p(lpDx), step((etoOptions& ETO_PDY) ? 2 : 1) { } ~ClpDx() { } int get(int val) { int result; if (p) { result = *p; p += step; } else { result = val; } return result; } int gety(int val) { // you must call gety BEFORE call get, gety won't move the pointer, thus has no side effect int result; if (step == 1) return val; //only search for values in ETO_PDY mode. if (p) { result = *(p + 1); } else { result = val; } return result; } }; /* FT_UInt FTC_CMapCache_Lookup2( FTC_CMapCache cache, FTC_FaceID face_id, FT_Int cmap_index, FT_UInt32 char_code, FT_Face freetype_face) { if ((int)face_id >= charmapCacheSize) { int oldsize = charmapCacheSize; charmapCacheSize = ((int)face_id / 100 + 1)*100; g_charmapCache = (FT_Int*)realloc(g_charmapCache, charmapCacheSize*sizeof(FT_Int)); memset(&g_charmapCache[oldsize], 0xff, (charmapCacheSize-oldsize)*sizeof(FT_Int)); } if (g_charmapCache[(int)face_id]==-1) if (!FTC_Manager_LookupFace(cache_man, face_id, &freetype_face)) { g_charmapCache[(int)face_id] = FT_Get_Charmap_Index(freetype_face->charmap); cmap_index = g_charmapCache[(int)face_id]; } else cmap_index = 0; return FTC_CMapCache_Lookup(cache, face_id, cmap_index, char_code); }*/ BOOL ForEachGetGlyphFT(FreeTypeDrawInfo& FTInfo, LPCTSTR lpString, int cbString, FT_Referenced_Glyph* GlyphArray, FT_DRAW_STATE* drState) { const CGdippSettings* pSettings = CGdippSettings::GetInstance(); //Snowie!! BOOL bIsSymbol = GetTextCharsetInfo(FTInfo.hdc, NULL, 0) == SYMBOL_CHARSET; BOOL bAllowDefaultLink = pSettings->GetFontLinkInfo().IsAllowFontLink((BYTE)GetTextCharsetInfo(FTInfo.hdc, NULL, 0)); //是否为符号 BOOL nRet = true; BOOL bWindowsLink = pSettings->FontLink() == 2; //!!Snowie /*const*/ FT_Face freetype_face = FTInfo.freetype_face; //去掉常量属性,下面要改他 const FT_Int cmap_index = FTInfo.cmap_index; const FT_Bool useKerning = FTInfo.useKerning; FT_Render_Mode render_mode = FTInfo.render_mode; const int LinkNum = FTInfo.face_id_list_num; int AAMode = FTInfo.pfs->GetAntiAliasMode(); // fix AAMode to LCD if harmony lcd is enabled. This is will not affect directwrite output. if (AAMode > 2 && pSettings->HarmonyLCD()) { AAMode = 2; } int* AAList = FTInfo.AAModes; const LOGFONTW& lf = FTInfo.LogFont(); FreeTypeFontCache* pftCache = FTInfo.pftCache; const CFontSettings*& pfs = FTInfo.pfs; FreeTypeFontInfo*& pfi = FTInfo.pfi; const bool bLoadColor = pSettings->LoadColorFont(); const bool bGlyphIndex = FTInfo.IsGlyphIndex(); //const bool bSizeOnly = FTInfo.IsSizeOnly(); //const bool bOwnCache = !(FTInfo.font_type.flags & FT_LOAD_RENDER); const LPCTSTR lpStart = lpString; const LPCTSTR lpEnd = lpString + cbString; FT_UInt previous = 0; WCHAR previouswch = 0; const bool bVertical = lf.lfFaceName[0] == _T('@'); bool bLcdMode = render_mode == FT_RENDER_MODE_LCD; bool bLightLcdMode = (AAMode == 4) || (AAMode == 5); ClpDx clpdx(FTInfo.lpDx, FTInfo.params->etoOptions); const bool bWidthGDI32 = true; const int ggoformatbase = (FTInfo.font_type.flags & FT_LOAD_NO_HINTING) ? GGO_UNHINTED | GGO_NATIVE : GGO_NATIVE; if (!s_GGOGlyphLoader.init(freetype_library)) { return FALSE; } WORD* gi = new WORD[cbString]; WORD* ggi = gi; //Snowie!! //Fast fontlink WORD** lpfontlink = NULL; HFONT hOldFont = NULL; if (!bGlyphIndex && bWindowsLink) //使用Windows fontlink { lpfontlink = (WORD**)new LPVOID[FTInfo.face_id_list_num]; for (int i = 0; i < LinkNum; i++) { lpfontlink[i] = new WORD[cbString]; ZeroMemory(lpfontlink[i], sizeof(WORD) * cbString); //初始化为无链接 } // hOldFont = (HFONT)GetCurrentObject(FTInfo.hdc, OBJ_FONT); //加载第一个字体 } //fontlink int* Dx = FTInfo.Dx; int* Dy = FTInfo.Dy; if (!bAllowDefaultLink && FTInfo.face_id_list_num > 1) FTInfo.face_id_list_num--; //如果是symbol页那就不链接到宋体 bool bUnicodePlane = false; for (int i = 0; lpString < lpEnd; ++lpString, ++gi, ++GlyphArray, ++drState, ++AAList, /*ggdi32++,*/ i++) { WCHAR wch = *lpString; if (bUnicodePlane) { *drState = FT_DRAW_NOTFOUND; bUnicodePlane = false; if (lpString < lpEnd - 1) { FTInfo.y -= clpdx.gety(0); FTInfo.x += clpdx.get(0); } else { int gdi32x = 0; GetCharWidth32W(FTInfo.hdc, wch, wch, &gdi32x); FTInfo.y -= clpdx.gety(0); FTInfo.x += clpdx.get(gdi32x); FTInfo.px = FTInfo.x; } goto cont; } if (!bGlyphIndex && bIsSymbol && !bWindowsLink) wch |= 0xF000; FT_Referenced_Glyph* glyph_bitmap = GlyphArray; int gdi32x = 0;// = *ggdi32; FTInfo.font_type.face_id = FTInfo.face_id_list[0]; FreeTypeCharData* chData = NULL; FT_UInt glyph_index = 0; BOOL bIsBold = false, bIsIndivBold = false; { chData = bGlyphIndex ? pftCache->FindGlyphIndex(wch) : pftCache->FindChar(wch); //looking for wch in char cache and glyph cache if (chData/* && FTInfo.width==chData->GetWidth()*/) { // found cache gdi32x = chData->GetGDIWidth(); *AAList = chData->GetAAMode(); CCriticalSectionLock __lock(CCriticalSectionLock::CS_LIBRARY); FT_Glyph_Ref_Copy((FT_Referenced_Glyph)chData->GetGlyph(render_mode), glyph_bitmap); // cached img-> glyph_bitmap //TRACE(_T("Cache Hit: %wc, size:%d, 0x%8.8X\n"), wch, chData->GetWidth(), glyph_bitmap); } } if (!*glyph_bitmap) { // case: no cache found FT_Referenced_Glyph glyph = NULL; bool f_glyph = false; //GLYPHMETRICS gm; const MAT2 mat2 = { { 0, 1 },{ 0, 0 },{ 0, 0 },{ 0, 1 } }; UINT ggoformat = ggoformatbase; CTempMem ggobuf; DWORD outlinesize = 0; if (bGlyphIndex) { // glyph index doesn't require any font linking f_glyph = !!wch; glyph_index = wch; *AAList = AAMode; GetCharWidthI(FTInfo.hdc, wch, 1, (LPWORD)&wch, &gdi32x); //index的文字必须计算宽度 if (FTInfo.font_type.height <= pSettings->BitmapHeight() && pfi->EmbeddedBmpExist(FTInfo.font_type.height)) { f_glyph = false; //使用点阵,不绘图 *drState = FT_DRAW_EMBEDDED_BITMAP; //设置为点阵绘图方式 } } else if (wch && !CID.myiswcntrl(lpString[0])) { // need to draw a non-control character for (int j = 0; j < FTInfo.face_id_list_num; ++j) { freetype_face = NULL; // reinitialize it in case no fontlinking is available. if (bWindowsLink) //使用Windows函数进行fontlink { if (!lpfontlink[j][i]) //还没初始化该字体的fontlink { SelectFont(FTInfo.hdc, FTInfo.ggo_font_list[j]); //加载ggo字体 GetGlyphIndices(FTInfo.hdc, lpString, cbString - i, &lpfontlink[j][i], GGI_MARK_NONEXISTING_GLYPHS); //进行fontlink SelectFont(FTInfo.hdc, hOldFont); } glyph_index = lpfontlink[j][i]; if (glyph_index == 0xffff) glyph_index = 0; } else //使用freetype进行fontlink { CCriticalSectionLock __lock(CCriticalSectionLock::CS_MANAGER); glyph_index = FTC_CMapCache_Lookup(cmap_cache, FTInfo.face_id_list[j], -1, wch); //glyph_index = FT_Get_Char_Index(FTInfo.GetFace(j), wch); } if (glyph_index) { GetCharWidth32W(FTInfo.hdc, wch, wch, &gdi32x); //有效文字,计算宽度 f_glyph = true; FTInfo.font_type.face_id = FTInfo.face_id_list[j]; freetype_face = FTInfo.GetFace(j); //同时更新对应faceid的实际face //接下来更新对应的fontsetting FTInfo.font_type.flags = FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH; // ヒンティング //extern CFontSetCache g_fsetcache; //pfs = g_fsetcache.Get(FTInfo.font_type.face_id); if (FTInfo.font_type.face_id == FTInfo.face_id_simsun && j > 0) { switch (FTInfo.font_type.height) { case 11: {FTInfo.font_type.height = 12; FTInfo.font_type.width++; break; } //对宋体进行特殊处理 case 13: {FTInfo.font_type.height = 15; FTInfo.font_type.width += 2; break; } } } pfi = g_pFTEngine->FindFont((int)FTInfo.font_type.face_id); if (pfi) { pfs = &pfi->GetFontSettings(); switch (pfs->GetHintingMode()) { case 0: // ignore. break; case 1: FTInfo.font_type.flags |= FT_LOAD_NO_HINTING; break; case 2: FTInfo.font_type.flags |= FT_LOAD_FORCE_AUTOHINT; break; } // アンチエイリアス if (FTInfo.IsMono()) { FTInfo.font_type.flags |= FT_LOAD_TARGET_MONO; render_mode = FT_RENDER_MODE_MONO; } else { switch (*AAList = pfs->GetAntiAliasMode()) { case -1: FTInfo.font_type.flags |= FT_LOAD_TARGET_MONO; render_mode = FT_RENDER_MODE_MONO; break; case 0: FTInfo.font_type.flags |= FT_LOAD_TARGET_NORMAL; render_mode = FT_RENDER_MODE_NORMAL; break; case 1: FTInfo.font_type.flags |= FT_LOAD_TARGET_LIGHT; render_mode = FT_RENDER_MODE_LIGHT; break; case 2: case 3: FTInfo.font_type.flags |= FT_LOAD_TARGET_LCD; render_mode = FT_RENDER_MODE_LCD; break; case 4: case 5: FTInfo.font_type.flags |= FT_LOAD_TARGET_LIGHT; render_mode = FT_RENDER_MODE_LCD; break; } } if (pSettings->HintSmallFont() && FTInfo.font_type.flags & FT_LOAD_TARGET_LIGHT && FTInfo.font_type.height != -1 && FTInfo.font_type.height < 12) //通用设置不使用hinting,但是打开了小字体hinting开关 FTInfo.font_type.flags = FTInfo.font_type.flags & (~FT_LOAD_NO_HINTING)/* | (pfi->FontHasHinting() ? FT_LOAD_DEFAULT : FT_LOAD_FORCE_AUTOHINT)*/; AAMode = *AAList/*pfs->GetAntiAliasMode()*/; bLcdMode = render_mode == FT_RENDER_MODE_LCD; bLightLcdMode = (AAMode == 4) || (AAMode == 5); //更新完成 } if (FTInfo.font_type.height <= pSettings->BitmapHeight() && pfi->EmbeddedBmpExist(FTInfo.font_type.height)) { f_glyph = false; //使用点阵,不绘图 *drState = FT_DRAW_EMBEDDED_BITMAP; //设置为点阵绘图方式 } break; } } } if (!f_glyph || !freetype_face) { //can't find suitable fontface, glyphindex case is already calculated. #ifdef _DEBUG GdiSetBatchLimit(0); #endif if (*drState == FT_DRAW_NORMAL || bGlyphIndex) *drState = FT_DRAW_NOTFOUND; //找不到文字 if ((!FTInfo.lpDx || lpString == lpEnd - 1) && !bGlyphIndex) //无效文字,而且没有事先排版或者是排版的最后一个字符了 { GetCharWidth32W(FTInfo.hdc, wch, wch, &gdi32x); } int cx = gdi32x; /* if (bSizeOnly) { FTInfo.x += cx; } else*/ { if (wch) { *glyph_bitmap = NULL; //无效文字 //ORIG_ExtTextOutW(FTInfo.hdc, FTInfo.x, FTInfo.yTop, FTInfo.GetETO(), NULL, &wch, 1, NULL); } BOOL isc = bGlyphIndex ? false : (CID.myiswcntrl(*lpString)); if (isc == CNTRL_UNICODE_PLANE) { if (!FTInfo.lpDx) { SIZE p = { 0 }; if (GetTextExtentExPointW(FTInfo.hdc, lpString, 2, 99999, NULL, NULL, &p)) { gdi32x = p.cx; cx = gdi32x; } } bUnicodePlane = true; } // else // if (isc == CNTRL_ZERO_WIDTH) //预计算的无宽度控制字 // cx = 0; int dyHeight = clpdx.gety(0); int dxWidth = clpdx.get(cx); if (isc == CNTRL_COMPLEX_TEXT) //控制字 { cx = dxWidth; //服从windows的宽度调度 //if (!dxWidth) // CID.setcntrlAttribute(wch, CNTRL_ZERO_WIDTH); } if (lpString < lpEnd - 1) { FTInfo.x += dxWidth; FTInfo.y -= dyHeight; } else { //if (gdi32x) //{ /* ABC abc = {0, cx, 0}; if (bGlyphIndex) GetCharABCWidthsI(FTInfo.hdc, wch, 1, NULL, &abc); else GetCharABCWidths(FTInfo.hdc, wch, wch, &abc);*/ //FTInfo.px = FTInfo.x+Max(clpdx.get(cx), abc.abcA+(int)abc.abcB+abc.abcC); //无效文字的情况下,绘图宽度=鼠标位置 FTInfo.px = FTInfo.x + cx; FTInfo.x += dxWidth;//Max(clpdx.get(cx), cx);/*(int)abc.abcB+abc.abcC*///Max(clpdx.get(cx), abc.abcB? abc.abcA:0); //} } if (!isc) FTInfo.x += FTInfo.params->charExtra; } goto cont; } // vertical font found if (bVertical) { glyph_index = ft2vert_get_gid( (struct ft2vert_st*)freetype_face->generic.data, glyph_index); } // カーニング if (useKerning) { if (previous != 0 && glyph_index) { FT_Vector delta; FT_Get_Kerning(freetype_face, previous, glyph_index, ft_kerning_default, &delta); FTInfo.x += FT_PosToInt(delta.x); } previous = glyph_index; } // 縦横 if (bVertical && IsVerticalChar(wch)) { FTInfo.font_type.flags |= FT_LOAD_VERTICAL_LAYOUT; if (bLcdMode) { if ((FTInfo.font_type.flags & FT_LOAD_TARGET_LCD) == FT_LOAD_TARGET_LCD) { FTInfo.font_type.flags &= ~FT_LOAD_TARGET_LCD; FTInfo.font_type.flags |= FT_LOAD_TARGET_LCD_V; } render_mode = FT_RENDER_MODE_LCD_V; } } else { if (bVertical) swap(FTInfo.font_type.height, FTInfo.font_type.width); //交换无法旋转的文字宽高 FTInfo.font_type.flags &= ~FT_LOAD_VERTICAL_LAYOUT; if (bLcdMode) { if (FTInfo.font_type.flags & FT_LOAD_TARGET_LCD_V == FT_LOAD_TARGET_LCD_V) { FTInfo.font_type.flags &= ~FT_LOAD_TARGET_LCD_V; FTInfo.font_type.flags |= FT_LOAD_TARGET_LCD; } render_mode = FT_RENDER_MODE_LCD; } } { bool bRequiredownsize; bIsIndivBold = freetype_face->style_flags & FT_STYLE_FLAG_BOLD; // separate bold font? bIsBold = (IsFontBold(lf) && !bIsIndivBold); // bold font creation required but no separate bold font found, we need to embold the regular bold to mimic it bRequiredownsize = bIsBold && /*(pSettings->BolderMode()==2 || (*/pSettings->BolderMode() != 1 /*&& FTInfo.height>FT_BOLD_LOW))*/; if (bRequiredownsize) { FTInfo.font_type.width -= (FTInfo.font_type.width) / 36; FTInfo.font_type.height -= (FTInfo.font_type.height) / 36; } { CCriticalSectionLock __lock(CCriticalSectionLock::CS_MANAGER); FT_Glyph temp_glyph = NULL; if (FTC_ImageCache_Lookup( image_cache, &FTInfo.font_type, glyph_index, &temp_glyph, NULL)) { nRet = false; goto gdiexit; } glyph = New_FT_Ref_Glyph(); FT_Glyph_Copy(temp_glyph, &(glyph->ft_glyph)); //转换为ref_glyph } FTInfo.font_type.height = FTInfo.height; FTInfo.font_type.width = FTInfo.width; } { CCriticalSectionLock __lock(CCriticalSectionLock::CS_LIBRARY); if (FT_Glyph_Ref_Copy(glyph, glyph_bitmap)) { FT_Done_Ref_Glyph(&glyph); nRet = FALSE; goto gdiexit; } FT_Done_Ref_Glyph(&glyph); } if ((*glyph_bitmap)->ft_glyph->format != FT_GLYPH_FORMAT_BITMAP) { int str_h; int str_v; bool fbold = false; str_h = str_v = FTInfo.pfi->CalcNormalWeight(); if (bIsIndivBold) str_h = str_v = FTInfo.pfi->GetExactBoldWeight() << 2; if (bIsBold) { fbold = true; str_h += FTInfo.font_type.height < 24 ? FTInfo.pfi->GetFTWeight() : (FTInfo.pfi->GetFTWeight() * FTInfo.font_type.height / 24); str_v = str_h; } if ((str_h || str_v) && New_FT_Outline_Embolden( &((FT_OutlineGlyph)((*glyph_bitmap)->ft_glyph))->outline, str_h, str_v, FTInfo.height)) { FT_Done_Ref_Glyph(glyph_bitmap); nRet = false; goto gdiexit; } if (fbold) { ((FT_BitmapGlyph)((*glyph_bitmap)->ft_glyph))->root.advance.x += 0x10000; } if (lf.lfItalic && !(freetype_face->style_flags & FT_STYLE_FLAG_ITALIC)) { FT_Matrix matrix; FTInfo.pfi->CalcItalicSlant(matrix); FT_Outline_Transform( &((FT_OutlineGlyph)((*glyph_bitmap)->ft_glyph))->outline, &matrix); } { CCriticalSectionLock __lock(CCriticalSectionLock::CS_LIBRARY); if (bLoadColor && FT_HAS_COLOR(freetype_face)) { // use custom API to get color bitmap if (FT_Glyph_To_BitmapEx(&((*glyph_bitmap)->ft_glyph), render_mode, 0, 1, 1, glyph_index, freetype_face)) { FT_Done_Ref_Glyph(glyph_bitmap); nRet = false; goto gdiexit; } } else if (FT_Glyph_To_Bitmap(&((*glyph_bitmap)->ft_glyph), render_mode, 0, 1)) { FT_Done_Ref_Glyph(glyph_bitmap); nRet = false; goto gdiexit; } } } } // end of "case: no cache found" int cx = (bVertical && IsVerticalChar(wch)) ? FT_FixedToInt(FT_BitmapGlyph((*glyph_bitmap)->ft_glyph)->root.advance.y) : FT_FixedToInt(FT_BitmapGlyph((*glyph_bitmap)->ft_glyph)->root.advance.x); { int dy = clpdx.gety(0); //获得高度 int dx = clpdx.get(bWidthGDI32 ? gdi32x : cx); //获得宽度 int left = FT_BitmapGlyph((*glyph_bitmap)->ft_glyph)->left; if (gdi32x == 0) { // zero width text (most likely a diacritic) if (FTInfo.x + dx + left < FTInfo.xBase) FTInfo.xBase = FTInfo.x + dx + left; //it needs to be drawn at the end of the offset (Windows specific, Windows will "share" half of letter's width to the diacritic) if (i > 0) { // we need to update the logical start position of the previous letter to compensate the strange behavior. *(Dx - 1) = FTInfo.x + dx; } } else { if (FTInfo.x + left < FTInfo.xBase) FTInfo.xBase = FTInfo.x + left; //如果有字符是负数起始位置的(合成符号), 调整文字的起始位置 } if (lpString < lpEnd - 1) { FTInfo.x += dx; FTInfo.y -= dy; } else { int bx = FT_BitmapGlyph((*glyph_bitmap)->ft_glyph)->bitmap.width; if (render_mode == FT_RENDER_MODE_LCD && FT_BitmapGlyph((*glyph_bitmap)->ft_glyph)->bitmap.pixel_mode != FT_PIXEL_MODE_BGRA) bx /= 3; bx += left; FTInfo.px = FTInfo.x + Max(Max(dx, bx), cx); //有文字的情况下,绘图宽度=ft计算的宽度,鼠标位置=win宽度 FTInfo.x += dx;//Max(dx, gdi32x);//Max(Max(dx, bx), cx); } } FTInfo.x += FTInfo.params->charExtra; //if (bSizeOnly || bOwnCache) { //キャッシュ化 if (glyph_index) { if (bGlyphIndex) { pftCache->AddGlyphData(glyph_index, /*cx*/FTInfo.width, gdi32x, (FT_Referenced_BitmapGlyph)*glyph_bitmap, render_mode, AAMode); } else { pftCache->AddCharData(wch, glyph_index, /*cx*/FTInfo.width, gdi32x, (FT_Referenced_BitmapGlyph)*glyph_bitmap, render_mode, AAMode); } } cont: *Dx = FTInfo.x; //Dx的位置是下一个字符开始的基准位置,并不是下一个字符开始画的位置 *Dy = FTInfo.y; //Dy的位置是下一个字符的y坐标 ++Dx; ++Dy; } gdiexit: delete[] ggi; // delete[] gdi32w; if (!bGlyphIndex && bWindowsLink) { for (int i = 0; i < LinkNum; i++) delete lpfontlink[i]; delete lpfontlink; } return nRet; } BOOL ForEachGetGlyphGGO(FreeTypeDrawInfo& FTInfo, LPCTSTR lpString, int cbString, FT_Referenced_Glyph* GlyphArray, FT_DRAW_STATE* drState) { const CGdippSettings* pSettings = CGdippSettings::GetInstance(); //Snowie!! BOOL bIsSymbol = GetTextCharsetInfo(FTInfo.hdc, NULL, 0) == SYMBOL_CHARSET; BOOL bAllowDefaultLink = pSettings->GetFontLinkInfo().IsAllowFontLink((BYTE)GetTextCharsetInfo(FTInfo.hdc, NULL, 0)); //是否为符号 BOOL nRet = true; BOOL bWindowsLink = pSettings->FontLink() == 2; //!!Snowie /*const*/ FT_Face freetype_face = FTInfo.freetype_face; //去掉常量属性,下面要改他 const FT_Int cmap_index = FTInfo.cmap_index; const FT_Bool useKerning = FTInfo.useKerning; FT_Render_Mode render_mode = FTInfo.render_mode; const int LinkNum = FTInfo.face_id_list_num; int AAMode = FTInfo.pfs->GetAntiAliasMode(); int* AAList = FTInfo.AAModes; const LOGFONTW& lf = FTInfo.LogFont(); FreeTypeFontCache* pftCache = FTInfo.pftCache; const CFontSettings*& pfs = FTInfo.pfs; FreeTypeFontInfo*& pfi = FTInfo.pfi; const bool bGlyphIndex = FTInfo.IsGlyphIndex(); //const bool bSizeOnly = FTInfo.IsSizeOnly(); //const bool bOwnCache = !(FTInfo.font_type.flags & FT_LOAD_RENDER); const LPCTSTR lpStart = lpString; const LPCTSTR lpEnd = lpString + cbString; FT_UInt previous = 0; WCHAR previouswch = 0; const bool bVertical = false; bool bLcdMode = render_mode == FT_RENDER_MODE_LCD; bool bLightLcdMode = (AAMode == 4) || (AAMode == 5); ClpDx clpdx(FTInfo.lpDx, FTInfo.params->etoOptions); const bool bWidthGDI32 = pSettings->WidthMode() == SETTING_WIDTHMODE_GDI32; const int ggoformatbase = (FTInfo.font_type.flags & FT_LOAD_NO_HINTING) ? GGO_UNHINTED | GGO_NATIVE : GGO_NATIVE; if (!s_GGOGlyphLoader.init(freetype_library)) { return FALSE; } // LPCTSTR dumy = lpString; // if (!bGlyphIndex) // for (; dumy 1) FTInfo.face_id_list_num--; //如果是symbol页那就不链接到宋体 for (int i = 0; lpString < lpEnd; ++lpString, gi++, GlyphArray++, drState++, ++AAList,/*ggdi32++,*/ i++) { WCHAR wch = *lpString; if (!bGlyphIndex && bIsSymbol && !bWindowsLink) wch |= 0xF000; FT_Referenced_Glyph* glyph_bitmap = GlyphArray; int gdi32x = 0;// = *ggdi32; FTInfo.font_type.face_id = FTInfo.face_id_list[0]; FreeTypeCharData* chData = NULL; FT_UInt glyph_index = 0; BOOL bIsBold = false, bIsIndivBold = false; { chData = bGlyphIndex ? pftCache->FindGlyphIndex(wch) : pftCache->FindChar(wch); if (chData && FTInfo.width == chData->GetWidth()) { /* if (bSizeOnly) { //TRACE(_T("Cache hit: GetCharWidth [%c]\n"), *lpString); int cx = chData->GetWidth(); FTInfo.x += (bWidthGDI32 ? gdi32x : cx) + FTInfo.params->charExtra; goto cont; }*/ gdi32x = chData->GetGDIWidth(); *AAList = chData->GetAAMode(); CCriticalSectionLock __lock(CCriticalSectionLock::CS_LIBRARY); FT_Glyph_Ref_Copy((FT_Referenced_Glyph)chData->GetGlyph(render_mode), glyph_bitmap); //TRACE(_T("Cache Hit: %wc, size:%d, 0x%8.8X\n"), wch, chData->GetWidth(), glyph_bitmap); } } if (!*glyph_bitmap) { FT_Referenced_Glyph glyph = NULL; bool f_glyph = false; GLYPHMETRICS gm; const MAT2 mat2 = { { 0, 1 },{ 0, 0 },{ 0, 0 },{ 0, 1 } }; UINT ggoformat = ggoformatbase; CTempMem ggobuf; DWORD outlinesize = 0; if (bGlyphIndex) { f_glyph = true; *AAList = AAMode; glyph_index = wch; ggoformat |= GGO_GLYPH_INDEX; GetCharWidthI(FTInfo.hdc, wch, 1, (LPWORD)&wch, &gdi32x); //index的文字必须计算宽度 } else { if (*(gi) != 0xffff) { glyph_index = *(gi); f_glyph = true; *AAList = AAMode; } GetCharWidth32W(FTInfo.hdc, wch, wch, &gdi32x); //有效文字,计算宽度 } if (lpString == lpStart && FTInfo.font_type.flags & FT_LOAD_FORCE_AUTOHINT) { // FORCE_AUTOHINT GetGlyphOutlineW(FTInfo.hdc, 0, GGO_METRICS | GGO_GLYPH_INDEX | GGO_NATIVE | GGO_UNHINTED, &gm, 0, NULL, &mat2); } outlinesize = GetGlyphOutlineW(FTInfo.hdc, wch, ggoformat, &gm, ggobuf.getsize(), ggobuf, &mat2); if (outlinesize == GDI_ERROR || outlinesize == 0) { glyph_index = 0; f_glyph = false; } else { glyph_index = wch; f_glyph = true; } if (!f_glyph) { //glyphindex的文字上面已经计算过了 #ifdef _DEBUG GdiSetBatchLimit(0); #endif if (*drState == FT_DRAW_NORMAL || bGlyphIndex) *drState = FT_DRAW_NOTFOUND; //找不到文字 if ((!FTInfo.lpDx || lpString == lpEnd - 1) && !bGlyphIndex) //无效文字,而且没有事先排版或者是排版的最后一个字符了 { GetCharWidth32W(FTInfo.hdc, wch, wch, &gdi32x); } int cx = gdi32x; /* if (bSizeOnly) { FTInfo.x += cx; } else*/ { if (wch) { *glyph_bitmap = NULL; //无效文字 //ORIG_ExtTextOutW(FTInfo.hdc, FTInfo.x, FTInfo.yTop, FTInfo.GetETO(), NULL, &wch, 1, NULL); } BOOL isc = bGlyphIndex ? false : (CID.myiswcntrl(*lpString)); if (isc) cx = 0; if (lpString < lpEnd - 1) { FTInfo.y -= clpdx.gety(0); FTInfo.x += clpdx.get(cx); } else { //if (gdi32x) { /* ABC abc = {0, cx, 0}; if (bGlyphIndex) GetCharABCWidthsI(FTInfo.hdc, wch, 1, NULL, &abc); else GetCharABCWidths(FTInfo.hdc, wch, wch, &abc);*/ //FTInfo.px = FTInfo.x+Max(clpdx.get(cx), abc.abcA+(int)abc.abcB+abc.abcC); //无效文字的情况下,绘图宽度=鼠标位置 FTInfo.px = FTInfo.x + cx; FTInfo.x += clpdx.get(cx); } } if (!isc) FTInfo.x += FTInfo.params->charExtra; } goto cont; } if (useKerning && !bGlyphIndex) { if (previouswch && wch) { FTInfo.x += FTInfo.ggokerning.get(previouswch, wch); } previouswch = wch; } // 縦横 if (bVertical && IsVerticalChar(wch)) { FTInfo.font_type.flags |= FT_LOAD_VERTICAL_LAYOUT; if (bLcdMode) { if (FTInfo.font_type.flags & FT_LOAD_TARGET_LCD == FT_LOAD_TARGET_LCD) { FTInfo.font_type.flags &= ~FT_LOAD_TARGET_LCD; FTInfo.font_type.flags |= FT_LOAD_TARGET_LCD_V; } render_mode = FT_RENDER_MODE_LCD_V; } } else { if (bVertical) swap(FTInfo.font_type.height, FTInfo.font_type.width); //交换无法旋转的文字宽高 FTInfo.font_type.flags &= ~FT_LOAD_VERTICAL_LAYOUT; if (bLcdMode) { if (FTInfo.font_type.flags & FT_LOAD_TARGET_LCD_V == FT_LOAD_TARGET_LCD_V) { FTInfo.font_type.flags &= ~FT_LOAD_TARGET_LCD_V; FTInfo.font_type.flags |= FT_LOAD_TARGET_LCD; } render_mode = FT_RENDER_MODE_LCD; } } CGGOOutlineGlyph ggoog; { if (outlinesize > ggobuf.getsize()) { if (!ggobuf.init(outlinesize)) { nRet = false; goto gdiexit; } //ggofont.change(); outlinesize = GetGlyphOutlineW(FTInfo.hdc, wch, ggoformat, &gm, ggobuf.getsize(), ggobuf, &mat2); //ggofont.restore(); } if (outlinesize > ggobuf.getsize()) { nRet = false; goto gdiexit; } if (!ggoog.init(outlinesize, ggobuf, gm)) { nRet = false; goto gdiexit; } glyph = New_FT_Ref_Glyph(); FT_Glyph_Copy((FT_Glyph)ggoog, &(glyph->ft_glyph)); //glyph = ggoog; } { CCriticalSectionLock __lock(CCriticalSectionLock::CS_LIBRARY); if (FT_Glyph_Ref_Copy(glyph, glyph_bitmap)) { FT_Done_Ref_Glyph(&glyph); nRet = FALSE; goto gdiexit; } FT_Done_Ref_Glyph(&glyph); } if ((*glyph_bitmap)->ft_glyph->format != FT_GLYPH_FORMAT_BITMAP) { int str_h; int str_v; bool fbold = false; str_h = str_v = FTInfo.pfi->CalcNormalWeight(); if (bIsIndivBold) str_h = str_v = FTInfo.pfi->GetExactBoldWeight() << 2; if (bIsBold) { fbold = true; str_h += FTInfo.font_type.height < 24 ? FTInfo.pfi->GetFTWeight() : (FTInfo.pfi->GetFTWeight() * FTInfo.font_type.height / 24); str_v = str_h; } if ((str_h || str_v) && New_FT_Outline_Embolden( &((FT_OutlineGlyph)((*glyph_bitmap)->ft_glyph))->outline, str_h, str_v, FTInfo.height)) { FT_Done_Ref_Glyph(glyph_bitmap); nRet = false; goto gdiexit; } if (fbold) { ((FT_BitmapGlyph)((*glyph_bitmap)->ft_glyph))->root.advance.x += 0x10000; } { CCriticalSectionLock __lock(CCriticalSectionLock::CS_LIBRARY); if (FT_Glyph_To_Bitmap(&((*glyph_bitmap)->ft_glyph), render_mode, 0, 1)) { FT_Done_Ref_Glyph(glyph_bitmap); nRet = false; goto gdiexit; } } } } int cx = (bVertical && IsVerticalChar(wch)) ? FT_FixedToInt(FT_BitmapGlyph((*glyph_bitmap)->ft_glyph)->root.advance.y) : FT_FixedToInt(FT_BitmapGlyph((*glyph_bitmap)->ft_glyph)->root.advance.x); //done /* if (bSizeOnly) { FTInfo.x += bWidthGDI32 ? gdi32x : cx; } else */ { int dy = clpdx.gety(0); int dx = clpdx.get(bWidthGDI32 ? gdi32x : cx); //获得宽度 int left = FT_BitmapGlyph((*glyph_bitmap)->ft_glyph)->left; if (FTInfo.x + left < FTInfo.xBase) FTInfo.xBase = FTInfo.x + left; //如果有字符是负数起始位置的(合成符号), 调整文字的起始位置 if (lpString < lpEnd - 1) { FTInfo.x += dx; FTInfo.y -= dy; } else { int bx = FT_BitmapGlyph((*glyph_bitmap)->ft_glyph)->bitmap.width; if (render_mode == FT_RENDER_MODE_LCD) bx /= 3; bx += left; FTInfo.px = FTInfo.x + Max(Max(dx, bx), cx); //有文字的情况下,绘图宽度=ft计算的宽度,鼠标位置=win宽度 FTInfo.x += dx;//Max(dx, gdi32x);//Max(Max(dx, bx), cx); } } FTInfo.x += FTInfo.params->charExtra; //if (bSizeOnly || bOwnCache) { //キャッシュ化 if (glyph_index) { if (bGlyphIndex) { pftCache->AddGlyphData(glyph_index, /*cx*/FTInfo.width, gdi32x, (FT_Referenced_BitmapGlyph)*glyph_bitmap, render_mode, AAMode); } else { pftCache->AddCharData(wch, glyph_index, /*cx*/FTInfo.width, gdi32x, (FT_Referenced_BitmapGlyph)*glyph_bitmap, render_mode, AAMode); } } //} // if (!bGlyphIndex && iswcntrl(wch) && *glyph_bitmap) // { // // FT_Done_Glyph(*glyph_bitmap); // *glyph_bitmap = NULL; // } cont: *Dx = FTInfo.x; *Dy = FTInfo.y; ++Dx; ++Dy; } gdiexit: delete[] ggi; // delete[] gdi32w; if (!bGlyphIndex && bWindowsLink) { for (int i = 0; i < LinkNum; i++) delete lpfontlink[i]; delete lpfontlink; } return nRet; } BOOL GetLogFontFromDC(HDC hdc, LOGFONT& lf) { LOGFONTW lfForce = { 0 }; HFONT hf = GetCurrentFont(hdc); if (!ORIG_GetObjectW(hf, sizeof(LOGFONTW), &lf)) return FALSE; const CGdippSettings* pSettings = CGdippSettings::GetInstance(); //if (pSettings->CopyForceFont(lfForce, lf)) // lf = lfForce; if (pSettings->LoadOnDemand()) { //AddFontToFT(lf.lfFaceName, lf.lfWeight, !!lf.lfItalic); } return TRUE; } BOOL CALLBACK TextOutCallback(FreeTypeGlyphInfo& FTGInfo) { FreeTypeDrawInfo* FTInfo = FTGInfo.FTInfo; FT_BitmapGlyph& glyph_bitmap = FTGInfo.FTGlyph; const bool bVertical = FTInfo->LogFont().lfFaceName[0] == _T('@'); int nOldAlpha = FTInfo->params->alpha; if (!FTGInfo.FTGlyph->bitmap.buffer) { //if (FTInfo->params->alpha == 1) { // if (!(FTInfo->GetETO() & ETO_GLYPH_INDEX) && wch==32) //空格 // ORIG_ExtTextOutW(FTInfo->hdc, FTInfo->x, FTInfo->yTop, FTInfo->GetETO() & ETO_IGNORELANGUAGE, NULL, &wch, 1, NULL); // else ORIG_ExtTextOutW(FTInfo->hdc, FTInfo->x, FTInfo->yTop, FTInfo->GetETO(), NULL, &FTGInfo.wch, 1, NULL); //} } else { const CGdippSettings* pSettings = CGdippSettings::GetInstance(); if (bVertical && IsVerticalChar(FTGInfo.wch) && pSettings->FontLoader() == SETTING_FONTLOADER_FREETYPE) { if (FTInfo->params->alpha > 1) { FreeTypeDrawBitmapV(FTGInfo, *FTGInfo.shadow, FTInfo->x + FTInfo->sx, FTInfo->yTop + FTInfo->params->otm->otmTextMetrics.tmHeight - (glyph_bitmap->left + glyph_bitmap->bitmap.width) - 1 + FTInfo->sy);//画阴影 FTInfo->params->alpha = 1; } if (!FreeTypeDrawBitmapV(FTGInfo, *FTGInfo.solid, FTInfo->x, FTInfo->yTop + FTInfo->params->otm->otmTextMetrics.tmHeight - (glyph_bitmap->left + glyph_bitmap->bitmap.width) - 1)) //画文字 { // fallback to GDI when fail to draw with FT ORIG_ExtTextOutW(FTInfo->hdc, FTInfo->x, FTInfo->yTop, FTInfo->GetETO(), NULL, &FTGInfo.wch, 1, NULL); } } else { if (FTInfo->params->alpha > 1) { FreeTypeDrawBitmap(FTGInfo, *FTGInfo.shadow, FTInfo->x + glyph_bitmap->left + FTInfo->sx, FTInfo->yTop + FTInfo->yBase - glyph_bitmap->top + FTInfo->sy); //画阴影 FTInfo->params->alpha = 1; } if (!FreeTypeDrawBitmap(FTGInfo, *FTGInfo.solid, FTInfo->x + glyph_bitmap->left, FTInfo->yTop + FTInfo->yBase - glyph_bitmap->top)) //画文字 { // fallback to GDI when fail to draw with FT ORIG_ExtTextOutW(FTInfo->hdc, FTInfo->x, FTInfo->yTop, FTInfo->GetETO(), NULL, &FTGInfo.wch, 1, NULL); } } } FTInfo->params->alpha = nOldAlpha; return TRUE; } int IsColorDark(DWORD Color, double Gamma) { //return (GetRValue(Color)*0.299 + GetGValue(Color)*0.587 + GetBValue(Color)*0.114); //原始算法 //=============================================================== //采用Photoshop sRGB的RGB->Lab算法进行换算,L为色彩视觉亮度 //感谢 西安理工大学 贾婉丽 的分析 //=============================================================== static double s_multipler = 116 / pow(100, (double)1.0 / 3.0); //预计算常数,强制使用double版本 double* RGBTable = s_AlphaBlendTable.GetRGBTable(); //获得显示器转换表 double ret = pow(23.9746 * RGBTable[GetRValue(Color)] + 73.0653 * RGBTable[GetGValue(Color)] + 6.13799 * RGBTable[GetBValue(Color)], 1.0 / 3.0) * s_multipler - 16; return max(int(ret + 0.499), 0); /*double r = GetRValue(Color)/255.0; double g = GetGValue(Color)/255.0; double b = GetBValue(Color)/255.0; double v; double m; double vm; double r2, g2, b2; double h = 0; // default to black double s = 0; double l = 0; v = Max(r,g); v = Max(v,b); m = Min(r,g); m = Min(m,b); l = (m + v) / 2.0; if (l <= 0.0) { return 0; } vm = v - m; s = vm; if (s > 0.0) { s /= (l <= 0.5) ? (v + m ) : (2.0 - v - m) ; } else { return l; } r2 = (v - r) / vm; g2 = (v - g) / vm; b2 = (v - b) / vm; if (r == v) { h = (g == m ? 5.0 + b2 : 1.0 - g2); } else if (g == v) { h = (b == m ? 1.0 + r2 : 3.0 - b2); } else { h = (r == m ? 3.0 + g2 : 5.0 - r2); } h /= 6.0; return l;*/ } /* BOOL GetColorDiff(DWORD Color) { / *const CGdippSettings* pSettings = CGdippSettings::GetInstance(); DWORD ShadowColorD = pSettings->ShadowDarkColor(); DWORD ShadowColorL = pSettings->ShadowLightColor(); DWORD ColorDiffD = RGBA(abs(GetRValue(Color)-GetRValue(ShadowColorD)),abs(GetGValue(Color)-GetGValue(ShadowColorD)),abs(GetBValue(Color)-GetBValue(ShadowColorD)),0); DWORD ColorDiffL = RGBA(abs(GetRValue(Color)-GetRValue(ShadowColorL)),abs(GetGValue(Color)-GetGValue(ShadowColorL)),abs(GetBValue(Color)-GetBValue(ShadowColorL)),0); double cd = IsColorDark(ColorDiffD), cl = IsColorDark(ColorDiffL); return cd==cl ? IsColorDark(Color)<0.7 : cd>cl;* / }*/ BOOL FreeTypeTextOut( const HDC hdc, // デバイスコンテキストのハンドル CBitmapCache& cache, LPCWSTR lpString, // 文字列 int cbString, // 文字数 FreeTypeDrawInfo& FTInfo, FT_Referenced_Glyph* Glyphs, FT_DRAW_STATE* drState ) { if (cbString <= 0 || lpString == NULL) return FALSE; CAlphaBlendColor* solid = NULL; CAlphaBlendColor* shadow = NULL; //CCriticalSectionLock __lock; FT_Face freetype_face = FTInfo.freetype_face; const LOGFONT& lf = FTInfo.LogFont(); FTInfo.x = -FTInfo.xBase; FTInfo.yTop = 0; const TEXTMETRIC& tm = FTInfo.params->otm->otmTextMetrics; FTInfo.yBase = tm.tmAscent; //===============计算颜色缓存====================== const CGdippSettings* pSettings = CGdippSettings::GetInstance(); int lightdiff, darkdiff, bDarkColor = 0, ShadowColor = 0; if (FTInfo.params->alpha != 1) { float Gamma = pSettings->GammaValue(); bDarkColor = IsColorDark(FTInfo.params->color, Gamma); int diff = max(darkdiff = abs(IsColorDark(pSettings->ShadowDarkColor(), Gamma) - bDarkColor), lightdiff = abs(IsColorDark(pSettings->ShadowLightColor(), Gamma) - bDarkColor)); ShadowColor = lightdiff <= darkdiff ? pSettings->ShadowDarkColor() : pSettings->ShadowLightColor(); bDarkColor = lightdiff <= darkdiff; if (/*diff<10 || abs(lightdiff-darkdiff)<20 &&*/ pSettings->ShadowDarkColor() == pSettings->ShadowLightColor()) { //无视底色问题,强制开启阴影 FTInfo.params->alphatuner = 1; } else { diff = abs(lightdiff - darkdiff); if (diff < 10) FTInfo.params->alpha = 1; else FTInfo.params->alphatuner = max(1, 100 / diff); //根据色差调整阴影浓度 } } char mode = (*Glyphs) ? FT_BitmapGlyph((*Glyphs)->ft_glyph)->bitmap.pixel_mode : FT_PIXEL_MODE_LCD; switch (mode) { case FT_PIXEL_MODE_MONO: return false; //break; case FT_PIXEL_MODE_LCD: solid = new CAlphaBlendColor(FTInfo.params->color, 1, true, true, true); shadow = new CAlphaBlendColor( /*FTInfo.params->color*/ShadowColor, FTInfo.params->alpha, true, bDarkColor, true); break; case FT_PIXEL_MODE_LCD_V: solid = new CAlphaBlendColor(FTInfo.params->color, 1, true, true, false); shadow = new CAlphaBlendColor( /*FTInfo.params->color*/ShadowColor, FTInfo.params->alpha, true, bDarkColor, false); break; case FT_PIXEL_MODE_GRAY: solid = new CAlphaBlendColor(FTInfo.params->color, 1, false, true, true); shadow = new CAlphaBlendColor( /*FTInfo.params->color*/ShadowColor, FTInfo.params->alpha, false, bDarkColor, true); break; default: solid = new CAlphaBlendColor(FTInfo.params->color, 1, pSettings->LcdFilter(), true); shadow = new CAlphaBlendColor( /*FTInfo.params->color*/ShadowColor, FTInfo.params->alpha, pSettings->LcdFilter(), bDarkColor); break; } //计算下划线或删除线的信息 int decorationInfo_height; int decorationInfo_thickness; OUTLINETEXTMETRIC& decorationInfo_otm = *FTInfo.params->otm; if (lf.lfUnderline || lf.lfStrikeOut) { if (lf.lfUnderline) { switch (pSettings->FontLoader()) { case SETTING_FONTLOADER_FREETYPE: decorationInfo_height = decorationInfo_otm.otmTextMetrics.tmHeight; //FT_PosToInt(freetype_face->size->metrics.height); decorationInfo_thickness = MulDiv(freetype_face->underline_thickness, FTInfo.font_type.height/*freetype_face->size->metrics.y_ppem*/, freetype_face->units_per_EM); break; case SETTING_FONTLOADER_WIN32: decorationInfo_height = decorationInfo_otm.otmTextMetrics.tmHeight; decorationInfo_thickness = decorationInfo_otm.otmsUnderscoreSize; break; } } if (lf.lfStrikeOut) { switch (pSettings->FontLoader()) { case SETTING_FONTLOADER_FREETYPE: decorationInfo_thickness = MulDiv(freetype_face->underline_thickness, FTInfo.font_type.height,// freetype_face->size->metrics.y_ppem, freetype_face->units_per_EM); break; case SETTING_FONTLOADER_WIN32: decorationInfo_thickness = decorationInfo_otm.otmsStrikeoutSize; break; } } } //===============计算完成========================== FreeTypeGlyphInfo FTGInfo = { &FTInfo, 0, 0, 0, solid, shadow, pSettings->InvertColor() }; for (int i = 0; i < cbString; ++i, ++lpString) { WCHAR wch = *lpString; if (Glyphs[i]) // paint text with FreeType { FTGInfo.wch = wch; FTGInfo.FTGlyph = (FT_BitmapGlyph)(Glyphs[i]->ft_glyph); FTGInfo.AAMode = FTInfo.AAModes[i]; TextOutCallback(FTGInfo); } else // paint text(bitmap) with gdi { int j = i; FT_DRAW_STATE st = drState[i]; while (++j < cbString && !Glyphs[j] && drState[j] == st) {}; if (st == FT_DRAW_EMBEDDED_BITMAP) ORIG_ExtTextOutW(hdc, FTInfo.x, FTInfo.yTop, FTInfo.GetETO() & ETO_IGNORELANGUAGE, NULL, lpString, j - i, FTInfo.lpDx ? FTInfo.lpDx + i : NULL); else ORIG_ExtTextOutW(hdc, FTInfo.x, FTInfo.yTop, FTInfo.GetETO(), NULL, lpString, j - i, FTInfo.lpDx ? FTInfo.lpDx + i : NULL); lpString += --j - i; i = j; } //draw underline or strikeline separated if (lf.lfUnderline) { int yPos = FTInfo.yBase - decorationInfo_otm.otmsUnderscorePosition + FTInfo.yTop; if (yPos >= decorationInfo_height) { yPos = decorationInfo_height - 1; } cache.DrawHorizontalLine(FTInfo.x, yPos, FTInfo.Dx[i], FTInfo.Color(), decorationInfo_thickness); } if (lf.lfStrikeOut) { int yPos = FTInfo.yBase - decorationInfo_otm.otmsStrikeoutPosition + FTInfo.yTop; cache.DrawHorizontalLine(FTInfo.x, yPos, FTInfo.Dx[i], FTInfo.Color(), decorationInfo_thickness); } //draw line end. FTInfo.x = FTInfo.Dx[i]; FTInfo.yTop = FTInfo.Dy[i]; } if (shadow) delete shadow; if (solid) delete solid; int x = FTInfo.x; int y = FTInfo.yBase; // 下線を(あれば)引く // if(lf.lfUnderline || lf.lfStrikeOut) { // OUTLINETEXTMETRIC &otm = *FTInfo.params->otm; // if(lf.lfUnderline){ // int yPos = 0; //下線の位置 // int height = 0; // int thickness = 0; // 適当な太さ // switch (pSettings->FontLoader()) { // case SETTING_FONTLOADER_FREETYPE: // yPos = y - otm.otmsUnderscorePosition; // height = otm.otmTextMetrics.tmHeight; //FT_PosToInt(freetype_face->size->metrics.height); // thickness = // MulDiv(freetype_face->underline_thickness, // FTInfo.font_type.height/*freetype_face->size->metrics.y_ppem*/, // freetype_face->units_per_EM); // break; // case SETTING_FONTLOADER_WIN32: // yPos = y - otm.otmsUnderscorePosition; // height = otm.otmTextMetrics.tmHeight; // thickness = otm.otmsUnderscoreSize; // break; // } // if (yPos >= height) { // yPos = height - 1; // } // cache.DrawHorizontalLine(0, yPos, x, FTInfo.Color(), thickness); // } // // if(lf.lfStrikeOut){ // int yPos = y - otm.otmsStrikeoutPosition; // int thickness = 0; // switch (pSettings->FontLoader()) { // case SETTING_FONTLOADER_FREETYPE: // thickness = // MulDiv(freetype_face->underline_thickness, // FTInfo.font_type.height,// freetype_face->size->metrics.y_ppem, // freetype_face->units_per_EM); // break; // case SETTING_FONTLOADER_WIN32: // thickness = otm.otmsStrikeoutSize; // break; // } // cache.DrawHorizontalLine(0, yPos, x, FTInfo.Color(), thickness); // } // } return TRUE; } BOOL FreeTypeGetGlyph( //获得所有图形和需要的宽度 FreeTypeDrawInfo& FTInfo, LPCWSTR lpString, int cbString, int& width, FT_Referenced_Glyph* Glyphs, FT_DRAW_STATE* drState ) { COwnedCriticalSectionLock __lock(1); { //CCriticalSectionLock __lock; if (!FreeTypePrepare(FTInfo)) return false; } const CGdippSettings* pSettings = CGdippSettings::GetInstance(); BOOL nRet = false; switch (pSettings->FontLoader()) { case SETTING_FONTLOADER_FREETYPE: nRet = ForEachGetGlyphFT(FTInfo, lpString, cbString, Glyphs, drState); break; case SETTING_FONTLOADER_WIN32: nRet = ForEachGetGlyphGGO(FTInfo, lpString, cbString, Glyphs, drState); break; } width = FTInfo.px; //获得了宽度 return nRet; } void VertFinalizer(void* object) { FT_Face face = (FT_Face)object; ft2vert_final(face, (struct ft2vert_st*)face->generic.data); } // // グリフをIVSで指定された字形をサポートするかどうか調べ、 // サポートしている場合はグリフを置換する。 // サポートしていなければ何もしない。 // /* void FreeTypeSubstGlyph(const HDC hdc, const WORD vsindex, const int baseChar, int cChars, SCRIPT_ANALYSIS* psa, WORD* pwOutGlyphs, WORD* pwLogClust, SCRIPT_VISATTR* psva, int* pcGlyphs ) { CThreadLocalInfo* pTLInfo = g_TLInfo.GetPtr(); CBitmapCache& cache = pTLInfo->BitmapCache(); CCriticalSectionLock __lock; LOGFONT lf; if (!GetLogFontFromDC(hdc, lf)) return; FREETYPE_PARAMS params(0, hdc); FreeTypeDrawInfo FTInfo(params, hdc, &lf, &cache); if(!FreeTypePrepare(FTInfo)) return; FT_UInt glyph_index = ft2_subst_uvs(FTInfo.freetype_face, pwOutGlyphs[*pcGlyphs - 1], vsindex, baseChar); TRACE(_T("FreeTypeSubstGlyph: %04X->%04X\n"), pwOutGlyphs[*pcGlyphs - 1], glyph_index); if (glyph_index) { pwOutGlyphs[*pcGlyphs - 1] = glyph_index; // 置換を実行 // ASCII空白のグリフを取得 glyph_index = FTC_CMapCache_Lookup( cmap_cache, FTInfo.font_type.face_id, FTInfo.cmap_index, ' '); // ゼロ幅グリフにする pwOutGlyphs[*pcGlyphs] = glyph_index; psva[*pcGlyphs].uJustification = SCRIPT_JUSTIFY_NONE; psva[*pcGlyphs].fClusterStart = 0; psva[*pcGlyphs].fDiacritic = 0; psva[*pcGlyphs].fZeroWidth = 1; psva[*pcGlyphs].fReserved = 0; psva[*pcGlyphs].fShapeReserved = 0; } else { // フォントは指定された字形を持たない。IVSのグリフを取得 glyph_index = FTC_CMapCache_Lookup( cmap_cache, FTInfo.font_type.face_id, FTInfo.cmap_index, vsindex + 0xE0100); // IVSをサポートしていないフォントはIVSのグリフを持っている可能性もほとんどない。 // missing glyphを返すとフォールバックされてしまうため確実に持っていそうなグリフを拾う if (!glyph_index) glyph_index = FTC_CMapCache_Lookup( cmap_cache, FTInfo.font_type.face_id, FTInfo.cmap_index, 0x30FB); pwOutGlyphs[*pcGlyphs] = glyph_index; psva[*pcGlyphs] = psva[*pcGlyphs - 1]; psva[*pcGlyphs].fClusterStart = 0; } pwLogClust[cChars - 2] = *pcGlyphs; pwLogClust[cChars - 1] = *pcGlyphs; ++*pcGlyphs; }*/ FT_Error face_requester( FTC_FaceID face_id, FT_Library /*library*/, FT_Pointer /*request_data*/, FT_Face* aface) { FT_Error ret = FT_Err_Ok; FT_Face face; FreeTypeFontInfo* pfi = g_pFTEngine->FindFont((int)face_id); Assert(pfi); if (!pfi) { return FT_Err_Invalid_Argument; } LPCTSTR fontname = pfi->GetName(); // 名称を指定してフォントを取得 FreeTypeSysFontData* pData = FreeTypeSysFontData::CreateInstance(fontname, pfi->GetFontWeight(), pfi->IsItalic()); if (pData == NULL) { return FT_Err_Cannot_Open_Resource; } face = pData->GetFace(); if (!face) return 0x6; //something wrong with the freetype that we aren't clear yet. //Assert(face != NULL); // Charmapを設定しておく ret = FT_Select_Charmap(face, FT_ENCODING_UNICODE); if (ret != FT_Err_Ok) ret = FT_Select_Charmap(face, FT_ENCODING_MS_SYMBOL); /* if(ret != FT_Err_Ok) ret = FT_Select_Charmap(face, FT_ENCODING_SJIS); if(ret != FT_Err_Ok) ret = FT_Select_Charmap(face, FT_ENCODING_GB2312); if(ret != FT_Err_Ok) ret = FT_Select_Charmap(face, FT_ENCODING_BIG5); if(ret != FT_Err_Ok) ret = FT_Select_Charmap(face, FT_ENCODING_WANSUNG); if(ret != FT_Err_Ok) ret = FT_Select_Charmap(face, FT_ENCODING_JOHAB); if(ret != FT_Err_Ok) ret = FT_Select_Charmap(face, FT_ENCODING_ADOBE_STANDARD); if(ret != FT_Err_Ok) ret = FT_Select_Charmap(face, FT_ENCODING _ADOBE_EXPERT); if(ret != FT_Err_Ok) ret = FT_Select_Charmap(face, FT_ENCODING_ADOBE_CUSTOM); if(ret != FT_Err_Ok) ret = FT_Select_Charmap(face, FT_ENCODING_ADOBE_LATIN_1); if(ret != FT_Err_Ok) ret = FT_Select_Charmap(face, FT_ENCODING_OLD_LATIN_2); if(ret != FT_Err_Ok) ret = FT_Select_Charmap(face, FT_ENCODING_APPLE_ROMAN); */ if (ret != FT_Err_Ok) { FT_Done_Face(face); return ret; } struct ft2vert_st* vert = ft2vert_init(face); face->generic.data = vert; face->generic.finalizer = VertFinalizer; // select named instance for variable font VarFontByAlias(face, pfi->GetStyleName()); *aface = face; return 0; } /* DWORD FreeTypeGetVersion() { int major = 0, minor = 0, patch = 0; FT_Library_Version(freetype_library, &major, &minor, &patch); //面倒なのでRGBマクロ使用 return RGB(major, minor, patch); }*/ //新太字アルゴリズム FT_Error New_FT_Outline_Embolden(FT_Outline* outline, FT_Pos str_h, FT_Pos str_v, FT_Int font_size) { const CGdippSettings* pSettings = CGdippSettings::GetInstance(); int orientation = 0; switch (pSettings->BolderMode()) { case 1: return FT_Outline_EmboldenXY(outline, str_h, 0); case 2: return FT_Outline_Embolden(outline, str_h); default: { if (!outline) return FT_Err_Invalid_Argument; //orientation = FT_Outline_Get_Orientation( outline ); //if ( orientation == FT_ORIENTATION_NONE ) // if ( outline->n_contours ) return FT_Err_Invalid_Argument; /* if (font_size>FT_BOLD_LOW || str_h<16) Vert_FT_Outline_Embolden( outline, str_v ); Old_FT_Outline_Embolden( outline, str_h );*/ if (font_size < FT_BOLD_LOW && str_h>32) { FT_Outline_EmboldenXY(outline, str_h, Min(long(32), str_v)); } else FT_Outline_Embolden(outline, str_h); return FT_Err_Ok; } } } //横方向だけ太らせるFT_Outline_Embolden FT_Error Old_FT_Outline_Embolden(FT_Outline* outline, FT_Pos strength) { FT_Vector* points; FT_Vector v_prev, v_first, v_next, v_cur; FT_Angle rotate, angle_in, angle_out; FT_Int c, n, first; FT_Int orientation; if (!outline) return FT_Err_Invalid_Argument; strength /= 2; if (strength == 0) return FT_Err_Ok; orientation = FT_Outline_Get_Orientation(outline); if (orientation == FT_ORIENTATION_NONE) { if (outline->n_contours) return FT_Err_Invalid_Argument; else return FT_Err_Ok; } if (orientation == FT_ORIENTATION_TRUETYPE) rotate = -FT_ANGLE_PI2; else rotate = FT_ANGLE_PI2; points = outline->points; first = 0; for (c = 0; c < outline->n_contours; c++) { int last = outline->contours[c]; v_first = points[first]; v_prev = points[last]; v_cur = v_first; for (n = first; n <= last; n++) { FT_Vector in, out; FT_Angle angle_diff; FT_Pos d; FT_Fixed scale; if (n < last) v_next = points[n + 1]; else v_next = v_first; /* compute the in and out vectors */ in.x = v_cur.x - v_prev.x; in.y = v_cur.y - v_prev.y; out.x = v_next.x - v_cur.x; out.y = v_next.y - v_cur.y; angle_in = FT_Atan2(in.x, in.y); angle_out = FT_Atan2(out.x, out.y); angle_diff = FT_Angle_Diff(angle_in, angle_out); scale = FT_Cos(angle_diff / 2); if (scale < 0x4000L && scale > -0x4000L) in.x = in.y = 0; else { d = FT_DivFix(strength, scale); FT_Vector_From_Polar(&in, d, angle_in + angle_diff / 2 - rotate); } outline->points[n].x = v_cur.x + strength + in.x; //↓これをコメントアウトしただけ //outline->points[n].y = v_cur.y + strength + in.y; v_prev = v_cur; v_cur = v_next; } first = last + 1; } return FT_Err_Ok; } //こっちは縦方向 FT_Error Vert_FT_Outline_Embolden(FT_Outline* outline, FT_Pos strength) { FT_Vector* points; FT_Vector v_prev, v_first, v_next, v_cur; FT_Angle rotate, angle_in, angle_out; FT_Int c, n, first; FT_Int orientation; if (!outline) return FT_Err_Invalid_Argument; strength /= 2; if (strength == 0) return FT_Err_Ok; orientation = FT_Outline_Get_Orientation(outline); if (orientation == FT_ORIENTATION_NONE) { if (outline->n_contours) return FT_Err_Invalid_Argument; else return FT_Err_Ok; } if (orientation == FT_ORIENTATION_TRUETYPE) rotate = -FT_ANGLE_PI2; else rotate = FT_ANGLE_PI2; points = outline->points; first = 0; for (c = 0; c < outline->n_contours; c++) { int last = outline->contours[c]; v_first = points[first]; v_prev = points[last]; v_cur = v_first; for (n = first; n <= last; n++) { FT_Vector in, out; FT_Angle angle_diff; FT_Pos d; FT_Fixed scale; if (n < last) v_next = points[n + 1]; else v_next = v_first; /* compute the in and out vectors */ in.x = v_cur.x - v_prev.x; in.y = v_cur.y - v_prev.y; out.x = v_next.x - v_cur.x; out.y = v_next.y - v_cur.y; angle_in = FT_Atan2(in.x, in.y); angle_out = FT_Atan2(out.x, out.y); angle_diff = FT_Angle_Diff(angle_in, angle_out); scale = FT_Cos(angle_diff / 2); if (scale < 0x4000L && scale > -0x4000L) in.x = in.y = 0; else { d = FT_DivFix(strength, scale); FT_Vector_From_Polar(&in, d, angle_in + angle_diff / 2 - rotate); } //outline->points[n].x = v_cur.x + strength + in.x; //↑これをコメントアウトしただけ outline->points[n].y = v_cur.y + strength + in.y; v_prev = v_cur; v_cur = v_next; } first = last + 1; } return FT_Err_Ok; } BOOL FontLInit(void) { CCriticalSectionLock __lock; if (FT_Init_FreeType(&freetype_library)) { return FALSE; } #ifdef INFINALITY #define TT_INTERPRETER_VERSION_35 35 #define TT_INTERPRETER_VERSION_38 38 #define TT_INTERPRETER_VERSION_40 40 FT_UInt interpreter_version = TT_INTERPRETER_VERSION_38; FT_Property_Set(freetype_library, "truetype", "interpreter-version", &interpreter_version); #endif //enable stem darkening feature introduced in 2.6.2 FT_Bool no_stem_darkening = FALSE; FT_Property_Set(freetype_library, "cff", "no-stem-darkening", &no_stem_darkening); const CGdippSettings* pSettings = CGdippSettings::GetInstance(); if (FTC_Manager_New(freetype_library, pSettings->CacheMaxFaces(), pSettings->CacheMaxSizes(), pSettings->CacheMaxBytes(), face_requester, NULL, &cache_man)) { FontLFree(); return FALSE; } if (FTC_CMapCache_New(cache_man, &cmap_cache)) { FontLFree(); return FALSE; } if (FTC_ImageCache_New(cache_man, &image_cache)) { FontLFree(); return FALSE; } //s_AlphaBlendTable.init(); s_AlphaBlendTable.initRGB(); return TRUE; } void FontLFree(void) { CCriticalSectionLock __lock; if (cache_man != NULL) FTC_Manager_Done(cache_man); if (freetype_library != NULL) FT_Done_FreeType(freetype_library); cache_man = NULL; freetype_library = NULL; } //Snowie void RefreshAlphaTable() { s_AlphaBlendTable.init(); } ================================================ FILE: ft.h ================================================ #ifndef FT_H #define FT_H #define FTO_MONO 0x0001 #define FTO_SIZE_ONLY 0x0002 #define CACHE_SIZE 20 #define MAX_CACHE_SIZE 1024 #define CNTRL_UNICODE_PLANE 2 #define CNTRL_COMPLEX_TEXT 1 #define CNTRL_ZERO_WIDTH 4 typedef char (*COLORCACHE)[3][256][256]; #include "fteng.h" enum FT_DRAW_STATE{ FT_DRAW_NORMAL = 0, FT_DRAW_EMBEDDED_BITMAP = 1, FT_DRAW_NOTFOUND = 2 }; BOOL FontLInit(void); void FontLFree(void); COLORREF GetPaletteColor(HDC hdc, UINT paletteindex); #define ROUND(x) ((x)>0? int(x+0.5):int(x-0.5)) // a special round method used by windows class CDCTransformer { private: float fXZoomFactor, fYZoomFactor; XFORM m_xfm; bool bZoomMode; bool bMirrorX, bMirrorY; public: CDCTransformer():bMirrorY(false), bMirrorX(false), bZoomMode(false), fXZoomFactor(0), fYZoomFactor(0) {}; void init(XFORM& xfm) { memcpy(&m_xfm, &xfm, sizeof(XFORM)); if (xfm.eM11<0) { bMirrorX = true; m_xfm.eM11 = -m_xfm.eM11; } if (xfm.eM22<0) { bMirrorY = true; m_xfm.eM11 = -m_xfm.eM22; } fXZoomFactor = m_xfm.eM11; fYZoomFactor = m_xfm.eM22; m_xfm.eDx=0; m_xfm.eDy=0; bZoomMode = fXZoomFactor==fYZoomFactor; } void SetSourceOffset(int X, int Y) { float temp = float(X)*m_xfm.eM11+m_xfm.eDx; m_xfm.eDx = temp-(int)temp; if (ROUND(m_xfm.eDx)<0) // change negive offset to positive m_xfm.eDx+=1; temp = float(Y)*m_xfm.eM22+m_xfm.eDy; m_xfm.eDy = temp-(int)temp; if (ROUND(m_xfm.eDy)<0) m_xfm.eDy+=1; } int XInit() {return ROUND(m_xfm.eDx);} int YInit() {return ROUND(m_xfm.eDy);} int GetXCeilingIntAB(int X) { return ROUND(ROUND((X-m_xfm.eDx)/m_xfm.eM11)*m_xfm.eM11+m_xfm.eDx); } int GetYCeilingIntAB(int Y) { return ROUND(ROUND((Y-m_xfm.eDy)/m_xfm.eM22)*m_xfm.eM22+m_xfm.eDy); } ~CDCTransformer() {}; void TransformRectAB(const RECT* lpInRect, PRECT lpOutRect) { lpOutRect->bottom = TransformYCoordinateAB(lpInRect->bottom); lpOutRect->left = TransformXCoordinateAB(lpInRect->left); lpOutRect->right = TransformXCoordinateAB(lpInRect->right); lpOutRect->top = TransformYCoordinateAB(lpInRect->top); } void TransformRectBA(const RECT* lpInRect, PRECT lpOutRect) { lpOutRect->bottom = ROUND(lpInRect->bottom/fYZoomFactor); lpOutRect->left = ROUND(lpInRect->left/fXZoomFactor); lpOutRect->right = ROUND(lpInRect->right/fXZoomFactor); lpOutRect->top = ROUND(lpInRect->top/fYZoomFactor); } int TransformXAB(int nX) { return ROUND(nX*fXZoomFactor); } int TransformXCoordinateAB(int nX) { return ROUND((float(nX))*fXZoomFactor/*+m_xfm.eDx*/); } int TransformXBA(int nX) { return ROUND(nX/fXZoomFactor); } int TransformXCoordinateBA(int nX) { return ROUND((float(nX)/*-m_xfm.eDx*/)/fXZoomFactor); } int TransformYAB(int nY) { return ROUND(nY*fYZoomFactor); } int TransformYCoordinateAB(int nY) { return ROUND((float(nY))*fYZoomFactor/*+m_xfm.eDy*/); } int TransformYBA(int nY) { return ROUND(nY/fYZoomFactor); } int TransformYCoordinateBA(int nY) { return ROUND((float(nY)/*-m_xfm.eDy*/)/fYZoomFactor); } void TransformlpDx(const int* lpDx, int* outlpDx, int szDx) { int LastPos = 0, LPCurPos = 0; double fDPLastPos = 0, fDPCurPos = 0; for (;szDx>0;--szDx) { LPCurPos += *lpDx++; // the logical position the letter belongs to fDPCurPos = LPCurPos*fXZoomFactor; // the device position the letter belongs to *outlpDx = ROUND(fDPCurPos-fDPLastPos); // the device coord fDPLastPos += *outlpDx++; // the coord after this letter is painted. In order to calculate the pos of the next letter. } } bool TransformMode() { return bZoomMode; } XFORM* GetTransform() { return &m_xfm; } bool MirrorX() { return bMirrorX; } bool MirrorY() { return bMirrorY; } }; class ControlIder { private: char* unicode; public: ControlIder() { unicode = new char[0xffff]; memset(unicode, 0, sizeof(char)*0xffff); // non-control char by default //memset(unicode, 2, sizeof(char)*32); for (int i=0;i<0x3000;i++) unicode[i]=!!iswcntrl(i); for (int i=0xa000;i<0xffff;i++) unicode[i]=!!iswcntrl(i); // Chinese memset(&unicode[0xd800],CNTRL_UNICODE_PLANE,sizeof(char)*(0xdfff-0xd800+1)); //unicode plane memset(&unicode[0x0590],CNTRL_COMPLEX_TEXT,sizeof(char)*(0x05FF-0x0590+1)); //hebrew memset(&unicode[0x0600],CNTRL_COMPLEX_TEXT,sizeof(char)*(0x06FF-0x0600+1)); //arabic memset(&unicode[0xFB50],CNTRL_COMPLEX_TEXT,sizeof(char)*(0xFDFF-0xFB50+1)); //Arabic Presentation Forms-A memset(&unicode[0xFE70],CNTRL_COMPLEX_TEXT,sizeof(char)*(0xFEFF-0xFE70+1)); //Arabic Presentation Forms-B memset(&unicode[0x0E00],CNTRL_COMPLEX_TEXT,sizeof(char)*(0x0E7F-0x0E00+1)); //thai // unicode[0xa] = 0; // unicode[0xd] = 0; // unicode[0x9] = 0; // Set width for some special control chars. They have zero width, but GetCharABCWidth gives wrong results for them. } ~ControlIder() { delete unicode; } void setcntrlAttribute(WCHAR wch, int cnType) { unicode[wch] = cnType; } char myiswcntrl(WCHAR str) { return unicode[str]; } bool myiscomplexscript(LPCWSTR lpString, int cbString) { for (;cbString>0;++lpString,--cbString) { if (unicode[*lpString]==CNTRL_COMPLEX_TEXT) return true; } return false; } }; struct FREETYPE_PARAMS { UINT etoOptions; UINT ftOptions; int charExtra; COLORREF color; int alpha; BYTE alphatuner; LOGFONTW* lplf; OUTLINETEXTMETRIC* otm; wstring strFamilyName, strFullName; FREETYPE_PARAMS() { ZeroMemory(this, sizeof(*this)); } //FreeTypeTextOut用 (サイズ計算+文字描画) FREETYPE_PARAMS(UINT eto, HDC hdc, LOGFONTW* p, OUTLINETEXTMETRIC* lpotm = NULL) : etoOptions(eto) , ftOptions(0) , charExtra(GetTextCharacterExtra(hdc)) , color(GetTextColor(hdc)) , alpha(0) , lplf(p) , otm(lpotm) , alphatuner(1) { if ((color>>24)%2 || (color>>28)%2) { color = GetPaletteColor(hdc, color); } if (otm) { strFamilyName = (LPWSTR)((DWORD_PTR)otm + (DWORD_PTR)otm->otmpFamilyName); strFullName = wstring((LPWSTR)((DWORD_PTR)otm + (DWORD_PTR)otm->otmpFullName)); std::wstring strStyleName = wstring((LPWSTR)((DWORD_PTR)otm + (DWORD_PTR)otm->otmpStyleName)); strFullName = MakeUniqueFontName(strFullName, strFamilyName, strStyleName); if (strFamilyName.size() > 0 && strFamilyName.c_str()[0] == L'@') strFullName = L'@' + strFullName; } } bool IsMono() const { return (ftOptions & FTO_MONO); } }; class CGGOKerning : public CMap { private: DWORD makekey(WORD first, WORD second) { return ((DWORD)first << 16) | second; } public: void init(HDC hdc) { DWORD rc; rc = GetKerningPairs(hdc, 0, NULL); if (rc <= 0) return; DWORD kpcnt = rc; LPKERNINGPAIR kpp = (LPKERNINGPAIR)calloc(kpcnt, sizeof *kpp); if (!kpp) return; rc = GetKerningPairs(hdc, kpcnt, kpp); for (DWORD i = 0; i < rc; ++i) { Add(makekey(kpp[i].wFirst, kpp[i].wSecond), kpp[i].iKernAmount); } free(kpp); } int get(WORD first, WORD second) { DWORD key = makekey(first, second); int x = FindKey(key); return (x >= 0) ? GetValueAt(x) : 0; } }; //fteng.cpp variables // forward declaration extern FT_Library freetype_library; extern FTC_Manager cache_man; extern FTC_CMapCache cmap_cache; extern FTC_ImageCache image_cache; struct FreeTypeDrawInfo { FT_FaceRec_ dummy_freetype_face; //FreeTypePrepareが設定する int sx,sy; FT_Face freetype_face; FT_Int cmap_index; FT_Bool useKerning; FT_Render_Mode render_mode; FTC_ImageTypeRec font_type; FTC_ScalerRec scaler; FreeTypeFontInfo* pfi; const CFontSettings* pfs; FreeTypeFontCache* pftCache; FTC_FaceID* face_id_list; HFONT* ggo_font_list; // for faster GGO fontlinking FTC_FaceID face_id_simsun; FT_Face freetype_face_list[CFontLinkInfo::FONTMAX * 2 + 1]; // in order to solve italic issues. int face_id_list_num; int* Dx; int* Dy; //呼び出し前に自分で設定する HDC hdc; int xBase; int y;//coord height, calculated by ETO_PDY, 0 if not provided int x;//coord width, calculated by win32 API int px; //x of paint, the real text width int yBase; int yTop; int height; //original width int width; const int* lpDx; CBitmapCache* pCache; FREETYPE_PARAMS* params; int* AAModes; FreeTypeDrawInfo(FREETYPE_PARAMS& fp, HDC dc, LOGFONTW* lf = NULL, CBitmapCache* ca = NULL, const int* dx = NULL, int cbString =0, int xs=0, int ys = 0) : freetype_face(&dummy_freetype_face), cmap_index(0), useKerning(0) , pfi(NULL), pfs(NULL), pftCache(NULL), face_id_list_num(0), ggo_font_list(NULL) , hdc(dc), x(0), y(0), yBase(0), yTop(0), face_id_simsun(NULL), px(0), xBase(0) { render_mode = FT_RENDER_MODE_NORMAL; ZeroMemory(&scaler, sizeof(scaler)); ZeroMemory(&font_type, sizeof(font_type)); ZeroMemory(&face_id_list, sizeof face_id_list); // init face list ZeroMemory(&freetype_face_list, sizeof freetype_face_list); lpDx = dx; pCache = ca; params = &fp; height = 0; width = 0; sx = xs; sy = ys; if(lf) params->lplf = lf; memset(&dummy_freetype_face, 0, sizeof dummy_freetype_face); Dx = new int[cbString]; Dy = new int[cbString]; AAModes = new int[cbString]; scaler.height = 12; scaler.width = 12; scaler.pixel = 1; } ~FreeTypeDrawInfo() { delete Dx; delete Dy; delete[] AAModes; } const LOGFONTW& LogFont() const { return *params->lplf; } COLORREF Color() const { return params->color; } UINT GetETO() const { return params->etoOptions; } bool IsGlyphIndex() const { return !!(params->etoOptions & ETO_GLYPH_INDEX); } bool IsMono() const { return !!(params->ftOptions & FTO_MONO); } bool IsSizeOnly() const { return !!(params->ftOptions & FTO_SIZE_ONLY); } CGGOKerning ggokerning; FT_Face GetFace(int index) // get face list { if (!freetype_face_list[index]) { CCriticalSectionLock __lock(CCriticalSectionLock::CS_MANAGER); FT_Size font_size; //FTC_ScalerRec fscaler={face_id_list[index], 1,1,1,0,0}; scaler.face_id = face_id_list[index]; if (FTC_Manager_LookupSize(cache_man, &scaler, &font_size)) //if (FTC_Manager_LookupFace(cache_man, face_id_list[index], &freetype_face_list[index])) freetype_face_list[index] = NULL; else { if (scaler.height == 0) return font_size->face; // return without save, because the scaler is not prepared yet. freetype_face_list[index] = font_size->face; } } return freetype_face_list[index]; } #ifdef _DEBUG void Validate() { Assert(params->lplf); }; #endif }; BOOL FreeTypeTextOut( const HDC hdc, CBitmapCache& cache, LPCWSTR lpString, int cbString, FreeTypeDrawInfo& FTInfo, FT_Referenced_Glyph * Glyphs, FT_DRAW_STATE* drState ); BOOL FreeTypeGetGlyph( // Get all the glyphs and widths needed. FreeTypeDrawInfo& FTInfo, LPCWSTR lpString, int cbString, int& width, FT_Referenced_Glyph* Glyphs, FT_DRAW_STATE* drState ); void RefreshAlphaTable(); #endif ================================================ FILE: ft2build.h ================================================ /***************************************************************************/ /* */ /* ft2build.h */ /* */ /* FreeType 2 build and setup macros. */ /* (Generic version) */ /* */ /* Copyright 1996-2001, 2006 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /*************************************************************************/ /* */ /* This file corresponds to the default `ft2build.h' file for */ /* FreeType 2. It uses the `freetype' include root. */ /* */ /* Note that specific platforms might use a different configuration. */ /* See builds/unix/ft2unix.h for an example. */ /* */ /*************************************************************************/ #ifndef __FT2_BUILD_GENERIC_H__ #define __FT2_BUILD_GENERIC_H__ #include #endif /* __FT2_BUILD_GENERIC_H__ */ /* END */ ================================================ FILE: ft2vert.c ================================================ /* * "ft2vert.c" * * Converter to vertical glyph ID by handling GSUB vrt2/vert feature * requires FreeType-2.1.10 or latter * * (C) 2005 Nobuyuki TSUCHIMURA * * using such Lookup * ScriptTag == 'kana' * DefaultLangSys or LangSysTag == 'JAN ' * FeatureTag == 'vrt2' or 'vert' * * [reference] * http://partners.adobe.com/public/developer/opentype/index_table_formats1.html * http://partners.adobe.com/public/developer/opentype/index_table_formats.html * http://partners.adobe.com/public/developer/opentype/index_tag9.html#vrt2 */ //#include "xdvi-config.h" //#include "xdvi.h" //#ifdef USE_ZEIT //#include #include #include FT_FREETYPE_H #include FT_OPENTYPE_VALIDATE_H #include #include #include "ft2vert.h" const struct ivs_otft_desc { int baseChar; int otft_index; } ivs_otft[] = { #define OTFT_DEF_BEGIN(index) /**/ #define OTFT_DEF(baseChar, otft_index) { baseChar, otft_index }, #define OTFT_DEF_END(count) /**/ #include "ivs_otft.h" #undef OTFT_DEF_BEGIN #undef OTFT_DEF #undef OTFT_DEF_END }; const int ivs_otft_index[] = { #define OTFT_DEF_BEGIN(index) index, #define OTFT_DEF(baseChar, otft_index) /**/ #define OTFT_DEF_END(count) /**/ #include "ivs_otft.h" #undef OTFT_DEF_BEGIN #undef OTFT_DEF #undef OTFT_DEF_END }; const int ivs_otft_count[] = { #define OTFT_DEF_BEGIN(index) /**/ #define OTFT_DEF(baseChar, otft_index) /**/ #define OTFT_DEF_END(count) count, #include "ivs_otft.h" #undef OTFT_DEF_BEGIN #undef OTFT_DEF #undef OTFT_DEF_END }; #define TAG_KANA FT_MAKE_TAG('k', 'a', 'n', 'a') #define TAG_HANI FT_MAKE_TAG('h', 'a', 'n', 'i') #define TAG_JAN FT_MAKE_TAG('J', 'A', 'N', ' ') #define TAG_VERT FT_MAKE_TAG('v', 'e', 'r', 't') #define TAG_VRT2 FT_MAKE_TAG('v', 'r', 't', '2') #define TAG_JP78 FT_MAKE_TAG('j', 'p', '7', '8') #define TAG_JP90 FT_MAKE_TAG('j', 'p', '9', '0') #define TAG_JP04 FT_MAKE_TAG('j', 'p', '0', '4') #define VERT_LOOKUP_INDEX 0 #define JP78_LOOKUP_INDEX 1 #define JP90_LOOKUP_INDEX 2 #define JP04_LOOKUP_INDEX 3 #define MALLOC(ptr, size) ptr = malloc(sizeof((ptr)[0]) * (size)) #define BYTE2(p) ((p) += 2, (int)(p)[-2] << 8 | (p)[-1]) #define BYTE4(p) ((p) += 4, (int)(p)[-4] << 24 | (int)(p)[-3] << 16 | \ (int)(p)[-2] << 8 | (p)[-1]) struct ft2vert_st { struct Lookup_st { int SubTableCount; struct SubTable_st { struct SingleSubst_st { FT_UInt SubstFormat; FT_UInt DeltaGlyphID; /* SubstFormat == 1 */ int GlyphCount; /* SubstFormat == 2 */ FT_UInt *Substitute; /* SubstFormat == 2 */ } SingleSubst; struct Coverage_st { FT_UInt CoverageFormat; int GlyphCount; /* CoverageFormat == 1 */ FT_UInt *GlyphArray; /* CoverageFormat == 1 */ int RangeCount; /* CoverageFormat == 2 */ struct RangeRecord_st *RangeRecord; /* CoverageFormat == 2 */ } Coverage; } *SubTable; } Lookup[4]; FT_Bytes GSUB_table; FT_Bytes kanaFeature, haniFeature; FT_Bytes vertLookup, vrt2Lookup; FT_Bytes jp78Lookup, jp90Lookup, jp04Lookup; FT_UInt32* variantSelectors; }; struct RangeRecord_st { FT_UInt Start; FT_UInt End; }; int isInIndex(FT_Bytes s, int index) { int i, count; if (s == NULL) return 0; count = BYTE2(s); for (i = 0; i < count; i++) { if (index == BYTE2(s)) return 1; } return 0; } /********** Debug ***************/ #ifdef DEBUG static FT_Bytes gsub_top; void print_offset(char *message, const FT_Bytes ptr) { printf("%s offset = %x\n", message, ptr - gsub_top); } char *tag_to_string(FT_Tag tag) { static char str[5]; str[0] = tag >> 24; str[1] = tag >> 16; str[2] = tag >> 8; str[3] = tag; return str; } void hex_dump(const FT_Bytes top) { int i, j; FT_Bytes s = top; for (j = 0; j < 100; j++) { printf("%04x : ", j*8); for (i = 0; i < 8; i++) { printf("%02x ", s[i+j*8]); } printf("\n"); } } #endif /* DEBUG */ /********** Lookup part ***************/ void scan_Coverage(struct ft2vert_st *ret, const FT_Bytes top, const int l) { int i; FT_Bytes s = top; struct Coverage_st *t; t = &ret->Lookup[l].SubTable[ret->Lookup[l].SubTableCount].Coverage; t->CoverageFormat = BYTE2(s); switch (t->CoverageFormat) { case 1: t->GlyphCount = BYTE2(s); MALLOC(t->GlyphArray, t->GlyphCount); memset(t->GlyphArray, 0, sizeof(t->GlyphArray[0]) * t->GlyphCount); for (i = 0; i < t->GlyphCount; i++) { t->GlyphArray[i] = BYTE2(s); } break; case 2: t->RangeCount = BYTE2(s); MALLOC(t->RangeRecord, t->RangeCount); memset(t->RangeRecord, 0, sizeof(t->RangeRecord[0]) * t->RangeCount); for (i = 0; i < t->RangeCount; i++) { t->RangeRecord[i].Start = BYTE2(s); t->RangeRecord[i].End = BYTE2(s); s += 2; /* drop StartCoverageIndex */ } break; default: #ifdef _DEBUG fprintf(stderr, "scan_Coverage: unknown CoverageFormat (%d).", t->CoverageFormat); #endif return; } ret->Lookup[l].SubTableCount++; } void scan_SubTable(struct ft2vert_st *ret, const FT_Bytes top, const int l) { int i; FT_Bytes s = top; FT_Offset Coverage; struct SingleSubst_st *t; t = &ret->Lookup[l].SubTable[ret->Lookup[l].SubTableCount].SingleSubst; t->SubstFormat = BYTE2(s); Coverage = BYTE2(s); scan_Coverage(ret, top + Coverage, l); switch (t->SubstFormat) { case 1: /* SingleSubstFormat1 */ t->DeltaGlyphID = BYTE2(s); break; case 2: /* SingleSubstFormat2 */ t->GlyphCount = BYTE2(s); MALLOC(t->Substitute, t->GlyphCount); memset(t->Substitute, 0, sizeof(t->Substitute[0]) * t->GlyphCount); for (i = 0; i < t->GlyphCount; i++) { t->Substitute[i] = BYTE2(s); } break; #ifdef _DEBUG default: fprintf(stderr, "scan_SubTable: unknown SubstFormat (%d).", t->SubstFormat); #endif } } void scan_Lookup(struct ft2vert_st *ret, const FT_Bytes top, const int l) { int i; FT_Bytes s = top; FT_UShort LookupType; FT_UShort LookupFlag; FT_UShort SubTableCount; FT_UShort SubTable; LookupType = BYTE2(s); LookupFlag = BYTE2(s); SubTableCount = BYTE2(s); SubTable = BYTE2(s); MALLOC(ret->Lookup[l].SubTable, SubTableCount); memset(ret->Lookup[l].SubTable, 0, sizeof(ret->Lookup[l].SubTable[0]) * SubTableCount); for (i = 0; i < SubTableCount; i++) { scan_SubTable(ret, top + SubTable, l); } if (ret->Lookup[l].SubTableCount != SubTableCount) { #ifdef _DEBUG fprintf(stderr, "warning (scan_Lookup): " "SubTableCount (=%d) is not expected (=%d).\n", ret->Lookup[l].SubTableCount, SubTableCount); #endif } } void scan_LookupList(struct ft2vert_st *ret, const FT_Bytes top) { int i; FT_Bytes s = top; int LookupCount; LookupCount = BYTE2(s); for (i = 0; i < LookupCount; i++) { FT_Bytes t = top + BYTE2(s); if (isInIndex(ret->vertLookup, i)) { scan_Lookup(ret, t, VERT_LOOKUP_INDEX); } else if (isInIndex(ret->jp78Lookup, i)) { scan_Lookup(ret, t, JP78_LOOKUP_INDEX); } else if (isInIndex(ret->jp90Lookup, i)) { scan_Lookup(ret, t, JP90_LOOKUP_INDEX); } else if (isInIndex(ret->jp04Lookup, i)) { scan_Lookup(ret, t, JP04_LOOKUP_INDEX); } } } /********** Feature part ****************/ void scan_FeatureList(struct ft2vert_st *ret, const FT_Bytes top) { int i; FT_Bytes s = top; int FeatureCount; FeatureCount = BYTE2(s); for (i = 0; i < FeatureCount; i++) { FT_Tag FeatureTag = BYTE4(s); FT_Offset Feature = BYTE2(s); if (isInIndex(ret->kanaFeature, i)) { switch (FeatureTag) { case TAG_VERT: ret->vertLookup = top + Feature + 2; break; case TAG_VRT2: ret->vrt2Lookup = top + Feature + 2; break; } } else if (isInIndex(ret->haniFeature, i)) { switch (FeatureTag) { case TAG_JP78: ret->jp78Lookup = top + Feature + 2; break; case TAG_JP90: ret->jp90Lookup = top + Feature + 2; break; case TAG_JP04: ret->jp04Lookup = top + Feature + 2; break; } } } } /********** Script part ****************/ void scan_LangSys(struct ft2vert_st *ret, const FT_Bytes top, const FT_Tag ScriptTag) { if (ScriptTag == TAG_KANA && ret->kanaFeature == NULL) ret->kanaFeature = top + 4; if (ScriptTag == TAG_HANI && ret->haniFeature == NULL) ret->haniFeature = top + 4; } void scan_Script(struct ft2vert_st *ret, const FT_Bytes top, const FT_Tag ScriptTag) { int i; FT_Bytes s = top; FT_Offset DefaultLangSys; int LangSysCount; DefaultLangSys = BYTE2(s); if (DefaultLangSys != 0) { scan_LangSys(ret, top + DefaultLangSys, ScriptTag); } LangSysCount = BYTE2(s); for (i = 0; i < LangSysCount; i++) { FT_Tag LangSysTag = BYTE4(s); FT_Bytes t = top + BYTE2(s); if (LangSysTag == TAG_JAN) { scan_LangSys(ret, t, ScriptTag); } } } void scan_ScriptList(struct ft2vert_st *ret, const FT_Bytes top) { int i; FT_Bytes s = top; int ScriptCount; ScriptCount = BYTE2(s); for (i = 0; i < ScriptCount; i++) { FT_Tag ScriptTag = BYTE4(s); FT_Bytes t = top + BYTE2(s); if (ScriptTag == TAG_KANA || ScriptTag == TAG_HANI) { scan_Script(ret, t, ScriptTag); } } } /********** header part *****************/ void scan_GSUB_Header(struct ft2vert_st *ret, const FT_Bytes top) { FT_Bytes s = top; FT_Fixed Version; FT_Offset ScriptList; FT_Offset FeatureList; FT_Offset LookupList; #ifdef DEBUG gsub_top = top; #endif /* DEBUG */ Version = BYTE4(s); ScriptList = BYTE2(s); FeatureList = BYTE2(s); LookupList = BYTE2(s); if (Version != 0x00010000) { #ifdef _DEBUG fprintf(stderr, "warning: GSUB Version (=%.1f) is not 1.0\n", (double)Version / 0x10000); #endif } scan_ScriptList(ret, top + ScriptList); scan_FeatureList(ret, top + FeatureList); /* vrt2 has higher priority over vert */ if (ret->vrt2Lookup != NULL) ret->vertLookup = ret->vrt2Lookup; scan_LookupList(ret, top + LookupList); } struct ft2vert_st *ft2vert_init(FT_Face face) { struct ft2vert_st *ret; int ft_error, i; FT_Bytes base = NULL; FT_Bytes gdef = NULL; FT_Bytes gpos = NULL; FT_Bytes jstf = NULL; MALLOC(ret, 1); memset(ret, 0, sizeof(ret[0])); for (i = 0; i < sizeof(ret->Lookup) / sizeof(ret->Lookup[0]); i++) { ret->Lookup[i].SubTableCount = 0; } ret->vertLookup = NULL; ret->vrt2Lookup = NULL; ret->jp78Lookup = NULL; ret->jp90Lookup = NULL; ret->jp04Lookup = NULL; ret->kanaFeature = NULL; ret->haniFeature = NULL; ret->GSUB_table = NULL; ret->variantSelectors = FT_Face_GetVariantSelectors(face); ft_error = FT_OpenType_Validate( face, FT_VALIDATE_GSUB, &base, &gdef, &gpos, &ret->GSUB_table, &jstf); if (ft_error == FT_Err_Unimplemented_Feature) { #ifdef _DEBUG fprintf(stderr, "warning: FT_OpenType_Validate is disabled. " "Replace FreeType2 with otvalid-enabled version.\n"); #endif return ret; } else if (ft_error != 0 || ret->GSUB_table == 0) { #ifdef _DEBUG fprintf(stderr, "warning: %s has no GSUB table.\n", face->family_name); #endif return ret; } scan_GSUB_Header(ret, ret->GSUB_table); if (ret->Lookup[VERT_LOOKUP_INDEX].SubTableCount == 0) { #ifdef _DEBUG fprintf(stderr, "warning: %s has no vrt2/vert feature.\n", face->family_name); #endif } // free((void*)GSUB_table); return ret; } void ft2vert_final(FT_Face face, struct ft2vert_st *vert){ int i, j; for (i = 0; i < sizeof(vert->Lookup) / sizeof(vert->Lookup[0]); i++) { for (j = 0; j < vert->Lookup[i].SubTableCount; j++) { free(vert->Lookup[i].SubTable[j].SingleSubst.Substitute); free(vert->Lookup[i].SubTable[j].Coverage.GlyphArray); free(vert->Lookup[i].SubTable[j].Coverage.RangeRecord); } free(vert->Lookup[i].SubTable); } FT_OpenType_Free(face, vert->GSUB_table); free(vert); // FT_Bytes kanaFeature; // FT_Bytes haniFeature; // FT_Bytes vertLookup; // FT_Bytes vrt2Lookup; // FT_Bytes jp78Lookup; // FT_Bytes jp90Lookup; // FT_Bytes jp04Lookup; // FT_UInt32* variantSelectors; } /********** converting part *****************/ static FT_UInt get_vert_nth_gid(struct SubTable_st *t, FT_UInt gid, int n) { switch (t->SingleSubst.SubstFormat) { case 1: return gid + t->SingleSubst.DeltaGlyphID; case 2: return t->SingleSubst.Substitute[n]; } #ifdef _DEBUG fprintf(stderr, "get_vert_nth_gid: internal error"); #endif return 0; } FT_UInt ft2gsub_get_gid(const struct ft2vert_st *ft2vert, const FT_UInt gid, const int l) { int i, k; int j = 0; /* StartCoverageIndex */ for (k = 0; k < ft2vert->Lookup[l].SubTableCount; k++) { struct SubTable_st *t = &ft2vert->Lookup[l].SubTable[k]; switch (t->Coverage.CoverageFormat) { case 1: for (i = 0; i < t->Coverage.GlyphCount; i++) { if (t->Coverage.GlyphArray[i] == gid) { return get_vert_nth_gid(t, gid, i); } } break; case 2: for (i = 0; i < t->Coverage.RangeCount; i++) { struct RangeRecord_st *r = &t->Coverage.RangeRecord[i]; if (r->Start <= gid && gid <= r->End) { return get_vert_nth_gid(t, gid, gid - r->Start + j); } j += r->End - r->Start + 1; } break; #ifdef _DEBUG default: fprintf(stderr, "ft2vert_get_gid: internal error"); #endif } } return 0; } FT_UInt ft2vert_get_gid(const struct ft2vert_st *ft2vert, const FT_UInt gid) { FT_UInt tmp = ft2gsub_get_gid(ft2vert, gid, VERT_LOOKUP_INDEX); return tmp ? tmp : gid; } int glyphs_comp(const void *_a, const void *_b) { const struct ivs_otft_desc *a = (const struct ivs_otft_desc *)_a; const struct ivs_otft_desc *b = (const struct ivs_otft_desc *)_b; if (a->baseChar < b->baseChar) return -1; else if (a->baseChar > b->baseChar) return 1; return 0; } FT_UInt ft2_subst_uvs(const FT_Face face, const FT_UInt gid, const FT_UInt vsindex, const FT_UInt baseChar) { FT_UInt newglyph; const struct ivs_otft_desc key = { baseChar }, *found; struct ft2vert_st *ft2vert = (struct ft2vert_st *)face->generic.data; if (!ft2vert) return 0; // 存在するならUVS Subtableから探す if (ft2vert->variantSelectors) return FT_Face_GetCharVariantIndex(face, baseChar, 0xE0100 + vsindex); // GSUBテーブルのOpenType featureによりシミュレートする if (vsindex >= sizeof ivs_otft_index / sizeof ivs_otft_index[0]) return 0; found = (const struct ivs_otft_desc *)bsearch(&key, ivs_otft + ivs_otft_index[vsindex], ivs_otft_count[vsindex], sizeof(struct ivs_otft_desc), glyphs_comp); if (!found) return 0; // シミュレートできるfeatureが見つかったので置換を試みる。 newglyph = ft2gsub_get_gid(ft2vert, gid, found->otft_index); // 置換に成功したらそれを返す if (newglyph) return newglyph; // フォントがGSUBテーブルに置換定義を持っていない。 // 'jp04'を持っているが'jp90'を持っていないときはJIS90フォントとみなし、 // 'jp90'を持っているが'jp04'を持っていないときはJIS2004フォントとみなす。 // JIS90フォントに'jp90'を要求された場合とJIS2004フォント'jp04'を要求された場合は // デフォルト字形が要求された字形であるとみなしてそのまま返す。 if (ft2vert->jp04Lookup && !ft2vert->jp90Lookup && found->otft_index == JP90_LOOKUP_INDEX || ft2vert->jp90Lookup && !ft2vert->jp04Lookup && found->otft_index == JP04_LOOKUP_INDEX) return gid; // どちらでもなければフォントは要求された字形を持っていないとみなす。 return 0; } //#endif /* USE_ZEIT */ ================================================ FILE: ft2vert.h ================================================ #ifdef __cplusplus extern "C"{ #endif /* store GSUB feature vert/vrt2 */ struct ft2vert_st *ft2vert_init(FT_Face face); void ft2vert_final(FT_Face face, struct ft2vert_st *vert); /* convert horizontal glyph index to vertical glyph index */ FT_UInt ft2vert_get_gid(const struct ft2vert_st *ft2vert, const FT_UInt gid); FT_UInt ft2_subst_uvs(const FT_Face face, const FT_UInt gid, const FT_UInt vsindex, const FT_UInt baseChar); #ifdef __cplusplus } #endif ================================================ FILE: fteng.cpp ================================================ #include "override.h" #include "ft.h" #include #include #include "fteng.h" #ifdef _DLL #pragma comment(linker, "/nod:msvcprt.lib /nod:msvcprtd.lib") #endif #if 0 #define FREETYPE_REQCOUNTMAX 10 #define GC_TRACE TRACE #define FREETYPE_GC_COUNTER 128 #else #define FREETYPE_REQCOUNTMAX 2048//默认4096,每缓存该数量的文字将刷新缓存降低内存占用 #define GC_TRACE NOP_FUNCTION #define FREETYPE_GC_COUNTER 1024//刷新缓存后保留文字数量 #endif FreeTypeFontEngine* g_pFTEngine; FT_Library freetype_library; FTC_Manager cache_man; FTC_CMapCache cmap_cache; FTC_ImageCache image_cache; CTLSDCArray TLSDCArray; int CALLBACK EnumFontCallBack(const LOGFONT *lplf, const TEXTMETRIC *lptm, DWORD /*FontType*/, LPARAM lParam) { LOGFONT * lf=(LOGFONT *)lParam; StringCchCopy(lf->lfFaceName, LF_FACESIZE, lplf->lfFaceName); lf->lfQuality=0x2d; //magic number return 0; } bool GetFontLocalName(TCHAR* pszFontName, __out TCHAR* pszNameOut) //获得字体的本地化名称,返回值为字体是否存在 { LOGFONT lf = {0}; TCHAR* ret; lf.lfQuality = 0x2d; if (!(ret = FontNameCache.Find((TCHAR*)pszFontName))) { StringCchCopy(lf.lfFaceName, LF_FACESIZE, pszFontName); lf.lfCharSet=DEFAULT_CHARSET; HDC dc=GetDC(NULL); lf.lfQuality=0; EnumFontFamiliesEx(dc, &lf, &EnumFontCallBack, (LPARAM)&lf, 0); ReleaseDC(NULL, dc); if (lf.lfQuality==0x2d) FontNameCache.Add((TCHAR*)pszFontName, lf.lfFaceName); ret=lf.lfFaceName; } StringCchCopy(pszNameOut, LF_FACESIZE, ret); return lf.lfQuality == 0x2d; } LOGFONTW* GetFontNameFromFile(LPCWSTR Filename) //获得一个字体文件内包含的所有字体名称s { LOGFONTW* logfonts = NULL; DWORD bufsize=0; if (GetFontResourceInfo(Filename, &bufsize, NULL, 2)) { logfonts = (LOGFONTW*)malloc(bufsize+1); if (GetFontResourceInfo(Filename, &bufsize, logfonts, 2)) { ((char*)logfonts)[bufsize]=0; return logfonts; } else { free(logfonts); return NULL; } } else { AddFontResourceW(Filename); if (GetFontResourceInfo(Filename, &bufsize, NULL, 2)) { logfonts = (LOGFONTW*)malloc(bufsize+1); if (GetFontResourceInfo(Filename, &bufsize, logfonts, 2)) { ((char*)logfonts)[bufsize]=0; ORIG_RemoveFontResourceExW(Filename,0,NULL); return logfonts; } else { free(logfonts); ORIG_RemoveFontResourceExW(Filename,0,NULL); return NULL; } } ORIG_RemoveFontResourceExW(Filename,0,NULL); return NULL; } } template struct GCCounterSortFunc : public std::binary_function { bool operator()(const T* arg1, const T* arg2) const { const int cnt1 = arg1 ? arg1->GetMruCounter() : -1; const int cnt2 = arg2 ? arg2->GetMruCounter() : -1; return cnt1 > cnt2; } }; struct DeleteCharFunc : public std::unary_function { void operator()(FreeTypeCharData*& arg) const { if (!arg) return; delete arg; arg = NULL; } }; template void CompactMap(T& pp, int count, int reduce) { CCriticalSectionLock __lock(CCriticalSectionLock::CS_FONTCACHE); int reducecount = pp.size() - reduce; T::iterator it= pp.begin(); for (int i=0;isecond->Erase(); delete it->second; pp.erase(it++); } return; } template void Compact(T** pp, int count, int reduce) { Assert(count >= 0); Assert(reduce > 0); if (!pp || !count || count < reduce) { return; } CCriticalSectionLock __lock(CCriticalSectionLock::CS_FONTCACHE); TRACE(_T("Compact(0x%p, %d, %d)\n"), pp, count, reduce); //GCモドキ //T::m_mrucounterの降順に並ぶので //reduceを超える部分を削除する T** ppTemp = (T**)malloc(sizeof(T*) * count); if (!ppTemp) { return; } memcpy(ppTemp, pp, sizeof(T*) * count); std::sort(ppTemp, ppTemp + count, GCCounterSortFunc()); int i; for (i=0; iResetMruCounter(); } //GC_TRACE(_T("GC:")); for (i=reduce; iGetChar()); ppTemp[i]->Erase(); } //GC_TRACE(_T("\n")); free(ppTemp); } //FreeTypeCharData FreeTypeCharData::FreeTypeCharData(FreeTypeCharData** ppCh, FreeTypeCharData** ppGl, WCHAR wch, UINT glyphindex, int width, int mru, int gdiWidth, int AAMode) : m_ppSelfGlyph(ppGl), m_glyphindex(glyphindex), m_width(width) , m_glyph(NULL), m_glyphMono(NULL), m_bmpSize(0), m_bmpMonoSize(0) , FreeTypeMruCounter(mru), m_gdiWidth(gdiWidth), m_AAMode(AAMode) { g_pFTEngine->AddMemUsedObj(this); AddChar(ppCh); #ifdef _DEBUG m_wch = wch; #endif } FreeTypeCharData::~FreeTypeCharData() { CharDataArray& arr = m_arrSelfChar; int n = arr.GetSize(); while (n--) { FreeTypeCharData** pp = arr[n]; Assert(*pp == this); *pp = NULL; } if(m_ppSelfGlyph) { Assert(*m_ppSelfGlyph == this); *m_ppSelfGlyph = NULL; } if(m_glyph){ FT_Done_Ref_Glyph((FT_Referenced_Glyph*)&m_glyph); } if(m_glyphMono){ FT_Done_Ref_Glyph((FT_Referenced_Glyph*)&m_glyphMono); } g_pFTEngine->SubMemUsed(m_bmpSize); g_pFTEngine->SubMemUsed(m_bmpMonoSize); g_pFTEngine->SubMemUsedObj(this); } void FreeTypeCharData::SetGlyph(FT_Render_Mode render_mode, FT_Referenced_BitmapGlyph glyph) { const bool bMono = (render_mode == FT_RENDER_MODE_MONO); FT_Referenced_BitmapGlyph& gl = bMono ? m_glyphMono : m_glyph; if (gl) FT_Done_Ref_Glyph((FT_Referenced_Glyph*)&gl); { FT_Glyph_Ref_Copy((FT_Referenced_Glyph)glyph, (FT_Referenced_Glyph*)&gl); if (gl) { int& size = bMono ? m_bmpMonoSize : m_bmpSize; size = FT_Bitmap_CalcSize(gl->ft_glyph); size += sizeof(FT_BitmapGlyphRec); g_pFTEngine->AddMemUsed(size); } } } //FreeTypeFontCache FreeTypeFontCache::FreeTypeFontCache(/*int px, int weight, bool italic, */int mru) : /*m_px(px), m_weight(weight), m_italic(italic), */m_active(false) , FreeTypeMruCounter(mru) { #ifdef _USE_ARRAY ZeroMemory(&m_tm, sizeof(TEXTMETRIC)); ZeroMemory(m_chars, sizeof(m_chars)); ZeroMemory(m_glyphs, sizeof(m_glyphs)); #else m_GlyphCache.clear(); #endif g_pFTEngine->AddMemUsedObj(this); } FreeTypeFontCache::~FreeTypeFontCache() { Erase(); g_pFTEngine->SubMemUsedObj(this); } void FreeTypeFontCache::Compact() { //TRACE(_T("FreeTypeFontCache::Compact: %d > %d\n"), countof(m_chars), FREETYPE_GC_COUNTER); ResetGCCounter(); #ifdef _USE_ARRAY ::Compact(m_glyphs, countof(m_glyphs), FREETYPE_GC_COUNTER); #else ::CompactMap(m_GlyphCache, m_GlyphCache.size(), FREETYPE_GC_COUNTER); #endif //GlyphCache::const_iterator it=m_GlyphCache.begin(); } void FreeTypeFontCache::Erase() { m_active = false; #ifdef _USE_ARRAY std::for_each(m_chars, m_chars + FT_MAX_CHARS, DeleteCharFunc()); std::for_each(m_glyphs, m_glyphs + FT_MAX_CHARS, DeleteCharFunc()); #else GlyphCache::iterator it=m_GlyphCache.begin(); for (;it!=m_GlyphCache.end();++it) delete it->second; m_GlyphCache.clear(); #endif } void FreeTypeFontCache::AddCharData(WCHAR wch, UINT glyphindex, int width, int gdiWidth, FT_Referenced_BitmapGlyph glyph, FT_Render_Mode render_mode, int AAMode) { if (glyphindex & 0xffff0000 /*|| !g_ccbCache*/) { return; } if (AddIncrement() >= FREETYPE_REQCOUNTMAX) { //先压缩,避免压缩后丢失的问题 Compact(); } #ifdef _USE_ARRAY FreeTypeCharData** ppChar = _GetChar(wch); if (*ppChar) { (*ppChar)->SetGlyph(render_mode, glyph); (*ppChar)->SetMruCounter(this); return; } #else GlyphCache::iterator it=m_GlyphCache.find(wch); if (it!=m_GlyphCache.end()) //找到了旧数据 { FreeTypeCharData* ppChar = it->second; if (ppChar) { ppChar->SetGlyph(render_mode, glyph); ppChar->SetMruCounter(this); ppChar->SetWidth(width); ppChar->SetGDIWidth(gdiWidth); return; } } #endif FreeTypeCharData* p = new FreeTypeCharData(/*ppChar*/NULL, NULL, wch, glyphindex, width, MruIncrement(), gdiWidth, AAMode); if (p == NULL) { return; } p->SetGlyph(render_mode, glyph); #ifdef _USE_ARRAY *ppChar = p; #else m_GlyphCache[wch]=p; #endif } void FreeTypeFontCache::AddGlyphData(UINT glyphindex, int width, int gdiWidth, FT_Referenced_BitmapGlyph glyph, FT_Render_Mode render_mode, int AAMode) { if (glyphindex & 0xffff0000 /*|| !g_ccbCache*/) { return; } //GC if (AddIncrement() >= FREETYPE_REQCOUNTMAX) { //TRACE(_T("Compact(0x%p)\n"), this); Compact(); } #ifdef _USE_ARRAY FreeTypeCharData** ppGlyph = _GetGlyph(glyphindex); if (*ppGlyph) { (*ppGlyph)->SetGlyph(render_mode, glyph); (*ppGlyph)->SetMruCounter(this); return; } #else GlyphCache::iterator it=m_GlyphCache.find(-(int)glyphindex); if (it!=m_GlyphCache.end()) //找到了旧数据 { FreeTypeCharData* ppChar = it->second; if (ppChar) { (ppChar)->SetGlyph(render_mode, glyph); (ppChar)->SetMruCounter(this); ppChar->SetWidth(width); ppChar->SetGDIWidth(gdiWidth); return; } } #endif //追加(glyphのみ) FreeTypeCharData* p = new FreeTypeCharData(NULL, /*ppGlyph*/NULL, 0, glyphindex, width, MruIncrement(), gdiWidth, AAMode); if (p == NULL) { return; } p->SetGlyph(render_mode, glyph); #ifdef _USE_ARRAY *ppGlyph = p; #else m_GlyphCache[-(int)glyphindex]=p; #endif } //FreeTypeFontInfo void FreeTypeFontInfo::Compact() { //TRACE(_T("FreeTypeFontInfo::Compact: %d > %d\n"), m_cache.GetSize(), m_nMaxSizes); ResetGCCounter(); ::CompactMap(m_cache, m_cache.size(), m_nMaxSizes); CacheArray::const_iterator it=m_cache.begin(); for (;it!=m_cache.end();++it) it->second->Deactive(); } void FreeTypeFontInfo::Createlink() { CFontFaceNamesEnumerator fn(m_hash.c_str(), m_nFontFamily); std::set linkset; //链接字体集合,防止重复链接,降低效率 linkset.insert(m_id); face_id_link[m_linknum] = (FTC_FaceID)m_id; ggo_link[m_linknum++] = m_ggoFont; //第一个链接一定是自己,不需要获取 LOGFONT lf; BOOL IsSimSun = false; memset(&lf, 0, sizeof(LOGFONT)); lf.lfCharSet=DEFAULT_CHARSET; const CGdippSettings* pSettings = CGdippSettings::GetInstance(); for (fn.next() ; !fn.atend(); fn.next()) { //跳过第一个链接 //FreeTypeFontInfo* pfitemp = g_pFTEngine->FindFont(fn, m_weight, m_italic); //if (pfitemp && pfitemp->m_isSimSun) // IsSimSun = true; if (!m_SimSunID) IsSimSun = (_wcsicmp(fn,L"宋体")==0 || _wcsicmp(fn,L"SimSun")==0); StringCchCopy(lf.lfFaceName, LF_FACESIZE, fn); if (!_wcsicmp(fn, m_familyname.c_str())) // allow font link to itself pSettings->CopyForceFont(lf,lf); FreeTypeFontInfo* pfitemp = g_pFTEngine->FindFont(lf.lfFaceName, /*m_weight*/0, /*m_italic*/false); if (pfitemp && linkset.find(pfitemp->GetId())==linkset.end()) { linkset.insert(pfitemp->GetId()); face_id_link[m_linknum] = (FTC_FaceID)pfitemp->GetId(); ggo_link[m_linknum++] = pfitemp->GetGGOFont(); if (!m_SimSunID && IsSimSun) m_SimSunID = (FTC_FaceID)pfitemp->GetId(); } } } bool FreeTypeFontInfo::EmbeddedBmpExist(int px) { if (px>=256 || px<0) return false; if (m_ebmps[px]!=-1) return !!m_ebmps[px]; CCriticalSectionLock __lock(CCriticalSectionLock::CS_MANAGER); FTC_ImageTypeRec imgtype={(FTC_FaceID)m_id, px, px, FT_LOAD_DEFAULT}; //构造一个当前大小的imagetype FT_Glyph temp_glyph=NULL; FT_UInt gindex = FTC_CMapCache_Lookup(cmap_cache, (FTC_FaceID)m_id, -1, FT_UInt32(L'0')); //获得0的索引值 FTC_ImageCache_Lookup(image_cache, &imgtype, gindex, &temp_glyph, NULL); if (temp_glyph && temp_glyph->format==FT_GLYPH_FORMAT_BITMAP) //如果可以读到0的点阵 m_ebmps[px]=1; //则该字号存在点阵 else { gindex = FTC_CMapCache_Lookup(cmap_cache, (FTC_FaceID)m_id, -1, FT_UInt32(L'的')); //获得"的"的索引值 if (gindex) FTC_ImageCache_Lookup(image_cache, &imgtype, gindex, &temp_glyph, NULL); //读取“的”的点阵 if (temp_glyph && temp_glyph->format==FT_GLYPH_FORMAT_BITMAP) //如果可以读到0的点阵 m_ebmps[px]=1; //则该字号存在点阵 else m_ebmps[px]=0; } return !!m_ebmps[px]; } FreeTypeFontCache* FreeTypeFontInfo::GetCache(FTC_ScalerRec& scaler, const LOGFONT& lf) { CCriticalSectionLock __lock(CCriticalSectionLock::CS_FONTCACHE); if (AddIncrement() > m_nMaxSizes) { //先压缩 Compact(); } int weight = lf.lfWeight; weight = weight < FW_BOLD ? 0: 1/*FW_BOLD*/; const bool italic = !!lf.lfItalic; if (scaler.height>0xfff || scaler.width>0xfff/* || scaler.height<0 || scaler.width<0*/) //超大字体不渲染 return NULL; FreeTypeFontCache* p = NULL; UINT hash=getCacheHash(scaler.height, weight, italic, lf.lfWidth ? scaler.width : 0); //计算hash CacheArray::iterator it=m_cache.find(hash); //寻找cache if (it!=m_cache.end())//cache存在 { p = it->second; goto OK; //返回cache } p = new FreeTypeFontCache(/*scaler.height, weight, italic,*/ MruIncrement()); if (!p) { return NULL; } if (m_cache[hash]=p) { goto OK; } delete p; return NULL; OK: Assert(p != NULL); if (p && p->Activate()) { DecIncrement(); //重复使用则减计数值 } return p; } //FreeTypeFontEngine void FreeTypeFontEngine::Compact() { CCriticalSectionLock __lock(CCriticalSectionLock::CS_FONTENG); TRACE(_T("FreeTypeFontEngine::Compact: %d > %d\n"), m_mfontMap.size(), m_nMaxFaces); ResetGCCounter(); //memset(m_arrFace, 0, sizeof(FT_Face)*m_nFaceCount); //超过最大face数了,老的face会被ft释放掉,所以需要全部重新获取 //FontListArray& arr = m_arrFontList; //::Compact(arr.GetData(), arr.GetSize(), m_nMaxFaces); } BOOL FreeTypeFontEngine::RemoveFont(FreeTypeFontInfo* fontinfo) { CCriticalSectionLock __lock(CCriticalSectionLock::CS_FONTMAP); { FontMap::const_iterator iter=m_mfontMap.begin(); //遍历fontmap while (iter!=m_mfontMap.end()) { FreeTypeFontInfo* p = iter->second; if (p==fontinfo) m_mfontMap.erase(iter++); //删除引用 else ++iter; } } { FullNameMap::const_iterator iter=m_mfullMap.begin(); //遍历fullmap while (iter!=m_mfullMap.end()) { FreeTypeFontInfo* p = iter->second; if (p==fontinfo) m_mfullMap.erase(iter++); //删除引用 else { iter->second->UpdateFontSetting(); ++iter; } } } delete fontinfo; return true; } BOOL FreeTypeFontEngine::RemoveThisFont(FreeTypeFontInfo* fontinfo, LOGFONT* lg) { CCriticalSectionLock __lock(CCriticalSectionLock::CS_FONTMAP); { FontMap::const_iterator iter=m_mfontMap.find(myfont(lg->lfFaceName, CalcBoldWeight(lg->lfWeight), lg->lfItalic)); //遍历fontmap if (iter!=m_mfontMap.end()) m_mfontMap.erase(iter); //删除引用 } { FullNameMap::const_iterator iter=m_mfullMap.find(fontinfo->GetFullName()); //遍历fullmap if (iter!=m_mfullMap.end()) m_mfullMap.erase(iter); //删除引用 } delete fontinfo; return true; } BOOL FreeTypeFontEngine::RemoveFont(LPCWSTR FontName) { if (!FontName) return false; LOGFONTW* fontarray = GetFontNameFromFile(FontName); LOGFONTW* c_fontarray = fontarray; //记录原始指针 if (!fontarray) return false; FTC_FaceID fid = NULL; BOOL bIsFontLoaded, bIsFontFileLoaded = false; COwnedCriticalSectionLock __lock2(2, COwnedCriticalSectionLock::OCS_DC); //获取所有权,现在要处理DC,禁止所有绘图函数访问 CCriticalSectionLock __lock(CCriticalSectionLock::CS_MANAGER); while (*(char*)fontarray) { bIsFontLoaded = false; FreeTypeFontInfo* result = FindFont(fontarray->lfFaceName, fontarray->lfWeight, !!fontarray->lfItalic, false, &bIsFontLoaded); if (result) { fid = (FTC_FaceID)result->GetId(); if (bIsFontLoaded) //该字体已经被使用过 { RemoveFont(result); //枚举字体信息全部删除 bIsFontFileLoaded = true; //设置字体文件也被使用过 } else RemoveThisFont(result, fontarray); CCriticalSectionLock __lock(CCriticalSectionLock::CS_FONTENG); FTC_Manager_RemoveFaceID(cache_man, fid); m_mfontList[(int)fid-1]=NULL; } fontarray++; } free(c_fontarray); //利用原始指针释放 if (bIsFontFileLoaded) //若字体文件被使用过,则需要清楚所有DC { CTLSDCArray::iterator iter = TLSDCArray.begin(); while (iter!=TLSDCArray.end()) { ((CBitmapCache*)*iter)->~CBitmapCache(); //清除掉所有使用中的DC ++iter; } } return true; } static int FaceIDHolder = 0; int GetFaceID(void) { return (int)InterlockedIncrement((LONG volatile*)&FaceIDHolder); } void ReleaseFaceID(void) { InterlockedDecrement((LONG volatile*)&FaceIDHolder); } FreeTypeFontInfo* FreeTypeFontEngine::AddFont(void* lpparams) { FREETYPE_PARAMS* params = (FREETYPE_PARAMS*)lpparams; CCriticalSectionLock __lock(CCriticalSectionLock::CS_FONTENG); const LOGFONT& lplf = *params->lplf; if(!*lplf.lfFaceName || _tcslen(lplf.lfFaceName) == 0) return NULL; const CGdippSettings* pSettings = CGdippSettings::GetInstance(); //const CFontSettings& fs = pSettings->FindIndividual(params->strFamilyName.c_str()); FreeTypeFontInfo* pfi = new FreeTypeFontInfo(/*m_mfullMap.size() + 1*/GetFaceID(), lplf.lfFaceName, lplf.lfWeight, !!lplf.lfItalic, MruIncrement(), params->strFullName, params->strFamilyName); if (!pfi) return NULL; if (pfi->GetFullName().size()==0) //点阵字 { delete pfi; ReleaseFaceID(); return NULL; } /* TCHAR buff[255]={0}; if (params->strFamilyName.length()==8) { wsprintf(buff, L"Adding familiyname \"%s\" fullname \"%s\" weight %d\n\result: \"%s\"\n", params->strFamilyName.c_str(), params->strFullName.c_str(), params->lplf->lfWeight, pfi->GetFullName().c_str()); Log(buff); }*/ FullNameMap::const_iterator it = m_mfullMap.find(pfi->GetFullName()); if (it!=m_mfullMap.end()) //是已经存在的字体了,原因是字体替换使两种名字指向一个字体 { delete pfi; //删除刚才创建的字体 ReleaseFaceID(); pfi = it->second;//指向原字体 } else { m_mfullMap[pfi->GetFullName()]=pfi; //不存在,添加到map表 m_mfontList.push_back(pfi); } if (pfi->GetFullName()!=params->strFullName) //如果目标字体的真实名称和需要的名称不一样,说明是字体替换 { pfi->AddRef(); //增加引用计数 m_mfullMap[params->strFullName] = pfi; //双重引用,指向同一个字体 } //bool ret = !!arr.Add(pfi); //weight = weight < FW_BOLD ? 0: FW_BOLD; myfont font(lplf.lfFaceName, lplf.lfWeight, !!params->otm->otmTextMetrics.tmItalic); /* FontMap::const_iterator it = m_mfontMap.find(font); if (it!=m_mfontMap.end()) { it->second->Release(); }*/ m_mfontMap[font]=pfi; /* if (!ret) { delete pfi; return NULL; }*/ #ifdef _DEBUG { const CFontSettings& fs = pfi->GetFontSettings(); TRACE(_T("AddFont: %s, %d, %d, %d, %d, %d, %d\n"), pfi->GetName(), fs.GetParam(0), fs.GetParam(1), fs.GetParam(2), fs.GetParam(3), fs.GetParam(4), fs.GetParam(5)); } #endif return pfi; } FreeTypeFontInfo* FreeTypeFontEngine::AddFont(LPCTSTR lpFaceName, int weight, bool italic, BOOL* bIsFontLoaded) { CCriticalSectionLock __lock(CCriticalSectionLock::CS_FONTENG); if(lpFaceName == NULL || _tcslen(lpFaceName) == 0/* || FontExists(lpFaceName, weight, italic)*/) return NULL; //FontListArray& arr = m_arrFontList; const CGdippSettings* pSettings = CGdippSettings::GetInstance(); //const CFontSettings& fs = pSettings->FindIndividual(lpFaceName); wstring dumy; //dumy.clear(); FreeTypeFontInfo* pfi = new FreeTypeFontInfo(/*m_mfullMap.size() + 1*/GetFaceID(), lpFaceName, weight, italic, MruIncrement(), dumy, dumy); if (!pfi) return NULL; if (pfi->GetFullName().size()==0) //点阵字 { delete pfi; ReleaseFaceID(); return NULL; } FullNameMap::const_iterator it = m_mfullMap.find(pfi->GetFullName()); //是否在主map表中存在了 if (it!=m_mfullMap.end()) //已经存在 { delete pfi; //删除创建出来的字体 ReleaseFaceID(); pfi = it->second; //指向已经存在的字体 if (bIsFontLoaded) *bIsFontLoaded = true; //pfi->AddRef(); } else { m_mfullMap[pfi->GetFullName()]=pfi; //不存在,添加到map表 m_mfontList.push_back(pfi); if (bIsFontLoaded) *bIsFontLoaded = false; } //bool ret = !!arr.Add(pfi); //weight = weight < FW_BOLD ? 0: FW_BOLD; myfont font(lpFaceName, weight, italic); m_mfontMap[font]=pfi; //添加在次要map表 /* if (!ret) { delete pfi; return NULL; }*/ #ifdef _DEBUG { const CFontSettings& fs = pfi->GetFontSettings(); TRACE(_T("AddFont: %s, %d, %d, %d, %d, %d, %d\n"), pfi->GetName(), fs.GetParam(0), fs.GetParam(1), fs.GetParam(2), fs.GetParam(3), fs.GetParam(4), fs.GetParam(5)); } #endif return pfi; } int FreeTypeFontEngine::GetFontIdByName(LPCTSTR lpFaceName, int weight, bool italic) { const FreeTypeFontInfo* pfi = FindFont(lpFaceName, weight, italic); return pfi ? pfi->GetId() : 0; } /* LPCTSTR FreeTypeFontEngine::GetFontById(int faceid, int& weight, bool& italic) { CCriticalSectionLock __lock; FreeTypeFontInfo** pp = m_arrFontList.Begin(); FreeTypeFontInfo** end = m_arrFontList.End(); for(; pp != end; ++pp) { FreeTypeFontInfo* p = *pp; if (p->GetId() == faceid) { p->SetMruCounter(this); weight = p->GetWeight(); italic = p->IsItalic(); return p->GetName(); } } return NULL; } */ FreeTypeFontInfo* FreeTypeFontEngine::FindFont(void* lpparams) { FREETYPE_PARAMS* params = (FREETYPE_PARAMS*)lpparams; CCriticalSectionLock __lock(CCriticalSectionLock::CS_FONTMAP); FullNameMap::const_iterator iter=m_mfullMap.find(params->strFullName); if (iter!=m_mfullMap.end()) { FreeTypeFontInfo* p = iter->second; if (p->GetFullName()!=params->strFullName) //属于替换字体 return FindFont(params->lplf->lfFaceName, params->lplf->lfWeight, !!params->lplf->lfItalic); p->SetMruCounter(this); return p; } //m_bAddOnFind = true; return AddFont(params); } FreeTypeFontInfo* FreeTypeFontEngine::FindFont(LPCTSTR lpFaceName, int weight, bool italic, bool AddOnFind, BOOL* bIsFontLoaded) { /* if (m_bAddOnFind) { m_bAddOnFind = false; return NULL; }*/ CCriticalSectionLock __lock(CCriticalSectionLock::CS_FONTMAP); weight = CalcBoldWeight(weight); myfont font(lpFaceName, weight, italic); FontMap::const_iterator iter=m_mfontMap.find(font); if (iter!=m_mfontMap.end()) { FreeTypeFontInfo* p = iter->second; p->SetMruCounter(this); /* TCHAR buff[255]={0}; if (wcslen(lpFaceName)==8) { wsprintf(buff, L"Finding familiyname \"%s\" weight %d\n\tFound: \"%s\"\n", lpFaceName, weight, p->GetFullName().c_str()); Log(buff); }*/ if (bIsFontLoaded) *bIsFontLoaded = true; return p; } //m_bAddOnFind = true; return AddFont(lpFaceName, weight, italic, bIsFontLoaded); } FreeTypeFontInfo* FreeTypeFontEngine::FindFont(int faceid) { CCriticalSectionLock __lock(CCriticalSectionLock::CS_FONTMAP); if (faceid>m_mfontList.size()) return NULL; else return m_mfontList[faceid-1]; //存在bug!!! /* FullNameMap::const_iterator iter=m_mfullMap.begin(); for(; iter != m_mfullMap.end(); ++iter) { FreeTypeFontInfo* p = iter->second; if (p->GetId() == faceid) { p->SetMruCounter(this); return p; } } return NULL;*/ } //FreeTypeSysFontData // http://kikyou.info/diary/?200510#i10 を参考にした #include // FT_TRUETYPE_TABLES_H #include //mmioFOURCC #define TVP_TT_TABLE_ttcf mmioFOURCC('t', 't', 'c', 'f') #define TVP_TT_TABLE_name mmioFOURCC('n', 'a', 'm', 'e') // Windowsに登録されているフォントのバイナリデータを名称から取得 FreeTypeSysFontData* FreeTypeSysFontData::CreateInstance(LPCTSTR name, int weight, bool italic) { FreeTypeSysFontData* pData = new FreeTypeSysFontData; if (!pData) { return NULL; } if (!pData->Init(name, weight, italic)) { delete pData; return NULL; } return pData; } bool FreeTypeSysFontData::Init(LPCTSTR name, int weight, bool italic) { const CGdippSettings* pSettings = CGdippSettings::GetInstance(); void* pNameFromGDI = NULL; // Windows から取得した name タグの内容 void* pNameFromFreeType = NULL; // FreeType から取得した name タグの内容 HFONT hf = NULL; DWORD cbNameTable; DWORD cbFontData; int index; DWORD buf; FT_StreamRec& fsr = m_ftStream; m_name.assign(name); m_hdc = CreateCompatibleDC(NULL); if(m_hdc == NULL) { return false; } // 名前以外適当 if (pSettings->FontSubstitutes() < SETTING_FONTSUBSTITUTE_ALL) { hf = CreateFont( 12, 0, 0, 0, weight, italic, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, FONT_MAGIC_NUMBER, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, name); } else hf = CreateFont( 12, 0, 0, 0, weight, italic, FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, name); if(hf == NULL){ return false; } m_hOldFont = SelectFont(m_hdc, hf); // フォントデータが得られそうかチェック cbNameTable = ORIG_GetFontData(m_hdc, TVP_TT_TABLE_name, 0, NULL, 0); if(cbNameTable == GDI_ERROR){ goto ERROR_Init; } pNameFromGDI = malloc(cbNameTable); if (!pNameFromGDI) { goto ERROR_Init; } pNameFromFreeType = malloc(cbNameTable); if (!pNameFromFreeType) { goto ERROR_Init; } //- name タグの内容をメモリに読み込む if(ORIG_GetFontData(m_hdc, TVP_TT_TABLE_name, 0, pNameFromGDI, cbNameTable) == GDI_ERROR){ goto ERROR_Init; } // フォントサイズ取得処理 cbFontData = ORIG_GetFontData(m_hdc, TVP_TT_TABLE_ttcf, 0, &buf, 1); if(cbFontData == 1){ // TTC ファイルだと思われる cbFontData = ORIG_GetFontData(m_hdc, TVP_TT_TABLE_ttcf, 0, NULL, 0); m_isTTC = true; } else{ cbFontData = ORIG_GetFontData(m_hdc, 0, 0, NULL, 0); } if(cbFontData == GDI_ERROR){ // エラー; GetFontData では扱えなかった goto ERROR_Init; } if (pSettings->UseMapping()) { HANDLE hmap = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE | SEC_COMMIT | SEC_NOCACHE, 0, cbFontData, NULL); if (!hmap) { goto ERROR_Init; } m_pMapping = MapViewOfFile(hmap, FILE_MAP_ALL_ACCESS, 0, 0, cbFontData); m_dwSize = cbFontData; CloseHandle(hmap); if (m_pMapping) { ORIG_GetFontData(m_hdc, m_isTTC ? TVP_TT_TABLE_ttcf : 0, 0, m_pMapping, cbFontData); } } // FT_StreamRec の各フィールドを埋める fsr.base = 0; fsr.size = cbFontData; fsr.pos = 0; fsr.descriptor.pointer = this; fsr.pathname.pointer = NULL; fsr.read = IoFunc; fsr.close = CloseFunc; index = 0; m_locked = true; if(!OpenFaceByIndex(index)){ goto ERROR_Init; } for(;;) { // FreeType から、name タグのサイズを取得する FT_ULong length = 0; FT_Error err = FT_Load_Sfnt_Table(m_ftFace, TTAG_name, 0, NULL, &length); if(err){ goto ERROR_Init; } // FreeType から得た name タグの長さを Windows から得た長さと比較 if(length == cbNameTable){ // FreeType から name タグを取得 err = FT_Load_Sfnt_Table(m_ftFace, TTAG_name, 0, (unsigned char*)pNameFromFreeType, &length); if(err){ goto ERROR_Init; } // FreeType から読み込んだ name タグの内容と、Windows から読み込んだ // name タグの内容を比較する。 // 一致していればその index のフォントを使う。 if(!memcmp(pNameFromGDI, pNameFromFreeType, cbNameTable)){ // 一致した // face は開いたまま break; // ループを抜ける } } // 一致しなかった // インデックスを一つ増やし、その face を開く index ++; if(!OpenFaceByIndex(index)){ // 一致する face がないまま インデックスが範囲を超えたと見られる // index を 0 に設定してその index を開き、ループを抜ける index = 0; if(!OpenFaceByIndex(index)){ goto ERROR_Init; } break; } } free(pNameFromGDI); free(pNameFromFreeType); m_locked = false; return true; ERROR_Init: m_locked = false; if (hf) { SelectFont(m_hdc, m_hOldFont); DeleteFont(hf); m_hOldFont = NULL; } free(pNameFromGDI); free(pNameFromFreeType); return false; } unsigned long FreeTypeSysFontData::IoFunc( FT_Stream stream, unsigned long offset, unsigned char* buffer, unsigned long count ) { if(count == 0){ return 0; } FreeTypeSysFontData * pThis = reinterpret_cast(stream->descriptor.pointer); Assert(pThis != NULL); DWORD result = 0; if (pThis->m_pMapping) { result = Min(pThis->m_dwSize - offset, count); memcpy(buffer, (const BYTE*)pThis->m_pMapping + offset, result); } else { result = ::GetFontData(pThis->m_hdc, pThis->m_isTTC ? TVP_TT_TABLE_ttcf : 0, offset, buffer, count); if(result == GDI_ERROR) { // エラー return 0; } } return result; } void FreeTypeSysFontData::CloseFunc(FT_Stream stream) { FreeTypeSysFontData * pThis = reinterpret_cast(stream->descriptor.pointer); Assert(pThis != NULL); if(!pThis->m_locked) delete pThis; } bool FreeTypeSysFontData::OpenFaceByIndex(int index) { if(m_ftFace) { FT_Done_Face(m_ftFace); m_ftFace = NULL; } FT_Open_Args args = { 0 }; args.flags = FT_OPEN_STREAM; args.stream = &m_ftStream; // FreeType で扱えるか? FT_Error ftErrCode = FT_Open_Face(freetype_library, &args, index, &m_ftFace); #ifdef DEBUG if (ftErrCode!=0) TRACE(L"Open face failed, error = %d\n", ftErrCode); #endif return (ftErrCode == 0); } ================================================ FILE: fteng.h ================================================ #pragma once #include #include /* FT_FREETYPE_H */ #include /* FT_CACHE_H */ #include #include // FT_TRUETYPE_TAGS_H #include #include #include "ftref.h" #include #include "undocAPI.h" class FreeTypeFontEngine; extern FreeTypeFontEngine* g_pFTEngine; extern BOOL g_ccbCache; extern BOOL g_ccbIndividual; extern FTC_Manager cache_man; typedef set CTLSDCArray; extern CTLSDCArray TLSDCArray; LOGFONTW* GetFontNameFromFile(LPCTSTR Filename); bool GetFontLocalName(TCHAR* pszFontName, __out TCHAR* pszNameOut); //获得字体的本地化名称 struct CFontSetCache { const CFontSettings** fontsetlist; int fontsetsize; CFontSetCache() :fontsetsize(0) { fontsetsize=64; fontsetlist = (const CFontSettings**)malloc(fontsetsize * sizeof(void*)); } ~CFontSetCache() { free(fontsetlist); } void Set(FTC_FaceID faceid, const CFontSettings& fset) { while ((INT_PTR)faceid>=fontsetsize) { fontsetsize+=64; fontsetlist = (const CFontSettings**)realloc(fontsetlist, fontsetsize); } fontsetlist[(INT_PTR)faceid]=&fset; } const CFontSettings*& Get(FTC_FaceID faceid) const { return fontsetlist[(INT_PTR)faceid]; } }; struct myfont { wstring name; int hash; bool operator < (const myfont& mf) const { return name==mf.name? hashMruIncrement(); } }; //文字幅、(glyph index)、FT_BitmapGlyph(太字、斜体のみ)をキャッシュする class FreeTypeCharData : public FreeTypeMruCounter { private: typedef CValArray CharDataArray; CharDataArray m_arrSelfChar; //自分自身の保存元(Char) FreeTypeCharData** m_ppSelfGlyph; //(Glyph) UINT m_glyphindex; //グリフ番号 int m_width; //文字幅 int m_gdiWidth; //使用GetCharWidth获得的GDI宽度 FT_Referenced_BitmapGlyph m_glyph; //カラー用 FT_Referenced_BitmapGlyph m_glyphMono; //モノクロ用 int m_bmpSize; //ビットマップサイズ int m_bmpMonoSize; // 〃 int m_AAMode; // LONG m_refcounter; //参照カウンタ #ifdef _DEBUG WCHAR m_wch; //UCS2文字 #endif NOCOPY(FreeTypeCharData); //FT_Bitmap::bufferのサイズを返す static inline int FT_Bitmap_CalcSize(FT_BitmapGlyph gl) { return gl->bitmap.pitch * gl->bitmap.rows; } public: FreeTypeCharData(FreeTypeCharData** ppCh, FreeTypeCharData** ppGl, WCHAR wch, UINT glyphindex, int width, int mru, int gdiWidth, int AAMode); ~FreeTypeCharData(); #ifdef _DEBUG WCHAR GetChar() const { return m_wch; } #else WCHAR GetChar() const { return L'?'; } #endif UINT GetGlyphIndex() const { return m_glyphindex; } int GetWidth() const { return m_width; } void SetWidth(int width) { m_width = width; } void SetGDIWidth(int width) { m_gdiWidth = width; } int GetGDIWidth() const {return m_gdiWidth; } int GetAAMode() const {return m_AAMode; } void AddChar(FreeTypeCharData** ppCh) { if (ppCh) m_arrSelfChar.Add(ppCh); } FT_Referenced_BitmapGlyph GetGlyph(FT_Render_Mode render_mode) const { return (render_mode == FT_RENDER_MODE_MONO) ? m_glyphMono : m_glyph; } void SetGlyph(FT_Render_Mode render_mode, FT_Referenced_BitmapGlyph glyph); void Erase() { //delete this; } }; static INT_PTR NULL_INT = NULL; class FreeTypeFontCache : public FreeTypeMruCounter, public FreeTypeGCCounter { typedef map GlyphCache; private: int m_px; int m_weight; bool m_italic; bool m_active; TEXTMETRIC m_tm; //4×65536×2=512KBぐらいたかが知れてるので固定配列で問題無し #ifdef _USE_ARRAY FreeTypeCharData* m_chars[FT_MAX_CHARS]; FreeTypeCharData* m_glyphs[FT_MAX_CHARS]; #else GlyphCache m_GlyphCache; #endif NOCOPY(FreeTypeFontCache); void Compact(); FreeTypeCharData** _GetChar(WCHAR wch) { #ifdef _USE_ARRAY return m_chars + wch; #else GlyphCache::iterator it=m_GlyphCache.find(wch); return it==m_GlyphCache.end()? reinterpret_cast(&NULL_INT): &(it->second); #endif } FreeTypeCharData** _GetGlyph(UINT glyph) { #ifdef _USE_ARRAY return m_glyphs + glyph; #else GlyphCache::iterator it=m_GlyphCache.find(-(int)glyph); return it == m_GlyphCache.end() ? reinterpret_cast(&NULL_INT) : &(it->second); #endif } public: FreeTypeFontCache(/*int px, int weight, bool italic, */int mru); ~FreeTypeFontCache(); const TEXTMETRIC& GetTextMetric(HDC hdc) { if (m_tm.tmHeight == 0) { ::GetTextMetrics(hdc, &m_tm); } return m_tm; } bool Equals(int px, int weight, bool italic) const { return (m_px == px && m_weight == weight && m_italic == italic); } FreeTypeCharData* FindChar(WCHAR wch) { /*if (!g_ccbCache) return NULL;*/ FreeTypeCharData* p = *_GetChar(wch); if(p) { p->SetMruCounter(this); } return p; } FreeTypeCharData* FindGlyphIndex(UINT glyph) { /*if (!g_ccbCache) return NULL;*/ FreeTypeCharData* p = (glyph & 0xffff0000) ? NULL : *_GetGlyph(glyph); if(p) { p->SetMruCounter(this); } return p; } bool Activate() { if (!m_active) { m_active = true; return true; } return false; } void Erase(); void Deactive() { m_active = false; }; void AddCharData(WCHAR wch, UINT glyphindex, int width, int gdiWidth, FT_Referenced_BitmapGlyph glyph, FT_Render_Mode render_mode, int AAMode); void AddGlyphData(UINT glyphindex, int width, int gdiWidth, FT_Referenced_BitmapGlyph glyph, FT_Render_Mode render_mode, int AAMode); }; // フォント名とFaceID(intを使うことにする) //extern CFontSetCache g_fsetcache; extern CHashedStringList FontNameCache; class FreeTypeFontInfo : public FreeTypeMruCounter, public FreeTypeGCCounter { private: INT_PTR m_id; int m_weight; bool m_italic; char m_hashinting; int m_ftWeight; int m_os2Weight; int m_nMaxSizes; int m_nFontFamily; HFONT m_ggoFont; TT_OS2* m_OS2Table; char m_ebmps[256]; LONG volatile count; CFontSettings m_set; StringHashFont m_hash; wstring m_fullname, m_familyname, m_stylename; typedef map CacheArray; CacheArray m_cache; //快速链接 FTC_FaceID face_id_link[CFontLinkInfo::FONTMAX * 2 + 1]; HFONT ggo_link[CFontLinkInfo::FONTMAX * 2 + 1]; bool m_linkinited; int m_linknum; FTC_FaceID m_SimSunID; NOCOPY(FreeTypeFontInfo); void Compact(); void Createlink(); public: void AddRef() {InterlockedIncrement(&count);}; void Release() { if (InterlockedDecrement(&count)==0) delete this; } TT_OS2* GetOS2Table() { if (!m_OS2Table) { TT_OS2 * os2_table = NULL; FT_Face freetype_face; CCriticalSectionLock __lock(CCriticalSectionLock::CS_MANAGER); if (FTC_Manager_LookupFace(cache_man, (FTC_FaceID)m_id, &freetype_face)) return NULL; os2_table = (TT_OS2*) FT_Get_Sfnt_Table(freetype_face, ft_sfnt_os2); if (!os2_table) return NULL; m_OS2Table = new TT_OS2; memcpy(m_OS2Table, os2_table, sizeof(TT_OS2)); } return m_OS2Table; } BOOL FontHasHinting() { if (m_hashinting==3) { FT_Face freetype_face; CCriticalSectionLock __lock(CCriticalSectionLock::CS_MANAGER); if (FTC_Manager_LookupFace(cache_man, (FTC_FaceID)m_id, &freetype_face)) //查询ft face { m_hashinting = false; return NULL; } FT_ULong length = 0; FT_Error err = FT_Load_Sfnt_Table(freetype_face, TTAG_fpgm, 0, NULL, &length); //获取fpgm表长度 if (!err && length>50) //成功读取表,并且长度较长 m_hashinting = true; //字体存在hinting else m_hashinting = false; } return m_hashinting; } wstring GetFullName() {return m_fullname;}; bool m_isSimSun; bool IsPixel; UINT getCacheHash(int px, int weight, bool italic, int width) {return ((px<<20)|(width<<8)|(weight<<1)|(int)italic); }; //计算一个hash值来定位cache FreeTypeFontInfo(int n, LPCTSTR name, int weight, bool italic, int mru, wstring fullname, wstring familyname) : m_id(n), m_weight(weight), m_italic(italic), m_OS2Table(NULL), IsPixel(false) , FreeTypeMruCounter(mru), m_isSimSun(false), m_ggoFont(NULL), m_linkinited(false), m_linknum(0), m_os2Weight(0) , m_SimSunID(0), count(1), m_fullname(fullname), m_familyname(familyname), m_hashinting(3), m_nFontFamily(0) { //m_set = set; memset(m_ebmps, 0xff, sizeof(m_ebmps)); enum { FTC_MAX_SIZES_DEFAULT = 4 }; const CGdippSettings* pSettings = CGdippSettings::GetInstance(); m_nMaxSizes = pSettings->CacheMaxSizes(); if (!m_nMaxSizes) m_nMaxSizes = FTC_MAX_SIZES_DEFAULT; //extern BOOL g_EngineCreateFont; if (pSettings->FontSubstitutes() < SETTING_FONTSUBSTITUTE_ALL) m_ggoFont = CreateFont(10,0,0,0,weight,italic,0,0,DEFAULT_CHARSET,0,FONT_MAGIC_NUMBER,0,0,name); //use magic number to create unsubstitud font else m_ggoFont = CreateFont(10,0,0,0,weight,italic,0,0,DEFAULT_CHARSET,0,0,0,0,name); HDC hdc = CreateCompatibleDC(NULL); HFONT old = SelectFont(hdc, m_ggoFont); //获得字体的全称 int nSize=GetOutlineTextMetrics(hdc, 0, NULL); if (nSize==0) m_fullname = L""; else //if (m_fullname.size()==0) //构造函数中不提供,自己获取 { LPOUTLINETEXTMETRIC otm = (LPOUTLINETEXTMETRIC)malloc(nSize); memset(otm, 0, nSize); otm->otmSize = nSize; GetOutlineTextMetrics(hdc, nSize, otm); m_fullname = wstring((LPWSTR)((DWORD_PTR)otm + (DWORD_PTR)otm->otmpFullName)); TCHAR * localname = (LPWSTR)((DWORD_PTR)otm+(DWORD_PTR)otm->otmpFamilyName); m_stylename = wstring((LPWSTR)((DWORD_PTR)otm + (DWORD_PTR)otm->otmpStyleName)); m_fullname = MakeUniqueFontName(m_fullname, localname, m_stylename); TCHAR buff[LF_FACESIZE+1]; GetFontLocalName(localname, buff); m_nFontFamily = otm->otmTextMetrics.tmPitchAndFamily & 0xF0; //获取字体家族,家族对应使用什么默认链接字体 m_familyname = (wstring)buff; m_set = pSettings->FindIndividual(m_familyname.c_str()); m_ftWeight = CalcBoldWeight(/*weight*/700); m_hash = StringHashFont(name); if (m_familyname.size()>0 && m_familyname.c_str()[0]==L'@') //附加一个@ m_fullname = L'@'+m_fullname; free(otm); } SelectFont(hdc, old); DeleteDC(hdc); //完成 // g_EngineCreateFont = false; face_id_link[0]=(FTC_FaceID)NULL; ggo_link[0] = NULL; //g_fsetcache.Set((FTC_FaceID)n, set); } ~FreeTypeFontInfo() { Erase(); DeleteFont(m_ggoFont); if (m_OS2Table) delete m_OS2Table; } HFONT GetGGOFont(){return m_ggoFont;}; int CalcNormalWeight() const { return m_set.GetNormalWeight(); } int CalcBoldWeight(int weight) const { // return weight - FW_NORMAL) / 8; // return ((weight - FW_NORMAL) / 12) + (m_set.GetBoldWeight() << 2); weight = weight < FW_BOLD ? 0: /*(weight > FW_BOLD ?*/ 612; if (weight <= FW_NORMAL) { return 0; } return ((weight - FW_NORMAL) / 8) + (m_set.GetBoldWeight() << 2); } int CalcBoldWeight(const LOGFONT& lf) const { return CalcBoldWeight(lf.lfWeight); } void CalcItalicSlant(FT_Matrix& matrix) const { matrix.xx = 1 << 16; // matrix.xy = 0x5800; matrix.xy = (5 + m_set.GetItalicSlant()) << 12; matrix.yx = 0; matrix.yy = 1 << 16; } bool Equals(const StringHashFont& hash, int weight, bool italic) const { weight = CalcBoldWeight(weight); return (m_ftWeight == weight && m_italic == italic && m_hash == hash); } void UpdateFontSetting() { m_ftWeight = CalcBoldWeight(700/*m_weight*/); //清除字体链接 face_id_link[0]=NULL; ggo_link[0]=NULL; m_linknum = 0; m_linkinited = false; m_SimSunID = 0; } int GetFTLink(FTC_FaceID** llplink) { CCriticalSectionLock __lock(CCriticalSectionLock::CS_FONTLINK); if (!*face_id_link) Createlink(); *llplink = face_id_link; return m_linknum; } int GetGGOLink(HFONT** llplink) { CCriticalSectionLock __lock(CCriticalSectionLock::CS_FONTLINK); if (!*ggo_link) Createlink(); *llplink = ggo_link; return m_linknum; } FTC_FaceID GetSimSunID() {return m_SimSunID;} INT_PTR GetId() const { return m_id; } LPCTSTR GetName() const { return m_hash.c_str(); } wstring GetStyleName() const { return m_stylename; } int GetFontWeight() const { return m_weight; } int GetExactBoldWeight() const {return m_set.GetBoldWeight(); } int GetFTWeight() const { return m_ftWeight; } bool IsItalic() const { return m_italic; } const StringHashFont& GetHash() const { return m_hash; } const CFontSettings& GetFontSettings() const { return m_set; } void SetFontSettings(const CFontSettings& set) { m_set = set;}; bool operator ==(const FreeTypeFontInfo& x) const { return (m_hash == x.m_hash); } FreeTypeFontCache* GetCache(FTC_ScalerRec& scaler, const LOGFONT& lf); bool EmbeddedBmpExist(int px); void Erase() { CCriticalSectionLock __lock(CCriticalSectionLock::CS_FONTCACHE); CacheArray::iterator it = m_cache.begin(); for (;it!=m_cache.end();++it) { delete it->second; } m_cache.clear(); } }; class FreeTypeFontEngine : public FreeTypeGCCounter { private: //typedef CArray FontListArray; typedef map FontMap; typedef map FullNameMap; typedef vector FontList; //FontListArray m_arrFontList; int m_nMaxFaces; int m_nMemUsed; bool m_bAddOnFind; FontMap m_mfontMap; FullNameMap m_mfullMap; FontList m_mfontList; FT_Face* m_arrFace; int m_nFaceCount; void Compact(); int GrowFace() { FT_Face* a=(FT_Face*)malloc(m_nFaceCount*sizeof(FT_Face)); memcpy(a, m_arrFace, sizeof(FT_Face)*m_nFaceCount); m_nFaceCount+=64; m_arrFace = (FT_Face*)realloc(m_arrFace, sizeof(FT_Face) * m_nFaceCount); memset(m_arrFace+m_nFaceCount-64, 0, sizeof(FT_Face)*64); for (int i=0;iCacheMaxFaces(); if (m_nMaxFaces == 0) m_nMaxFaces = FTC_MAX_FACES_DEFAULT; //m_arrFace = (FT_Face*)malloc(m_nFaceCount*sizeof(FT_Face)); //memset(m_arrFace, 0, sizeof(FT_Face)*m_nFaceCount); } ~FreeTypeFontEngine() { TRACE(_T("MaxFaces: %d\n"), m_mfontMap.size()); TRACE(_T("MemUsed : %d\n"), m_nMemUsed); //FontListArray& arr = m_arrFontList; FullNameMap::const_iterator iter=m_mfullMap.begin(); for (;iter!=m_mfullMap.end();++iter) iter->second->Release(); //free(m_arrFace); } int CalcBoldWeight(int weight) const { return weight < FW_BOLD ? 0: FW_BOLD; } FreeTypeFontInfo* AddFont(LPCTSTR lpFaceName, int weight, bool italic, BOOL* bIsFontLoaded = NULL); FreeTypeFontInfo* AddFont(void* lpparams); int GetFontIdByName(LPCTSTR lpFaceName, int weight, bool italic); // LPCTSTR GetFontById(int faceid, int& weight, bool& italic); FreeTypeFontInfo* FindFont(LPCTSTR lpFaceName, int weight, bool italic, bool AddOnFind = true, BOOL* bIsFontLoaded=NULL); FreeTypeFontInfo* FindFont(int faceid); FreeTypeFontInfo* FindFont(void* lpparams); bool FontExists(LPCTSTR lpFaceName, int weight, bool italic) { return !!FindFont(lpFaceName, weight, italic); } BOOL RemoveFont(LPCWSTR FontName); BOOL RemoveFont(FreeTypeFontInfo* fontinfo); BOOL RemoveThisFont(FreeTypeFontInfo* fontinfo, LOGFONT* lg); //メモリ使用量カウンタ void AddMemUsed(int x) { m_nMemUsed += x; } void SubMemUsed(int x) { m_nMemUsed -= x; if (m_nMemUsed < 0) m_nMemUsed = 0; } template void AddMemUsedObj(T* /*p*/) { AddMemUsed(sizeof(T)); } template void SubMemUsedObj(T* /*p*/) { SubMemUsed(sizeof(T)); } void ReloadAll() { //重新载入全部字体,即清空所有字体缓存 COwnedCriticalSectionLock __olock(2); CCriticalSectionLock __lock; CGdippSettings* pSettings = CGdippSettings::GetInstance(); FullNameMap::const_iterator iter=m_mfullMap.begin(); for (;iter!=m_mfullMap.end();) { FreeTypeFontInfo* p =iter->second; if (p) { /* if (p->GetFullName()!=iter->first) //是替换字体 { p->Release(); //释放掉多重引用 m_mfullMap.erase(iter++); continue; }*/ p->Erase(); p->SetFontSettings(pSettings->FindIndividual(p->GetName())); p->UpdateFontSetting(); } ++iter; } //m_mfontMap.clear(); } }; //GetFontDataのメモリストリーム class FreeTypeSysFontData { private: HDC m_hdc; HFONT m_hOldFont; bool m_isTTC; bool m_locked; void* m_pMapping; DWORD m_dwSize; FT_Face m_ftFace; wstring m_name; FT_StreamRec m_ftStream; FreeTypeSysFontData() : m_hdc(NULL) , m_hOldFont(NULL) , m_isTTC(false) , m_locked(false) , m_pMapping(NULL) , m_dwSize(0) , m_ftFace(NULL) { ZeroMemory(&m_ftStream, sizeof(FT_StreamRec)); } static unsigned long IoFunc(FT_Stream stream, unsigned long offset, unsigned char* buffer, unsigned long count); static void CloseFunc(FT_Stream stream); bool OpenFaceByIndex(int index); bool Init(LPCTSTR name, int weight, bool italic); public: static FreeTypeSysFontData* CreateInstance(LPCTSTR name, int weight, bool italic); ~FreeTypeSysFontData() { if (m_pMapping) { UnmapViewOfFile(m_pMapping); } if (m_hOldFont) { DeleteFont(SelectFont(m_hdc, m_hOldFont)); } if (m_hdc) { DeleteDC(m_hdc); } } FT_Face GetFace() { FT_Face face = m_ftFace; m_ftFace = NULL; return face; } }; ================================================ FILE: ftref.c ================================================ #include "ftref.h" #define InterlockedIncrementInt(x) InterlockedIncrement((volatile LONG *)&(x)) #define InterlockedDecrementInt(x) InterlockedDecrement((volatile LONG *)&(x)) #define InterlockedExchangeInt(x, y) InterlockedExchange((volatile LONG *)&(x), LONG(y)) FT_Error FT_Glyph_Ref_Copy( FT_Referenced_Glyph source, FT_Referenced_Glyph *target ) { if (source->refcount<0) return 1; if (source->ft_glyph->format == FT_GLYPH_FORMAT_NONE) return 2; InterlockedIncrementInt(source->refcount); *target = source; return 0; } void FT_Done_Ref_Glyph( FT_Referenced_Glyph *glyph ) { if (InterlockedDecrementInt((*glyph)->refcount) == 0) { if ((*glyph)->ft_glyph && (*glyph)->ft_glyph->library) FT_Done_Glyph((*glyph)->ft_glyph); free(*glyph); } *glyph = NULL; } void FT_Glyph_To_Ref_Glyph( FT_Glyph source, FT_Referenced_Glyph *target) { *target = (FT_Referenced_Glyph)malloc(sizeof(FT_Referenced_GlyphRec)); (*target)->ft_glyph = source; (*target)->refcount = 1; } FT_Referenced_Glyph New_FT_Ref_Glyph() { FT_Referenced_Glyph copy = (FT_Referenced_Glyph)malloc(sizeof(FT_Referenced_GlyphRec)); copy->ft_glyph = NULL; copy->refcount = 1; return copy; } ================================================ FILE: ftref.h ================================================ #include #include #ifdef __cplusplus extern "C"{ #endif typedef struct { FT_Glyph ft_glyph; int refcount; }FT_Referenced_GlyphRec, *FT_Referenced_Glyph; typedef struct { FT_BitmapGlyph ft_glyph; int refcount; }FT_Referenced_BitmapGlyphRec, *FT_Referenced_BitmapGlyph; FT_Error FT_Glyph_Ref_Copy( FT_Referenced_Glyph source, FT_Referenced_Glyph *target ); void FT_Done_Ref_Glyph( FT_Referenced_Glyph *glyph ); void FT_Glyph_To_Ref_Glyph( FT_Glyph source, FT_Referenced_Glyph *target); FT_Referenced_Glyph New_FT_Ref_Glyph(); #ifdef __cplusplus } #endif ================================================ FILE: gdiPlusFlat2.cpp ================================================ #include "gdiPlusFlat2.h" #include GdipDrawString pfnGdipDrawString = NULL; GdipGetBrushType pfnGdipGetBrushType = NULL; GdipGetDC pfnGdipGetDC = NULL; GdipGetLogFontW pfnGdipGetLogFontW = NULL; GdipGetSolidFillColor pfnGdipGetSolidFillColor = NULL; GdipGetStringFormatAlign pfnGdipGetStringFormatAlign = NULL; GdipGetStringFormatHotkeyPrefix pfnGdipGetStringFormatHotkeyPrefix = NULL; GdipGetStringFormatTrimming pfnGdipGetStringFormatTrimming = NULL; GdipReleaseDC pfnGdipReleaseDC = NULL; bool InitGdiplusFuncs(){ static bool bInited = false; if (!bInited) { bInited = true; HMODULE hGdiplusDll = GetModuleHandle(_T("Gdiplus.dll")); if (hGdiplusDll) { pfnGdipDrawString = (GdipDrawString)GetProcAddress(hGdiplusDll, "GdipDrawString"); pfnGdipGetBrushType = (GdipGetBrushType)GetProcAddress(hGdiplusDll, "GdipGetBrushType"); pfnGdipGetDC = (GdipGetDC)GetProcAddress(hGdiplusDll, "GdipGetDC"); pfnGdipGetLogFontW = (GdipGetLogFontW)GetProcAddress(hGdiplusDll, "GdipGetLogFontW"); pfnGdipGetSolidFillColor = (GdipGetSolidFillColor)GetProcAddress(hGdiplusDll, "GdipGetSolidFillColor"); pfnGdipGetStringFormatAlign = (GdipGetStringFormatAlign)GetProcAddress(hGdiplusDll, "GdipGetStringFormatAlign"); pfnGdipGetStringFormatHotkeyPrefix = (GdipGetStringFormatHotkeyPrefix)GetProcAddress(hGdiplusDll, "GdipGetStringFormatHotkeyPrefix"); pfnGdipGetStringFormatTrimming = (GdipGetStringFormatTrimming)GetProcAddress(hGdiplusDll, "GdipGetStringFormatTrimming"); pfnGdipReleaseDC = (GdipReleaseDC)GetProcAddress(hGdiplusDll, "GdipReleaseDC"); return true; } else return false; } else return true; } ================================================ FILE: gdiPlusFlat2.h ================================================ #ifndef _GDIPLUSFLAT_H #define _GDIPLUSFLAT_H #include #include "GdiPlusTypes2.h" #include #include #include #define GDIPCONST const #define WINGDIPAPI __stdcall typedef Status GpStatus; typedef GpStatus (WINGDIPAPI* GdipDrawString)( GpGraphics *graphics, GDIPCONST WCHAR *string, INT length, GDIPCONST GpFont *font, GDIPCONST RectF *layoutRect, GDIPCONST GpStringFormat *stringFormat, GDIPCONST GpBrush *brush );//绘制文字的函数 typedef GpStatus (WINGDIPAPI* GdipGetLogFontW)(GpFont * font, GpGraphics *graphics, LOGFONTW * logfontW);//从GPFont获取Logfont typedef GpStatus (WINGDIPAPI* GdipGetDC)(GpGraphics* graphics, HDC * hdc); //从GPGraphic获取HDC typedef GpStatus (WINGDIPAPI* GdipReleaseDC)(GpGraphics* graphics, HDC hdc); typedef GpStatus (WINGDIPAPI* GdipGetStringFormatAlign)(GDIPCONST GpStringFormat *format, StringAlignment *align); typedef GpStatus (WINGDIPAPI* GdipGetStringFormatTrimming)( GDIPCONST GpStringFormat *format, StringTrimming *trimming ); //获取字符串的缩略方式。当字符串长度超过矩形长度时,将使用设置的方式删除中间的部分文字。 //转换成GDI后应使用DrawText来模拟。 typedef GpStatus (WINGDIPAPI* GdipGetStringFormatHotkeyPrefix)(GDIPCONST GpStringFormat *format, INT *hotkeyPrefix); //获取&符号的显示方式,隐藏,显示下划线或者不处理&。由DrawText模拟。 typedef GpStatus (WINGDIPAPI* GdipGetBrushType)(GpBrush *brush, GpBrushType *type); typedef GpStatus (WINGDIPAPI* GdipGetSolidFillColor)(GpSolidFill *brush, ARGB *color); //获取单色Brush的颜色 extern GdipDrawString pfnGdipDrawString ; extern GdipGetBrushType pfnGdipGetBrushType ; extern GdipGetDC pfnGdipGetDC ; extern GdipGetLogFontW pfnGdipGetLogFontW ; extern GdipGetSolidFillColor pfnGdipGetSolidFillColor ; extern GdipGetStringFormatAlign pfnGdipGetStringFormatAlign ; extern GdipGetStringFormatHotkeyPrefix pfnGdipGetStringFormatHotkeyPrefix ; extern GdipGetStringFormatTrimming pfnGdipGetStringFormatTrimming ; extern GdipReleaseDC pfnGdipReleaseDC ; bool InitGdiplusFuncs(); #endif ================================================ FILE: gdidll.rc ================================================ // Microsoft Visual C++ generated resource script. // #pragma code_page(65001) #include "resource." #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 2 resource. // #include "afxres.h" ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // Neutral (Sys. Default) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NEUSD) LANGUAGE LANG_NEUTRAL, SUBLANG_SYS_DEFAULT ///////////////////////////////////////////////////////////////////////////// // // Version // VS_VERSION_INFO VERSIONINFO FILEVERSION 1,2025,409,1 PRODUCTVERSION 1,2025,409,1 FILEFLAGSMASK 0x8L #ifdef _DEBUG FILEFLAGS 0xbL #else FILEFLAGS 0xaL #endif FILEOS 0x40004L FILETYPE 0x2L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "000004b0" BEGIN VALUE "Comments", "Portions of this software are copyright (c) 2005-2021 The FreeType Project (www.freetype.org). All rights reserved." VALUE "CompanyName", "2ch & THEMEX & everyone" VALUE "FileDescription", "The Ultimate Font Rasterizer" VALUE "FileVersion", "1.2025.409.1" VALUE "InternalName", "MacType" VALUE "LegalCopyright", "(C) 460, 168, Higambana, 555 and sy567. All rights reserved. FlyingSnow republished" VALUE "OriginalFilename", "MacType.dll" VALUE "ProductName", "The Ultimate Font Rasterizer" VALUE "ProductVersion", "1.2025.409.1" VALUE "URL", "http://www.mactype.net http://drwatson.nobody.jp/gdi++/" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x0, 1200 END END #endif // Neutral (Sys. Default) resources ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // Chinese (Simplified, China) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_CHS) LANGUAGE LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED #ifdef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // TEXTINCLUDE // 1 TEXTINCLUDE BEGIN "resource.\0" END 3 TEXTINCLUDE BEGIN "\r\0" END 2 TEXTINCLUDE BEGIN "#include ""afxres.h""\r\0" END #endif // APSTUDIO_INVOKED #endif // Chinese (Simplified, China) resources ///////////////////////////////////////////////////////////////////////////// #ifndef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 3 resource. // ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED ================================================ FILE: gdipp.icproj ================================================ ================================================ FILE: gdipp.sln ================================================ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.4.33103.184 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MacType", "gdipp.vcxproj", "{15C33FD9-0811-4981-B08F-E0BAD74A3028}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "macloader", "macloader.vcxproj", "{6D6AC860-BA16-4BE7-9169-21787F21CB6F}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug Infinality|Win32 = Debug Infinality|Win32 Debug Infinality|x64 = Debug Infinality|x64 Debug|Win32 = Debug|Win32 Debug|x64 = Debug|x64 Rel+Detours|Win32 = Rel+Detours|Win32 Rel+Detours|x64 = Rel+Detours|x64 Rel+Trace|Win32 = Rel+Trace|Win32 Rel+Trace|x64 = Rel+Trace|x64 Release Infinality|Win32 = Release Infinality|Win32 Release Infinality|x64 = Release Infinality|x64 Release|Win32 = Release|Win32 Release|x64 = Release|x64 Release+StaticHook|Win32 = Release+StaticHook|Win32 Release+StaticHook|x64 = Release+StaticHook|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Debug Infinality|Win32.ActiveCfg = Debug Infinality|Win32 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Debug Infinality|Win32.Build.0 = Debug Infinality|Win32 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Debug Infinality|x64.ActiveCfg = Debug Infinality|x64 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Debug Infinality|x64.Build.0 = Debug Infinality|x64 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Debug|Win32.ActiveCfg = Debug|Win32 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Debug|Win32.Build.0 = Debug|Win32 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Debug|x64.ActiveCfg = Debug|x64 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Debug|x64.Build.0 = Debug|x64 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Rel+Detours|Win32.ActiveCfg = Rel+Detours|Win32 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Rel+Detours|Win32.Build.0 = Rel+Detours|Win32 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Rel+Detours|x64.ActiveCfg = Rel+Detours|x64 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Rel+Detours|x64.Build.0 = Rel+Detours|x64 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Rel+Trace|Win32.ActiveCfg = Rel+Trace|Win32 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Rel+Trace|Win32.Build.0 = Rel+Trace|Win32 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Rel+Trace|x64.ActiveCfg = Rel+Trace|x64 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Rel+Trace|x64.Build.0 = Rel+Trace|x64 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Release Infinality|Win32.ActiveCfg = Release Infinality|Win32 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Release Infinality|Win32.Build.0 = Release Infinality|Win32 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Release Infinality|x64.ActiveCfg = Release Infinality|x64 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Release Infinality|x64.Build.0 = Release Infinality|x64 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Release|Win32.ActiveCfg = Release|Win32 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Release|Win32.Build.0 = Release|Win32 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Release|x64.ActiveCfg = Release|x64 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Release|x64.Build.0 = Release|x64 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Release+StaticHook|Win32.ActiveCfg = Release+StaticHook|Win32 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Release+StaticHook|Win32.Build.0 = Release+StaticHook|Win32 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Release+StaticHook|x64.ActiveCfg = Release+StaticHook|x64 {15C33FD9-0811-4981-B08F-E0BAD74A3028}.Release+StaticHook|x64.Build.0 = Release+StaticHook|x64 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Debug Infinality|Win32.ActiveCfg = Debug|Win32 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Debug Infinality|Win32.Build.0 = Debug|Win32 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Debug Infinality|x64.ActiveCfg = Debug|x64 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Debug Infinality|x64.Build.0 = Debug|x64 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Debug|Win32.ActiveCfg = Debug|Win32 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Debug|Win32.Build.0 = Debug|Win32 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Debug|x64.ActiveCfg = Debug|x64 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Debug|x64.Build.0 = Debug|x64 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Rel+Detours|Win32.ActiveCfg = Release|Win32 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Rel+Detours|Win32.Build.0 = Release|Win32 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Rel+Detours|x64.ActiveCfg = Release|x64 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Rel+Detours|x64.Build.0 = Release|x64 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Rel+Trace|Win32.ActiveCfg = Release|Win32 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Rel+Trace|Win32.Build.0 = Release|Win32 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Rel+Trace|x64.ActiveCfg = Release|x64 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Rel+Trace|x64.Build.0 = Release|x64 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Release Infinality|Win32.ActiveCfg = Release|Win32 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Release Infinality|Win32.Build.0 = Release|Win32 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Release Infinality|x64.ActiveCfg = Release|x64 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Release Infinality|x64.Build.0 = Release|x64 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Release|Win32.ActiveCfg = Release|Win32 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Release|Win32.Build.0 = Release|Win32 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Release|x64.ActiveCfg = Release|x64 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Release|x64.Build.0 = Release|x64 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Release+StaticHook|Win32.ActiveCfg = Release|Win32 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Release+StaticHook|Win32.Build.0 = Release|Win32 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Release+StaticHook|x64.ActiveCfg = Release|x64 {6D6AC860-BA16-4BE7-9169-21787F21CB6F}.Release+StaticHook|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {3F209D78-C531-4FA9-941E-68BEF65161FD} EndGlobalSection EndGlobal ================================================ FILE: gdipp.vcxproj ================================================ Debug Infinality Win32 Debug Infinality x64 Debug Win32 Debug x64 EXE Win32 EXE x64 Rel+Detours Win32 Rel+Detours x64 Rel+Trace Win32 Rel+Trace x64 Release Infinality Win32 Release Infinality x64 Release+StaticHook Win32 Release+StaticHook x64 Release Win32 Release x64 MacType {15C33FD9-0811-4981-B08F-E0BAD74A3028} gdipp Win32Proj 10.0 Application Unicode true v143 DynamicLibrary Unicode true v143 DynamicLibrary Unicode true v143 DynamicLibrary Unicode true v143 DynamicLibrary v143 Unicode true DynamicLibrary v143 Unicode DynamicLibrary v143 Unicode DynamicLibrary v143 Unicode true DynamicLibrary v143 Unicode true DynamicLibrary v143 Unicode true DynamicLibrary v143 Unicode true DynamicLibrary v143 Unicode true DynamicLibrary v143 Unicode DynamicLibrary v143 Unicode v143 v143 <_ProjectFileVersion>12.0.21005.1 $(SolutionDir)$(Configuration)\ $(Configuration)\ true false $(ProjectName).Core $(INI_PARSER_PATH);$(FREETYPE_PATH)\include;$(IncludePath) $(SolutionDir)lib;$(LibraryPath) $(SolutionDir)$(Configuration)\ $(Configuration)\ true false $(ProjectName).Core $(INI_PARSER_PATH);$(FREETYPE_PATH)\include;$(IncludePath) $(SolutionDir)lib;$(LibraryPath) $(SolutionDir)$(Platform)\$(Configuration)\ $(Platform)\$(Configuration)\ true false $(ProjectName)64.Core $(INI_PARSER_PATH);$(FREETYPE_PATH)\include;$(IncludePath) $(SolutionDir)lib;$(LibraryPath) $(SolutionDir)$(Platform)\$(Configuration)\ $(Platform)\$(Configuration)\ true false $(ProjectName)64.Core $(INI_PARSER_PATH);$(FREETYPE_PATH)\include;$(IncludePath) $(SolutionDir)lib;$(LibraryPath) $(SolutionDir)$(Configuration)\ $(Configuration)\ false false $(ProjectName).Core $(INI_PARSER_PATH);$(FREETYPE_PATH)\include;$(IncludePath) $(SolutionDir)lib;$(LibraryPath) $(SolutionDir)$(Configuration)\ $(Configuration)\ false false $(ProjectName).Core $(INI_PARSER_PATH);$(FREETYPE_PATH)\include;$(IncludePath) $(SolutionDir)lib;$(LibraryPath) $(SolutionDir)$(Configuration)\ $(Configuration)\ false false $(ProjectName).Core $(INI_PARSER_PATH);$(FREETYPE_PATH)\include;$(IncludePath) $(SolutionDir)lib;$(LibraryPath) $(SolutionDir)$(Configuration)\ $(Configuration)\ false false $(ProjectName).Core $(INI_PARSER_PATH);$(FREETYPE_PATH)\include;$(IncludePath) $(SolutionDir)lib;$(LibraryPath) $(SolutionDir)$(Configuration)\ $(Configuration)\ false false $(ProjectName).Core $(INI_PARSER_PATH);$(FREETYPE_PATH)\include;$(IncludePath) $(SolutionDir)lib;$(LibraryPath) $(SolutionDir)$(Platform)\$(Configuration)\ $(Platform)\$(Configuration)\ false false $(ProjectName)64.Core $(INI_PARSER_PATH);$(FREETYPE_PATH)\include;$(IncludePath) $(SolutionDir)lib;$(LibraryPath) $(SolutionDir)$(Platform)\$(Configuration)\ $(Platform)\$(Configuration)\ false false $(ProjectName)64.Core $(INI_PARSER_PATH);$(FREETYPE_PATH)\include;$(IncludePath) $(SolutionDir)lib;$(LibraryPath) $(SolutionDir)$(Platform)\$(Configuration)\ $(Platform)\$(Configuration)\ false false $(ProjectName)64.Core $(INI_PARSER_PATH);$(FREETYPE_PATH)\include;$(IncludePath) $(SolutionDir)lib;$(LibraryPath) $(SolutionDir)$(Platform)\$(Configuration)\ $(Platform)\$(Configuration)\ false false $(ProjectName)64.Core $(INI_PARSER_PATH);$(FREETYPE_PATH)\include;$(IncludePath) $(SolutionDir)lib;$(LibraryPath) $(SolutionDir)$(Platform)\$(Configuration)\ $(Platform)\$(Configuration)\ false false $(ProjectName)64.Core $(INI_PARSER_PATH);$(FREETYPE_PATH)\include;$(IncludePath) $(SolutionDir)lib;$(LibraryPath) Disabled Neither false false STATIC_LIB;EASYHOOK;WIN32;_DEBUG;_WINDOWS;_USRDLL;GDIPP_EXPORTS;_GDIPP_DLL;EASYHOOK;%(PreprocessorDefinitions) true EnableFastChecks MultiThreadedDebug Level3 EditAndContinue /utf-8 %(AdditionalOptions) freetype.lib;usp10.lib;%(AdditionalDependencies) LIBCMT;%(IgnoreSpecificDefaultLibraries) expfunc.def true Windows true MachineX86 /DEBUG easyhk32.dll false Disabled Neither false false WIN32;_DEBUG;_WINDOWS;_USRDLL;GDIPP_EXPORTS;_GDIPP_DLL;INFINALITY;%(PreprocessorDefinitions) true EnableFastChecks MultiThreadedDebug Level3 EditAndContinue /utf-8 %(AdditionalOptions) freetype_inf.lib;usp10.lib;%(AdditionalDependencies) LIBCMT;%(IgnoreSpecificDefaultLibraries) expfunc.def true Windows true MachineX86 /DEBUG easyhook32.dll X64 Disabled Neither false false STATIC_LIB;WIN32;_DEBUG;_WINDOWS;_USRDLL;GDIPP_EXPORTS;_GDIPP_DLL;EASYHOOK;%(PreprocessorDefinitions) true EnableFastChecks MultiThreadedDebug Level3 ProgramDatabase /utf-8 %(AdditionalOptions) freetype64.lib;usp10.lib;%(AdditionalDependencies) LIBCMT;%(IgnoreSpecificDefaultLibraries) expfunc.def true Windows true MachineX64 /DEBUG %(AdditionalOptions) easyhook64.dll X64 Disabled Neither false false WIN32;_DEBUG;_WINDOWS;_USRDLL;GDIPP_EXPORTS;_GDIPP_DLL;%(PreprocessorDefinitions) true EnableFastChecks MultiThreadedDebug Level3 ProgramDatabase /utf-8 %(AdditionalOptions) freetype64.lib;usp10.lib;%(AdditionalDependencies) LIBCMT;%(IgnoreSpecificDefaultLibraries) expfunc.def true Windows true MachineX64 /DEBUG %(AdditionalOptions) easyhook64.dll MaxSpeed true Speed false WIN32;NDEBUG;_WINDOWS;_USRDLL;GDIPP_EXPORTS;_GDIPP_EXE;EASYHOOK;%(PreprocessorDefinitions) Sync MultiThreaded false false StreamingSIMDExtensions2 Precise Level3 ProgramDatabase $(SolutionDir)deps\include;%(AdditionalIncludeDirectories) /Zc:threadSafeInit- /utf-8 %(AdditionalOptions) freetype.lib;usp10.lib;dwrite.lib;%(AdditionalDependencies) false expfunc.def true Windows true true true true MachineX86 easyhk32.dll $(SolutionDir)deps\lib;%(AdditionalLibraryDirectories) UseLinkTimeCodeGeneration MaxSpeed true Speed false WIN32;NDEBUG;_WINDOWS;_USRDLL;GDIPP_EXPORTS;_GDIPP_DLL;USE_DETOURS;%(PreprocessorDefinitions) Sync MultiThreaded false false StreamingSIMDExtensions2 Precise Level3 ProgramDatabase $(SolutionDir)deps\include;%(AdditionalIncludeDirectories) /Zc:threadSafeInit- /utf-8 %(AdditionalOptions) freetype.lib;usp10.lib;dwrite.lib;%(AdditionalDependencies) false expfunc.def true Windows true true true MachineX86 $(SolutionDir)deps\lib;%(AdditionalLibraryDirectories) UseLinkTimeCodeGeneration MaxSpeed true Speed false STATIC_LIB;EASYHOOK;WIN32;NDEBUG;_WINDOWS;_USRDLL;GDIPP_EXPORTS;_GDIPP_DLL;%(PreprocessorDefinitions) Sync MultiThreaded false false StreamingSIMDExtensions2 Precise Level3 ProgramDatabase $(SolutionDir)deps\include;%(AdditionalIncludeDirectories) /Zc:threadSafeInit- /utf-8 %(AdditionalOptions) freetype.lib;usp10.lib;dwrite.lib;%(AdditionalDependencies) false expfunc.def true Windows true true true MachineX86 $(SolutionDir)deps\lib;%(AdditionalLibraryDirectories) UseLinkTimeCodeGeneration MaxSpeed true Speed false WIN32;NDEBUG;_WINDOWS;_USRDLL;GDIPP_EXPORTS;_GDIPP_DLL;%(PreprocessorDefinitions) Sync MultiThreaded false false StreamingSIMDExtensions2 Precise Level3 ProgramDatabase $(SolutionDir)deps\include;%(AdditionalIncludeDirectories) /Zc:threadSafeInit- /utf-8 %(AdditionalOptions) freetype.lib;usp10.lib;dwrite.lib;%(AdditionalDependencies) false expfunc.def true Windows true true true true MachineX86 easyhk32.dll $(SolutionDir)deps\lib;%(AdditionalLibraryDirectories) UseLinkTimeCodeGeneration MaxSpeed true Speed false WIN32;NDEBUG;_WINDOWS;_USRDLL;GDIPP_EXPORTS;_GDIPP_DLL;INFINALITY;%(PreprocessorDefinitions) Sync MultiThreaded false false StreamingSIMDExtensions2 Precise Level3 ProgramDatabase /utf-8 %(AdditionalOptions) freetype_inf.lib;usp10.lib;dwrite.lib;%(AdditionalDependencies) false expfunc.def true Windows true true true true MachineX86 easyhook32.dll X64 MaxSpeed true Speed NDEBUG;_WINDOWS;_USRDLL;GDIPP_EXPORTS;_GDIPP_DLL;EASYHOOK;%(PreprocessorDefinitions) Sync MultiThreaded false true StreamingSIMDExtensions2 Level3 ProgramDatabase $(SolutionDir)deps\include;%(AdditionalIncludeDirectories) /utf-8 %(AdditionalOptions) freetype64.lib;usp10.lib;%(AdditionalDependencies) false expfunc.def true Windows true true true true MachineX64 easyhk64.dll $(SolutionDir)deps\lib;%(AdditionalLibraryDirectories) true X64 MaxSpeed true Speed NDEBUG;_WINDOWS;_USRDLL;GDIPP_EXPORTS;_GDIPP_DLL;USE_DETOURS;%(PreprocessorDefinitions) Sync MultiThreaded false true StreamingSIMDExtensions2 Level3 ProgramDatabase $(SolutionDir)deps\include;%(AdditionalIncludeDirectories) /utf-8 %(AdditionalOptions) freetype64.lib;usp10.lib;%(AdditionalDependencies) false expfunc.def true Windows true true true MachineX64 $(SolutionDir)deps\lib;%(AdditionalLibraryDirectories) true X64 MaxSpeed true Speed STATIC_LIB;EASYHOOK;NDEBUG;_WINDOWS;_USRDLL;GDIPP_EXPORTS;_GDIPP_DLL;%(PreprocessorDefinitions) Sync MultiThreaded false true StreamingSIMDExtensions2 Level3 ProgramDatabase $(SolutionDir)deps\include;%(AdditionalIncludeDirectories) /utf-8 %(AdditionalOptions) freetype64.lib;usp10.lib;%(AdditionalDependencies) false expfunc.def true Windows true true true MachineX64 $(SolutionDir)deps\lib;%(AdditionalLibraryDirectories) true X64 MaxSpeed true Speed NDEBUG;_WINDOWS;_USRDLL;GDIPP_EXPORTS;_GDIPP_DLL;TRACE;%(PreprocessorDefinitions) Sync MultiThreaded false true StreamingSIMDExtensions2 Level3 ProgramDatabase $(SolutionDir)deps\include;%(AdditionalIncludeDirectories) /utf-8 %(AdditionalOptions) freetype64.lib;usp10.lib;%(AdditionalDependencies) false expfunc.def true Windows true true true true MachineX64 easyhk64.dll $(SolutionDir)deps\lib;%(AdditionalLibraryDirectories) true X64 MaxSpeed true Speed NDEBUG;_WINDOWS;_USRDLL;GDIPP_EXPORTS;_GDIPP_DLL;INFINALITY;%(PreprocessorDefinitions) Sync MultiThreaded false true StreamingSIMDExtensions2 Level3 ProgramDatabase /utf-8 %(AdditionalOptions) freetype64_inf.lib;usp10.lib;%(AdditionalDependencies) false expfunc.def true Windows true true true true MachineX64 easyhook64.dll Sync Sync Sync Sync Sync ================================================ FILE: gdipp.vcxproj.filters ================================================ {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Resource Files ================================================ FILE: hash_list.cpp ================================================ #include "hash_list.h" #include #include void CHashedStringList::Add(TCHAR * String, TCHAR * Value) { std::wstring buff = String; if (!m_bCaseSense) std::transform(buff.begin(), buff.end(), buff.begin(), ::towlower); strmap::iterator it = stringmap.find(buff); if (it == stringmap.end()) { stringmap[buff] = _wcsdup(Value); } } void CHashedStringList::Delete(TCHAR * String) { std::wstring buff = String; if (!m_bCaseSense) std::transform(buff.begin(), buff.end(), buff.begin(), ::towlower); stringmap.erase(buff); } TCHAR * CHashedStringList::Find(TCHAR * String) { TCHAR* b = _wcsdup(String); if (!m_bCaseSense) b = _wcslwr(b); std::wstring buff = b; free(b); strmap::iterator it = stringmap.find(buff); if (it != stringmap.end()) return it->second; else return NULL; } ================================================ FILE: hash_list.h ================================================ //#include "stdint.h" #include "malloc.h" #include "string.h" #include "windows.h" #include #include typedef std::map strmap; class CHashedStringList { public: void Add(TCHAR * String, TCHAR * Value); void Delete(TCHAR * String); TCHAR * Find(TCHAR * String); CHashedStringList() : m_bCaseSense(false){} CHashedStringList(BOOL bCaseSensative) : m_bCaseSense(bCaseSensative){} ~CHashedStringList(){ strmap::iterator it = stringmap.begin(); while (it != stringmap.end()) { free(it->second); ++it; } } protected: private: strmap stringmap; BOOL m_bCaseSense; }; ================================================ FILE: hook.cpp ================================================ // API hook // // GetProcAddressで得たcall先(関数本体)を直接書き換え、 // 自分のフック関数にjmpさせる。 // // 内部で元のAPIを使う時は、コードを一度戻してからcall。 // すぐにjmpコードに戻す。 // // マルチスレッドで 書き換え中にcallされると困るので、 // CriticalSectionで排他制御しておく。 // #include "override.h" #include "ft.h" #include "fteng.h" #include #include "undocAPI.h" #include "delayimp.h" #include #include #include #include "EventLogging.h" #include "hookCounter.h" #ifdef STATIC_LIB #include #include #pragma comment(lib, "aux_ulib.lib") #pragma comment(lib, "psapi.lib") #endif #ifndef _WIN64 #include "wow64ext.h" #endif #ifdef INFINALITY #include #endif #pragma comment(lib, "delayimp") HINSTANCE g_dllInstance; //PFNLdrGetProcedureAddress LdrGetProcedureAddress = (PFNLdrGetProcedureAddress)GetProcAddress(LoadLibrary(_T("ntdll.dll")),"LdrGetProcedureAddress"); //PFNCreateProcessW nCreateProcessW = (PFNCreateProcessW)MyGetProcAddress(LoadLibrary(_T("kernel32.dll")),"CreateProcessW"); //PFNCreateProcessA nCreateProcessA = (PFNCreateProcessA)MyGetProcAddress(LoadLibrary(_T("kernel32.dll")),"CreateProcessA"); // HMODULE hGDIPP = GetModuleHandleW(L"gdiplus.dll"); // typedef int (WINAPI *PFNGdipCreateFontFamilyFromName)(const WCHAR *name, void *fontCollection, void **FontFamily); // PFNGdipCreateFontFamilyFromName GdipCreateFontFamilyFromName = hGDIPP? (PFNGdipCreateFontFamilyFromName)GetProcAddress(hGDIPP, "GdipCreateFontFamilyFromName"):0; #ifdef USE_DETOURS #include "detours.h" #ifdef _M_IX86 #pragma comment (lib, "detours.lib") #else #pragma comment (lib, "detours64.lib") #endif // DATA_foo、ORIG_foo の2つをまとめて定義するマクロ #define HOOK_MANUALLY HOOK_DEFINE #define HOOK_DEFINE(rettype, name, argtype, arglist) \ rettype (WINAPI * ORIG_##name) argtype; \ BOOL IsHooked_##name = false; \ rettype WINAPI REF_##name argtype { \ HCounter _; \ return IMPL_##name arglist; \ } #include "hooklist.h" #undef HOOK_DEFINE #undef HOOK_MANUALLY // #define HOOK_MANUALLY(rettype, name, argtype, arglist) ; #define HOOK_DEFINE(rettype, name, argtype, arglist) \ ORIG_##name = name; #pragma optimize("s", on) static void hook_initinternal() { #include "hooklist.h" } #pragma optimize("", on) #undef HOOK_DEFINE #undef HOOK_MANUALLY #define HOOK_MANUALLY(rettype, name, argtype, arglist) ; #define HOOK_DEFINE(rettype, name, argtype, arglist) \ if (&ORIG_##name && !IsHooked_##name) { \ if (DetourAttach(&(PVOID&)ORIG_##name, REF_##name) == NOERROR) IsHooked_##name = true; \ } static LONG hook_init() { DetourRestoreAfterWith(); DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); #include "hooklist.h" LONG error = DetourTransactionCommit(); if (error != NOERROR) { TRACE(_T("hook_init error: %#x\n"), error); } return error; } #undef HOOK_DEFINE #undef HOOK_MANUALLY #define HOOK_DEFINE(rettype, name, argtype, arglist); #define HOOK_MANUALLY(rettype, name, argtype, arglist) \ LONG hook_demand_##name(bool bForce = false){ \ DetourRestoreAfterWith(); \ DetourTransactionBegin(); \ DetourUpdateThread(GetCurrentThread()); \ if (&ORIG_##name && (bForce || !IsHooked_##name)) { DetourAttach(&(PVOID&)ORIG_##name, REF_##name); IsHooked_##name = true; } \ LONG error = DetourTransactionCommit(); \ if (error != NOERROR) { \ TRACE(_T("hook_init error: %#x\n"), error); \ } \ return error; \ } #include "hooklist.h" #undef HOOK_MANUALLY #undef HOOK_DEFINE // #define HOOK_MANUALLY HOOK_DEFINE #define HOOK_DEFINE(rettype, name, argtype, arglist) \ if (IsHooked_##name) DetourDetach(&(PVOID&)ORIG_##name, REF_##name); \ IsHooked_##name = false; static void hook_term() { DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); #include "hooklist.h" LONG error = DetourTransactionCommit(); if (error != NOERROR) { TRACE(_T("hook_term error: %#x\n"), error); } HCounter::wait(3000); } #undef HOOK_DEFINE #undef HOOK_MANUALLY #else #include "easyhook.h" #ifdef STATIC_LIB #ifdef _M_IX86 #pragma comment (lib, "easyhk32_s.lib") #else #pragma comment (lib, "easyhk64_s.lib") #endif #else #ifdef _M_IX86 #pragma comment (lib, "easyhk32.lib") #else #pragma comment (lib, "easyhk64.lib") #endif #endif #define HOOK_MANUALLY HOOK_DEFINE #define HOOK_DEFINE(rettype, name, argtype, arglist) \ rettype (WINAPI * ORIG_##name) argtype; \ HOOK_TRACE_INFO HOOK_##name = {0}; //建立hook结构 #include "hooklist.h" #undef HOOK_DEFINE #undef HOOK_MANUALLY // #define HOOK_MANUALLY(rettype, name, argtype, arglist) ; #define HOOK_DEFINE(rettype, name, argtype, arglist) \ ORIG_##name = name; #pragma optimize("s", on) static void hook_initinternal() { #include "hooklist.h" } #pragma optimize("", on) #undef HOOK_DEFINE #undef HOOK_MANUALLY #define FORCE(expr) {if(!SUCCEEDED(NtStatus = (expr))) goto ERROR_ABORT;} #define HOOK_DEFINE(rettype, name, argtype, arglist) \ if (&ORIG_##name) { \ FORCE(LhInstallHook((PVOID&)ORIG_##name, IMPL_##name, (PVOID)0, &HOOK_##name)); \ *(void**)&ORIG_##name = (void*)HOOK_##name.Link->OldProc; \ FORCE(LhSetExclusiveACL(ACLEntries, 0, &HOOK_##name)); } #define HOOK_MANUALLY(rettype, name, argtype, arglist) ; static LONG hook_init() { ULONG ACLEntries[1] = {0}; NTSTATUS NtStatus; #include "hooklist.h" #undef HOOK_DEFINE FORCE(LhSetGlobalExclusiveACL(ACLEntries, 0)); return NOERROR; ERROR_ABORT: TRACE(_T("hook_init error: %#x\n"), NtStatus); return 1; } #undef HOOK_DEFINE #undef HOOK_MANUALLY #define HOOK_DEFINE(rettype, name, argtype, arglist); #define HOOK_MANUALLY(rettype, name, argtype, arglist) \ LONG hook_demand_##name(bool bForce = false){ \ NTSTATUS NtStatus; \ ULONG ACLEntries[1] = { 0 }; \ if (bForce) { \ memset((void*)&HOOK_##name, 0, sizeof(HOOK_TRACE_INFO)); \ } \ if (&ORIG_##name) { \ FORCE(LhInstallHook((PVOID&)ORIG_##name, IMPL_##name, (PVOID)0, &HOOK_##name)); \ *(void**)&ORIG_##name = (void*)HOOK_##name.Link->OldProc; \ FORCE(LhSetExclusiveACL(ACLEntries, 0, &HOOK_##name)); } \ return NOERROR; \ ERROR_ABORT: \ TRACE(_T("hook_init error: %#x\n"), NtStatus); \ return 1; \ } #include "hooklist.h" #undef HOOK_MANUALLY #undef HOOK_MANUALLY #undef HOOK_DEFINE #define HOOK_MANUALLY(rettype, name, argtype, arglist) ; #define HOOK_DEFINE(rettype, name, argtype, arglist) \ ORIG_##name = name; #pragma optimize("s", on) static LONG hook_term() { #include "hooklist.h" LhUninstallAllHooks(); return LhWaitForPendingRemovals(); } #endif #pragma optimize("", on) #undef HOOK_DEFINE #undef HOOK_MANUALLY //--- CTlsData g_TLInfo; HINSTANCE g_hinstDLL; LONG g_bHookEnabled; #ifdef _DEBUG HANDLE g_hfDbgText; #endif //void InstallManagerHook(); //void RemoveManagerHook(); //#include "APITracer.hpp" //ベースアドレスを変えた方がロードが早くなる #if _DLL #pragma comment(linker, "/base:0x06540000") #endif typedef BOOL(WINAPI *TIsImmersiveProcess)(_In_ HANDLE hProcess); TIsImmersiveProcess IsUWP = (TIsImmersiveProcess)GetProcAddress(GetModuleHandle(L"user32.dll"), "IsImmersiveProcess"); BOOL WINAPI IsRunAsUser(VOID) { if (IsUWP && IsUWP(GetCurrentProcess())) return true; // treat all UWP apps as user exe HANDLE hProcessToken = NULL; DWORD groupLength = 50; PTOKEN_GROUPS groupInfo = (PTOKEN_GROUPS)LocalAlloc(0, groupLength); SID_IDENTIFIER_AUTHORITY siaNt = SECURITY_NT_AUTHORITY; PSID InteractiveSid = NULL; PSID ServiceSid = NULL; DWORD i; // Start with assumption that process is an SERVICE, not a EXE; BOOL fExe = FALSE; if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hProcessToken)) goto ret; if (groupInfo == NULL) goto ret; if (!GetTokenInformation(hProcessToken, TokenGroups, groupInfo, groupLength, &groupLength)) { if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) goto ret; LocalFree(groupInfo); groupInfo = NULL; groupInfo = (PTOKEN_GROUPS)LocalAlloc(0, groupLength); if (groupInfo == NULL) goto ret; if (!GetTokenInformation(hProcessToken, TokenGroups, groupInfo, groupLength, &groupLength)) { goto ret; } } // // We now know the groups associated with this token. We want to look to see if // the interactive group is active in the token, and if so, we know that // this is an interactive process. // // We also look for the "service" SID, and if it's present, we know we're a service. // // The service SID will be present iff the service is running in a // user account (and was invoked by the service controller). // if (!AllocateAndInitializeSid(&siaNt, 1, SECURITY_INTERACTIVE_RID, 0, 0, 0, 0, 0, 0, 0, &InteractiveSid)) { goto ret; } if (!AllocateAndInitializeSid(&siaNt, 1, SECURITY_SERVICE_RID, 0, 0, 0, 0, 0, 0, 0, &ServiceSid)) { goto ret; } for (i = 0; i < groupInfo->GroupCount; i += 1) { SID_AND_ATTRIBUTES sanda = groupInfo->Groups[i]; PSID Sid = sanda.Sid; // // Check to see if the group we're looking at is one of // the 2 groups we're interested in. // if (EqualSid(Sid, InteractiveSid)) { // // This process has the Interactive SID in its // token. This means that the process is running as // an EXE. // fExe = true; goto ret; } else if (EqualSid(Sid, ServiceSid)) { // // This process has the Service SID in its // token. This means that the process is running as // a service running in a user account. // fExe = FALSE; goto ret; } } // // Neither Interactive or Service was present in the current users token, // This implies that the process is running as a service, most likely // running as LocalSystem. // fExe = FALSE; ret: if (InteractiveSid) FreeSid(InteractiveSid); if (ServiceSid) FreeSid(ServiceSid); if (groupInfo) LocalFree(groupInfo); if (hProcessToken) CloseHandle(hProcessToken); // EventLogging logger; // TCHAR s[100] = { 0 }; // wsprintf(s, L"Loading processid %d, isUserProcess=%d", GetCurrentProcessId(), (int)fExe); // LPCTSTR lpStrings[] = {s}; // logger.LogIt(1, 1, lpStrings, 1); return(fExe); } BOOL AddEasyHookEnv() { TCHAR dir[MAX_PATH]; int dirlen = GetModuleFileName(GetDLLInstance(), dir, MAX_PATH); LPTSTR lpfilename=dir+dirlen; while (lpfilename>dir && *lpfilename!=_T('\\') && *lpfilename!=_T('/')) --lpfilename; *lpfilename = 0; _tcscat(dir, _T(";")); dirlen = _tcslen(dir); int sz=GetEnvironmentVariable(_T("path"), NULL, 0); LPTSTR lpPath = (LPTSTR)malloc((sz+dirlen+2)*sizeof(TCHAR)); GetEnvironmentVariable(_T("path"), lpPath, sz); if (!_tcsstr(lpPath, dir)) { if (lpPath[sz-2]!=_T(';')) _tcscat(lpPath, _T(";")); _tcscat(lpPath, dir); SetEnvironmentVariable(_T("path"), lpPath); } free(lpPath); return true; } void HookFontCreation() { HMODULE gdi32 = GetModuleHandle(L"gdi32full.dll"); // prefer to hook deeply if (!gdi32) { gdi32 = GetModuleHandle(L"gdi32.dll"); } if (gdi32) { void* CreateFontIndirectW = GetProcAddress(gdi32, "CreateFontIndirectWImpl"); void* CreateFontIndirectExW = GetProcAddress(gdi32, "CreateFontIndirectExW"); if (!CreateFontIndirectW) { CreateFontIndirectW = GetProcAddress(gdi32, "CreateFontIndirectW"); } *(DWORD_PTR*)&ORIG_CreateFontIndirectW = (DWORD_PTR)CreateFontIndirectW; *(DWORD_PTR*)&ORIG_CreateFontIndirectExW = (DWORD_PTR)CreateFontIndirectExW; hook_demand_CreateFontIndirectExW(); hook_demand_CreateFontIndirectW(); } } extern FT_Int * g_charmapCache; extern BYTE* AACache, *AACacheFull; extern HFONT g_alterGUIFont; extern void DebugOut(const WCHAR* szFormat, ...); void EZHookMain(HINSTANCE instance, DWORD reason, LPVOID lpReserved) { #ifdef STATIC_LIB switch (reason) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: EasyHookDllMain(instance, reason, lpReserved); } #else switch (reason) { case DLL_PROCESS_ATTACH: { LPWSTR dllPath = new WCHAR[MAX_PATH + 1]; int nSize = GetModuleFileName(g_dllInstance, dllPath, MAX_PATH + 1); WCHAR* p = &dllPath[nSize]; while (*--p != L'\\'); *p = L'\0'; #ifdef _WIN64 wcscat(dllPath, L"\\easyhk64.dll"); #else wcscat(dllPath, L"\\easyhk32.dll"); #endif HMODULE hEasyhk = LoadLibrary(dllPath); delete[]dllPath; if (!hEasyhk) { DebugOut(L"Failed to load Easyhook, exiting"); return; } } } #endif } extern COLORCACHE* g_AACache2[MAX_CACHE_SIZE]; HANDLE hDelayHook = 0; BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID lpReserved) { try { static bool bDllInited = false; BOOL IsUnload = false, bEnableDW = true, bUseFontSubstitute = false; switch (reason) { case DLL_PROCESS_ATTACH: #ifdef DEBUG MessageBox(0, L"Load", NULL, MB_OK); #endif DebugOut(L"Begin core loading stage, pid %d", ::GetCurrentProcessId()); if (bDllInited) return true; g_dllInstance = instance; #ifdef EASYHOOK EZHookMain(instance, reason, lpReserved); #endif //初期化順序 //DLL_PROCESS_DETACHではこれの逆順にする //1. CRT関数の初期化 //2. クリティカルセクションの初期化 //3. TLSの準備 //4. CGdippSettingsのインスタンス生成、INI読み込み //5. ExcludeModuleチェック // 6. FreeTypeライブラリの初期化 // 7. FreeTypeFontEngineのインスタンス生成 // 8. APIをフック // 9. ManagerのGetProcAddressをフック //1 _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF); _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_WNDW); //_CrtSetBreakAlloc(100); //Operaよ止まれ~ //Assert(GetModuleHandleA("opera.exe") == NULL); //setlocale(LC_ALL, ""); g_hinstDLL = instance; //APITracer::Start(instance, APITracer::OutputFile); //2, 3 CCriticalSectionLock::Init(); COwnedCriticalSectionLock::Init(); CThreadCounter::Init(); if (!g_TLInfo.ProcessInit()) { DebugOut(L"Can't initialize process, exiting"); return FALSE; } // Above classes are heavily referenced and must be initialized as early as possible. // Unload dll is not safe until their initialization is complete. bDllInited = true; //4 { #ifdef INFINALITY // enable infinality exclusive features FT_initEnv(); #endif CGdippSettings* pSettings = CGdippSettings::CreateInstance(); if (!pSettings || !pSettings->LoadSettings(instance)) { CGdippSettings::DestroyInstance(); return FALSE; } IsUnload = IsProcessUnload(); bEnableDW = pSettings->DirectWrite(); bUseFontSubstitute = !!pSettings->FontSubstitutes(); } if (!IsUnload) hook_initinternal(); //不加载的模块就不做任何事莵E //5 if (!IsProcessExcluded() && !IsUnload) { #ifndef _WIN64 InitWow64ext(); #endif if (!FontLInit()) { DebugOut(L"FreeType failed to initialize, exiting"); return FALSE; } g_pFTEngine = new FreeTypeFontEngine; if (!g_pFTEngine) { return FALSE; } //if (!AddEasyHookEnv()) return FALSE; //fail to load easyhook InterlockedExchange(&g_bHookEnabled, TRUE); if (hook_init() != NOERROR) { DebugOut(L"Can't do hooking, exiting"); return FALSE; } //hook d2d if already loaded /* DWORD dwSessionID = 0; if (ProcessIdToSessionIdProc) ProcessIdToSessionIdProc(GetCurrentThreadId(), &dwSessionID); else dwSessionID = 1;*/ if (IsRunAsUser() && bEnableDW && IsWindowsVistaOrGreater()) //vista or later { HookD2DDll(); //hook_demand_LdrLoadDll(); } // only hook font creation funcs if font substition is set. if (bUseFontSubstitute) { HookFontCreation(); } } //获得当前加载模式 if (IsUnload) { HANDLE mutex_offical = OpenMutex(MUTEX_ALL_ACCESS, false, _T("{46AD3688-30D0-411e-B2AA-CB177818F428}")); HANDLE mutex_gditray2 = OpenMutex(MUTEX_ALL_ACCESS, false, _T("Global\\MacType")); if (!mutex_gditray2) mutex_gditray2 = OpenMutex(MUTEX_ALL_ACCESS, false, _T("MacType")); HANDLE mutex_CompMode = OpenMutex(MUTEX_ALL_ACCESS, false, _T("Global\\MacTypeCompMode")); if (!mutex_CompMode) mutex_CompMode = OpenMutex(MUTEX_ALL_ACCESS, false, _T("MacTypeCompMode")); BOOL HookMode = (mutex_offical || (mutex_gditray2 && mutex_CompMode)) || (!mutex_offical && !mutex_gditray2); //是否在兼容模式下 CloseHandle(mutex_CompMode); CloseHandle(mutex_gditray2); CloseHandle(mutex_offical); if (!HookMode) { //非兼容模式下,拒绝加载 DebugOut(L"Process is in unloaddll list, exiting"); return false; } } //APITracer::Finish(); break; case DLL_THREAD_ATTACH: #ifdef EASYHOOK EZHookMain(instance, reason, lpReserved); #endif break; case DLL_THREAD_DETACH: g_TLInfo.ThreadTerm(); #ifdef EASYHOOK EZHookMain(instance, reason, lpReserved); #endif break; case DLL_PROCESS_DETACH: // RemoveManagerHook(); if (!bDllInited) return true; bDllInited = false; if (InterlockedExchange(&g_bHookEnabled, FALSE) && lpReserved == NULL) { //如果是进程终止,则不需要释放 hook_term(); //delete AACacheFull; //delete AACache; // for (int i=0;i std::atomic HCounter::ref(0); ================================================ FILE: hookCounter.h ================================================ #pragma once #include #include #include class HCounter { static std::atomic ref; public: HCounter() { ++this->ref; } ~HCounter() { --this->ref; } static bool wait(int nCount) { while (--nCount && HCounter::ref.load()) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } return !HCounter::ref; } }; ================================================ FILE: hooklist.h ================================================ HOOK_DEFINE(int, GetObjectW, (__in HANDLE h, __in int c, __out_bcount_opt(c) LPVOID pv), (h, c, pv)) HOOK_DEFINE(int, GetObjectA, (__in HANDLE h, __in int c, __out_bcount_opt(c) LPVOID pv), (h, c, pv)) HOOK_DEFINE(int, GetTextFaceAliasW, (HDC hdc, int nLen, LPWSTR lpAliasW), (hdc, nLen, lpAliasW)) HOOK_DEFINE(BOOL, DeleteObject, ( HGDIOBJ hObject),(hObject)) HOOK_DEFINE(int, GetTextFaceW, ( __in HDC hdc, __in int c, __out_ecount_part_opt(c, return) LPWSTR lpName), (hdc, c, lpName)) HOOK_DEFINE(int, GetTextFaceA, ( __in HDC hdc, __in int c, __out_ecount_part_opt(c, return) LPSTR lpName), (hdc, c, lpName)) // dc->window detection helper HOOK_MANUALLY(HDC, CreateCompatibleDC, (_In_opt_ HDC hdc), (hdc)) HOOK_MANUALLY(BOOL, DeleteDC, (_In_ HDC hdc), (hdc)) HOOK_MANUALLY(HDC, GetDC, (_In_opt_ HWND hWnd), (hWnd)) HOOK_MANUALLY(BOOL, ReleaseDC, (_In_opt_ HWND hWnd, _In_ HDC hDC), (hWnd, hDC)) /* * BeginBufferedPaint calls CreateCompatibleDC internally HOOK_DEFINE(HPAINTBUFFER, BeginBufferedPaint, ( HDC hdcTarget, const RECT * prcTarget, BP_BUFFERFORMAT dwFormat, BP_PAINTPARAMS * pPaintParams, HDC * phdc ), (hdcTarget, prcTarget, dwFormat, pPaintParams, phdc)) HOOK_DEFINE(HRESULT, EndBufferedPaint, ( HPAINTBUFFER hBufferedPaint, BOOL fUpdateTarget ), (hBufferedPaint, fUpdateTarget)) */ HOOK_DEFINE(DWORD, GetGlyphOutlineW, ( __in HDC hdc, \ __in UINT uChar, \ __in UINT fuFormat, \ __out LPGLYPHMETRICS lpgm, \ __in DWORD cjBuffer, \ __out_bcount_opt(cjBuffer) LPVOID pvBuffer, \ __in CONST MAT2 *lpmat2 \ ), (hdc, uChar, fuFormat, lpgm, cjBuffer, pvBuffer, lpmat2)) HOOK_DEFINE(DWORD, GetGlyphOutlineA, (__in HDC hdc, \ __in UINT uChar, \ __in UINT fuFormat, \ __out LPGLYPHMETRICS lpgm, \ __in DWORD cjBuffer, \ __out_bcount_opt(cjBuffer) LPVOID pvBuffer, \ __in CONST MAT2 *lpmat2), \ (hdc, uChar, fuFormat, lpgm, cjBuffer, pvBuffer, lpmat2)) // DrawTextA,W // DrawTextExA,W // TabbedTextOutA,W // TextOutA,W // ExtTextOutA // は内部で ExtTextOutWを呼んでるから ExtTextOutW だけ実装すればOK。←XPの場合 // Windows 2000 でも動くようにその他のAPIもフックを掛けておく。 HOOK_MANUALLY(HFONT, CreateFontIndirectW, (CONST LOGFONTW *lplf), (lplf)) HOOK_MANUALLY(HFONT, CreateFontIndirectExW, (CONST ENUMLOGFONTEXDV *penumlfex), (penumlfex)) // HOOK_DEFINE(BOOL, GetCharWidthW, (HDC hdc, UINT iFirstChar, UINT iLastChar, LPINT lpBuffer)) // HOOK_DEFINE(BOOL, GetCharWidth32W, (HDC hdc, UINT iFirstChar, UINT iLastChar, LPINT lpBuffer)) HOOK_DEFINE(BOOL, TextOutA, (HDC hdc, int nXStart, int nYStart, LPCSTR lpString, int cbString), (hdc, nXStart, nYStart, lpString, cbString)) HOOK_DEFINE(BOOL, TextOutW, (HDC hdc, int nXStart, int nYStart, LPCWSTR lpString, int cbString), (hdc, nXStart, nYStart, lpString, cbString)) HOOK_DEFINE(BOOL, ExtTextOutA, (HDC hdc, int nXStart, int nYStart, UINT fuOptions, CONST RECT *lprc, LPCSTR lpString, UINT cbString, CONST INT *lpDx), (hdc, nXStart, nYStart, fuOptions, lprc, lpString, cbString, lpDx)) HOOK_DEFINE(BOOL, ExtTextOutW, (HDC hdc, int nXStart, int nYStart, UINT fuOptions, CONST RECT *lprc, LPCWSTR lpString, UINT cbString, CONST INT *lpDx), (hdc, nXStart, nYStart, fuOptions, lprc, lpString, cbString, lpDx)) HOOK_DEFINE(BOOL, RemoveFontResourceExW, (__in LPCWSTR name, __in DWORD fl, __reserved PVOID pdv), (name, fl, pdv)) //HOOK_DEFINE(BOOL, RemoveFontResourceW, (__in LPCWSTR lpFileName)) HOOK_DEFINE(HGDIOBJ, GetStockObject, (__in int i), (i)) HOOK_DEFINE(BOOL, BeginPath, (HDC hdc), (hdc)) HOOK_DEFINE(BOOL, EndPath, (HDC hdc), (hdc)) HOOK_DEFINE(BOOL, AbortPath, (HDC hdc), (hdc)); HOOK_DEFINE(DWORD, GetFontData, (_In_ HDC hdc, _In_ DWORD dwTable, _In_ DWORD dwOffset, _Out_writes_bytes_to_opt_(cjBuffer, return) PVOID pvBuffer, _In_ DWORD cjBuffer ), (hdc, dwTable, dwOffset, pvBuffer, cjBuffer)); HOOK_MANUALLY(HRESULT, BitmapRenderTarget_DrawGlyphRun, ( IDWriteBitmapRenderTarget* This, FLOAT baselineOriginX, FLOAT baselineOriginY, DWRITE_MEASURING_MODE measuringMode, DWRITE_GLYPH_RUN const* glyphRun, IDWriteRenderingParams* renderingParams, COLORREF textColor, RECT* blackBoxRect), (This, baselineOriginX, baselineOriginY, measuringMode, glyphRun, renderingParams, textColor, blackBoxRect)) /* HOOK_MANUALLY(void, SetTextAntialiasMode, ( ID2D1RenderTarget* self, D2D1_TEXT_ANTIALIAS_MODE textAntialiasMode)) HOOK_MANUALLY(void, SetTextRenderingParams, ( ID2D1RenderTarget* self, __in_opt IDWriteRenderingParams *textRenderingParams ))*/ HOOK_MANUALLY(HRESULT, DWriteCreateFactory, ( __in DWRITE_FACTORY_TYPE factoryType, __in REFIID iid, __out IUnknown **factory), (factoryType, iid, factory)) HOOK_MANUALLY(HRESULT, D2D1CreateDevice, ( IDXGIDevice* dxgiDevice, CONST D2D1_CREATION_PROPERTIES* creationProperties, ID2D1Device** d2dDevice), (dxgiDevice, creationProperties, d2dDevice)) HOOK_MANUALLY(HRESULT, D2D1CreateDeviceContext, ( IDXGISurface* dxgiSurface, CONST D2D1_CREATION_PROPERTIES* creationProperties, ID2D1DeviceContext** d2dDeviceContext), (dxgiSurface, creationProperties, d2dDeviceContext)) HOOK_MANUALLY(HRESULT, D2D1CreateFactory, ( D2D1_FACTORY_TYPE factoryType, REFIID riid, const D2D1_FACTORY_OPTIONS* pFactoryOptions, void** ppIFactory), (factoryType, riid, pFactoryOptions, ppIFactory)) HOOK_MANUALLY(HRESULT, GetGdiInterop, ( IDWriteFactory* This, IDWriteGdiInterop** gdiInterop ), (This, gdiInterop)) HOOK_MANUALLY(HRESULT, CreateGlyphRunAnalysis, ( IDWriteFactory* This, DWRITE_GLYPH_RUN const* glyphRun, FLOAT pixelsPerDip, DWRITE_MATRIX const* transform, DWRITE_RENDERING_MODE renderingMode, DWRITE_MEASURING_MODE measuringMode, FLOAT baselineOriginX, FLOAT baselineOriginY, IDWriteGlyphRunAnalysis** glyphRunAnalysis ), (This, glyphRun, pixelsPerDip, transform, renderingMode, measuringMode, baselineOriginX, baselineOriginY, glyphRunAnalysis)) HOOK_MANUALLY(HRESULT, CreateGlyphRunAnalysis2, ( IDWriteFactory2* This, DWRITE_GLYPH_RUN const* glyphRun, DWRITE_MATRIX const* transform, DWRITE_RENDERING_MODE renderingMode, DWRITE_MEASURING_MODE measuringMode, DWRITE_GRID_FIT_MODE gridFitMode, DWRITE_TEXT_ANTIALIAS_MODE antialiasMode, FLOAT baselineOriginX, FLOAT baselineOriginY, IDWriteGlyphRunAnalysis** glyphRunAnalysis ), (This, glyphRun, transform, renderingMode, measuringMode, gridFitMode, antialiasMode, baselineOriginX, baselineOriginY, glyphRunAnalysis)) HOOK_MANUALLY(HRESULT, CreateGlyphRunAnalysis3, ( IDWriteFactory3* This, DWRITE_GLYPH_RUN const* glyphRun, DWRITE_MATRIX const* transform, DWRITE_RENDERING_MODE1 renderingMode, DWRITE_MEASURING_MODE measuringMode, DWRITE_GRID_FIT_MODE gridFitMode, DWRITE_TEXT_ANTIALIAS_MODE antialiasMode, FLOAT baselineOriginX, FLOAT baselineOriginY, IDWriteGlyphRunAnalysis** glyphRunAnalysis ), (This, glyphRun, transform, renderingMode, measuringMode, gridFitMode, antialiasMode, baselineOriginX, baselineOriginY, glyphRunAnalysis)) HOOK_MANUALLY(HRESULT, GetAlphaBlendParams, ( IDWriteGlyphRunAnalysis* This, IDWriteRenderingParams* renderingParams, FLOAT* blendGamma, FLOAT* blendEnhancedContrast, FLOAT* blendClearTypeLevel ), (This, renderingParams, blendGamma, blendEnhancedContrast, blendClearTypeLevel)) HOOK_MANUALLY(HRESULT, CreateDeviceContext, ( ID2D1Device* This, D2D1_DEVICE_CONTEXT_OPTIONS options, ID2D1DeviceContext** deviceContext ), (This, options, deviceContext)) HOOK_MANUALLY(HRESULT, CreateDeviceContext2, ( ID2D1Device1* This, D2D1_DEVICE_CONTEXT_OPTIONS options, ID2D1DeviceContext1** deviceContext ), (This, options, deviceContext)) HOOK_MANUALLY(HRESULT, CreateDeviceContext3, ( ID2D1Device2* This, D2D1_DEVICE_CONTEXT_OPTIONS options, ID2D1DeviceContext2** deviceContext ), (This, options, deviceContext)) HOOK_MANUALLY(HRESULT, CreateDeviceContext4, ( ID2D1Device3* This, D2D1_DEVICE_CONTEXT_OPTIONS options, ID2D1DeviceContext3** deviceContext ), (This, options, deviceContext)) HOOK_MANUALLY(HRESULT, CreateDeviceContext5, ( ID2D1Device4* This, D2D1_DEVICE_CONTEXT_OPTIONS options, ID2D1DeviceContext4** deviceContext ), (This, options, deviceContext)) HOOK_MANUALLY(HRESULT, CreateDeviceContext6, ( ID2D1Device5* This, D2D1_DEVICE_CONTEXT_OPTIONS options, ID2D1DeviceContext5** deviceContext ), (This, options, deviceContext)) HOOK_MANUALLY(HRESULT, CreateDeviceContext7, ( ID2D1Device6* This, D2D1_DEVICE_CONTEXT_OPTIONS options, ID2D1DeviceContext6** deviceContext ), (This, options, deviceContext)) HOOK_MANUALLY(HRESULT, CreateTextFormat, ( IDWriteFactory* self, __in_z WCHAR const* fontFamilyName, __maybenull IDWriteFontCollection* fontCollection, DWRITE_FONT_WEIGHT fontWeight, DWRITE_FONT_STYLE fontStyle, DWRITE_FONT_STRETCH fontStretch, FLOAT fontSize, __in_z WCHAR const* localeName, __out IDWriteTextFormat** textFormat), (self, fontFamilyName, fontCollection, fontWeight, fontStyle, fontStretch, fontSize, localeName, textFormat)) HOOK_MANUALLY(HRESULT, CreateFontFace, ( IDWriteFont* self, __out IDWriteFontFace** fontFace ), (self, fontFace)) HOOK_MANUALLY(HRESULT, DWriteFontFaceReference_CreateFontFace, ( IDWriteFontFaceReference* self, __out IDWriteFontFace3** fontFace ), (self, fontFace)) HOOK_MANUALLY(HRESULT, DWriteFontFaceReference_CreateFontFaceWithSimulations, ( IDWriteFontFaceReference* self, DWRITE_FONT_SIMULATIONS fontFaceSimulationFlags, __out IDWriteFontFace3** fontFace ), (self, fontFaceSimulationFlags, fontFace)) HOOK_MANUALLY(HRESULT, CreateBitmapRenderTarget, ( IDWriteGdiInterop* This, HDC hdc, UINT32 width, UINT32 height, IDWriteBitmapRenderTarget** renderTarget ), (This, hdc, width, height, renderTarget)) HOOK_MANUALLY(HRESULT, CreateCompatibleRenderTarget, ( ID2D1RenderTarget* This, CONST D2D1_SIZE_F* desiredSize, CONST D2D1_SIZE_U* desiredPixelSize, CONST D2D1_PIXEL_FORMAT* desiredFormat, D2D1_COMPATIBLE_RENDER_TARGET_OPTIONS options, ID2D1BitmapRenderTarget** bitmapRenderTarget ), (This, desiredSize, desiredPixelSize, desiredFormat, options, bitmapRenderTarget)) HOOK_MANUALLY(void, D2D1RenderTarget_SetTextAntialiasMode, ( ID2D1RenderTarget* This, D2D1_TEXT_ANTIALIAS_MODE textAntialiasMode), (This, textAntialiasMode)); HOOK_MANUALLY(void, D2D1DeviceContext_SetTextAntialiasMode, ( ID2D1DeviceContext* This, D2D1_TEXT_ANTIALIAS_MODE textAntialiasMode), (This, textAntialiasMode)); HOOK_MANUALLY(void, D2D1RenderTarget_SetTextRenderingParams, ( ID2D1RenderTarget* This, _In_opt_ IDWriteRenderingParams* textRenderingParams), (This, textRenderingParams)); HOOK_MANUALLY(void, D2D1DeviceContext_SetTextRenderingParams, ( ID2D1DeviceContext* This, _In_opt_ IDWriteRenderingParams* textRenderingParams), (This, textRenderingParams)); /* HOOK_MANUALLY(GpStatus, GdipDrawString, ( GpGraphics *graphics, GDIPCONST WCHAR *string, INT length, GDIPCONST GpFont *font, GDIPCONST RectF *layoutRect, GDIPCONST GpStringFormat *stringFormat, GDIPCONST GpBrush *brush ))*/ HOOK_MANUALLY(HRESULT, CreateWicBitmapRenderTarget, ( ID2D1Factory* This, IWICBitmap* target, const D2D1_RENDER_TARGET_PROPERTIES* renderTargetProperties, ID2D1RenderTarget** renderTarget), (This, target, renderTargetProperties, renderTarget)); HOOK_MANUALLY(HRESULT, CreateHwndRenderTarget, ( ID2D1Factory* This, const D2D1_RENDER_TARGET_PROPERTIES* renderTargetProperties, const D2D1_HWND_RENDER_TARGET_PROPERTIES* hwndRenderTargetProperties, ID2D1HwndRenderTarget** hwndRenderTarget), (This, renderTargetProperties, hwndRenderTargetProperties, hwndRenderTarget)); HOOK_MANUALLY(HRESULT, CreateDxgiSurfaceRenderTarget, ( ID2D1Factory* This, IDXGISurface* dxgiSurface, const D2D1_RENDER_TARGET_PROPERTIES* renderTargetProperties, ID2D1RenderTarget** renderTarget), (This, dxgiSurface, renderTargetProperties, renderTarget)); HOOK_MANUALLY(HRESULT, CreateDCRenderTarget, ( ID2D1Factory* This, const D2D1_RENDER_TARGET_PROPERTIES* renderTargetProperties, ID2D1DCRenderTarget** dcRenderTarget), (This, renderTargetProperties, dcRenderTarget)); HOOK_MANUALLY(HRESULT, CreateDevice1, ( ID2D1Factory1* This, IDXGIDevice* dxgiDevice, ID2D1Device** d2dDevice), (This, dxgiDevice, d2dDevice)); HOOK_MANUALLY(HRESULT, CreateDevice2, ( ID2D1Factory2* This, IDXGIDevice* dxgiDevice, ID2D1Device1** d2dDevice1 ), (This, dxgiDevice, d2dDevice1)); HOOK_MANUALLY(HRESULT, CreateDevice3, ( ID2D1Factory3* This, IDXGIDevice* dxgiDevice, ID2D1Device2** d2dDevice2 ), (This, dxgiDevice, d2dDevice2)); HOOK_MANUALLY(HRESULT, CreateDevice4, ( ID2D1Factory4* This, IDXGIDevice* dxgiDevice, ID2D1Device3** d2dDevice3 ), (This, dxgiDevice, d2dDevice3)); HOOK_MANUALLY(HRESULT, CreateDevice5, ( ID2D1Factory5* This, IDXGIDevice* dxgiDevice, ID2D1Device4** d2dDevice4 ), (This, dxgiDevice, d2dDevice4)); HOOK_MANUALLY(HRESULT, CreateDevice6, ( ID2D1Factory6* This, IDXGIDevice* dxgiDevice, ID2D1Device5** d2dDevice5 ), (This, dxgiDevice, d2dDevice5)); HOOK_MANUALLY(HRESULT, CreateDevice7, ( ID2D1Factory7* This, IDXGIDevice* dxgiDevice, ID2D1Device6** d2dDevice6 ), (This, dxgiDevice, d2dDevice6)); HOOK_MANUALLY(BOOL, MySetProcessMitigationPolicy, ( _In_ PROCESS_MITIGATION_POLICY MitigationPolicy, _In_ PVOID lpBuffer, _In_ SIZE_T dwLength ), (MitigationPolicy, lpBuffer, dwLength)); HOOK_MANUALLY(void, D2D1RenderTarget_DrawGlyphRun1, ( ID2D1DeviceContext *This, D2D1_POINT_2F baselineOrigin, CONST DWRITE_GLYPH_RUN *glyphRun, CONST DWRITE_GLYPH_RUN_DESCRIPTION *glyphRunDescription, ID2D1Brush *foregroundBrush, DWRITE_MEASURING_MODE measuringMode), (This, baselineOrigin, glyphRun, glyphRunDescription, foregroundBrush, measuringMode)); HOOK_MANUALLY(void, D2D1RenderTarget1_DrawGlyphRun1, ( ID2D1DeviceContext *This, D2D1_POINT_2F baselineOrigin, CONST DWRITE_GLYPH_RUN *glyphRun, CONST DWRITE_GLYPH_RUN_DESCRIPTION *glyphRunDescription, ID2D1Brush *foregroundBrush, DWRITE_MEASURING_MODE measuringMode), (This, baselineOrigin, glyphRun, glyphRunDescription, foregroundBrush, measuringMode)); HOOK_MANUALLY(void, D2D1DeviceContext_DrawGlyphRun1, ( ID2D1DeviceContext *This, D2D1_POINT_2F baselineOrigin, CONST DWRITE_GLYPH_RUN *glyphRun, CONST DWRITE_GLYPH_RUN_DESCRIPTION *glyphRunDescription, ID2D1Brush *foregroundBrush, DWRITE_MEASURING_MODE measuringMode), (This, baselineOrigin, glyphRun, glyphRunDescription, foregroundBrush, measuringMode)); HOOK_MANUALLY(void, D2D1RenderTarget_DrawGlyphRun, ( ID2D1RenderTarget* This, D2D1_POINT_2F baselineOrigin, CONST DWRITE_GLYPH_RUN *glyphRun, ID2D1Brush *foregroundBrush, DWRITE_MEASURING_MODE measuringMode ), (This, baselineOrigin, glyphRun, foregroundBrush, measuringMode)); HOOK_MANUALLY(void, D2D1RenderTarget1_DrawGlyphRun, ( ID2D1RenderTarget* This, D2D1_POINT_2F baselineOrigin, CONST DWRITE_GLYPH_RUN *glyphRun, ID2D1Brush *foregroundBrush, DWRITE_MEASURING_MODE measuringMode ), (This, baselineOrigin, glyphRun, foregroundBrush, measuringMode)); HOOK_MANUALLY(void, D2D1DeviceContext_DrawGlyphRun, ( ID2D1DeviceContext* This, D2D1_POINT_2F baselineOrigin, CONST DWRITE_GLYPH_RUN *glyphRun, ID2D1Brush *foregroundBrush, DWRITE_MEASURING_MODE measuringMode ), (This, baselineOrigin, glyphRun, foregroundBrush, measuringMode)); HOOK_MANUALLY(void, D2D1RenderTarget_DrawText, ( ID2D1RenderTarget* This, CONST WCHAR *string, UINT32 stringLength, IDWriteTextFormat *textFormat, CONST D2D1_RECT_F *layoutRect, ID2D1Brush *defaultForegroundBrush, D2D1_DRAW_TEXT_OPTIONS options, DWRITE_MEASURING_MODE measuringMode), (This, string, stringLength, textFormat, layoutRect, defaultForegroundBrush, options, measuringMode)); HOOK_MANUALLY(void, D2D1DeviceContext_DrawText, ( ID2D1DeviceContext* This, CONST WCHAR *string, UINT32 stringLength, IDWriteTextFormat *textFormat, CONST D2D1_RECT_F *layoutRect, ID2D1Brush *defaultForegroundBrush, D2D1_DRAW_TEXT_OPTIONS options, DWRITE_MEASURING_MODE measuringMode), (This, string, stringLength, textFormat, layoutRect, defaultForegroundBrush, options, measuringMode)); HOOK_MANUALLY(void, D2D1RenderTarget_DrawTextLayout, ( ID2D1RenderTarget* This, D2D1_POINT_2F origin, IDWriteTextLayout *textLayout, ID2D1Brush *defaultForegroundBrush, D2D1_DRAW_TEXT_OPTIONS options ), (This, origin, textLayout, defaultForegroundBrush, options)); //EOF ================================================ FILE: ivs_otft.h ================================================ OTFT_DEF_BEGIN(0) /* E0100 */ OTFT_DEF(0x5026, 2) /* jp90 */ OTFT_DEF(0x50C5, 2) /* jp90 */ OTFT_DEF(0x5132, 2) /* jp90 */ OTFT_DEF(0x514E, 2) /* jp90 */ OTFT_DEF(0x5154, 1) /* jp78 */ OTFT_DEF(0x5195, 1) /* jp78 */ OTFT_DEF(0x51A4, 2) /* jp90 */ OTFT_DEF(0x53A9, 2) /* jp90 */ OTFT_DEF(0x53C9, 2) /* jp90 */ OTFT_DEF(0x53DB, 2) /* jp90 */ OTFT_DEF(0x53DF, 2) /* jp90 */ OTFT_DEF(0x54AC, 2) /* jp90 */ OTFT_DEF(0x54E8, 2) /* jp90 */ OTFT_DEF(0x55B0, 2) /* jp90 */ OTFT_DEF(0x5632, 2) /* jp90 */ OTFT_DEF(0x5642, 2) /* jp90 */ OTFT_DEF(0x564C, 2) /* jp90 */ OTFT_DEF(0x56C0, 2) /* jp90 */ OTFT_DEF(0x5835, 2) /* jp90 */ OTFT_DEF(0x5906, 2) /* jp90 */ OTFT_DEF(0x5A29, 2) /* jp90 */ OTFT_DEF(0x5C51, 2) /* jp90 */ OTFT_DEF(0x5C60, 2) /* jp90 */ OTFT_DEF(0x5DF7, 2) /* jp90 */ OTFT_DEF(0x5DFD, 1) /* jp78 */ OTFT_DEF(0x5E96, 2) /* jp90 */ OTFT_DEF(0x5EDF, 2) /* jp90 */ OTFT_DEF(0x5EFB, 2) /* jp90 */ OTFT_DEF(0x5F98, 2) /* jp90 */ OTFT_DEF(0x5FBD, 2) /* jp90 */ OTFT_DEF(0x6062, 2) /* jp90 */ OTFT_DEF(0x609E, 2) /* jp90 */ OTFT_DEF(0x6108, 2) /* jp90 */ OTFT_DEF(0x6241, 2) /* jp90 */ OTFT_DEF(0x633A, 2) /* jp90 */ OTFT_DEF(0x633D, 2) /* jp90 */ OTFT_DEF(0x6357, 2) /* jp90 */ OTFT_DEF(0x6372, 2) /* jp90 */ OTFT_DEF(0x63C3, 2) /* jp90 */ OTFT_DEF(0x646F, 2) /* jp90 */ OTFT_DEF(0x647A, 2) /* jp90 */ OTFT_DEF(0x64B0, 2) /* jp90 */ OTFT_DEF(0x64E2, 2) /* jp90 */ OTFT_DEF(0x65A7, 2) /* jp90 */ OTFT_DEF(0x6666, 2) /* jp90 */ OTFT_DEF(0x66B5, 2) /* jp90 */ OTFT_DEF(0x6753, 2) /* jp90 */ OTFT_DEF(0x6756, 2) /* jp90 */ OTFT_DEF(0x6897, 2) /* jp90 */ OTFT_DEF(0x6962, 2) /* jp90 */ OTFT_DEF(0x696F, 2) /* jp90 */ OTFT_DEF(0x698A, 2) /* jp90 */ OTFT_DEF(0x6994, 2) /* jp90 */ OTFT_DEF(0x69CC, 2) /* jp90 */ OTFT_DEF(0x6A0B, 2) /* jp90 */ OTFT_DEF(0x6A3D, 2) /* jp90 */ OTFT_DEF(0x6A9C, 1) /* jp78 */ OTFT_DEF(0x6ADB, 1) /* jp78 */ OTFT_DEF(0x6B4E, 2) /* jp90 */ OTFT_DEF(0x6C72, 2) /* jp90 */ OTFT_DEF(0x6DEB, 2) /* jp90 */ OTFT_DEF(0x6E1A, 1) /* jp78 */ OTFT_DEF(0x6EA2, 2) /* jp90 */ OTFT_DEF(0x6EBA, 2) /* jp90 */ OTFT_DEF(0x6F23, 1) /* jp78 */ OTFT_DEF(0x6F51, 1) /* jp78 */ OTFT_DEF(0x7015, 2) /* jp90 */ OTFT_DEF(0x701E, 2) /* jp90 */ OTFT_DEF(0x7026, 2) /* jp90 */ OTFT_DEF(0x7058, 2) /* jp90 */ OTFT_DEF(0x7078, 2) /* jp90 */ OTFT_DEF(0x707C, 2) /* jp90 */ OTFT_DEF(0x7149, 1) /* jp78 */ OTFT_DEF(0x714E, 2) /* jp90 */ OTFT_DEF(0x7152, 2) /* jp90 */ OTFT_DEF(0x717D, 2) /* jp90 */ OTFT_DEF(0x7228, 1) /* jp78 */ OTFT_DEF(0x723A, 2) /* jp90 */ OTFT_DEF(0x724C, 2) /* jp90 */ OTFT_DEF(0x7259, 2) /* jp90 */ OTFT_DEF(0x72E1, 2) /* jp90 */ OTFT_DEF(0x7337, 2) /* jp90 */ OTFT_DEF(0x7422, 1) /* jp78 */ OTFT_DEF(0x7511, 2) /* jp90 */ OTFT_DEF(0x7515, 2) /* jp90 */ OTFT_DEF(0x7526, 2) /* jp90 */ OTFT_DEF(0x75BC, 2) /* jp90 */ OTFT_DEF(0x77A5, 2) /* jp90 */ OTFT_DEF(0x783A, 1) /* jp78 */ OTFT_DEF(0x792A, 1) /* jp78 */ OTFT_DEF(0x7941, 2) /* jp90 */ OTFT_DEF(0x7947, 2) /* jp90 */ OTFT_DEF(0x79B0, 2) /* jp90 */ OTFT_DEF(0x79B1, 1) /* jp78 */ OTFT_DEF(0x79E4, 2) /* jp90 */ OTFT_DEF(0x7A17, 2) /* jp90 */ OTFT_DEF(0x7A7F, 2) /* jp90 */ OTFT_DEF(0x7AC8, 2) /* jp90 */ OTFT_DEF(0x7B08, 2) /* jp90 */ OTFT_DEF(0x7B75, 2) /* jp90 */ OTFT_DEF(0x7BAD, 2) /* jp90 */ OTFT_DEF(0x7BB8, 2) /* jp90 */ OTFT_DEF(0x7BC7, 2) /* jp90 */ OTFT_DEF(0x7BDD, 2) /* jp90 */ OTFT_DEF(0x7C3E, 2) /* jp90 */ OTFT_DEF(0x7C7E, 2) /* jp90 */ OTFT_DEF(0x7C82, 2) /* jp90 */ OTFT_DEF(0x7FEB, 2) /* jp90 */ OTFT_DEF(0x7FF0, 2) /* jp90 */ OTFT_DEF(0x8171, 2) /* jp90 */ OTFT_DEF(0x817F, 2) /* jp90 */ OTFT_DEF(0x8258, 2) /* jp90 */ OTFT_DEF(0x8292, 2) /* jp90 */ OTFT_DEF(0x82A6, 2) /* jp90 */ OTFT_DEF(0x8328, 2) /* jp90 */ OTFT_DEF(0x845B, 2) /* jp90 */ OTFT_DEF(0x84EC, 2) /* jp90 */ OTFT_DEF(0x84EE, 1) /* jp78 */ OTFT_DEF(0x8511, 2) /* jp90 */ OTFT_DEF(0x853D, 2) /* jp90 */ OTFT_DEF(0x85A9, 2) /* jp90 */ OTFT_DEF(0x85AF, 2) /* jp90 */ OTFT_DEF(0x85F7, 2) /* jp90 */ OTFT_DEF(0x8654, 2) /* jp90 */ OTFT_DEF(0x86F8, 2) /* jp90 */ OTFT_DEF(0x8703, 2) /* jp90 */ OTFT_DEF(0x8755, 2) /* jp90 */ OTFT_DEF(0x8805, 2) /* jp90 */ OTFT_DEF(0x8956, 2) /* jp90 */ OTFT_DEF(0x8A0A, 2) /* jp90 */ OTFT_DEF(0x8A1D, 2) /* jp90 */ OTFT_DEF(0x8A3B, 2) /* jp90 */ OTFT_DEF(0x8A6E, 2) /* jp90 */ OTFT_DEF(0x8AB9, 2) /* jp90 */ OTFT_DEF(0x8AFA, 2) /* jp90 */ OTFT_DEF(0x8B0E, 2) /* jp90 */ OTFT_DEF(0x8B2C, 2) /* jp90 */ OTFT_DEF(0x8B7F, 2) /* jp90 */ OTFT_DEF(0x8C79, 2) /* jp90 */ OTFT_DEF(0x8CED, 2) /* jp90 */ OTFT_DEF(0x8FBB, 2) /* jp90 */ OTFT_DEF(0x8FBF, 2) /* jp90 */ OTFT_DEF(0x8FC2, 2) /* jp90 */ OTFT_DEF(0x8FC4, 2) /* jp90 */ OTFT_DEF(0x8FE6, 2) /* jp90 */ OTFT_DEF(0x9017, 2) /* jp90 */ OTFT_DEF(0x9019, 2) /* jp90 */ OTFT_DEF(0x9022, 2) /* jp90 */ OTFT_DEF(0x903C, 2) /* jp90 */ OTFT_DEF(0x9041, 2) /* jp90 */ OTFT_DEF(0x905C, 2) /* jp90 */ OTFT_DEF(0x9061, 2) /* jp90 */ OTFT_DEF(0x9087, 1) /* jp78 */ OTFT_DEF(0x912D, 2) /* jp90 */ OTFT_DEF(0x914B, 2) /* jp90 */ OTFT_DEF(0x91B1, 1) /* jp78 */ OTFT_DEF(0x91DC, 2) /* jp90 */ OTFT_DEF(0x9306, 2) /* jp90 */ OTFT_DEF(0x9375, 2) /* jp90 */ OTFT_DEF(0x939A, 2) /* jp90 */ OTFT_DEF(0x9453, 2) /* jp90 */ OTFT_DEF(0x9699, 2) /* jp90 */ OTFT_DEF(0x9771, 2) /* jp90 */ OTFT_DEF(0x9784, 2) /* jp90 */ OTFT_DEF(0x9798, 2) /* jp90 */ OTFT_DEF(0x97AD, 2) /* jp90 */ OTFT_DEF(0x983B, 1) /* jp78 */ OTFT_DEF(0x98F4, 2) /* jp90 */ OTFT_DEF(0x9905, 2) /* jp90 */ OTFT_DEF(0x990C, 2) /* jp90 */ OTFT_DEF(0x9910, 2) /* jp90 */ OTFT_DEF(0x9957, 2) /* jp90 */ OTFT_DEF(0x99C1, 2) /* jp90 */ OTFT_DEF(0x9A19, 2) /* jp90 */ OTFT_DEF(0x9A4A, 2) /* jp90 */ OTFT_DEF(0x9BAB, 2) /* jp90 */ OTFT_DEF(0x9BD6, 2) /* jp90 */ OTFT_DEF(0x9C2F, 2) /* jp90 */ OTFT_DEF(0x9C52, 2) /* jp90 */ OTFT_DEF(0x9D09, 2) /* jp90 */ OTFT_DEF(0x9D60, 2) /* jp90 */ OTFT_DEF_END(181) OTFT_DEF_BEGIN(181) /* E0101 */ OTFT_DEF(0x5026, 3) /* jp04 */ OTFT_DEF(0x50C5, 3) /* jp04 */ OTFT_DEF(0x5132, 3) /* jp04 */ OTFT_DEF(0x514E, 3) /* jp04 */ OTFT_DEF(0x5189, 1) /* jp78 */ OTFT_DEF(0x51A4, 1) /* jp78 */ OTFT_DEF(0x51CB, 1) /* jp78 */ OTFT_DEF(0x5275, 1) /* jp78 */ OTFT_DEF(0x537F, 2) /* jp90 */ OTFT_DEF(0x53A9, 1) /* jp78 */ OTFT_DEF(0x53C9, 3) /* jp04 */ OTFT_DEF(0x53DB, 3) /* jp04 */ OTFT_DEF(0x53DF, 3) /* jp04 */ OTFT_DEF(0x54AC, 3) /* jp04 */ OTFT_DEF(0x54E8, 3) /* jp04 */ OTFT_DEF(0x5533, 1) /* jp78 */ OTFT_DEF(0x5539, 1) /* jp78 */ OTFT_DEF(0x5544, 1) /* jp78 */ OTFT_DEF(0x559D, 1) /* jp78 */ OTFT_DEF(0x55B0, 3) /* jp04 */ OTFT_DEF(0x5632, 3) /* jp04 */ OTFT_DEF(0x5642, 3) /* jp04 */ OTFT_DEF(0x564C, 3) /* jp04 */ OTFT_DEF(0x5678, 1) /* jp78 */ OTFT_DEF(0x56A5, 1) /* jp78 */ OTFT_DEF(0x56C0, 3) /* jp04 */ OTFT_DEF(0x580B, 1) /* jp78 */ OTFT_DEF(0x5835, 3) /* jp04 */ OTFT_DEF(0x5858, 1) /* jp78 */ OTFT_DEF(0x585A, 1) /* jp78 */ OTFT_DEF(0x5906, 3) /* jp04 */ OTFT_DEF(0x5A29, 3) /* jp04 */ OTFT_DEF(0x5A9B, 1) /* jp78 */ OTFT_DEF(0x5ABE, 1) /* jp78 */ OTFT_DEF(0x5ACC, 1) /* jp78 */ OTFT_DEF(0x5C51, 3) /* jp04 */ OTFT_DEF(0x5C60, 1) /* jp78 */ OTFT_DEF(0x5DF7, 3) /* jp04 */ OTFT_DEF(0x5E96, 3) /* jp04 */ OTFT_DEF(0x5EDF, 3) /* jp04 */ OTFT_DEF(0x5EE0, 1) /* jp78 */ OTFT_DEF(0x5EFB, 3) /* jp04 */ OTFT_DEF(0x5F98, 3) /* jp04 */ OTFT_DEF(0x5FBD, 3) /* jp04 */ OTFT_DEF(0x6062, 1) /* jp78 */ OTFT_DEF(0x6097, 1) /* jp78 */ OTFT_DEF(0x609E, 3) /* jp04 */ OTFT_DEF(0x6108, 3) /* jp04 */ OTFT_DEF(0x6167, 1) /* jp78 */ OTFT_DEF(0x61F2, 2) /* jp90 */ OTFT_DEF(0x6241, 3) /* jp04 */ OTFT_DEF(0x6248, 1) /* jp78 */ OTFT_DEF(0x6249, 1) /* jp78 */ OTFT_DEF(0x62D0, 1) /* jp78 */ OTFT_DEF(0x633A, 3) /* jp04 */ OTFT_DEF(0x633D, 3) /* jp04 */ OTFT_DEF(0x6357, 3) /* jp04 */ OTFT_DEF(0x6369, 1) /* jp78 */ OTFT_DEF(0x6372, 3) /* jp04 */ OTFT_DEF(0x63C3, 3) /* jp04 */ OTFT_DEF(0x6406, 1) /* jp78 */ OTFT_DEF(0x646F, 3) /* jp04 */ OTFT_DEF(0x647A, 3) /* jp04 */ OTFT_DEF(0x64B0, 3) /* jp04 */ OTFT_DEF(0x64E2, 3) /* jp04 */ OTFT_DEF(0x6583, 1) /* jp78 */ OTFT_DEF(0x65A7, 3) /* jp04 */ OTFT_DEF(0x6666, 3) /* jp04 */ OTFT_DEF(0x66B5, 3) /* jp04 */ OTFT_DEF(0x66D9, 1) /* jp78 */ OTFT_DEF(0x6753, 1) /* jp78 */ OTFT_DEF(0x6756, 3) /* jp04 */ OTFT_DEF(0x67A6, 1) /* jp78 */ OTFT_DEF(0x67CA, 1) /* jp78 */ OTFT_DEF(0x6813, 1) /* jp78 */ OTFT_DEF(0x6897, 3) /* jp04 */ OTFT_DEF(0x689B, 1) /* jp78 */ OTFT_DEF(0x68A2, 1) /* jp78 */ OTFT_DEF(0x68DA, 1) /* jp78 */ OTFT_DEF(0x6962, 3) /* jp04 */ OTFT_DEF(0x696F, 3) /* jp04 */ OTFT_DEF(0x698A, 3) /* jp04 */ OTFT_DEF(0x6994, 3) /* jp04 */ OTFT_DEF(0x69CC, 3) /* jp04 */ OTFT_DEF(0x6A0B, 3) /* jp04 */ OTFT_DEF(0x6A3D, 3) /* jp04 */ OTFT_DEF(0x6ADB, 2) /* jp90 */ OTFT_DEF(0x6B1D, 1) /* jp78 */ OTFT_DEF(0x6B4E, 3) /* jp04 */ OTFT_DEF(0x6C72, 3) /* jp04 */ OTFT_DEF(0x6CE1, 1) /* jp78 */ OTFT_DEF(0x6DEB, 3) /* jp04 */ OTFT_DEF(0x6E6E, 1) /* jp78 */ OTFT_DEF(0x6E9D, 1) /* jp78 */ OTFT_DEF(0x6EA2, 3) /* jp04 */ OTFT_DEF(0x6EBA, 1) /* jp78 */ OTFT_DEF(0x6F23, 2) /* jp90 */ OTFT_DEF(0x6FEF, 1) /* jp78 */ OTFT_DEF(0x7015, 3) /* jp04 */ OTFT_DEF(0x701E, 3) /* jp04 */ OTFT_DEF(0x7026, 3) /* jp04 */ OTFT_DEF(0x7058, 3) /* jp04 */ OTFT_DEF(0x7078, 3) /* jp04 */ OTFT_DEF(0x707C, 3) /* jp04 */ OTFT_DEF(0x7149, 2) /* jp90 */ OTFT_DEF(0x714E, 3) /* jp04 */ OTFT_DEF(0x7152, 3) /* jp04 */ OTFT_DEF(0x717D, 1) /* jp78 */ OTFT_DEF(0x7194, 1) /* jp78 */ OTFT_DEF(0x723A, 3) /* jp04 */ OTFT_DEF(0x724C, 3) /* jp04 */ OTFT_DEF(0x7259, 3) /* jp04 */ OTFT_DEF(0x72E1, 3) /* jp04 */ OTFT_DEF(0x7337, 1) /* jp78 */ OTFT_DEF(0x73CA, 1) /* jp78 */ OTFT_DEF(0x73CE, 1) /* jp78 */ OTFT_DEF(0x7504, 1) /* jp78 */ OTFT_DEF(0x750D, 1) /* jp78 */ OTFT_DEF(0x7511, 1) /* jp78 */ OTFT_DEF(0x7515, 1) /* jp78 */ OTFT_DEF(0x7526, 3) /* jp04 */ OTFT_DEF(0x75BC, 3) /* jp04 */ OTFT_DEF(0x7626, 1) /* jp78 */ OTFT_DEF(0x7652, 1) /* jp78 */ OTFT_DEF(0x7693, 1) /* jp78 */ OTFT_DEF(0x77A5, 3) /* jp04 */ OTFT_DEF(0x787C, 1) /* jp78 */ OTFT_DEF(0x7941, 3) /* jp04 */ OTFT_DEF(0x7947, 3) /* jp04 */ OTFT_DEF(0x79B0, 3) /* jp04 */ OTFT_DEF(0x79E4, 3) /* jp04 */ OTFT_DEF(0x7A17, 3) /* jp04 */ OTFT_DEF(0x7A31, 1) /* jp78 */ OTFT_DEF(0x7A7F, 3) /* jp04 */ OTFT_DEF(0x7AC8, 3) /* jp04 */ OTFT_DEF(0x7B75, 3) /* jp04 */ OTFT_DEF(0x7B99, 1) /* jp78 */ OTFT_DEF(0x7BAD, 3) /* jp04 */ OTFT_DEF(0x7BB8, 3) /* jp04 */ OTFT_DEF(0x7BC7, 3) /* jp04 */ OTFT_DEF(0x7BDD, 3) /* jp04 */ OTFT_DEF(0x7C7E, 1) /* jp78 */ OTFT_DEF(0x7C82, 3) /* jp04 */ OTFT_DEF(0x7C90, 1) /* jp78 */ OTFT_DEF(0x7CAE, 1) /* jp78 */ OTFT_DEF(0x7D9B, 1) /* jp78 */ OTFT_DEF(0x7D9F, 1) /* jp78 */ OTFT_DEF(0x7DAE, 1) /* jp78 */ OTFT_DEF(0x7FD4, 1) /* jp78 */ OTFT_DEF(0x7FE0, 1) /* jp78 */ OTFT_DEF(0x7FEB, 3) /* jp04 */ OTFT_DEF(0x7FF0, 3) /* jp04 */ OTFT_DEF(0x8000, 1) /* jp78 */ OTFT_DEF(0x8171, 3) /* jp04 */ OTFT_DEF(0x817F, 3) /* jp04 */ OTFT_DEF(0x822E, 1) /* jp78 */ OTFT_DEF(0x8258, 3) /* jp04 */ OTFT_DEF(0x828D, 1) /* jp78 */ OTFT_DEF(0x8292, 3) /* jp04 */ OTFT_DEF(0x82A6, 3) /* jp04 */ OTFT_DEF(0x82D2, 1) /* jp78 */ OTFT_DEF(0x8323, 1) /* jp78 */ OTFT_DEF(0x8328, 3) /* jp04 */ OTFT_DEF(0x8375, 1) /* jp78 */ OTFT_DEF(0x83DF, 1) /* jp78 */ OTFT_DEF(0x845B, 3) /* jp04 */ OTFT_DEF(0x84EC, 3) /* jp04 */ OTFT_DEF(0x8511, 3) /* jp04 */ OTFT_DEF(0x8517, 1) /* jp78 */ OTFT_DEF(0x853D, 3) /* jp04 */ OTFT_DEF(0x85A9, 3) /* jp04 */ OTFT_DEF(0x85AF, 3) /* jp04 */ OTFT_DEF(0x85F7, 3) /* jp04 */ OTFT_DEF(0x8612, 2) /* jp90 */ OTFT_DEF(0x8654, 3) /* jp04 */ OTFT_DEF(0x86F8, 3) /* jp04 */ OTFT_DEF(0x8703, 3) /* jp04 */ OTFT_DEF(0x8755, 3) /* jp04 */ OTFT_DEF(0x8782, 1) /* jp78 */ OTFT_DEF(0x87D2, 1) /* jp78 */ OTFT_DEF(0x890A, 1) /* jp78 */ OTFT_DEF(0x8956, 3) /* jp04 */ OTFT_DEF(0x89AF, 1) /* jp78 */ OTFT_DEF(0x8A0A, 3) /* jp04 */ OTFT_DEF(0x8A3B, 3) /* jp04 */ OTFT_DEF(0x8A6E, 3) /* jp04 */ OTFT_DEF(0x8AB9, 3) /* jp04 */ OTFT_DEF(0x8ADE, 1) /* jp78 */ OTFT_DEF(0x8AFA, 3) /* jp04 */ OTFT_DEF(0x8B0E, 3) /* jp04 */ OTFT_DEF(0x8B2C, 3) /* jp04 */ OTFT_DEF(0x8B41, 1) /* jp78 */ OTFT_DEF(0x8B7F, 3) /* jp04 */ OTFT_DEF(0x8C79, 3) /* jp04 */ OTFT_DEF(0x8CED, 3) /* jp04 */ OTFT_DEF(0x8DDA, 1) /* jp78 */ OTFT_DEF(0x8E09, 1) /* jp78 */ OTFT_DEF(0x8F13, 1) /* jp78 */ OTFT_DEF(0x8FBF, 3) /* jp04 */ OTFT_DEF(0x8FC2, 3) /* jp04 */ OTFT_DEF(0x8FC4, 3) /* jp04 */ OTFT_DEF(0x8FE6, 3) /* jp04 */ OTFT_DEF(0x8FE9, 1) /* jp78 */ OTFT_DEF(0x8FEA, 1) /* jp78 */ OTFT_DEF(0x9017, 3) /* jp04 */ OTFT_DEF(0x9019, 3) /* jp04 */ OTFT_DEF(0x901D, 1) /* jp78 */ OTFT_DEF(0x903C, 3) /* jp04 */ OTFT_DEF(0x9041, 1) /* jp78 */ OTFT_DEF(0x9058, 1) /* jp78 */ OTFT_DEF(0x905C, 3) /* jp04 */ OTFT_DEF(0x9061, 3) /* jp04 */ OTFT_DEF(0x906E, 1) /* jp78 */ OTFT_DEF(0x907C, 1) /* jp78 */ OTFT_DEF(0x90A3, 1) /* jp78 */ OTFT_DEF(0x912D, 3) /* jp04 */ OTFT_DEF(0x914B, 3) /* jp04 */ OTFT_DEF(0x91C1, 1) /* jp78 */ OTFT_DEF(0x91C7, 1) /* jp78 */ OTFT_DEF(0x91DC, 3) /* jp04 */ OTFT_DEF(0x9306, 3) /* jp04 */ OTFT_DEF(0x9375, 3) /* jp04 */ OTFT_DEF(0x939A, 3) /* jp04 */ OTFT_DEF(0x9453, 3) /* jp04 */ OTFT_DEF(0x9699, 3) /* jp04 */ OTFT_DEF(0x9724, 1) /* jp78 */ OTFT_DEF(0x9760, 1) /* jp78 */ OTFT_DEF(0x976D, 1) /* jp78 */ OTFT_DEF(0x9771, 1) /* jp78 */ OTFT_DEF(0x9774, 1) /* jp78 */ OTFT_DEF(0x9784, 3) /* jp04 */ OTFT_DEF(0x9798, 3) /* jp04 */ OTFT_DEF(0x97AD, 3) /* jp04 */ OTFT_DEF(0x9813, 1) /* jp78 */ OTFT_DEF(0x9824, 1) /* jp78 */ OTFT_DEF(0x98F4, 3) /* jp04 */ OTFT_DEF(0x9905, 3) /* jp04 */ OTFT_DEF(0x990C, 1) /* jp78 */ OTFT_DEF(0x9910, 3) /* jp04 */ OTFT_DEF(0x9957, 3) /* jp04 */ OTFT_DEF(0x99C1, 3) /* jp04 */ OTFT_DEF(0x9A19, 3) /* jp04 */ OTFT_DEF(0x9A4A, 3) /* jp04 */ OTFT_DEF(0x9B2E, 1) /* jp78 */ OTFT_DEF(0x9B97, 1) /* jp78 */ OTFT_DEF(0x9BAB, 3) /* jp04 */ OTFT_DEF(0x9BD6, 3) /* jp04 */ OTFT_DEF(0x9BF2, 1) /* jp78 */ OTFT_DEF(0x9C2F, 3) /* jp04 */ OTFT_DEF(0x9C48, 1) /* jp78 */ OTFT_DEF(0x9C52, 3) /* jp04 */ OTFT_DEF(0x9D07, 1) /* jp78 */ OTFT_DEF(0x9D09, 3) /* jp04 */ OTFT_DEF(0x9D60, 3) /* jp04 */ OTFT_DEF(0x9EAA, 1) /* jp78 */ OTFT_DEF(0x9EDB, 1) /* jp78 */ OTFT_DEF(0x9F9C, 1) /* jp78 */ OTFT_DEF(0x9F9D, 1) /* jp78 */ OTFT_DEF_END(258) OTFT_DEF_BEGIN(439) /* E0102 */ OTFT_DEF(0x537F, 3) /* jp04 */ OTFT_DEF(0x6062, 3) /* jp04 */ OTFT_DEF(0x717D, 3) /* jp04 */ OTFT_DEF(0x7337, 3) /* jp04 */ OTFT_DEF(0x7515, 3) /* jp04 */ OTFT_DEF(0x7B08, 3) /* jp04 */ OTFT_DEF(0x7C3E, 3) /* jp04 */ OTFT_DEF(0x7C7E, 3) /* jp04 */ OTFT_DEF(0x8612, 3) /* jp04 */ OTFT_DEF(0x8805, 3) /* jp04 */ OTFT_DEF(0x8A1D, 3) /* jp04 */ OTFT_DEF(0x9041, 3) /* jp04 */ OTFT_DEF(0x9771, 3) /* jp04 */ OTFT_DEF_END(13) OTFT_DEF_BEGIN(452) /* E0103 */ OTFT_DEF(0x61F2, 3) /* jp04 */ OTFT_DEF(0x7511, 3) /* jp04 */ OTFT_DEF(0x990C, 3) /* jp04 */ OTFT_DEF_END(3) OTFT_DEF_BEGIN(455) /* E0104 */ OTFT_DEF_END(0) OTFT_DEF_BEGIN(455) /* E0105 */ OTFT_DEF(0x53A9, 3) /* jp04 */ OTFT_DEF_END(1) ================================================ FILE: json.hpp ================================================ /* __ _____ _____ _____ __| | __| | | | JSON for Modern C++ | | |__ | | | | | | version 3.10.5 |_____|_____|_____|_|___| https://github.com/nlohmann/json Licensed under the MIT License . SPDX-License-Identifier: MIT Copyright (c) 2013-2022 Niels Lohmann . Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /****************************************************************************\ * Note on documentation: The source files contain links to the online * * documentation of the public API at https://json.nlohmann.me. This URL * * contains the most recent documentation and should also be applicable to * * previous versions; documentation for deprecated functions is not * * removed, but marked deprecated. See "Generate documentation" section in * * file doc/README.md. * \****************************************************************************/ #ifndef INCLUDE_NLOHMANN_JSON_HPP_ #define INCLUDE_NLOHMANN_JSON_HPP_ #define NLOHMANN_JSON_VERSION_MAJOR 3 #define NLOHMANN_JSON_VERSION_MINOR 10 #define NLOHMANN_JSON_VERSION_PATCH 5 #include // all_of, find, for_each #include // nullptr_t, ptrdiff_t, size_t #include // hash, less #include // initializer_list #ifndef JSON_NO_IO #include // istream, ostream #endif // JSON_NO_IO #include // random_access_iterator_tag #include // unique_ptr #include // accumulate #include // string, stoi, to_string #include // declval, forward, move, pair, swap #include // vector // #include #include #include // #include #include // transform #include // array #include // forward_list #include // inserter, front_inserter, end #include // map #include // string #include // tuple, make_tuple #include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible #include // unordered_map #include // pair, declval #include // valarray // #include #include // exception #include // runtime_error #include // to_string #include // vector // #include #include // array #include // size_t #include // uint8_t #include // string namespace nlohmann { namespace detail { /////////////////////////// // JSON type enumeration // /////////////////////////// /*! @brief the JSON type enumeration This enumeration collects the different JSON types. It is internally used to distinguish the stored values, and the functions @ref basic_json::is_null(), @ref basic_json::is_object(), @ref basic_json::is_array(), @ref basic_json::is_string(), @ref basic_json::is_boolean(), @ref basic_json::is_number() (with @ref basic_json::is_number_integer(), @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and @ref basic_json::is_structured() rely on it. @note There are three enumeration entries (number_integer, number_unsigned, and number_float), because the library distinguishes these three types for numbers: @ref basic_json::number_unsigned_t is used for unsigned integers, @ref basic_json::number_integer_t is used for signed integers, and @ref basic_json::number_float_t is used for floating-point numbers or to approximate integers which do not fit in the limits of their respective type. @sa see @ref basic_json::basic_json(const value_t value_type) -- create a JSON value with the default value for a given type @since version 1.0.0 */ enum class value_t : std::uint8_t { null, ///< null value object, ///< object (unordered set of name/value pairs) array, ///< array (ordered collection of values) string, ///< string value boolean, ///< boolean value number_integer, ///< number value (signed integer) number_unsigned, ///< number value (unsigned integer) number_float, ///< number value (floating-point) binary, ///< binary array (ordered collection of bytes) discarded ///< discarded by the parser callback function }; /*! @brief comparison operator for JSON types Returns an ordering that is similar to Python: - order: null < boolean < number < object < array < string < binary - furthermore, each type is not smaller than itself - discarded values are not comparable - binary is represented as a b"" string in python and directly comparable to a string; however, making a binary array directly comparable with a string would be surprising behavior in a JSON file. @since version 1.0.0 */ inline bool operator<(const value_t lhs, const value_t rhs) noexcept { static constexpr std::array order = {{ 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */, 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */, 6 /* binary */ } }; const auto l_index = static_cast(lhs); const auto r_index = static_cast(rhs); return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index]; } } // namespace detail } // namespace nlohmann // #include #include // #include #include // declval, pair // #include /* Hedley - https://nemequ.github.io/hedley * Created by Evan Nemerson * * To the extent possible under law, the author(s) have dedicated all * copyright and related and neighboring rights to this software to * the public domain worldwide. This software is distributed without * any warranty. * * For details, see . * SPDX-License-Identifier: CC0-1.0 */ #if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 15) #if defined(JSON_HEDLEY_VERSION) #undef JSON_HEDLEY_VERSION #endif #define JSON_HEDLEY_VERSION 15 #if defined(JSON_HEDLEY_STRINGIFY_EX) #undef JSON_HEDLEY_STRINGIFY_EX #endif #define JSON_HEDLEY_STRINGIFY_EX(x) #x #if defined(JSON_HEDLEY_STRINGIFY) #undef JSON_HEDLEY_STRINGIFY #endif #define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x) #if defined(JSON_HEDLEY_CONCAT_EX) #undef JSON_HEDLEY_CONCAT_EX #endif #define JSON_HEDLEY_CONCAT_EX(a,b) a##b #if defined(JSON_HEDLEY_CONCAT) #undef JSON_HEDLEY_CONCAT #endif #define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b) #if defined(JSON_HEDLEY_CONCAT3_EX) #undef JSON_HEDLEY_CONCAT3_EX #endif #define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c #if defined(JSON_HEDLEY_CONCAT3) #undef JSON_HEDLEY_CONCAT3 #endif #define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c) #if defined(JSON_HEDLEY_VERSION_ENCODE) #undef JSON_HEDLEY_VERSION_ENCODE #endif #define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision)) #if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR) #undef JSON_HEDLEY_VERSION_DECODE_MAJOR #endif #define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000) #if defined(JSON_HEDLEY_VERSION_DECODE_MINOR) #undef JSON_HEDLEY_VERSION_DECODE_MINOR #endif #define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000) #if defined(JSON_HEDLEY_VERSION_DECODE_REVISION) #undef JSON_HEDLEY_VERSION_DECODE_REVISION #endif #define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000) #if defined(JSON_HEDLEY_GNUC_VERSION) #undef JSON_HEDLEY_GNUC_VERSION #endif #if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__) #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) #elif defined(__GNUC__) #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0) #endif #if defined(JSON_HEDLEY_GNUC_VERSION_CHECK) #undef JSON_HEDLEY_GNUC_VERSION_CHECK #endif #if defined(JSON_HEDLEY_GNUC_VERSION) #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_MSVC_VERSION) #undef JSON_HEDLEY_MSVC_VERSION #endif #if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000) && !defined(__ICL) #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100) #elif defined(_MSC_FULL_VER) && !defined(__ICL) #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10) #elif defined(_MSC_VER) && !defined(__ICL) #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0) #endif #if defined(JSON_HEDLEY_MSVC_VERSION_CHECK) #undef JSON_HEDLEY_MSVC_VERSION_CHECK #endif #if !defined(JSON_HEDLEY_MSVC_VERSION) #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0) #elif defined(_MSC_VER) && (_MSC_VER >= 1400) #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch))) #elif defined(_MSC_VER) && (_MSC_VER >= 1200) #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch))) #else #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor))) #endif #if defined(JSON_HEDLEY_INTEL_VERSION) #undef JSON_HEDLEY_INTEL_VERSION #endif #if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && !defined(__ICL) #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE) #elif defined(__INTEL_COMPILER) && !defined(__ICL) #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0) #endif #if defined(JSON_HEDLEY_INTEL_VERSION_CHECK) #undef JSON_HEDLEY_INTEL_VERSION_CHECK #endif #if defined(JSON_HEDLEY_INTEL_VERSION) #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_INTEL_CL_VERSION) #undef JSON_HEDLEY_INTEL_CL_VERSION #endif #if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && defined(__ICL) #define JSON_HEDLEY_INTEL_CL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER, __INTEL_COMPILER_UPDATE, 0) #endif #if defined(JSON_HEDLEY_INTEL_CL_VERSION_CHECK) #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK #endif #if defined(JSON_HEDLEY_INTEL_CL_VERSION) #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_CL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_PGI_VERSION) #undef JSON_HEDLEY_PGI_VERSION #endif #if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__) #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__) #endif #if defined(JSON_HEDLEY_PGI_VERSION_CHECK) #undef JSON_HEDLEY_PGI_VERSION_CHECK #endif #if defined(JSON_HEDLEY_PGI_VERSION) #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_SUNPRO_VERSION) #undef JSON_HEDLEY_SUNPRO_VERSION #endif #if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000) #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), (__SUNPRO_C & 0xf) * 10) #elif defined(__SUNPRO_C) #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf) #elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000) #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), (__SUNPRO_CC & 0xf) * 10) #elif defined(__SUNPRO_CC) #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf) #endif #if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK) #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK #endif #if defined(JSON_HEDLEY_SUNPRO_VERSION) #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) #undef JSON_HEDLEY_EMSCRIPTEN_VERSION #endif #if defined(__EMSCRIPTEN__) #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__) #endif #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK) #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK #endif #if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_ARM_VERSION) #undef JSON_HEDLEY_ARM_VERSION #endif #if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION) #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100) #elif defined(__CC_ARM) && defined(__ARMCC_VERSION) #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100) #endif #if defined(JSON_HEDLEY_ARM_VERSION_CHECK) #undef JSON_HEDLEY_ARM_VERSION_CHECK #endif #if defined(JSON_HEDLEY_ARM_VERSION) #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_IBM_VERSION) #undef JSON_HEDLEY_IBM_VERSION #endif #if defined(__ibmxl__) #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__) #elif defined(__xlC__) && defined(__xlC_ver__) #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff) #elif defined(__xlC__) #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0) #endif #if defined(JSON_HEDLEY_IBM_VERSION_CHECK) #undef JSON_HEDLEY_IBM_VERSION_CHECK #endif #if defined(JSON_HEDLEY_IBM_VERSION) #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_TI_VERSION) #undef JSON_HEDLEY_TI_VERSION #endif #if \ defined(__TI_COMPILER_VERSION__) && \ ( \ defined(__TMS470__) || defined(__TI_ARM__) || \ defined(__MSP430__) || \ defined(__TMS320C2000__) \ ) #if (__TI_COMPILER_VERSION__ >= 16000000) #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) #endif #endif #if defined(JSON_HEDLEY_TI_VERSION_CHECK) #undef JSON_HEDLEY_TI_VERSION_CHECK #endif #if defined(JSON_HEDLEY_TI_VERSION) #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_TI_CL2000_VERSION) #undef JSON_HEDLEY_TI_CL2000_VERSION #endif #if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__) #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) #endif #if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK) #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK #endif #if defined(JSON_HEDLEY_TI_CL2000_VERSION) #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_TI_CL430_VERSION) #undef JSON_HEDLEY_TI_CL430_VERSION #endif #if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__) #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) #endif #if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK) #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK #endif #if defined(JSON_HEDLEY_TI_CL430_VERSION) #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_TI_ARMCL_VERSION) #undef JSON_HEDLEY_TI_ARMCL_VERSION #endif #if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__)) #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) #endif #if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK) #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK #endif #if defined(JSON_HEDLEY_TI_ARMCL_VERSION) #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_TI_CL6X_VERSION) #undef JSON_HEDLEY_TI_CL6X_VERSION #endif #if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__) #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) #endif #if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK) #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK #endif #if defined(JSON_HEDLEY_TI_CL6X_VERSION) #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_TI_CL7X_VERSION) #undef JSON_HEDLEY_TI_CL7X_VERSION #endif #if defined(__TI_COMPILER_VERSION__) && defined(__C7000__) #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) #endif #if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK) #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK #endif #if defined(JSON_HEDLEY_TI_CL7X_VERSION) #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_TI_CLPRU_VERSION) #undef JSON_HEDLEY_TI_CLPRU_VERSION #endif #if defined(__TI_COMPILER_VERSION__) && defined(__PRU__) #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) #endif #if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK) #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK #endif #if defined(JSON_HEDLEY_TI_CLPRU_VERSION) #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_CRAY_VERSION) #undef JSON_HEDLEY_CRAY_VERSION #endif #if defined(_CRAYC) #if defined(_RELEASE_PATCHLEVEL) #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL) #else #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0) #endif #endif #if defined(JSON_HEDLEY_CRAY_VERSION_CHECK) #undef JSON_HEDLEY_CRAY_VERSION_CHECK #endif #if defined(JSON_HEDLEY_CRAY_VERSION) #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_IAR_VERSION) #undef JSON_HEDLEY_IAR_VERSION #endif #if defined(__IAR_SYSTEMS_ICC__) #if __VER__ > 1000 #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000)) #else #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(__VER__ / 100, __VER__ % 100, 0) #endif #endif #if defined(JSON_HEDLEY_IAR_VERSION_CHECK) #undef JSON_HEDLEY_IAR_VERSION_CHECK #endif #if defined(JSON_HEDLEY_IAR_VERSION) #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_TINYC_VERSION) #undef JSON_HEDLEY_TINYC_VERSION #endif #if defined(__TINYC__) #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100) #endif #if defined(JSON_HEDLEY_TINYC_VERSION_CHECK) #undef JSON_HEDLEY_TINYC_VERSION_CHECK #endif #if defined(JSON_HEDLEY_TINYC_VERSION) #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_DMC_VERSION) #undef JSON_HEDLEY_DMC_VERSION #endif #if defined(__DMC__) #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf) #endif #if defined(JSON_HEDLEY_DMC_VERSION_CHECK) #undef JSON_HEDLEY_DMC_VERSION_CHECK #endif #if defined(JSON_HEDLEY_DMC_VERSION) #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_COMPCERT_VERSION) #undef JSON_HEDLEY_COMPCERT_VERSION #endif #if defined(__COMPCERT_VERSION__) #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100) #endif #if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK) #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK #endif #if defined(JSON_HEDLEY_COMPCERT_VERSION) #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_PELLES_VERSION) #undef JSON_HEDLEY_PELLES_VERSION #endif #if defined(__POCC__) #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0) #endif #if defined(JSON_HEDLEY_PELLES_VERSION_CHECK) #undef JSON_HEDLEY_PELLES_VERSION_CHECK #endif #if defined(JSON_HEDLEY_PELLES_VERSION) #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_MCST_LCC_VERSION) #undef JSON_HEDLEY_MCST_LCC_VERSION #endif #if defined(__LCC__) && defined(__LCC_MINOR__) #define JSON_HEDLEY_MCST_LCC_VERSION JSON_HEDLEY_VERSION_ENCODE(__LCC__ / 100, __LCC__ % 100, __LCC_MINOR__) #endif #if defined(JSON_HEDLEY_MCST_LCC_VERSION_CHECK) #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK #endif #if defined(JSON_HEDLEY_MCST_LCC_VERSION) #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_MCST_LCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_GCC_VERSION) #undef JSON_HEDLEY_GCC_VERSION #endif #if \ defined(JSON_HEDLEY_GNUC_VERSION) && \ !defined(__clang__) && \ !defined(JSON_HEDLEY_INTEL_VERSION) && \ !defined(JSON_HEDLEY_PGI_VERSION) && \ !defined(JSON_HEDLEY_ARM_VERSION) && \ !defined(JSON_HEDLEY_CRAY_VERSION) && \ !defined(JSON_HEDLEY_TI_VERSION) && \ !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \ !defined(JSON_HEDLEY_TI_CL430_VERSION) && \ !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \ !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \ !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \ !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \ !defined(__COMPCERT__) && \ !defined(JSON_HEDLEY_MCST_LCC_VERSION) #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION #endif #if defined(JSON_HEDLEY_GCC_VERSION_CHECK) #undef JSON_HEDLEY_GCC_VERSION_CHECK #endif #if defined(JSON_HEDLEY_GCC_VERSION) #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) #else #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0) #endif #if defined(JSON_HEDLEY_HAS_ATTRIBUTE) #undef JSON_HEDLEY_HAS_ATTRIBUTE #endif #if \ defined(__has_attribute) && \ ( \ (!defined(JSON_HEDLEY_IAR_VERSION) || JSON_HEDLEY_IAR_VERSION_CHECK(8,5,9)) \ ) # define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute) #else # define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0) #endif #if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE) #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE #endif #if defined(__has_attribute) #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) #else #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE) #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE #endif #if defined(__has_attribute) #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) #else #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE) #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE #endif #if \ defined(__has_cpp_attribute) && \ defined(__cplusplus) && \ (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute) #else #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0) #endif #if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS) #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS #endif #if !defined(__cplusplus) || !defined(__has_cpp_attribute) #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) #elif \ !defined(JSON_HEDLEY_PGI_VERSION) && \ !defined(JSON_HEDLEY_IAR_VERSION) && \ (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \ (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0)) #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute) #else #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) #endif #if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE) #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE #endif #if defined(__has_cpp_attribute) && defined(__cplusplus) #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) #else #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE) #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE #endif #if defined(__has_cpp_attribute) && defined(__cplusplus) #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) #else #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_HAS_BUILTIN) #undef JSON_HEDLEY_HAS_BUILTIN #endif #if defined(__has_builtin) #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin) #else #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0) #endif #if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN) #undef JSON_HEDLEY_GNUC_HAS_BUILTIN #endif #if defined(__has_builtin) #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) #else #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_GCC_HAS_BUILTIN) #undef JSON_HEDLEY_GCC_HAS_BUILTIN #endif #if defined(__has_builtin) #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) #else #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_HAS_FEATURE) #undef JSON_HEDLEY_HAS_FEATURE #endif #if defined(__has_feature) #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature) #else #define JSON_HEDLEY_HAS_FEATURE(feature) (0) #endif #if defined(JSON_HEDLEY_GNUC_HAS_FEATURE) #undef JSON_HEDLEY_GNUC_HAS_FEATURE #endif #if defined(__has_feature) #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) #else #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_GCC_HAS_FEATURE) #undef JSON_HEDLEY_GCC_HAS_FEATURE #endif #if defined(__has_feature) #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) #else #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_HAS_EXTENSION) #undef JSON_HEDLEY_HAS_EXTENSION #endif #if defined(__has_extension) #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension) #else #define JSON_HEDLEY_HAS_EXTENSION(extension) (0) #endif #if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION) #undef JSON_HEDLEY_GNUC_HAS_EXTENSION #endif #if defined(__has_extension) #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) #else #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_GCC_HAS_EXTENSION) #undef JSON_HEDLEY_GCC_HAS_EXTENSION #endif #if defined(__has_extension) #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) #else #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE) #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE #endif #if defined(__has_declspec_attribute) #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute) #else #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0) #endif #if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE) #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE #endif #if defined(__has_declspec_attribute) #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) #else #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE) #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE #endif #if defined(__has_declspec_attribute) #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) #else #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_HAS_WARNING) #undef JSON_HEDLEY_HAS_WARNING #endif #if defined(__has_warning) #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning) #else #define JSON_HEDLEY_HAS_WARNING(warning) (0) #endif #if defined(JSON_HEDLEY_GNUC_HAS_WARNING) #undef JSON_HEDLEY_GNUC_HAS_WARNING #endif #if defined(__has_warning) #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) #else #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_GCC_HAS_WARNING) #undef JSON_HEDLEY_GCC_HAS_WARNING #endif #if defined(__has_warning) #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) #else #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) #endif #if \ (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ defined(__clang__) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \ JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \ (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR)) #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value) #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) #define JSON_HEDLEY_PRAGMA(value) __pragma(value) #else #define JSON_HEDLEY_PRAGMA(value) #endif #if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH) #undef JSON_HEDLEY_DIAGNOSTIC_PUSH #endif #if defined(JSON_HEDLEY_DIAGNOSTIC_POP) #undef JSON_HEDLEY_DIAGNOSTIC_POP #endif #if defined(__clang__) #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push") #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop") #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push") #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop") #elif \ JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push)) #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop)) #elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push") #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop") #elif \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push") #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop") #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") #else #define JSON_HEDLEY_DIAGNOSTIC_PUSH #define JSON_HEDLEY_DIAGNOSTIC_POP #endif /* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ #endif #if defined(__cplusplus) # if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat") # if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions") # if JSON_HEDLEY_HAS_WARNING("-Wc++1z-extensions") # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ _Pragma("clang diagnostic ignored \"-Wc++1z-extensions\"") \ xpr \ JSON_HEDLEY_DIAGNOSTIC_POP # else # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ xpr \ JSON_HEDLEY_DIAGNOSTIC_POP # endif # else # define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ xpr \ JSON_HEDLEY_DIAGNOSTIC_POP # endif # endif #endif #if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x #endif #if defined(JSON_HEDLEY_CONST_CAST) #undef JSON_HEDLEY_CONST_CAST #endif #if defined(__cplusplus) # define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast(expr)) #elif \ JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) # define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \ ((T) (expr)); \ JSON_HEDLEY_DIAGNOSTIC_POP \ })) #else # define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr)) #endif #if defined(JSON_HEDLEY_REINTERPRET_CAST) #undef JSON_HEDLEY_REINTERPRET_CAST #endif #if defined(__cplusplus) #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast(expr)) #else #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr)) #endif #if defined(JSON_HEDLEY_STATIC_CAST) #undef JSON_HEDLEY_STATIC_CAST #endif #if defined(__cplusplus) #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast(expr)) #else #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr)) #endif #if defined(JSON_HEDLEY_CPP_CAST) #undef JSON_HEDLEY_CPP_CAST #endif #if defined(__cplusplus) # if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast") # define JSON_HEDLEY_CPP_CAST(T, expr) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \ ((T) (expr)) \ JSON_HEDLEY_DIAGNOSTIC_POP # elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0) # define JSON_HEDLEY_CPP_CAST(T, expr) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("diag_suppress=Pe137") \ JSON_HEDLEY_DIAGNOSTIC_POP # else # define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr)) # endif #else # define JSON_HEDLEY_CPP_CAST(T, expr) (expr) #endif #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED) #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED #endif #if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations") #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)") #elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:1478 1786)) #elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1216,1444,1445") #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996)) #elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") #elif \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718") #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)") #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)") #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215") #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)") #else #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED #endif #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS) #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS #endif #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"") #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)") #elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:161)) #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675") #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"") #elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068)) #elif \ JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161") #elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 161") #else #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS #endif #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES) #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES #endif #if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes") #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"") #elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") #elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)") #elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:1292)) #elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030)) #elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097,1098") #elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)") #elif \ JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173") #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097") #elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") #else #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES #endif #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL) #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL #endif #if JSON_HEDLEY_HAS_WARNING("-Wcast-qual") #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"") #elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)") #elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"") #else #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL #endif #if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION) #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION #endif #if JSON_HEDLEY_HAS_WARNING("-Wunused-function") #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("clang diagnostic ignored \"-Wunused-function\"") #elif JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("GCC diagnostic ignored \"-Wunused-function\"") #elif JSON_HEDLEY_MSVC_VERSION_CHECK(1,0,0) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION __pragma(warning(disable:4505)) #elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("diag_suppress 3142") #else #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION #endif #if defined(JSON_HEDLEY_DEPRECATED) #undef JSON_HEDLEY_DEPRECATED #endif #if defined(JSON_HEDLEY_DEPRECATED_FOR) #undef JSON_HEDLEY_DEPRECATED_FOR #endif #if \ JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since)) #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement)) #elif \ (JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \ JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since))) #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement))) #elif defined(__cplusplus) && (__cplusplus >= 201402L) #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]]) #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]]) #elif \ JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__)) #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__)) #elif \ JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated) #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated) #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated") #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated") #else #define JSON_HEDLEY_DEPRECATED(since) #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) #endif #if defined(JSON_HEDLEY_UNAVAILABLE) #undef JSON_HEDLEY_UNAVAILABLE #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since))) #else #define JSON_HEDLEY_UNAVAILABLE(available_since) #endif #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT) #undef JSON_HEDLEY_WARN_UNUSED_RESULT #endif #if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG) #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__)) #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__)) #elif (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L) #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]]) #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) #elif defined(_Check_return_) /* SAL */ #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_ #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_ #else #define JSON_HEDLEY_WARN_UNUSED_RESULT #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) #endif #if defined(JSON_HEDLEY_SENTINEL) #undef JSON_HEDLEY_SENTINEL #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position))) #else #define JSON_HEDLEY_SENTINEL(position) #endif #if defined(JSON_HEDLEY_NO_RETURN) #undef JSON_HEDLEY_NO_RETURN #endif #if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) #define JSON_HEDLEY_NO_RETURN __noreturn #elif \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) #elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L #define JSON_HEDLEY_NO_RETURN _Noreturn #elif defined(__cplusplus) && (__cplusplus >= 201103L) #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]]) #elif \ JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return") #elif \ JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;") #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) #define JSON_HEDLEY_NO_RETURN __attribute((noreturn)) #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) #else #define JSON_HEDLEY_NO_RETURN #endif #if defined(JSON_HEDLEY_NO_ESCAPE) #undef JSON_HEDLEY_NO_ESCAPE #endif #if JSON_HEDLEY_HAS_ATTRIBUTE(noescape) #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__)) #else #define JSON_HEDLEY_NO_ESCAPE #endif #if defined(JSON_HEDLEY_UNREACHABLE) #undef JSON_HEDLEY_UNREACHABLE #endif #if defined(JSON_HEDLEY_UNREACHABLE_RETURN) #undef JSON_HEDLEY_UNREACHABLE_RETURN #endif #if defined(JSON_HEDLEY_ASSUME) #undef JSON_HEDLEY_ASSUME #endif #if \ JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) #define JSON_HEDLEY_ASSUME(expr) __assume(expr) #elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume) #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr) #elif \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) #if defined(__cplusplus) #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr) #else #define JSON_HEDLEY_ASSUME(expr) _nassert(expr) #endif #endif #if \ (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5) || \ JSON_HEDLEY_CRAY_VERSION_CHECK(10,0,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable() #elif defined(JSON_HEDLEY_ASSUME) #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) #endif #if !defined(JSON_HEDLEY_ASSUME) #if defined(JSON_HEDLEY_UNREACHABLE) #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1))) #else #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr) #endif #endif #if defined(JSON_HEDLEY_UNREACHABLE) #if \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value)) #else #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE() #endif #else #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value) #endif #if !defined(JSON_HEDLEY_UNREACHABLE) #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) #endif JSON_HEDLEY_DIAGNOSTIC_PUSH #if JSON_HEDLEY_HAS_WARNING("-Wpedantic") #pragma clang diagnostic ignored "-Wpedantic" #endif #if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus) #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" #endif #if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0) #if defined(__clang__) #pragma clang diagnostic ignored "-Wvariadic-macros" #elif defined(JSON_HEDLEY_GCC_VERSION) #pragma GCC diagnostic ignored "-Wvariadic-macros" #endif #endif #if defined(JSON_HEDLEY_NON_NULL) #undef JSON_HEDLEY_NON_NULL #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__))) #else #define JSON_HEDLEY_NON_NULL(...) #endif JSON_HEDLEY_DIAGNOSTIC_POP #if defined(JSON_HEDLEY_PRINTF_FORMAT) #undef JSON_HEDLEY_PRINTF_FORMAT #endif #if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO) #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check))) #elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO) #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check))) #elif \ JSON_HEDLEY_HAS_ATTRIBUTE(format) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check))) #elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0) #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check)) #else #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) #endif #if defined(JSON_HEDLEY_CONSTEXPR) #undef JSON_HEDLEY_CONSTEXPR #endif #if defined(__cplusplus) #if __cplusplus >= 201103L #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr) #endif #endif #if !defined(JSON_HEDLEY_CONSTEXPR) #define JSON_HEDLEY_CONSTEXPR #endif #if defined(JSON_HEDLEY_PREDICT) #undef JSON_HEDLEY_PREDICT #endif #if defined(JSON_HEDLEY_LIKELY) #undef JSON_HEDLEY_LIKELY #endif #if defined(JSON_HEDLEY_UNLIKELY) #undef JSON_HEDLEY_UNLIKELY #endif #if defined(JSON_HEDLEY_UNPREDICTABLE) #undef JSON_HEDLEY_UNPREDICTABLE #endif #if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable) #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr)) #endif #if \ (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) && !defined(JSON_HEDLEY_PGI_VERSION)) || \ JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) # define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability)) # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability)) # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability)) # define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 ) # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 ) #elif \ (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \ JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) # define JSON_HEDLEY_PREDICT(expr, expected, probability) \ (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))) # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \ (__extension__ ({ \ double hedley_probability_ = (probability); \ ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \ })) # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \ (__extension__ ({ \ double hedley_probability_ = (probability); \ ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \ })) # define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1) # define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0) #else # define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)) # define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr)) # define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr)) # define JSON_HEDLEY_LIKELY(expr) (!!(expr)) # define JSON_HEDLEY_UNLIKELY(expr) (!!(expr)) #endif #if !defined(JSON_HEDLEY_UNPREDICTABLE) #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5) #endif #if defined(JSON_HEDLEY_MALLOC) #undef JSON_HEDLEY_MALLOC #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_MALLOC __attribute__((__malloc__)) #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory") #elif \ JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) #define JSON_HEDLEY_MALLOC __declspec(restrict) #else #define JSON_HEDLEY_MALLOC #endif #if defined(JSON_HEDLEY_PURE) #undef JSON_HEDLEY_PURE #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \ JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) # define JSON_HEDLEY_PURE __attribute__((__pure__)) #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) # define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data") #elif defined(__cplusplus) && \ ( \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \ ) # define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;") #else # define JSON_HEDLEY_PURE #endif #if defined(JSON_HEDLEY_CONST) #undef JSON_HEDLEY_CONST #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(const) || \ JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_CONST __attribute__((__const__)) #elif \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) #define JSON_HEDLEY_CONST _Pragma("no_side_effect") #else #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE #endif #if defined(JSON_HEDLEY_RESTRICT) #undef JSON_HEDLEY_RESTRICT #endif #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus) #define JSON_HEDLEY_RESTRICT restrict #elif \ JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \ JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ defined(__clang__) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_RESTRICT __restrict #elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus) #define JSON_HEDLEY_RESTRICT _Restrict #else #define JSON_HEDLEY_RESTRICT #endif #if defined(JSON_HEDLEY_INLINE) #undef JSON_HEDLEY_INLINE #endif #if \ (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ (defined(__cplusplus) && (__cplusplus >= 199711L)) #define JSON_HEDLEY_INLINE inline #elif \ defined(JSON_HEDLEY_GCC_VERSION) || \ JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0) #define JSON_HEDLEY_INLINE __inline__ #elif \ JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_INLINE __inline #else #define JSON_HEDLEY_INLINE #endif #if defined(JSON_HEDLEY_ALWAYS_INLINE) #undef JSON_HEDLEY_ALWAYS_INLINE #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) # define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE #elif \ JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) # define JSON_HEDLEY_ALWAYS_INLINE __forceinline #elif defined(__cplusplus) && \ ( \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \ ) # define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;") #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) # define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced") #else # define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE #endif #if defined(JSON_HEDLEY_NEVER_INLINE) #undef JSON_HEDLEY_NEVER_INLINE #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__)) #elif \ JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) #elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0) #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline") #elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;") #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never") #elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline)) #elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) #else #define JSON_HEDLEY_NEVER_INLINE #endif #if defined(JSON_HEDLEY_PRIVATE) #undef JSON_HEDLEY_PRIVATE #endif #if defined(JSON_HEDLEY_PUBLIC) #undef JSON_HEDLEY_PUBLIC #endif #if defined(JSON_HEDLEY_IMPORT) #undef JSON_HEDLEY_IMPORT #endif #if defined(_WIN32) || defined(__CYGWIN__) # define JSON_HEDLEY_PRIVATE # define JSON_HEDLEY_PUBLIC __declspec(dllexport) # define JSON_HEDLEY_IMPORT __declspec(dllimport) #else # if \ JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ ( \ defined(__TI_EABI__) && \ ( \ (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \ ) \ ) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) # define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden"))) # define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default"))) # else # define JSON_HEDLEY_PRIVATE # define JSON_HEDLEY_PUBLIC # endif # define JSON_HEDLEY_IMPORT extern #endif #if defined(JSON_HEDLEY_NO_THROW) #undef JSON_HEDLEY_NO_THROW #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__)) #elif \ JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) #define JSON_HEDLEY_NO_THROW __declspec(nothrow) #else #define JSON_HEDLEY_NO_THROW #endif #if defined(JSON_HEDLEY_FALL_THROUGH) #undef JSON_HEDLEY_FALL_THROUGH #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \ JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__)) #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough) #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]]) #elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough) #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]]) #elif defined(__fallthrough) /* SAL */ #define JSON_HEDLEY_FALL_THROUGH __fallthrough #else #define JSON_HEDLEY_FALL_THROUGH #endif #if defined(JSON_HEDLEY_RETURNS_NON_NULL) #undef JSON_HEDLEY_RETURNS_NON_NULL #endif #if \ JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__)) #elif defined(_Ret_notnull_) /* SAL */ #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_ #else #define JSON_HEDLEY_RETURNS_NON_NULL #endif #if defined(JSON_HEDLEY_ARRAY_PARAM) #undef JSON_HEDLEY_ARRAY_PARAM #endif #if \ defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ !defined(__STDC_NO_VLA__) && \ !defined(__cplusplus) && \ !defined(JSON_HEDLEY_PGI_VERSION) && \ !defined(JSON_HEDLEY_TINYC_VERSION) #define JSON_HEDLEY_ARRAY_PARAM(name) (name) #else #define JSON_HEDLEY_ARRAY_PARAM(name) #endif #if defined(JSON_HEDLEY_IS_CONSTANT) #undef JSON_HEDLEY_IS_CONSTANT #endif #if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR) #undef JSON_HEDLEY_REQUIRE_CONSTEXPR #endif /* JSON_HEDLEY_IS_CONSTEXPR_ is for HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ #if defined(JSON_HEDLEY_IS_CONSTEXPR_) #undef JSON_HEDLEY_IS_CONSTEXPR_ #endif #if \ JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \ JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \ JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr) #endif #if !defined(__cplusplus) # if \ JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \ JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24) #if defined(__INTPTR_TYPE__) #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*) #else #include #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*) #endif # elif \ ( \ defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \ !defined(JSON_HEDLEY_SUNPRO_VERSION) && \ !defined(JSON_HEDLEY_PGI_VERSION) && \ !defined(JSON_HEDLEY_IAR_VERSION)) || \ (JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \ JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0) #if defined(__INTPTR_TYPE__) #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0) #else #include #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0) #endif # elif \ defined(JSON_HEDLEY_GCC_VERSION) || \ defined(JSON_HEDLEY_INTEL_VERSION) || \ defined(JSON_HEDLEY_TINYC_VERSION) || \ defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \ JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \ defined(JSON_HEDLEY_TI_CL2000_VERSION) || \ defined(JSON_HEDLEY_TI_CL6X_VERSION) || \ defined(JSON_HEDLEY_TI_CL7X_VERSION) || \ defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \ defined(__clang__) # define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \ sizeof(void) != \ sizeof(*( \ 1 ? \ ((void*) ((expr) * 0L) ) : \ ((struct { char v[sizeof(void) * 2]; } *) 1) \ ) \ ) \ ) # endif #endif #if defined(JSON_HEDLEY_IS_CONSTEXPR_) #if !defined(JSON_HEDLEY_IS_CONSTANT) #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr) #endif #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1)) #else #if !defined(JSON_HEDLEY_IS_CONSTANT) #define JSON_HEDLEY_IS_CONSTANT(expr) (0) #endif #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr) #endif #if defined(JSON_HEDLEY_BEGIN_C_DECLS) #undef JSON_HEDLEY_BEGIN_C_DECLS #endif #if defined(JSON_HEDLEY_END_C_DECLS) #undef JSON_HEDLEY_END_C_DECLS #endif #if defined(JSON_HEDLEY_C_DECL) #undef JSON_HEDLEY_C_DECL #endif #if defined(__cplusplus) #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" { #define JSON_HEDLEY_END_C_DECLS } #define JSON_HEDLEY_C_DECL extern "C" #else #define JSON_HEDLEY_BEGIN_C_DECLS #define JSON_HEDLEY_END_C_DECLS #define JSON_HEDLEY_C_DECL #endif #if defined(JSON_HEDLEY_STATIC_ASSERT) #undef JSON_HEDLEY_STATIC_ASSERT #endif #if \ !defined(__cplusplus) && ( \ (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \ (JSON_HEDLEY_HAS_FEATURE(c_static_assert) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ defined(_Static_assert) \ ) # define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message) #elif \ (defined(__cplusplus) && (__cplusplus >= 201103L)) || \ JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) # define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message)) #else # define JSON_HEDLEY_STATIC_ASSERT(expr, message) #endif #if defined(JSON_HEDLEY_NULL) #undef JSON_HEDLEY_NULL #endif #if defined(__cplusplus) #if __cplusplus >= 201103L #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr) #elif defined(NULL) #define JSON_HEDLEY_NULL NULL #else #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0) #endif #elif defined(NULL) #define JSON_HEDLEY_NULL NULL #else #define JSON_HEDLEY_NULL ((void*) 0) #endif #if defined(JSON_HEDLEY_MESSAGE) #undef JSON_HEDLEY_MESSAGE #endif #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") # define JSON_HEDLEY_MESSAGE(msg) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ JSON_HEDLEY_PRAGMA(message msg) \ JSON_HEDLEY_DIAGNOSTIC_POP #elif \ JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg) #elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg) #elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) #elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0) # define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) #else # define JSON_HEDLEY_MESSAGE(msg) #endif #if defined(JSON_HEDLEY_WARNING) #undef JSON_HEDLEY_WARNING #endif #if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") # define JSON_HEDLEY_WARNING(msg) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ JSON_HEDLEY_PRAGMA(clang warning msg) \ JSON_HEDLEY_DIAGNOSTIC_POP #elif \ JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \ JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg) #elif \ JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg)) #else # define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg) #endif #if defined(JSON_HEDLEY_REQUIRE) #undef JSON_HEDLEY_REQUIRE #endif #if defined(JSON_HEDLEY_REQUIRE_MSG) #undef JSON_HEDLEY_REQUIRE_MSG #endif #if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if) # if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat") # define JSON_HEDLEY_REQUIRE(expr) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ __attribute__((diagnose_if(!(expr), #expr, "error"))) \ JSON_HEDLEY_DIAGNOSTIC_POP # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ __attribute__((diagnose_if(!(expr), msg, "error"))) \ JSON_HEDLEY_DIAGNOSTIC_POP # else # define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error"))) # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error"))) # endif #else # define JSON_HEDLEY_REQUIRE(expr) # define JSON_HEDLEY_REQUIRE_MSG(expr,msg) #endif #if defined(JSON_HEDLEY_FLAGS) #undef JSON_HEDLEY_FLAGS #endif #if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum) && (!defined(__cplusplus) || JSON_HEDLEY_HAS_WARNING("-Wbitfield-enum-conversion")) #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__)) #else #define JSON_HEDLEY_FLAGS #endif #if defined(JSON_HEDLEY_FLAGS_CAST) #undef JSON_HEDLEY_FLAGS_CAST #endif #if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0) # define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \ JSON_HEDLEY_DIAGNOSTIC_PUSH \ _Pragma("warning(disable:188)") \ ((T) (expr)); \ JSON_HEDLEY_DIAGNOSTIC_POP \ })) #else # define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr) #endif #if defined(JSON_HEDLEY_EMPTY_BASES) #undef JSON_HEDLEY_EMPTY_BASES #endif #if \ (JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)) || \ JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases) #else #define JSON_HEDLEY_EMPTY_BASES #endif /* Remaining macros are deprecated. */ #if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK) #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK #endif #if defined(__clang__) #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0) #else #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) #endif #if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE) #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE #endif #define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) #if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE) #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE #endif #define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) #if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN) #undef JSON_HEDLEY_CLANG_HAS_BUILTIN #endif #define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin) #if defined(JSON_HEDLEY_CLANG_HAS_FEATURE) #undef JSON_HEDLEY_CLANG_HAS_FEATURE #endif #define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature) #if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION) #undef JSON_HEDLEY_CLANG_HAS_EXTENSION #endif #define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension) #if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE) #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE #endif #define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) #if defined(JSON_HEDLEY_CLANG_HAS_WARNING) #undef JSON_HEDLEY_CLANG_HAS_WARNING #endif #define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning) #endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */ // #include #include // #include namespace nlohmann { namespace detail { template struct make_void { using type = void; }; template using void_t = typename make_void::type; } // namespace detail } // namespace nlohmann // https://en.cppreference.com/w/cpp/experimental/is_detected namespace nlohmann { namespace detail { struct nonesuch { nonesuch() = delete; ~nonesuch() = delete; nonesuch(nonesuch const&) = delete; nonesuch(nonesuch const&&) = delete; void operator=(nonesuch const&) = delete; void operator=(nonesuch&&) = delete; }; template class Op, class... Args> struct detector { using value_t = std::false_type; using type = Default; }; template class Op, class... Args> struct detector>, Op, Args...> { using value_t = std::true_type; using type = Op; }; template class Op, class... Args> using is_detected = typename detector::value_t; template class Op, class... Args> struct is_detected_lazy : is_detected { }; template class Op, class... Args> using detected_t = typename detector::type; template class Op, class... Args> using detected_or = detector; template class Op, class... Args> using detected_or_t = typename detected_or::type; template class Op, class... Args> using is_detected_exact = std::is_same>; template class Op, class... Args> using is_detected_convertible = std::is_convertible, To>; } // namespace detail } // namespace nlohmann // This file contains all internal macro definitions // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them // exclude unsupported compilers #if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) #if defined(__clang__) #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" #endif #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" #endif #endif #endif // C++ language standard detection // if the user manually specified the used c++ version this is skipped #if !defined(JSON_HAS_CPP_20) && !defined(JSON_HAS_CPP_17) && !defined(JSON_HAS_CPP_14) && !defined(JSON_HAS_CPP_11) #if (defined(__cplusplus) && __cplusplus >= 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L) #define JSON_HAS_CPP_20 #define JSON_HAS_CPP_17 #define JSON_HAS_CPP_14 #elif (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 #define JSON_HAS_CPP_17 #define JSON_HAS_CPP_14 #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) #define JSON_HAS_CPP_14 #endif // the cpp 11 flag is always specified because it is the minimal required version #define JSON_HAS_CPP_11 #endif #if !defined(JSON_HAS_FILESYSTEM) && !defined(JSON_HAS_EXPERIMENTAL_FILESYSTEM) #ifdef JSON_HAS_CPP_17 #if defined(__cpp_lib_filesystem) #define JSON_HAS_FILESYSTEM 1 #elif defined(__cpp_lib_experimental_filesystem) #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 #elif !defined(__has_include) #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 #elif __has_include() #define JSON_HAS_FILESYSTEM 1 #elif __has_include() #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 #endif // std::filesystem does not work on MinGW GCC 8: https://sourceforge.net/p/mingw-w64/bugs/737/ #if defined(__MINGW32__) && defined(__GNUC__) && __GNUC__ == 8 #undef JSON_HAS_FILESYSTEM #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM #endif // no filesystem support before GCC 8: https://en.cppreference.com/w/cpp/compiler_support #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 8 #undef JSON_HAS_FILESYSTEM #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM #endif // no filesystem support before Clang 7: https://en.cppreference.com/w/cpp/compiler_support #if defined(__clang_major__) && __clang_major__ < 7 #undef JSON_HAS_FILESYSTEM #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM #endif // no filesystem support before MSVC 19.14: https://en.cppreference.com/w/cpp/compiler_support #if defined(_MSC_VER) && _MSC_VER < 1940 #undef JSON_HAS_FILESYSTEM #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM #endif // no filesystem support before iOS 13 #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED < 130000 #undef JSON_HAS_FILESYSTEM #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM #endif // no filesystem support before macOS Catalina #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500 #undef JSON_HAS_FILESYSTEM #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM #endif #endif #endif #ifndef JSON_HAS_EXPERIMENTAL_FILESYSTEM #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 0 #endif #ifndef JSON_HAS_FILESYSTEM #define JSON_HAS_FILESYSTEM 0 #endif // disable documentation warnings on clang #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation" #pragma clang diagnostic ignored "-Wdocumentation-unknown-command" #endif // allow disabling exceptions #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) #define JSON_THROW(exception) throw exception #define JSON_TRY try #define JSON_CATCH(exception) catch(exception) #define JSON_INTERNAL_CATCH(exception) catch(exception) #else #include #define JSON_THROW(exception) std::abort() #define JSON_TRY if(true) #define JSON_CATCH(exception) if(false) #define JSON_INTERNAL_CATCH(exception) if(false) #endif // override exception macros #if defined(JSON_THROW_USER) #undef JSON_THROW #define JSON_THROW JSON_THROW_USER #endif #if defined(JSON_TRY_USER) #undef JSON_TRY #define JSON_TRY JSON_TRY_USER #endif #if defined(JSON_CATCH_USER) #undef JSON_CATCH #define JSON_CATCH JSON_CATCH_USER #undef JSON_INTERNAL_CATCH #define JSON_INTERNAL_CATCH JSON_CATCH_USER #endif #if defined(JSON_INTERNAL_CATCH_USER) #undef JSON_INTERNAL_CATCH #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER #endif // allow overriding assert #if !defined(JSON_ASSERT) #include // assert #define JSON_ASSERT(x) assert(x) #endif // allow to access some private functions (needed by the test suite) #if defined(JSON_TESTS_PRIVATE) #define JSON_PRIVATE_UNLESS_TESTED public #else #define JSON_PRIVATE_UNLESS_TESTED private #endif /*! @brief macro to briefly define a mapping between an enum and JSON @def NLOHMANN_JSON_SERIALIZE_ENUM @since version 3.4.0 */ #define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ template \ inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ { \ static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ static const std::pair m[] = __VA_ARGS__; \ auto it = std::find_if(std::begin(m), std::end(m), \ [e](const std::pair& ej_pair) -> bool \ { \ return ej_pair.first == e; \ }); \ j = ((it != std::end(m)) ? it : std::begin(m))->second; \ } \ template \ inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ { \ static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ static const std::pair m[] = __VA_ARGS__; \ auto it = std::find_if(std::begin(m), std::end(m), \ [&j](const std::pair& ej_pair) -> bool \ { \ return ej_pair.second == j; \ }); \ e = ((it != std::end(m)) ? it : std::begin(m))->first; \ } // Ugly macros to avoid uglier copy-paste when specializing basic_json. They // may be removed in the future once the class is split. #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ template class ObjectType, \ template class ArrayType, \ class StringType, class BooleanType, class NumberIntegerType, \ class NumberUnsignedType, class NumberFloatType, \ template class AllocatorType, \ template class JSONSerializer, \ class BinaryType> #define NLOHMANN_BASIC_JSON_TPL \ basic_json // Macros to simplify conversion from/to types #define NLOHMANN_JSON_EXPAND( x ) x #define NLOHMANN_JSON_GET_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, NAME,...) NAME #define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \ NLOHMANN_JSON_PASTE64, \ NLOHMANN_JSON_PASTE63, \ NLOHMANN_JSON_PASTE62, \ NLOHMANN_JSON_PASTE61, \ NLOHMANN_JSON_PASTE60, \ NLOHMANN_JSON_PASTE59, \ NLOHMANN_JSON_PASTE58, \ NLOHMANN_JSON_PASTE57, \ NLOHMANN_JSON_PASTE56, \ NLOHMANN_JSON_PASTE55, \ NLOHMANN_JSON_PASTE54, \ NLOHMANN_JSON_PASTE53, \ NLOHMANN_JSON_PASTE52, \ NLOHMANN_JSON_PASTE51, \ NLOHMANN_JSON_PASTE50, \ NLOHMANN_JSON_PASTE49, \ NLOHMANN_JSON_PASTE48, \ NLOHMANN_JSON_PASTE47, \ NLOHMANN_JSON_PASTE46, \ NLOHMANN_JSON_PASTE45, \ NLOHMANN_JSON_PASTE44, \ NLOHMANN_JSON_PASTE43, \ NLOHMANN_JSON_PASTE42, \ NLOHMANN_JSON_PASTE41, \ NLOHMANN_JSON_PASTE40, \ NLOHMANN_JSON_PASTE39, \ NLOHMANN_JSON_PASTE38, \ NLOHMANN_JSON_PASTE37, \ NLOHMANN_JSON_PASTE36, \ NLOHMANN_JSON_PASTE35, \ NLOHMANN_JSON_PASTE34, \ NLOHMANN_JSON_PASTE33, \ NLOHMANN_JSON_PASTE32, \ NLOHMANN_JSON_PASTE31, \ NLOHMANN_JSON_PASTE30, \ NLOHMANN_JSON_PASTE29, \ NLOHMANN_JSON_PASTE28, \ NLOHMANN_JSON_PASTE27, \ NLOHMANN_JSON_PASTE26, \ NLOHMANN_JSON_PASTE25, \ NLOHMANN_JSON_PASTE24, \ NLOHMANN_JSON_PASTE23, \ NLOHMANN_JSON_PASTE22, \ NLOHMANN_JSON_PASTE21, \ NLOHMANN_JSON_PASTE20, \ NLOHMANN_JSON_PASTE19, \ NLOHMANN_JSON_PASTE18, \ NLOHMANN_JSON_PASTE17, \ NLOHMANN_JSON_PASTE16, \ NLOHMANN_JSON_PASTE15, \ NLOHMANN_JSON_PASTE14, \ NLOHMANN_JSON_PASTE13, \ NLOHMANN_JSON_PASTE12, \ NLOHMANN_JSON_PASTE11, \ NLOHMANN_JSON_PASTE10, \ NLOHMANN_JSON_PASTE9, \ NLOHMANN_JSON_PASTE8, \ NLOHMANN_JSON_PASTE7, \ NLOHMANN_JSON_PASTE6, \ NLOHMANN_JSON_PASTE5, \ NLOHMANN_JSON_PASTE4, \ NLOHMANN_JSON_PASTE3, \ NLOHMANN_JSON_PASTE2, \ NLOHMANN_JSON_PASTE1)(__VA_ARGS__)) #define NLOHMANN_JSON_PASTE2(func, v1) func(v1) #define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2) #define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3) #define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4) #define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5) #define NLOHMANN_JSON_PASTE7(func, v1, v2, v3, v4, v5, v6) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE6(func, v2, v3, v4, v5, v6) #define NLOHMANN_JSON_PASTE8(func, v1, v2, v3, v4, v5, v6, v7) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE7(func, v2, v3, v4, v5, v6, v7) #define NLOHMANN_JSON_PASTE9(func, v1, v2, v3, v4, v5, v6, v7, v8) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8) #define NLOHMANN_JSON_PASTE10(func, v1, v2, v3, v4, v5, v6, v7, v8, v9) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE9(func, v2, v3, v4, v5, v6, v7, v8, v9) #define NLOHMANN_JSON_PASTE11(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE10(func, v2, v3, v4, v5, v6, v7, v8, v9, v10) #define NLOHMANN_JSON_PASTE12(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE11(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) #define NLOHMANN_JSON_PASTE13(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE12(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) #define NLOHMANN_JSON_PASTE14(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE13(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) #define NLOHMANN_JSON_PASTE15(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE14(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) #define NLOHMANN_JSON_PASTE16(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE15(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) #define NLOHMANN_JSON_PASTE17(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE16(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) #define NLOHMANN_JSON_PASTE18(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE17(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) #define NLOHMANN_JSON_PASTE19(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE18(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) #define NLOHMANN_JSON_PASTE20(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE19(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) #define NLOHMANN_JSON_PASTE21(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE20(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) #define NLOHMANN_JSON_PASTE22(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE21(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) #define NLOHMANN_JSON_PASTE23(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE22(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) #define NLOHMANN_JSON_PASTE24(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE23(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) #define NLOHMANN_JSON_PASTE25(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE24(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) #define NLOHMANN_JSON_PASTE26(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE25(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) #define NLOHMANN_JSON_PASTE27(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE26(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) #define NLOHMANN_JSON_PASTE28(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE27(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) #define NLOHMANN_JSON_PASTE29(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE28(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) #define NLOHMANN_JSON_PASTE30(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE29(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) #define NLOHMANN_JSON_PASTE31(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE30(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) #define NLOHMANN_JSON_PASTE32(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE31(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) #define NLOHMANN_JSON_PASTE33(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE32(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) #define NLOHMANN_JSON_PASTE34(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE33(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) #define NLOHMANN_JSON_PASTE35(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE34(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) #define NLOHMANN_JSON_PASTE36(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE35(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) #define NLOHMANN_JSON_PASTE37(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE36(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) #define NLOHMANN_JSON_PASTE38(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE37(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) #define NLOHMANN_JSON_PASTE39(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE38(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) #define NLOHMANN_JSON_PASTE40(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE39(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) #define NLOHMANN_JSON_PASTE41(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE40(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) #define NLOHMANN_JSON_PASTE42(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE41(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) #define NLOHMANN_JSON_PASTE43(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE42(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) #define NLOHMANN_JSON_PASTE44(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE43(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) #define NLOHMANN_JSON_PASTE45(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE44(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) #define NLOHMANN_JSON_PASTE46(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE45(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) #define NLOHMANN_JSON_PASTE47(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE46(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) #define NLOHMANN_JSON_PASTE48(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE47(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) #define NLOHMANN_JSON_PASTE49(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE48(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) #define NLOHMANN_JSON_PASTE50(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE49(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) #define NLOHMANN_JSON_PASTE51(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE50(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) #define NLOHMANN_JSON_PASTE52(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE51(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) #define NLOHMANN_JSON_PASTE53(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE52(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) #define NLOHMANN_JSON_PASTE54(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE53(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) #define NLOHMANN_JSON_PASTE55(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE54(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) #define NLOHMANN_JSON_PASTE56(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE55(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) #define NLOHMANN_JSON_PASTE57(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE56(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) #define NLOHMANN_JSON_PASTE58(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE57(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) #define NLOHMANN_JSON_PASTE59(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE58(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) #define NLOHMANN_JSON_PASTE60(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE59(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) #define NLOHMANN_JSON_PASTE61(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE60(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) #define NLOHMANN_JSON_PASTE62(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE61(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) #define NLOHMANN_JSON_PASTE63(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE62(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) #define NLOHMANN_JSON_PASTE64(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE63(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) #define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1; #define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1); /*! @brief macro @def NLOHMANN_DEFINE_TYPE_INTRUSIVE @since version 3.9.0 */ #define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...) \ friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } /*! @brief macro @def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE @since version 3.9.0 */ #define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...) \ inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } // inspired from https://stackoverflow.com/a/26745591 // allows to call any std function as if (e.g. with begin): // using std::begin; begin(x); // // it allows using the detected idiom to retrieve the return type // of such an expression #define NLOHMANN_CAN_CALL_STD_FUNC_IMPL(std_name) \ namespace detail { \ using std::std_name; \ \ template \ using result_of_##std_name = decltype(std_name(std::declval()...)); \ } \ \ namespace detail2 { \ struct std_name##_tag \ { \ }; \ \ template \ std_name##_tag std_name(T&&...); \ \ template \ using result_of_##std_name = decltype(std_name(std::declval()...)); \ \ template \ struct would_call_std_##std_name \ { \ static constexpr auto const value = ::nlohmann::detail:: \ is_detected_exact::value; \ }; \ } /* namespace detail2 */ \ \ template \ struct would_call_std_##std_name : detail2::would_call_std_##std_name \ { \ } #ifndef JSON_USE_IMPLICIT_CONVERSIONS #define JSON_USE_IMPLICIT_CONVERSIONS 1 #endif #if JSON_USE_IMPLICIT_CONVERSIONS #define JSON_EXPLICIT #else #define JSON_EXPLICIT explicit #endif #ifndef JSON_DIAGNOSTICS #define JSON_DIAGNOSTICS 0 #endif namespace nlohmann { namespace detail { /*! @brief replace all occurrences of a substring by another string @param[in,out] s the string to manipulate; changed so that all occurrences of @a f are replaced with @a t @param[in] f the substring to replace with @a t @param[in] t the string to replace @a f @pre The search string @a f must not be empty. **This precondition is enforced with an assertion.** @since version 2.0.0 */ inline void replace_substring(std::string& s, const std::string& f, const std::string& t) { JSON_ASSERT(!f.empty()); for (auto pos = s.find(f); // find first occurrence of f pos != std::string::npos; // make sure f was found s.replace(pos, f.size(), t), // replace with t, and pos = s.find(f, pos + t.size())) // find next occurrence of f {} } /*! * @brief string escaping as described in RFC 6901 (Sect. 4) * @param[in] s string to escape * @return escaped string * * Note the order of escaping "~" to "~0" and "/" to "~1" is important. */ inline std::string escape(std::string s) { replace_substring(s, "~", "~0"); replace_substring(s, "/", "~1"); return s; } /*! * @brief string unescaping as described in RFC 6901 (Sect. 4) * @param[in] s string to unescape * @return unescaped string * * Note the order of escaping "~1" to "/" and "~0" to "~" is important. */ static void unescape(std::string& s) { replace_substring(s, "~1", "/"); replace_substring(s, "~0", "~"); } } // namespace detail } // namespace nlohmann // #include #include // size_t namespace nlohmann { namespace detail { /// struct to capture the start position of the current token struct position_t { /// the total number of characters read std::size_t chars_read_total = 0; /// the number of characters read in the current line std::size_t chars_read_current_line = 0; /// the number of lines read std::size_t lines_read = 0; /// conversion to size_t to preserve SAX interface constexpr operator size_t() const { return chars_read_total; } }; } // namespace detail } // namespace nlohmann // #include namespace nlohmann { namespace detail { //////////////// // exceptions // //////////////// /// @brief general exception of the @ref basic_json class /// @sa https://json.nlohmann.me/api/basic_json/exception/ class exception : public std::exception { public: /// returns the explanatory string const char* what() const noexcept override { return m.what(); } /// the id of the exception const int id; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) protected: JSON_HEDLEY_NON_NULL(3) exception(int id_, const char* what_arg) : id(id_), m(what_arg) {} // NOLINT(bugprone-throw-keyword-missing) static std::string name(const std::string& ename, int id_) { return "[json.exception." + ename + "." + std::to_string(id_) + "] "; } template static std::string diagnostics(const BasicJsonType& leaf_element) { #if JSON_DIAGNOSTICS std::vector tokens; for (const auto* current = &leaf_element; current->m_parent != nullptr; current = current->m_parent) { switch (current->m_parent->type()) { case value_t::array: { for (std::size_t i = 0; i < current->m_parent->m_value.array->size(); ++i) { if (¤t->m_parent->m_value.array->operator[](i) == current) { tokens.emplace_back(std::to_string(i)); break; } } break; } case value_t::object: { for (const auto& element : *current->m_parent->m_value.object) { if (&element.second == current) { tokens.emplace_back(element.first.c_str()); break; } } break; } case value_t::null: // LCOV_EXCL_LINE case value_t::string: // LCOV_EXCL_LINE case value_t::boolean: // LCOV_EXCL_LINE case value_t::number_integer: // LCOV_EXCL_LINE case value_t::number_unsigned: // LCOV_EXCL_LINE case value_t::number_float: // LCOV_EXCL_LINE case value_t::binary: // LCOV_EXCL_LINE case value_t::discarded: // LCOV_EXCL_LINE default: // LCOV_EXCL_LINE break; // LCOV_EXCL_LINE } } if (tokens.empty()) { return ""; } return "(" + std::accumulate(tokens.rbegin(), tokens.rend(), std::string{}, [](const std::string & a, const std::string & b) { return a + "/" + detail::escape(b); }) + ") "; #else static_cast(leaf_element); return ""; #endif } private: /// an exception object as storage for error messages std::runtime_error m; }; /// @brief exception indicating a parse error /// @sa https://json.nlohmann.me/api/basic_json/parse_error/ class parse_error : public exception { public: /*! @brief create a parse error exception @param[in] id_ the id of the exception @param[in] pos the position where the error occurred (or with chars_read_total=0 if the position cannot be determined) @param[in] what_arg the explanatory string @return parse_error object */ template static parse_error create(int id_, const position_t& pos, const std::string& what_arg, const BasicJsonType& context) { std::string w = exception::name("parse_error", id_) + "parse error" + position_string(pos) + ": " + exception::diagnostics(context) + what_arg; return {id_, pos.chars_read_total, w.c_str()}; } template static parse_error create(int id_, std::size_t byte_, const std::string& what_arg, const BasicJsonType& context) { std::string w = exception::name("parse_error", id_) + "parse error" + (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") + ": " + exception::diagnostics(context) + what_arg; return {id_, byte_, w.c_str()}; } /*! @brief byte index of the parse error The byte index of the last read character in the input file. @note For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack). */ const std::size_t byte; private: parse_error(int id_, std::size_t byte_, const char* what_arg) : exception(id_, what_arg), byte(byte_) {} static std::string position_string(const position_t& pos) { return " at line " + std::to_string(pos.lines_read + 1) + ", column " + std::to_string(pos.chars_read_current_line); } }; /// @brief exception indicating errors with iterators /// @sa https://json.nlohmann.me/api/basic_json/invalid_iterator/ class invalid_iterator : public exception { public: template static invalid_iterator create(int id_, const std::string& what_arg, const BasicJsonType& context) { std::string w = exception::name("invalid_iterator", id_) + exception::diagnostics(context) + what_arg; return {id_, w.c_str()}; } private: JSON_HEDLEY_NON_NULL(3) invalid_iterator(int id_, const char* what_arg) : exception(id_, what_arg) {} }; /// @brief exception indicating executing a member function with a wrong type /// @sa https://json.nlohmann.me/api/basic_json/type_error/ class type_error : public exception { public: template static type_error create(int id_, const std::string& what_arg, const BasicJsonType& context) { std::string w = exception::name("type_error", id_) + exception::diagnostics(context) + what_arg; return {id_, w.c_str()}; } private: JSON_HEDLEY_NON_NULL(3) type_error(int id_, const char* what_arg) : exception(id_, what_arg) {} }; /// @brief exception indicating access out of the defined range /// @sa https://json.nlohmann.me/api/basic_json/out_of_range/ class out_of_range : public exception { public: template static out_of_range create(int id_, const std::string& what_arg, const BasicJsonType& context) { std::string w = exception::name("out_of_range", id_) + exception::diagnostics(context) + what_arg; return {id_, w.c_str()}; } private: JSON_HEDLEY_NON_NULL(3) out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {} }; /// @brief exception indicating other library errors /// @sa https://json.nlohmann.me/api/basic_json/other_error/ class other_error : public exception { public: template static other_error create(int id_, const std::string& what_arg, const BasicJsonType& context) { std::string w = exception::name("other_error", id_) + exception::diagnostics(context) + what_arg; return {id_, w.c_str()}; } private: JSON_HEDLEY_NON_NULL(3) other_error(int id_, const char* what_arg) : exception(id_, what_arg) {} }; } // namespace detail } // namespace nlohmann // #include // #include #include // size_t #include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type #include // index_sequence, make_index_sequence, index_sequence_for // #include namespace nlohmann { namespace detail { template using uncvref_t = typename std::remove_cv::type>::type; #ifdef JSON_HAS_CPP_14 // the following utilities are natively available in C++14 using std::enable_if_t; using std::index_sequence; using std::make_index_sequence; using std::index_sequence_for; #else // alias templates to reduce boilerplate template using enable_if_t = typename std::enable_if::type; // The following code is taken from https://github.com/abseil/abseil-cpp/blob/10cb35e459f5ecca5b2ff107635da0bfa41011b4/absl/utility/utility.h // which is part of Google Abseil (https://github.com/abseil/abseil-cpp), licensed under the Apache License 2.0. //// START OF CODE FROM GOOGLE ABSEIL // integer_sequence // // Class template representing a compile-time integer sequence. An instantiation // of `integer_sequence` has a sequence of integers encoded in its // type through its template arguments (which is a common need when // working with C++11 variadic templates). `absl::integer_sequence` is designed // to be a drop-in replacement for C++14's `std::integer_sequence`. // // Example: // // template< class T, T... Ints > // void user_function(integer_sequence); // // int main() // { // // user_function's `T` will be deduced to `int` and `Ints...` // // will be deduced to `0, 1, 2, 3, 4`. // user_function(make_integer_sequence()); // } template struct integer_sequence { using value_type = T; static constexpr std::size_t size() noexcept { return sizeof...(Ints); } }; // index_sequence // // A helper template for an `integer_sequence` of `size_t`, // `absl::index_sequence` is designed to be a drop-in replacement for C++14's // `std::index_sequence`. template using index_sequence = integer_sequence; namespace utility_internal { template struct Extend; // Note that SeqSize == sizeof...(Ints). It's passed explicitly for efficiency. template struct Extend, SeqSize, 0> { using type = integer_sequence < T, Ints..., (Ints + SeqSize)... >; }; template struct Extend, SeqSize, 1> { using type = integer_sequence < T, Ints..., (Ints + SeqSize)..., 2 * SeqSize >; }; // Recursion helper for 'make_integer_sequence'. // 'Gen::type' is an alias for 'integer_sequence'. template struct Gen { using type = typename Extend < typename Gen < T, N / 2 >::type, N / 2, N % 2 >::type; }; template struct Gen { using type = integer_sequence; }; } // namespace utility_internal // Compile-time sequences of integers // make_integer_sequence // // This template alias is equivalent to // `integer_sequence`, and is designed to be a drop-in // replacement for C++14's `std::make_integer_sequence`. template using make_integer_sequence = typename utility_internal::Gen::type; // make_index_sequence // // This template alias is equivalent to `index_sequence<0, 1, ..., N-1>`, // and is designed to be a drop-in replacement for C++14's // `std::make_index_sequence`. template using make_index_sequence = make_integer_sequence; // index_sequence_for // // Converts a typename pack into an index sequence of the same length, and // is designed to be a drop-in replacement for C++14's // `std::index_sequence_for()` template using index_sequence_for = make_index_sequence; //// END OF CODE FROM GOOGLE ABSEIL #endif // dispatch utility (taken from ranges-v3) template struct priority_tag : priority_tag < N - 1 > {}; template<> struct priority_tag<0> {}; // taken from ranges-v3 template struct static_const { static constexpr T value{}; }; template constexpr T static_const::value; // NOLINT(readability-redundant-declaration) } // namespace detail } // namespace nlohmann // #include namespace nlohmann { namespace detail { // dispatching helper struct template struct identity_tag {}; } // namespace detail } // namespace nlohmann // #include #include // numeric_limits #include // false_type, is_constructible, is_integral, is_same, true_type #include // declval #include // tuple // #include // #include #include // random_access_iterator_tag // #include // #include namespace nlohmann { namespace detail { template struct iterator_types {}; template struct iterator_types < It, void_t> { using difference_type = typename It::difference_type; using value_type = typename It::value_type; using pointer = typename It::pointer; using reference = typename It::reference; using iterator_category = typename It::iterator_category; }; // This is required as some compilers implement std::iterator_traits in a way that // doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. template struct iterator_traits { }; template struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> : iterator_types { }; template struct iterator_traits::value>> { using iterator_category = std::random_access_iterator_tag; using value_type = T; using difference_type = ptrdiff_t; using pointer = T*; using reference = T&; }; } // namespace detail } // namespace nlohmann // #include // #include namespace nlohmann { NLOHMANN_CAN_CALL_STD_FUNC_IMPL(begin); } // namespace nlohmann // #include // #include namespace nlohmann { NLOHMANN_CAN_CALL_STD_FUNC_IMPL(end); } // namespace nlohmann // #include // #include // #include #ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ #define INCLUDE_NLOHMANN_JSON_FWD_HPP_ #include // int64_t, uint64_t #include // map #include // allocator #include // string #include // vector /*! @brief namespace for Niels Lohmann @see https://github.com/nlohmann @since version 1.0.0 */ namespace nlohmann { /*! @brief default JSONSerializer template argument This serializer ignores the template arguments and uses ADL ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) for serialization. */ template struct adl_serializer; /// a class to store JSON values /// @sa https://json.nlohmann.me/api/basic_json/ template class ObjectType = std::map, template class ArrayType = std::vector, class StringType = std::string, class BooleanType = bool, class NumberIntegerType = std::int64_t, class NumberUnsignedType = std::uint64_t, class NumberFloatType = double, template class AllocatorType = std::allocator, template class JSONSerializer = adl_serializer, class BinaryType = std::vector> class basic_json; /// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document /// @sa https://json.nlohmann.me/api/json_pointer/ template class json_pointer; /*! @brief default specialization @sa https://json.nlohmann.me/api/json/ */ using json = basic_json<>; /// @brief a minimal map-like container that preserves insertion order /// @sa https://json.nlohmann.me/api/ordered_map/ template struct ordered_map; /// @brief specialization that maintains the insertion order of object keys /// @sa https://json.nlohmann.me/api/ordered_json/ using ordered_json = basic_json; } // namespace nlohmann #endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ namespace nlohmann { /*! @brief detail namespace with internal helper functions This namespace collects functions that should not be exposed, implementations of some @ref basic_json methods, and meta-programming helpers. @since version 2.1.0 */ namespace detail { ///////////// // helpers // ///////////// // Note to maintainers: // // Every trait in this file expects a non CV-qualified type. // The only exceptions are in the 'aliases for detected' section // (i.e. those of the form: decltype(T::member_function(std::declval()))) // // In this case, T has to be properly CV-qualified to constraint the function arguments // (e.g. to_json(BasicJsonType&, const T&)) template struct is_basic_json : std::false_type {}; NLOHMANN_BASIC_JSON_TPL_DECLARATION struct is_basic_json : std::true_type {}; ////////////////////// // json_ref helpers // ////////////////////// template class json_ref; template struct is_json_ref : std::false_type {}; template struct is_json_ref> : std::true_type {}; ////////////////////////// // aliases for detected // ////////////////////////// template using mapped_type_t = typename T::mapped_type; template using key_type_t = typename T::key_type; template using value_type_t = typename T::value_type; template using difference_type_t = typename T::difference_type; template using pointer_t = typename T::pointer; template using reference_t = typename T::reference; template using iterator_category_t = typename T::iterator_category; template using to_json_function = decltype(T::to_json(std::declval()...)); template using from_json_function = decltype(T::from_json(std::declval()...)); template using get_template_function = decltype(std::declval().template get()); // trait checking if JSONSerializer::from_json(json const&, udt&) exists template struct has_from_json : std::false_type {}; // trait checking if j.get is valid // use this trait instead of std::is_constructible or std::is_convertible, // both rely on, or make use of implicit conversions, and thus fail when T // has several constructors/operator= (see https://github.com/nlohmann/json/issues/958) template struct is_getable { static constexpr bool value = is_detected::value; }; template struct has_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> { using serializer = typename BasicJsonType::template json_serializer; static constexpr bool value = is_detected_exact::value; }; // This trait checks if JSONSerializer::from_json(json const&) exists // this overload is used for non-default-constructible user-defined-types template struct has_non_default_from_json : std::false_type {}; template struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> { using serializer = typename BasicJsonType::template json_serializer; static constexpr bool value = is_detected_exact::value; }; // This trait checks if BasicJsonType::json_serializer::to_json exists // Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion. template struct has_to_json : std::false_type {}; template struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> { using serializer = typename BasicJsonType::template json_serializer; static constexpr bool value = is_detected_exact::value; }; /////////////////// // is_ functions // /////////////////// // https://en.cppreference.com/w/cpp/types/conjunction template struct conjunction : std::true_type { }; template struct conjunction : B1 { }; template struct conjunction : std::conditional, B1>::type {}; // https://en.cppreference.com/w/cpp/types/negation template struct negation : std::integral_constant < bool, !B::value > { }; // Reimplementation of is_constructible and is_default_constructible, due to them being broken for // std::pair and std::tuple until LWG 2367 fix (see https://cplusplus.github.io/LWG/lwg-defects.html#2367). // This causes compile errors in e.g. clang 3.5 or gcc 4.9. template struct is_default_constructible : std::is_default_constructible {}; template struct is_default_constructible> : conjunction, is_default_constructible> {}; template struct is_default_constructible> : conjunction, is_default_constructible> {}; template struct is_default_constructible> : conjunction...> {}; template struct is_default_constructible> : conjunction...> {}; template struct is_constructible : std::is_constructible {}; template struct is_constructible> : is_default_constructible> {}; template struct is_constructible> : is_default_constructible> {}; template struct is_constructible> : is_default_constructible> {}; template struct is_constructible> : is_default_constructible> {}; template struct is_iterator_traits : std::false_type {}; template struct is_iterator_traits> { private: using traits = iterator_traits; public: static constexpr auto value = is_detected::value && is_detected::value && is_detected::value && is_detected::value && is_detected::value; }; template struct is_range { private: using t_ref = typename std::add_lvalue_reference::type; using iterator = detected_t; using sentinel = detected_t; // to be 100% correct, it should use https://en.cppreference.com/w/cpp/iterator/input_or_output_iterator // and https://en.cppreference.com/w/cpp/iterator/sentinel_for // but reimplementing these would be too much work, as a lot of other concepts are used underneath static constexpr auto is_iterator_begin = is_iterator_traits>::value; public: static constexpr bool value = !std::is_same::value && !std::is_same::value && is_iterator_begin; }; template using iterator_t = enable_if_t::value, result_of_begin())>>; template using range_value_t = value_type_t>>; // The following implementation of is_complete_type is taken from // https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/ // and is written by Xiang Fan who agreed to using it in this library. template struct is_complete_type : std::false_type {}; template struct is_complete_type : std::true_type {}; template struct is_compatible_object_type_impl : std::false_type {}; template struct is_compatible_object_type_impl < BasicJsonType, CompatibleObjectType, enable_if_t < is_detected::value&& is_detected::value >> { using object_t = typename BasicJsonType::object_t; // macOS's is_constructible does not play well with nonesuch... static constexpr bool value = is_constructible::value && is_constructible::value; }; template struct is_compatible_object_type : is_compatible_object_type_impl {}; template struct is_constructible_object_type_impl : std::false_type {}; template struct is_constructible_object_type_impl < BasicJsonType, ConstructibleObjectType, enable_if_t < is_detected::value&& is_detected::value >> { using object_t = typename BasicJsonType::object_t; static constexpr bool value = (is_default_constructible::value && (std::is_move_assignable::value || std::is_copy_assignable::value) && (is_constructible::value && std::is_same < typename object_t::mapped_type, typename ConstructibleObjectType::mapped_type >::value)) || (has_from_json::value || has_non_default_from_json < BasicJsonType, typename ConstructibleObjectType::mapped_type >::value); }; template struct is_constructible_object_type : is_constructible_object_type_impl {}; template struct is_compatible_string_type { static constexpr auto value = is_constructible::value; }; template struct is_constructible_string_type { static constexpr auto value = is_constructible::value; }; template struct is_compatible_array_type_impl : std::false_type {}; template struct is_compatible_array_type_impl < BasicJsonType, CompatibleArrayType, enable_if_t < is_detected::value&& is_iterator_traits>>::value&& // special case for types like std::filesystem::path whose iterator's value_type are themselves // c.f. https://github.com/nlohmann/json/pull/3073 !std::is_same>::value >> { static constexpr bool value = is_constructible>::value; }; template struct is_compatible_array_type : is_compatible_array_type_impl {}; template struct is_constructible_array_type_impl : std::false_type {}; template struct is_constructible_array_type_impl < BasicJsonType, ConstructibleArrayType, enable_if_t::value >> : std::true_type {}; template struct is_constructible_array_type_impl < BasicJsonType, ConstructibleArrayType, enable_if_t < !std::is_same::value&& !is_compatible_string_type::value&& is_default_constructible::value&& (std::is_move_assignable::value || std::is_copy_assignable::value)&& is_detected::value&& is_iterator_traits>>::value&& is_detected::value&& // special case for types like std::filesystem::path whose iterator's value_type are themselves // c.f. https://github.com/nlohmann/json/pull/3073 !std::is_same>::value&& is_complete_type < detected_t>::value >> { using value_type = range_value_t; static constexpr bool value = std::is_same::value || has_from_json::value || has_non_default_from_json < BasicJsonType, value_type >::value; }; template struct is_constructible_array_type : is_constructible_array_type_impl {}; template struct is_compatible_integer_type_impl : std::false_type {}; template struct is_compatible_integer_type_impl < RealIntegerType, CompatibleNumberIntegerType, enable_if_t < std::is_integral::value&& std::is_integral::value&& !std::is_same::value >> { // is there an assert somewhere on overflows? using RealLimits = std::numeric_limits; using CompatibleLimits = std::numeric_limits; static constexpr auto value = is_constructible::value && CompatibleLimits::is_integer && RealLimits::is_signed == CompatibleLimits::is_signed; }; template struct is_compatible_integer_type : is_compatible_integer_type_impl {}; template struct is_compatible_type_impl: std::false_type {}; template struct is_compatible_type_impl < BasicJsonType, CompatibleType, enable_if_t::value >> { static constexpr bool value = has_to_json::value; }; template struct is_compatible_type : is_compatible_type_impl {}; template struct is_constructible_tuple : std::false_type {}; template struct is_constructible_tuple> : conjunction...> {}; // a naive helper to check if a type is an ordered_map (exploits the fact that // ordered_map inherits capacity() from std::vector) template struct is_ordered_map { using one = char; struct two { char x[2]; // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) }; template static one test( decltype(&C::capacity) ) ; template static two test(...); enum { value = sizeof(test(nullptr)) == sizeof(char) }; // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) }; // to avoid useless casts (see https://github.com/nlohmann/json/issues/2893#issuecomment-889152324) template < typename T, typename U, enable_if_t < !std::is_same::value, int > = 0 > T conditional_static_cast(U value) { return static_cast(value); } template::value, int> = 0> T conditional_static_cast(U value) { return value; } } // namespace detail } // namespace nlohmann // #include #if JSON_HAS_EXPERIMENTAL_FILESYSTEM #include namespace nlohmann::detail { namespace std_fs = std::experimental::filesystem; } // namespace nlohmann::detail #elif JSON_HAS_FILESYSTEM #include namespace nlohmann::detail { namespace std_fs = std::filesystem; } // namespace nlohmann::detail #endif namespace nlohmann { namespace detail { template void from_json(const BasicJsonType& j, typename std::nullptr_t& n) { if (JSON_HEDLEY_UNLIKELY(!j.is_null())) { JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name()), j)); } n = nullptr; } // overloads for basic_json template parameters template < typename BasicJsonType, typename ArithmeticType, enable_if_t < std::is_arithmetic::value&& !std::is_same::value, int > = 0 > void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val) { switch (static_cast(j)) { case value_t::number_unsigned: { val = static_cast(*j.template get_ptr()); break; } case value_t::number_integer: { val = static_cast(*j.template get_ptr()); break; } case value_t::number_float: { val = static_cast(*j.template get_ptr()); break; } case value_t::null: case value_t::object: case value_t::array: case value_t::string: case value_t::boolean: case value_t::binary: case value_t::discarded: default: JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j)); } } template void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b) { if (JSON_HEDLEY_UNLIKELY(!j.is_boolean())) { JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name()), j)); } b = *j.template get_ptr(); } template void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s) { if (JSON_HEDLEY_UNLIKELY(!j.is_string())) { JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j)); } s = *j.template get_ptr(); } template < typename BasicJsonType, typename ConstructibleStringType, enable_if_t < is_constructible_string_type::value&& !std::is_same::value, int > = 0 > void from_json(const BasicJsonType& j, ConstructibleStringType& s) { if (JSON_HEDLEY_UNLIKELY(!j.is_string())) { JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j)); } s = *j.template get_ptr(); } template void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val) { get_arithmetic_value(j, val); } template void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val) { get_arithmetic_value(j, val); } template void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val) { get_arithmetic_value(j, val); } template::value, int> = 0> void from_json(const BasicJsonType& j, EnumType& e) { typename std::underlying_type::type val; get_arithmetic_value(j, val); e = static_cast(val); } // forward_list doesn't have an insert method template::value, int> = 0> void from_json(const BasicJsonType& j, std::forward_list& l) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); } l.clear(); std::transform(j.rbegin(), j.rend(), std::front_inserter(l), [](const BasicJsonType & i) { return i.template get(); }); } // valarray doesn't have an insert method template::value, int> = 0> void from_json(const BasicJsonType& j, std::valarray& l) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); } l.resize(j.size()); std::transform(j.begin(), j.end(), std::begin(l), [](const BasicJsonType & elem) { return elem.template get(); }); } template auto from_json(const BasicJsonType& j, T (&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) -> decltype(j.template get(), void()) { for (std::size_t i = 0; i < N; ++i) { arr[i] = j.at(i).template get(); } } template void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/) { arr = *j.template get_ptr(); } template auto from_json_array_impl(const BasicJsonType& j, std::array& arr, priority_tag<2> /*unused*/) -> decltype(j.template get(), void()) { for (std::size_t i = 0; i < N; ++i) { arr[i] = j.at(i).template get(); } } template::value, int> = 0> auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/) -> decltype( arr.reserve(std::declval()), j.template get(), void()) { using std::end; ConstructibleArrayType ret; ret.reserve(j.size()); std::transform(j.begin(), j.end(), std::inserter(ret, end(ret)), [](const BasicJsonType & i) { // get() returns *this, this won't call a from_json // method when value_type is BasicJsonType return i.template get(); }); arr = std::move(ret); } template::value, int> = 0> void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<0> /*unused*/) { using std::end; ConstructibleArrayType ret; std::transform( j.begin(), j.end(), std::inserter(ret, end(ret)), [](const BasicJsonType & i) { // get() returns *this, this won't call a from_json // method when value_type is BasicJsonType return i.template get(); }); arr = std::move(ret); } template < typename BasicJsonType, typename ConstructibleArrayType, enable_if_t < is_constructible_array_type::value&& !is_constructible_object_type::value&& !is_constructible_string_type::value&& !std::is_same::value&& !is_basic_json::value, int > = 0 > auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr) -> decltype(from_json_array_impl(j, arr, priority_tag<3> {}), j.template get(), void()) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); } from_json_array_impl(j, arr, priority_tag<3> {}); } template < typename BasicJsonType, typename T, std::size_t... Idx > std::array from_json_inplace_array_impl(BasicJsonType&& j, identity_tag> /*unused*/, index_sequence /*unused*/) { return { { std::forward(j).at(Idx).template get()... } }; } template < typename BasicJsonType, typename T, std::size_t N > auto from_json(BasicJsonType&& j, identity_tag> tag) -> decltype(from_json_inplace_array_impl(std::forward(j), tag, make_index_sequence {})) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); } return from_json_inplace_array_impl(std::forward(j), tag, make_index_sequence {}); } template void from_json(const BasicJsonType& j, typename BasicJsonType::binary_t& bin) { if (JSON_HEDLEY_UNLIKELY(!j.is_binary())) { JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(j.type_name()), j)); } bin = *j.template get_ptr(); } template::value, int> = 0> void from_json(const BasicJsonType& j, ConstructibleObjectType& obj) { if (JSON_HEDLEY_UNLIKELY(!j.is_object())) { JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name()), j)); } ConstructibleObjectType ret; const auto* inner_object = j.template get_ptr(); using value_type = typename ConstructibleObjectType::value_type; std::transform( inner_object->begin(), inner_object->end(), std::inserter(ret, ret.begin()), [](typename BasicJsonType::object_t::value_type const & p) { return value_type(p.first, p.second.template get()); }); obj = std::move(ret); } // overload for arithmetic types, not chosen for basic_json template arguments // (BooleanType, etc..); note: Is it really necessary to provide explicit // overloads for boolean_t etc. in case of a custom BooleanType which is not // an arithmetic type? template < typename BasicJsonType, typename ArithmeticType, enable_if_t < std::is_arithmetic::value&& !std::is_same::value&& !std::is_same::value&& !std::is_same::value&& !std::is_same::value, int > = 0 > void from_json(const BasicJsonType& j, ArithmeticType& val) { switch (static_cast(j)) { case value_t::number_unsigned: { val = static_cast(*j.template get_ptr()); break; } case value_t::number_integer: { val = static_cast(*j.template get_ptr()); break; } case value_t::number_float: { val = static_cast(*j.template get_ptr()); break; } case value_t::boolean: { val = static_cast(*j.template get_ptr()); break; } case value_t::null: case value_t::object: case value_t::array: case value_t::string: case value_t::binary: case value_t::discarded: default: JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j)); } } template std::tuple from_json_tuple_impl_base(BasicJsonType&& j, index_sequence /*unused*/) { return std::make_tuple(std::forward(j).at(Idx).template get()...); } template < typename BasicJsonType, class A1, class A2 > std::pair from_json_tuple_impl(BasicJsonType&& j, identity_tag> /*unused*/, priority_tag<0> /*unused*/) { return {std::forward(j).at(0).template get(), std::forward(j).at(1).template get()}; } template void from_json_tuple_impl(BasicJsonType&& j, std::pair& p, priority_tag<1> /*unused*/) { p = from_json_tuple_impl(std::forward(j), identity_tag> {}, priority_tag<0> {}); } template std::tuple from_json_tuple_impl(BasicJsonType&& j, identity_tag> /*unused*/, priority_tag<2> /*unused*/) { return from_json_tuple_impl_base(std::forward(j), index_sequence_for {}); } template void from_json_tuple_impl(BasicJsonType&& j, std::tuple& t, priority_tag<3> /*unused*/) { t = from_json_tuple_impl_base(std::forward(j), index_sequence_for {}); } template auto from_json(BasicJsonType&& j, TupleRelated&& t) -> decltype(from_json_tuple_impl(std::forward(j), std::forward(t), priority_tag<3> {})) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); } return from_json_tuple_impl(std::forward(j), std::forward(t), priority_tag<3> {}); } template < typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator, typename = enable_if_t < !std::is_constructible < typename BasicJsonType::string_t, Key >::value >> void from_json(const BasicJsonType& j, std::map& m) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); } m.clear(); for (const auto& p : j) { if (JSON_HEDLEY_UNLIKELY(!p.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j)); } m.emplace(p.at(0).template get(), p.at(1).template get()); } } template < typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator, typename = enable_if_t < !std::is_constructible < typename BasicJsonType::string_t, Key >::value >> void from_json(const BasicJsonType& j, std::unordered_map& m) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); } m.clear(); for (const auto& p : j) { if (JSON_HEDLEY_UNLIKELY(!p.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j)); } m.emplace(p.at(0).template get(), p.at(1).template get()); } } #if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM template void from_json(const BasicJsonType& j, std_fs::path& p) { if (JSON_HEDLEY_UNLIKELY(!j.is_string())) { JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j)); } p = *j.template get_ptr(); } #endif struct from_json_fn { template auto operator()(const BasicJsonType& j, T&& val) const noexcept(noexcept(from_json(j, std::forward(val)))) -> decltype(from_json(j, std::forward(val))) { return from_json(j, std::forward(val)); } }; } // namespace detail /// namespace to hold default `from_json` function /// to see why this is required: /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces) { constexpr const auto& from_json = detail::static_const::value; // NOLINT(misc-definitions-in-headers) } // namespace } // namespace nlohmann // #include #include // copy #include // begin, end #include // string #include // tuple, get #include // is_same, is_constructible, is_floating_point, is_enum, underlying_type #include // move, forward, declval, pair #include // valarray #include // vector // #include // #include #include // size_t #include // input_iterator_tag #include // string, to_string #include // tuple_size, get, tuple_element #include // move // #include // #include namespace nlohmann { namespace detail { template void int_to_string( string_type& target, std::size_t value ) { // For ADL using std::to_string; target = to_string(value); } template class iteration_proxy_value { public: using difference_type = std::ptrdiff_t; using value_type = iteration_proxy_value; using pointer = value_type * ; using reference = value_type & ; using iterator_category = std::input_iterator_tag; using string_type = typename std::remove_cv< typename std::remove_reference().key() ) >::type >::type; private: /// the iterator IteratorType anchor; /// an index for arrays (used to create key names) std::size_t array_index = 0; /// last stringified array index mutable std::size_t array_index_last = 0; /// a string representation of the array index mutable string_type array_index_str = "0"; /// an empty string (to return a reference for primitive values) const string_type empty_str{}; public: explicit iteration_proxy_value(IteratorType it) noexcept : anchor(std::move(it)) {} /// dereference operator (needed for range-based for) iteration_proxy_value& operator*() { return *this; } /// increment operator (needed for range-based for) iteration_proxy_value& operator++() { ++anchor; ++array_index; return *this; } /// equality operator (needed for InputIterator) bool operator==(const iteration_proxy_value& o) const { return anchor == o.anchor; } /// inequality operator (needed for range-based for) bool operator!=(const iteration_proxy_value& o) const { return anchor != o.anchor; } /// return key of the iterator const string_type& key() const { JSON_ASSERT(anchor.m_object != nullptr); switch (anchor.m_object->type()) { // use integer array index as key case value_t::array: { if (array_index != array_index_last) { int_to_string( array_index_str, array_index ); array_index_last = array_index; } return array_index_str; } // use key from the object case value_t::object: return anchor.key(); // use an empty key for all primitive types case value_t::null: case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: return empty_str; } } /// return value of the iterator typename IteratorType::reference value() const { return anchor.value(); } }; /// proxy class for the items() function template class iteration_proxy { private: /// the container to iterate typename IteratorType::reference container; public: /// construct iteration proxy from a container explicit iteration_proxy(typename IteratorType::reference cont) noexcept : container(cont) {} /// return iterator begin (needed for range-based for) iteration_proxy_value begin() noexcept { return iteration_proxy_value(container.begin()); } /// return iterator end (needed for range-based for) iteration_proxy_value end() noexcept { return iteration_proxy_value(container.end()); } }; // Structured Bindings Support // For further reference see https://blog.tartanllama.xyz/structured-bindings/ // And see https://github.com/nlohmann/json/pull/1391 template = 0> auto get(const nlohmann::detail::iteration_proxy_value& i) -> decltype(i.key()) { return i.key(); } // Structured Bindings Support // For further reference see https://blog.tartanllama.xyz/structured-bindings/ // And see https://github.com/nlohmann/json/pull/1391 template = 0> auto get(const nlohmann::detail::iteration_proxy_value& i) -> decltype(i.value()) { return i.value(); } } // namespace detail } // namespace nlohmann // The Addition to the STD Namespace is required to add // Structured Bindings Support to the iteration_proxy_value class // For further reference see https://blog.tartanllama.xyz/structured-bindings/ // And see https://github.com/nlohmann/json/pull/1391 namespace std { #if defined(__clang__) // Fix: https://github.com/nlohmann/json/issues/1401 #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wmismatched-tags" #endif template class tuple_size<::nlohmann::detail::iteration_proxy_value> : public std::integral_constant {}; template class tuple_element> { public: using type = decltype( get(std::declval < ::nlohmann::detail::iteration_proxy_value> ())); }; #if defined(__clang__) #pragma clang diagnostic pop #endif } // namespace std // #include // #include // #include #if JSON_HAS_EXPERIMENTAL_FILESYSTEM #include namespace nlohmann::detail { namespace std_fs = std::experimental::filesystem; } // namespace nlohmann::detail #elif JSON_HAS_FILESYSTEM #include namespace nlohmann::detail { namespace std_fs = std::filesystem; } // namespace nlohmann::detail #endif namespace nlohmann { namespace detail { ////////////////// // constructors // ////////////////// /* * Note all external_constructor<>::construct functions need to call * j.m_value.destroy(j.m_type) to avoid a memory leak in case j contains an * allocated value (e.g., a string). See bug issue * https://github.com/nlohmann/json/issues/2865 for more information. */ template struct external_constructor; template<> struct external_constructor { template static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept { j.m_value.destroy(j.m_type); j.m_type = value_t::boolean; j.m_value = b; j.assert_invariant(); } }; template<> struct external_constructor { template static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s) { j.m_value.destroy(j.m_type); j.m_type = value_t::string; j.m_value = s; j.assert_invariant(); } template static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s) { j.m_value.destroy(j.m_type); j.m_type = value_t::string; j.m_value = std::move(s); j.assert_invariant(); } template < typename BasicJsonType, typename CompatibleStringType, enable_if_t < !std::is_same::value, int > = 0 > static void construct(BasicJsonType& j, const CompatibleStringType& str) { j.m_value.destroy(j.m_type); j.m_type = value_t::string; j.m_value.string = j.template create(str); j.assert_invariant(); } }; template<> struct external_constructor { template static void construct(BasicJsonType& j, const typename BasicJsonType::binary_t& b) { j.m_value.destroy(j.m_type); j.m_type = value_t::binary; j.m_value = typename BasicJsonType::binary_t(b); j.assert_invariant(); } template static void construct(BasicJsonType& j, typename BasicJsonType::binary_t&& b) { j.m_value.destroy(j.m_type); j.m_type = value_t::binary; j.m_value = typename BasicJsonType::binary_t(std::move(b)); j.assert_invariant(); } }; template<> struct external_constructor { template static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept { j.m_value.destroy(j.m_type); j.m_type = value_t::number_float; j.m_value = val; j.assert_invariant(); } }; template<> struct external_constructor { template static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept { j.m_value.destroy(j.m_type); j.m_type = value_t::number_unsigned; j.m_value = val; j.assert_invariant(); } }; template<> struct external_constructor { template static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept { j.m_value.destroy(j.m_type); j.m_type = value_t::number_integer; j.m_value = val; j.assert_invariant(); } }; template<> struct external_constructor { template static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr) { j.m_value.destroy(j.m_type); j.m_type = value_t::array; j.m_value = arr; j.set_parents(); j.assert_invariant(); } template static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr) { j.m_value.destroy(j.m_type); j.m_type = value_t::array; j.m_value = std::move(arr); j.set_parents(); j.assert_invariant(); } template < typename BasicJsonType, typename CompatibleArrayType, enable_if_t < !std::is_same::value, int > = 0 > static void construct(BasicJsonType& j, const CompatibleArrayType& arr) { using std::begin; using std::end; j.m_value.destroy(j.m_type); j.m_type = value_t::array; j.m_value.array = j.template create(begin(arr), end(arr)); j.set_parents(); j.assert_invariant(); } template static void construct(BasicJsonType& j, const std::vector& arr) { j.m_value.destroy(j.m_type); j.m_type = value_t::array; j.m_value = value_t::array; j.m_value.array->reserve(arr.size()); for (const bool x : arr) { j.m_value.array->push_back(x); j.set_parent(j.m_value.array->back()); } j.assert_invariant(); } template::value, int> = 0> static void construct(BasicJsonType& j, const std::valarray& arr) { j.m_value.destroy(j.m_type); j.m_type = value_t::array; j.m_value = value_t::array; j.m_value.array->resize(arr.size()); if (arr.size() > 0) { std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin()); } j.set_parents(); j.assert_invariant(); } }; template<> struct external_constructor { template static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj) { j.m_value.destroy(j.m_type); j.m_type = value_t::object; j.m_value = obj; j.set_parents(); j.assert_invariant(); } template static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj) { j.m_value.destroy(j.m_type); j.m_type = value_t::object; j.m_value = std::move(obj); j.set_parents(); j.assert_invariant(); } template < typename BasicJsonType, typename CompatibleObjectType, enable_if_t < !std::is_same::value, int > = 0 > static void construct(BasicJsonType& j, const CompatibleObjectType& obj) { using std::begin; using std::end; j.m_value.destroy(j.m_type); j.m_type = value_t::object; j.m_value.object = j.template create(begin(obj), end(obj)); j.set_parents(); j.assert_invariant(); } }; ///////////// // to_json // ///////////// template::value, int> = 0> void to_json(BasicJsonType& j, T b) noexcept { external_constructor::construct(j, b); } template::value, int> = 0> void to_json(BasicJsonType& j, const CompatibleString& s) { external_constructor::construct(j, s); } template void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s) { external_constructor::construct(j, std::move(s)); } template::value, int> = 0> void to_json(BasicJsonType& j, FloatType val) noexcept { external_constructor::construct(j, static_cast(val)); } template::value, int> = 0> void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept { external_constructor::construct(j, static_cast(val)); } template::value, int> = 0> void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept { external_constructor::construct(j, static_cast(val)); } template::value, int> = 0> void to_json(BasicJsonType& j, EnumType e) noexcept { using underlying_type = typename std::underlying_type::type; external_constructor::construct(j, static_cast(e)); } template void to_json(BasicJsonType& j, const std::vector& e) { external_constructor::construct(j, e); } template < typename BasicJsonType, typename CompatibleArrayType, enable_if_t < is_compatible_array_type::value&& !is_compatible_object_type::value&& !is_compatible_string_type::value&& !std::is_same::value&& !is_basic_json::value, int > = 0 > void to_json(BasicJsonType& j, const CompatibleArrayType& arr) { external_constructor::construct(j, arr); } template void to_json(BasicJsonType& j, const typename BasicJsonType::binary_t& bin) { external_constructor::construct(j, bin); } template::value, int> = 0> void to_json(BasicJsonType& j, const std::valarray& arr) { external_constructor::construct(j, std::move(arr)); } template void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr) { external_constructor::construct(j, std::move(arr)); } template < typename BasicJsonType, typename CompatibleObjectType, enable_if_t < is_compatible_object_type::value&& !is_basic_json::value, int > = 0 > void to_json(BasicJsonType& j, const CompatibleObjectType& obj) { external_constructor::construct(j, obj); } template void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj) { external_constructor::construct(j, std::move(obj)); } template < typename BasicJsonType, typename T, std::size_t N, enable_if_t < !std::is_constructible::value, // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) int > = 0 > void to_json(BasicJsonType& j, const T(&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) { external_constructor::construct(j, arr); } template < typename BasicJsonType, typename T1, typename T2, enable_if_t < std::is_constructible::value&& std::is_constructible::value, int > = 0 > void to_json(BasicJsonType& j, const std::pair& p) { j = { p.first, p.second }; } // for https://github.com/nlohmann/json/pull/1134 template>::value, int> = 0> void to_json(BasicJsonType& j, const T& b) { j = { {b.key(), b.value()} }; } template void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence /*unused*/) { j = { std::get(t)... }; } template::value, int > = 0> void to_json(BasicJsonType& j, const T& t) { to_json_tuple_impl(j, t, make_index_sequence::value> {}); } #if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM template void to_json(BasicJsonType& j, const std_fs::path& p) { j = p.string(); } #endif struct to_json_fn { template auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward(val)))) -> decltype(to_json(j, std::forward(val)), void()) { return to_json(j, std::forward(val)); } }; } // namespace detail /// namespace to hold default `to_json` function /// to see why this is required: /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces) { constexpr const auto& to_json = detail::static_const::value; // NOLINT(misc-definitions-in-headers) } // namespace } // namespace nlohmann // #include // #include namespace nlohmann { /// @sa https://json.nlohmann.me/api/adl_serializer/ template struct adl_serializer { /// @brief convert a JSON value to any value type /// @sa https://json.nlohmann.me/api/adl_serializer/from_json/ template static auto from_json(BasicJsonType && j, TargetType& val) noexcept( noexcept(::nlohmann::from_json(std::forward(j), val))) -> decltype(::nlohmann::from_json(std::forward(j), val), void()) { ::nlohmann::from_json(std::forward(j), val); } /// @brief convert a JSON value to any value type /// @sa https://json.nlohmann.me/api/adl_serializer/from_json/ template static auto from_json(BasicJsonType && j) noexcept( noexcept(::nlohmann::from_json(std::forward(j), detail::identity_tag {}))) -> decltype(::nlohmann::from_json(std::forward(j), detail::identity_tag {})) { return ::nlohmann::from_json(std::forward(j), detail::identity_tag {}); } /// @brief convert any value type to a JSON value /// @sa https://json.nlohmann.me/api/adl_serializer/to_json/ template static auto to_json(BasicJsonType& j, TargetType && val) noexcept( noexcept(::nlohmann::to_json(j, std::forward(val)))) -> decltype(::nlohmann::to_json(j, std::forward(val)), void()) { ::nlohmann::to_json(j, std::forward(val)); } }; } // namespace nlohmann // #include #include // uint8_t, uint64_t #include // tie #include // move namespace nlohmann { /// @brief an internal type for a backed binary type /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/ template class byte_container_with_subtype : public BinaryType { public: using container_type = BinaryType; using subtype_type = std::uint64_t; /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ byte_container_with_subtype() noexcept(noexcept(container_type())) : container_type() {} /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ byte_container_with_subtype(const container_type& b) noexcept(noexcept(container_type(b))) : container_type(b) {} /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ byte_container_with_subtype(container_type&& b) noexcept(noexcept(container_type(std::move(b)))) : container_type(std::move(b)) {} /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ byte_container_with_subtype(const container_type& b, subtype_type subtype_) noexcept(noexcept(container_type(b))) : container_type(b) , m_subtype(subtype_) , m_has_subtype(true) {} /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ byte_container_with_subtype(container_type&& b, subtype_type subtype_) noexcept(noexcept(container_type(std::move(b)))) : container_type(std::move(b)) , m_subtype(subtype_) , m_has_subtype(true) {} bool operator==(const byte_container_with_subtype& rhs) const { return std::tie(static_cast(*this), m_subtype, m_has_subtype) == std::tie(static_cast(rhs), rhs.m_subtype, rhs.m_has_subtype); } bool operator!=(const byte_container_with_subtype& rhs) const { return !(rhs == *this); } /// @brief sets the binary subtype /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/set_subtype/ void set_subtype(subtype_type subtype_) noexcept { m_subtype = subtype_; m_has_subtype = true; } /// @brief return the binary subtype /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/subtype/ constexpr subtype_type subtype() const noexcept { return m_has_subtype ? m_subtype : static_cast(-1); } /// @brief return whether the value has a subtype /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/has_subtype/ constexpr bool has_subtype() const noexcept { return m_has_subtype; } /// @brief clears the binary subtype /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/clear_subtype/ void clear_subtype() noexcept { m_subtype = 0; m_has_subtype = false; } private: subtype_type m_subtype = 0; bool m_has_subtype = false; }; } // namespace nlohmann // #include // #include // #include // #include #include // uint8_t #include // size_t #include // hash // #include // #include namespace nlohmann { namespace detail { // boost::hash_combine inline std::size_t combine(std::size_t seed, std::size_t h) noexcept { seed ^= h + 0x9e3779b9 + (seed << 6U) + (seed >> 2U); return seed; } /*! @brief hash a JSON value The hash function tries to rely on std::hash where possible. Furthermore, the type of the JSON value is taken into account to have different hash values for null, 0, 0U, and false, etc. @tparam BasicJsonType basic_json specialization @param j JSON value to hash @return hash value of j */ template std::size_t hash(const BasicJsonType& j) { using string_t = typename BasicJsonType::string_t; using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; const auto type = static_cast(j.type()); switch (j.type()) { case BasicJsonType::value_t::null: case BasicJsonType::value_t::discarded: { return combine(type, 0); } case BasicJsonType::value_t::object: { auto seed = combine(type, j.size()); for (const auto& element : j.items()) { const auto h = std::hash {}(element.key()); seed = combine(seed, h); seed = combine(seed, hash(element.value())); } return seed; } case BasicJsonType::value_t::array: { auto seed = combine(type, j.size()); for (const auto& element : j) { seed = combine(seed, hash(element)); } return seed; } case BasicJsonType::value_t::string: { const auto h = std::hash {}(j.template get_ref()); return combine(type, h); } case BasicJsonType::value_t::boolean: { const auto h = std::hash {}(j.template get()); return combine(type, h); } case BasicJsonType::value_t::number_integer: { const auto h = std::hash {}(j.template get()); return combine(type, h); } case BasicJsonType::value_t::number_unsigned: { const auto h = std::hash {}(j.template get()); return combine(type, h); } case BasicJsonType::value_t::number_float: { const auto h = std::hash {}(j.template get()); return combine(type, h); } case BasicJsonType::value_t::binary: { auto seed = combine(type, j.get_binary().size()); const auto h = std::hash {}(j.get_binary().has_subtype()); seed = combine(seed, h); seed = combine(seed, static_cast(j.get_binary().subtype())); for (const auto byte : j.get_binary()) { seed = combine(seed, std::hash {}(byte)); } return seed; } default: // LCOV_EXCL_LINE JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE return 0; // LCOV_EXCL_LINE } } } // namespace detail } // namespace nlohmann // #include #include // generate_n #include // array #include // ldexp #include // size_t #include // uint8_t, uint16_t, uint32_t, uint64_t #include // snprintf #include // memcpy #include // back_inserter #include // numeric_limits #include // char_traits, string #include // make_pair, move #include // vector // #include // #include #include // array #include // size_t #include // strlen #include // begin, end, iterator_traits, random_access_iterator_tag, distance, next #include // shared_ptr, make_shared, addressof #include // accumulate #include // string, char_traits #include // enable_if, is_base_of, is_pointer, is_integral, remove_pointer #include // pair, declval #ifndef JSON_NO_IO #include // FILE * #include // istream #endif // JSON_NO_IO // #include // #include namespace nlohmann { namespace detail { /// the supported input formats enum class input_format_t { json, cbor, msgpack, ubjson, bson }; //////////////////// // input adapters // //////////////////// #ifndef JSON_NO_IO /*! Input adapter for stdio file access. This adapter read only 1 byte and do not use any buffer. This adapter is a very low level adapter. */ class file_input_adapter { public: using char_type = char; JSON_HEDLEY_NON_NULL(2) explicit file_input_adapter(std::FILE* f) noexcept : m_file(f) {} // make class move-only file_input_adapter(const file_input_adapter&) = delete; file_input_adapter(file_input_adapter&&) noexcept = default; file_input_adapter& operator=(const file_input_adapter&) = delete; file_input_adapter& operator=(file_input_adapter&&) = delete; ~file_input_adapter() = default; std::char_traits::int_type get_character() noexcept { return std::fgetc(m_file); } private: /// the file pointer to read from std::FILE* m_file; }; /*! Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at beginning of input. Does not support changing the underlying std::streambuf in mid-input. Maintains underlying std::istream and std::streambuf to support subsequent use of standard std::istream operations to process any input characters following those used in parsing the JSON input. Clears the std::istream flags; any input errors (e.g., EOF) will be detected by the first subsequent call for input from the std::istream. */ class input_stream_adapter { public: using char_type = char; ~input_stream_adapter() { // clear stream flags; we use underlying streambuf I/O, do not // maintain ifstream flags, except eof if (is != nullptr) { is->clear(is->rdstate() & std::ios::eofbit); } } explicit input_stream_adapter(std::istream& i) : is(&i), sb(i.rdbuf()) {} // delete because of pointer members input_stream_adapter(const input_stream_adapter&) = delete; input_stream_adapter& operator=(input_stream_adapter&) = delete; input_stream_adapter& operator=(input_stream_adapter&&) = delete; input_stream_adapter(input_stream_adapter&& rhs) noexcept : is(rhs.is), sb(rhs.sb) { rhs.is = nullptr; rhs.sb = nullptr; } // std::istream/std::streambuf use std::char_traits::to_int_type, to // ensure that std::char_traits::eof() and the character 0xFF do not // end up as the same value, e.g. 0xFFFFFFFF. std::char_traits::int_type get_character() { auto res = sb->sbumpc(); // set eof manually, as we don't use the istream interface. if (JSON_HEDLEY_UNLIKELY(res == std::char_traits::eof())) { is->clear(is->rdstate() | std::ios::eofbit); } return res; } private: /// the associated input stream std::istream* is = nullptr; std::streambuf* sb = nullptr; }; #endif // JSON_NO_IO // General-purpose iterator-based adapter. It might not be as fast as // theoretically possible for some containers, but it is extremely versatile. template class iterator_input_adapter { public: using char_type = typename std::iterator_traits::value_type; iterator_input_adapter(IteratorType first, IteratorType last) : current(std::move(first)), end(std::move(last)) {} typename std::char_traits::int_type get_character() { if (JSON_HEDLEY_LIKELY(current != end)) { auto result = std::char_traits::to_int_type(*current); std::advance(current, 1); return result; } return std::char_traits::eof(); } private: IteratorType current; IteratorType end; template friend struct wide_string_input_helper; bool empty() const { return current == end; } }; template struct wide_string_input_helper; template struct wide_string_input_helper { // UTF-32 static void fill_buffer(BaseInputAdapter& input, std::array::int_type, 4>& utf8_bytes, size_t& utf8_bytes_index, size_t& utf8_bytes_filled) { utf8_bytes_index = 0; if (JSON_HEDLEY_UNLIKELY(input.empty())) { utf8_bytes[0] = std::char_traits::eof(); utf8_bytes_filled = 1; } else { // get the current character const auto wc = input.get_character(); // UTF-32 to UTF-8 encoding if (wc < 0x80) { utf8_bytes[0] = static_cast::int_type>(wc); utf8_bytes_filled = 1; } else if (wc <= 0x7FF) { utf8_bytes[0] = static_cast::int_type>(0xC0u | ((static_cast(wc) >> 6u) & 0x1Fu)); utf8_bytes[1] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); utf8_bytes_filled = 2; } else if (wc <= 0xFFFF) { utf8_bytes[0] = static_cast::int_type>(0xE0u | ((static_cast(wc) >> 12u) & 0x0Fu)); utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); utf8_bytes[2] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); utf8_bytes_filled = 3; } else if (wc <= 0x10FFFF) { utf8_bytes[0] = static_cast::int_type>(0xF0u | ((static_cast(wc) >> 18u) & 0x07u)); utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 12u) & 0x3Fu)); utf8_bytes[2] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); utf8_bytes[3] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); utf8_bytes_filled = 4; } else { // unknown character utf8_bytes[0] = static_cast::int_type>(wc); utf8_bytes_filled = 1; } } } }; template struct wide_string_input_helper { // UTF-16 static void fill_buffer(BaseInputAdapter& input, std::array::int_type, 4>& utf8_bytes, size_t& utf8_bytes_index, size_t& utf8_bytes_filled) { utf8_bytes_index = 0; if (JSON_HEDLEY_UNLIKELY(input.empty())) { utf8_bytes[0] = std::char_traits::eof(); utf8_bytes_filled = 1; } else { // get the current character const auto wc = input.get_character(); // UTF-16 to UTF-8 encoding if (wc < 0x80) { utf8_bytes[0] = static_cast::int_type>(wc); utf8_bytes_filled = 1; } else if (wc <= 0x7FF) { utf8_bytes[0] = static_cast::int_type>(0xC0u | ((static_cast(wc) >> 6u))); utf8_bytes[1] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); utf8_bytes_filled = 2; } else if (0xD800 > wc || wc >= 0xE000) { utf8_bytes[0] = static_cast::int_type>(0xE0u | ((static_cast(wc) >> 12u))); utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); utf8_bytes[2] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); utf8_bytes_filled = 3; } else { if (JSON_HEDLEY_UNLIKELY(!input.empty())) { const auto wc2 = static_cast(input.get_character()); const auto charcode = 0x10000u + (((static_cast(wc) & 0x3FFu) << 10u) | (wc2 & 0x3FFu)); utf8_bytes[0] = static_cast::int_type>(0xF0u | (charcode >> 18u)); utf8_bytes[1] = static_cast::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu)); utf8_bytes[2] = static_cast::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu)); utf8_bytes[3] = static_cast::int_type>(0x80u | (charcode & 0x3Fu)); utf8_bytes_filled = 4; } else { utf8_bytes[0] = static_cast::int_type>(wc); utf8_bytes_filled = 1; } } } } }; // Wraps another input apdater to convert wide character types into individual bytes. template class wide_string_input_adapter { public: using char_type = char; wide_string_input_adapter(BaseInputAdapter base) : base_adapter(base) {} typename std::char_traits::int_type get_character() noexcept { // check if buffer needs to be filled if (utf8_bytes_index == utf8_bytes_filled) { fill_buffer(); JSON_ASSERT(utf8_bytes_filled > 0); JSON_ASSERT(utf8_bytes_index == 0); } // use buffer JSON_ASSERT(utf8_bytes_filled > 0); JSON_ASSERT(utf8_bytes_index < utf8_bytes_filled); return utf8_bytes[utf8_bytes_index++]; } private: BaseInputAdapter base_adapter; template void fill_buffer() { wide_string_input_helper::fill_buffer(base_adapter, utf8_bytes, utf8_bytes_index, utf8_bytes_filled); } /// a buffer for UTF-8 bytes std::array::int_type, 4> utf8_bytes = {{0, 0, 0, 0}}; /// index to the utf8_codes array for the next valid byte std::size_t utf8_bytes_index = 0; /// number of valid bytes in the utf8_codes array std::size_t utf8_bytes_filled = 0; }; template struct iterator_input_adapter_factory { using iterator_type = IteratorType; using char_type = typename std::iterator_traits::value_type; using adapter_type = iterator_input_adapter; static adapter_type create(IteratorType first, IteratorType last) { return adapter_type(std::move(first), std::move(last)); } }; template struct is_iterator_of_multibyte { using value_type = typename std::iterator_traits::value_type; enum { value = sizeof(value_type) > 1 }; }; template struct iterator_input_adapter_factory::value>> { using iterator_type = IteratorType; using char_type = typename std::iterator_traits::value_type; using base_adapter_type = iterator_input_adapter; using adapter_type = wide_string_input_adapter; static adapter_type create(IteratorType first, IteratorType last) { return adapter_type(base_adapter_type(std::move(first), std::move(last))); } }; // General purpose iterator-based input template typename iterator_input_adapter_factory::adapter_type input_adapter(IteratorType first, IteratorType last) { using factory_type = iterator_input_adapter_factory; return factory_type::create(first, last); } // Convenience shorthand from container to iterator // Enables ADL on begin(container) and end(container) // Encloses the using declarations in namespace for not to leak them to outside scope namespace container_input_adapter_factory_impl { using std::begin; using std::end; template struct container_input_adapter_factory {}; template struct container_input_adapter_factory< ContainerType, void_t()), end(std::declval()))>> { using adapter_type = decltype(input_adapter(begin(std::declval()), end(std::declval()))); static adapter_type create(const ContainerType& container) { return input_adapter(begin(container), end(container)); } }; } // namespace container_input_adapter_factory_impl template typename container_input_adapter_factory_impl::container_input_adapter_factory::adapter_type input_adapter(const ContainerType& container) { return container_input_adapter_factory_impl::container_input_adapter_factory::create(container); } #ifndef JSON_NO_IO // Special cases with fast paths inline file_input_adapter input_adapter(std::FILE* file) { return file_input_adapter(file); } inline input_stream_adapter input_adapter(std::istream& stream) { return input_stream_adapter(stream); } inline input_stream_adapter input_adapter(std::istream&& stream) { return input_stream_adapter(stream); } #endif // JSON_NO_IO using contiguous_bytes_input_adapter = decltype(input_adapter(std::declval(), std::declval())); // Null-delimited strings, and the like. template < typename CharT, typename std::enable_if < std::is_pointer::value&& !std::is_array::value&& std::is_integral::type>::value&& sizeof(typename std::remove_pointer::type) == 1, int >::type = 0 > contiguous_bytes_input_adapter input_adapter(CharT b) { auto length = std::strlen(reinterpret_cast(b)); const auto* ptr = reinterpret_cast(b); return input_adapter(ptr, ptr + length); } template auto input_adapter(T (&array)[N]) -> decltype(input_adapter(array, array + N)) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) { return input_adapter(array, array + N); } // This class only handles inputs of input_buffer_adapter type. // It's required so that expressions like {ptr, len} can be implicitly cast // to the correct adapter. class span_input_adapter { public: template < typename CharT, typename std::enable_if < std::is_pointer::value&& std::is_integral::type>::value&& sizeof(typename std::remove_pointer::type) == 1, int >::type = 0 > span_input_adapter(CharT b, std::size_t l) : ia(reinterpret_cast(b), reinterpret_cast(b) + l) {} template::iterator_category, std::random_access_iterator_tag>::value, int>::type = 0> span_input_adapter(IteratorType first, IteratorType last) : ia(input_adapter(first, last)) {} contiguous_bytes_input_adapter&& get() { return std::move(ia); // NOLINT(hicpp-move-const-arg,performance-move-const-arg) } private: contiguous_bytes_input_adapter ia; }; } // namespace detail } // namespace nlohmann // #include #include #include // string #include // move #include // vector // #include // #include namespace nlohmann { /*! @brief SAX interface This class describes the SAX interface used by @ref nlohmann::json::sax_parse. Each function is called in different situations while the input is parsed. The boolean return value informs the parser whether to continue processing the input. */ template struct json_sax { using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; /*! @brief a null value was read @return whether parsing should proceed */ virtual bool null() = 0; /*! @brief a boolean value was read @param[in] val boolean value @return whether parsing should proceed */ virtual bool boolean(bool val) = 0; /*! @brief an integer number was read @param[in] val integer value @return whether parsing should proceed */ virtual bool number_integer(number_integer_t val) = 0; /*! @brief an unsigned integer number was read @param[in] val unsigned integer value @return whether parsing should proceed */ virtual bool number_unsigned(number_unsigned_t val) = 0; /*! @brief a floating-point number was read @param[in] val floating-point value @param[in] s raw token value @return whether parsing should proceed */ virtual bool number_float(number_float_t val, const string_t& s) = 0; /*! @brief a string value was read @param[in] val string value @return whether parsing should proceed @note It is safe to move the passed string value. */ virtual bool string(string_t& val) = 0; /*! @brief a binary value was read @param[in] val binary value @return whether parsing should proceed @note It is safe to move the passed binary value. */ virtual bool binary(binary_t& val) = 0; /*! @brief the beginning of an object was read @param[in] elements number of object elements or -1 if unknown @return whether parsing should proceed @note binary formats may report the number of elements */ virtual bool start_object(std::size_t elements) = 0; /*! @brief an object key was read @param[in] val object key @return whether parsing should proceed @note It is safe to move the passed string. */ virtual bool key(string_t& val) = 0; /*! @brief the end of an object was read @return whether parsing should proceed */ virtual bool end_object() = 0; /*! @brief the beginning of an array was read @param[in] elements number of array elements or -1 if unknown @return whether parsing should proceed @note binary formats may report the number of elements */ virtual bool start_array(std::size_t elements) = 0; /*! @brief the end of an array was read @return whether parsing should proceed */ virtual bool end_array() = 0; /*! @brief a parse error occurred @param[in] position the position in the input where the error occurs @param[in] last_token the last read token @param[in] ex an exception object describing the error @return whether parsing should proceed (must return false) */ virtual bool parse_error(std::size_t position, const std::string& last_token, const detail::exception& ex) = 0; json_sax() = default; json_sax(const json_sax&) = default; json_sax(json_sax&&) noexcept = default; json_sax& operator=(const json_sax&) = default; json_sax& operator=(json_sax&&) noexcept = default; virtual ~json_sax() = default; }; namespace detail { /*! @brief SAX implementation to create a JSON value from SAX events This class implements the @ref json_sax interface and processes the SAX events to create a JSON value which makes it basically a DOM parser. The structure or hierarchy of the JSON value is managed by the stack `ref_stack` which contains a pointer to the respective array or object for each recursion depth. After successful parsing, the value that is passed by reference to the constructor contains the parsed value. @tparam BasicJsonType the JSON type */ template class json_sax_dom_parser { public: using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; /*! @param[in,out] r reference to a JSON value that is manipulated while parsing @param[in] allow_exceptions_ whether parse errors yield exceptions */ explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true) : root(r), allow_exceptions(allow_exceptions_) {} // make class move-only json_sax_dom_parser(const json_sax_dom_parser&) = delete; json_sax_dom_parser(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete; json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) ~json_sax_dom_parser() = default; bool null() { handle_value(nullptr); return true; } bool boolean(bool val) { handle_value(val); return true; } bool number_integer(number_integer_t val) { handle_value(val); return true; } bool number_unsigned(number_unsigned_t val) { handle_value(val); return true; } bool number_float(number_float_t val, const string_t& /*unused*/) { handle_value(val); return true; } bool string(string_t& val) { handle_value(val); return true; } bool binary(binary_t& val) { handle_value(std::move(val)); return true; } bool start_object(std::size_t len) { ref_stack.push_back(handle_value(BasicJsonType::value_t::object)); if (JSON_HEDLEY_UNLIKELY(len != static_cast(-1) && len > ref_stack.back()->max_size())) { JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len), *ref_stack.back())); } return true; } bool key(string_t& val) { // add null at given key and store the reference for later object_element = &(ref_stack.back()->m_value.object->operator[](val)); return true; } bool end_object() { ref_stack.back()->set_parents(); ref_stack.pop_back(); return true; } bool start_array(std::size_t len) { ref_stack.push_back(handle_value(BasicJsonType::value_t::array)); if (JSON_HEDLEY_UNLIKELY(len != static_cast(-1) && len > ref_stack.back()->max_size())) { JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len), *ref_stack.back())); } return true; } bool end_array() { ref_stack.back()->set_parents(); ref_stack.pop_back(); return true; } template bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const Exception& ex) { errored = true; static_cast(ex); if (allow_exceptions) { JSON_THROW(ex); } return false; } constexpr bool is_errored() const { return errored; } private: /*! @invariant If the ref stack is empty, then the passed value will be the new root. @invariant If the ref stack contains a value, then it is an array or an object to which we can add elements */ template JSON_HEDLEY_RETURNS_NON_NULL BasicJsonType* handle_value(Value&& v) { if (ref_stack.empty()) { root = BasicJsonType(std::forward(v)); return &root; } JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object()); if (ref_stack.back()->is_array()) { ref_stack.back()->m_value.array->emplace_back(std::forward(v)); return &(ref_stack.back()->m_value.array->back()); } JSON_ASSERT(ref_stack.back()->is_object()); JSON_ASSERT(object_element); *object_element = BasicJsonType(std::forward(v)); return object_element; } /// the parsed JSON value BasicJsonType& root; /// stack to model hierarchy of values std::vector ref_stack {}; /// helper to hold the reference for the next object element BasicJsonType* object_element = nullptr; /// whether a syntax error occurred bool errored = false; /// whether to throw exceptions in case of errors const bool allow_exceptions = true; }; template class json_sax_dom_callback_parser { public: using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; using parser_callback_t = typename BasicJsonType::parser_callback_t; using parse_event_t = typename BasicJsonType::parse_event_t; json_sax_dom_callback_parser(BasicJsonType& r, const parser_callback_t cb, const bool allow_exceptions_ = true) : root(r), callback(cb), allow_exceptions(allow_exceptions_) { keep_stack.push_back(true); } // make class move-only json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete; json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete; json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) ~json_sax_dom_callback_parser() = default; bool null() { handle_value(nullptr); return true; } bool boolean(bool val) { handle_value(val); return true; } bool number_integer(number_integer_t val) { handle_value(val); return true; } bool number_unsigned(number_unsigned_t val) { handle_value(val); return true; } bool number_float(number_float_t val, const string_t& /*unused*/) { handle_value(val); return true; } bool string(string_t& val) { handle_value(val); return true; } bool binary(binary_t& val) { handle_value(std::move(val)); return true; } bool start_object(std::size_t len) { // check callback for object start const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::object_start, discarded); keep_stack.push_back(keep); auto val = handle_value(BasicJsonType::value_t::object, true); ref_stack.push_back(val.second); // check object limit if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != static_cast(-1) && len > ref_stack.back()->max_size())) { JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len), *ref_stack.back())); } return true; } bool key(string_t& val) { BasicJsonType k = BasicJsonType(val); // check callback for key const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::key, k); key_keep_stack.push_back(keep); // add discarded value at given key and store the reference for later if (keep && ref_stack.back()) { object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded); } return true; } bool end_object() { if (ref_stack.back()) { if (!callback(static_cast(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back())) { // discard object *ref_stack.back() = discarded; } else { ref_stack.back()->set_parents(); } } JSON_ASSERT(!ref_stack.empty()); JSON_ASSERT(!keep_stack.empty()); ref_stack.pop_back(); keep_stack.pop_back(); if (!ref_stack.empty() && ref_stack.back() && ref_stack.back()->is_structured()) { // remove discarded value for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it) { if (it->is_discarded()) { ref_stack.back()->erase(it); break; } } } return true; } bool start_array(std::size_t len) { const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::array_start, discarded); keep_stack.push_back(keep); auto val = handle_value(BasicJsonType::value_t::array, true); ref_stack.push_back(val.second); // check array limit if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != static_cast(-1) && len > ref_stack.back()->max_size())) { JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len), *ref_stack.back())); } return true; } bool end_array() { bool keep = true; if (ref_stack.back()) { keep = callback(static_cast(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back()); if (keep) { ref_stack.back()->set_parents(); } else { // discard array *ref_stack.back() = discarded; } } JSON_ASSERT(!ref_stack.empty()); JSON_ASSERT(!keep_stack.empty()); ref_stack.pop_back(); keep_stack.pop_back(); // remove discarded value if (!keep && !ref_stack.empty() && ref_stack.back()->is_array()) { ref_stack.back()->m_value.array->pop_back(); } return true; } template bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const Exception& ex) { errored = true; static_cast(ex); if (allow_exceptions) { JSON_THROW(ex); } return false; } constexpr bool is_errored() const { return errored; } private: /*! @param[in] v value to add to the JSON value we build during parsing @param[in] skip_callback whether we should skip calling the callback function; this is required after start_array() and start_object() SAX events, because otherwise we would call the callback function with an empty array or object, respectively. @invariant If the ref stack is empty, then the passed value will be the new root. @invariant If the ref stack contains a value, then it is an array or an object to which we can add elements @return pair of boolean (whether value should be kept) and pointer (to the passed value in the ref_stack hierarchy; nullptr if not kept) */ template std::pair handle_value(Value&& v, const bool skip_callback = false) { JSON_ASSERT(!keep_stack.empty()); // do not handle this value if we know it would be added to a discarded // container if (!keep_stack.back()) { return {false, nullptr}; } // create value auto value = BasicJsonType(std::forward(v)); // check callback const bool keep = skip_callback || callback(static_cast(ref_stack.size()), parse_event_t::value, value); // do not handle this value if we just learnt it shall be discarded if (!keep) { return {false, nullptr}; } if (ref_stack.empty()) { root = std::move(value); return {true, &root}; } // skip this value if we already decided to skip the parent // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360) if (!ref_stack.back()) { return {false, nullptr}; } // we now only expect arrays and objects JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object()); // array if (ref_stack.back()->is_array()) { ref_stack.back()->m_value.array->emplace_back(std::move(value)); return {true, &(ref_stack.back()->m_value.array->back())}; } // object JSON_ASSERT(ref_stack.back()->is_object()); // check if we should store an element for the current key JSON_ASSERT(!key_keep_stack.empty()); const bool store_element = key_keep_stack.back(); key_keep_stack.pop_back(); if (!store_element) { return {false, nullptr}; } JSON_ASSERT(object_element); *object_element = std::move(value); return {true, object_element}; } /// the parsed JSON value BasicJsonType& root; /// stack to model hierarchy of values std::vector ref_stack {}; /// stack to manage which values to keep std::vector keep_stack {}; /// stack to manage which object keys to keep std::vector key_keep_stack {}; /// helper to hold the reference for the next object element BasicJsonType* object_element = nullptr; /// whether a syntax error occurred bool errored = false; /// callback function const parser_callback_t callback = nullptr; /// whether to throw exceptions in case of errors const bool allow_exceptions = true; /// a discarded value for the callback BasicJsonType discarded = BasicJsonType::value_t::discarded; }; template class json_sax_acceptor { public: using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; bool null() { return true; } bool boolean(bool /*unused*/) { return true; } bool number_integer(number_integer_t /*unused*/) { return true; } bool number_unsigned(number_unsigned_t /*unused*/) { return true; } bool number_float(number_float_t /*unused*/, const string_t& /*unused*/) { return true; } bool string(string_t& /*unused*/) { return true; } bool binary(binary_t& /*unused*/) { return true; } bool start_object(std::size_t /*unused*/ = static_cast(-1)) { return true; } bool key(string_t& /*unused*/) { return true; } bool end_object() { return true; } bool start_array(std::size_t /*unused*/ = static_cast(-1)) { return true; } bool end_array() { return true; } bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/) { return false; } }; } // namespace detail } // namespace nlohmann // #include #include // array #include // localeconv #include // size_t #include // snprintf #include // strtof, strtod, strtold, strtoll, strtoull #include // initializer_list #include // char_traits, string #include // move #include // vector // #include // #include // #include namespace nlohmann { namespace detail { /////////// // lexer // /////////// template class lexer_base { public: /// token types for the parser enum class token_type { uninitialized, ///< indicating the scanner is uninitialized literal_true, ///< the `true` literal literal_false, ///< the `false` literal literal_null, ///< the `null` literal value_string, ///< a string -- use get_string() for actual value value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value value_integer, ///< a signed integer -- use get_number_integer() for actual value value_float, ///< an floating point number -- use get_number_float() for actual value begin_array, ///< the character for array begin `[` begin_object, ///< the character for object begin `{` end_array, ///< the character for array end `]` end_object, ///< the character for object end `}` name_separator, ///< the name separator `:` value_separator, ///< the value separator `,` parse_error, ///< indicating a parse error end_of_input, ///< indicating the end of the input buffer literal_or_value ///< a literal or the begin of a value (only for diagnostics) }; /// return name of values of type token_type (only used for errors) JSON_HEDLEY_RETURNS_NON_NULL JSON_HEDLEY_CONST static const char* token_type_name(const token_type t) noexcept { switch (t) { case token_type::uninitialized: return ""; case token_type::literal_true: return "true literal"; case token_type::literal_false: return "false literal"; case token_type::literal_null: return "null literal"; case token_type::value_string: return "string literal"; case token_type::value_unsigned: case token_type::value_integer: case token_type::value_float: return "number literal"; case token_type::begin_array: return "'['"; case token_type::begin_object: return "'{'"; case token_type::end_array: return "']'"; case token_type::end_object: return "'}'"; case token_type::name_separator: return "':'"; case token_type::value_separator: return "','"; case token_type::parse_error: return ""; case token_type::end_of_input: return "end of input"; case token_type::literal_or_value: return "'[', '{', or a literal"; // LCOV_EXCL_START default: // catch non-enum values return "unknown token"; // LCOV_EXCL_STOP } } }; /*! @brief lexical analysis This class organizes the lexical analysis during JSON deserialization. */ template class lexer : public lexer_base { using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using char_type = typename InputAdapterType::char_type; using char_int_type = typename std::char_traits::int_type; public: using token_type = typename lexer_base::token_type; explicit lexer(InputAdapterType&& adapter, bool ignore_comments_ = false) noexcept : ia(std::move(adapter)) , ignore_comments(ignore_comments_) , decimal_point_char(static_cast(get_decimal_point())) {} // delete because of pointer members lexer(const lexer&) = delete; lexer(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) lexer& operator=(lexer&) = delete; lexer& operator=(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) ~lexer() = default; private: ///////////////////// // locales ///////////////////// /// return the locale-dependent decimal point JSON_HEDLEY_PURE static char get_decimal_point() noexcept { const auto* loc = localeconv(); JSON_ASSERT(loc != nullptr); return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point); } ///////////////////// // scan functions ///////////////////// /*! @brief get codepoint from 4 hex characters following `\u` For input "\u c1 c2 c3 c4" the codepoint is: (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4 = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0) Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f' must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The conversion is done by subtracting the offset (0x30, 0x37, and 0x57) between the ASCII value of the character and the desired integer value. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or non-hex character) */ int get_codepoint() { // this function only makes sense after reading `\u` JSON_ASSERT(current == 'u'); int codepoint = 0; const auto factors = { 12u, 8u, 4u, 0u }; for (const auto factor : factors) { get(); if (current >= '0' && current <= '9') { codepoint += static_cast((static_cast(current) - 0x30u) << factor); } else if (current >= 'A' && current <= 'F') { codepoint += static_cast((static_cast(current) - 0x37u) << factor); } else if (current >= 'a' && current <= 'f') { codepoint += static_cast((static_cast(current) - 0x57u) << factor); } else { return -1; } } JSON_ASSERT(0x0000 <= codepoint && codepoint <= 0xFFFF); return codepoint; } /*! @brief check if the next byte(s) are inside a given range Adds the current byte and, for each passed range, reads a new byte and checks if it is inside the range. If a violation was detected, set up an error message and return false. Otherwise, return true. @param[in] ranges list of integers; interpreted as list of pairs of inclusive lower and upper bound, respectively @pre The passed list @a ranges must have 2, 4, or 6 elements; that is, 1, 2, or 3 pairs. This precondition is enforced by an assertion. @return true if and only if no range violation was detected */ bool next_byte_in_range(std::initializer_list ranges) { JSON_ASSERT(ranges.size() == 2 || ranges.size() == 4 || ranges.size() == 6); add(current); for (auto range = ranges.begin(); range != ranges.end(); ++range) { get(); if (JSON_HEDLEY_LIKELY(*range <= current && current <= *(++range))) { add(current); } else { error_message = "invalid string: ill-formed UTF-8 byte"; return false; } } return true; } /*! @brief scan a string literal This function scans a string according to Sect. 7 of RFC 8259. While scanning, bytes are escaped and copied into buffer token_buffer. Then the function returns successfully, token_buffer is *not* null-terminated (as it may contain \0 bytes), and token_buffer.size() is the number of bytes in the string. @return token_type::value_string if string could be successfully scanned, token_type::parse_error otherwise @note In case of errors, variable error_message contains a textual description. */ token_type scan_string() { // reset token_buffer (ignore opening quote) reset(); // we entered the function by reading an open quote JSON_ASSERT(current == '\"'); while (true) { // get next character switch (get()) { // end of file while parsing string case std::char_traits::eof(): { error_message = "invalid string: missing closing quote"; return token_type::parse_error; } // closing quote case '\"': { return token_type::value_string; } // escapes case '\\': { switch (get()) { // quotation mark case '\"': add('\"'); break; // reverse solidus case '\\': add('\\'); break; // solidus case '/': add('/'); break; // backspace case 'b': add('\b'); break; // form feed case 'f': add('\f'); break; // line feed case 'n': add('\n'); break; // carriage return case 'r': add('\r'); break; // tab case 't': add('\t'); break; // unicode escapes case 'u': { const int codepoint1 = get_codepoint(); int codepoint = codepoint1; // start with codepoint1 if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1)) { error_message = "invalid string: '\\u' must be followed by 4 hex digits"; return token_type::parse_error; } // check if code point is a high surrogate if (0xD800 <= codepoint1 && codepoint1 <= 0xDBFF) { // expect next \uxxxx entry if (JSON_HEDLEY_LIKELY(get() == '\\' && get() == 'u')) { const int codepoint2 = get_codepoint(); if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1)) { error_message = "invalid string: '\\u' must be followed by 4 hex digits"; return token_type::parse_error; } // check if codepoint2 is a low surrogate if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 && codepoint2 <= 0xDFFF)) { // overwrite codepoint codepoint = static_cast( // high surrogate occupies the most significant 22 bits (static_cast(codepoint1) << 10u) // low surrogate occupies the least significant 15 bits + static_cast(codepoint2) // there is still the 0xD800, 0xDC00 and 0x10000 noise // in the result, so we have to subtract with: // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00 - 0x35FDC00u); } else { error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF"; return token_type::parse_error; } } else { error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF"; return token_type::parse_error; } } else { if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 && codepoint1 <= 0xDFFF)) { error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF"; return token_type::parse_error; } } // result of the above calculation yields a proper codepoint JSON_ASSERT(0x00 <= codepoint && codepoint <= 0x10FFFF); // translate codepoint into bytes if (codepoint < 0x80) { // 1-byte characters: 0xxxxxxx (ASCII) add(static_cast(codepoint)); } else if (codepoint <= 0x7FF) { // 2-byte characters: 110xxxxx 10xxxxxx add(static_cast(0xC0u | (static_cast(codepoint) >> 6u))); add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); } else if (codepoint <= 0xFFFF) { // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx add(static_cast(0xE0u | (static_cast(codepoint) >> 12u))); add(static_cast(0x80u | ((static_cast(codepoint) >> 6u) & 0x3Fu))); add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); } else { // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx add(static_cast(0xF0u | (static_cast(codepoint) >> 18u))); add(static_cast(0x80u | ((static_cast(codepoint) >> 12u) & 0x3Fu))); add(static_cast(0x80u | ((static_cast(codepoint) >> 6u) & 0x3Fu))); add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); } break; } // other characters after escape default: error_message = "invalid string: forbidden character after backslash"; return token_type::parse_error; } break; } // invalid control characters case 0x00: { error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000"; return token_type::parse_error; } case 0x01: { error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001"; return token_type::parse_error; } case 0x02: { error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002"; return token_type::parse_error; } case 0x03: { error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003"; return token_type::parse_error; } case 0x04: { error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004"; return token_type::parse_error; } case 0x05: { error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005"; return token_type::parse_error; } case 0x06: { error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006"; return token_type::parse_error; } case 0x07: { error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007"; return token_type::parse_error; } case 0x08: { error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b"; return token_type::parse_error; } case 0x09: { error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t"; return token_type::parse_error; } case 0x0A: { error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n"; return token_type::parse_error; } case 0x0B: { error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B"; return token_type::parse_error; } case 0x0C: { error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f"; return token_type::parse_error; } case 0x0D: { error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r"; return token_type::parse_error; } case 0x0E: { error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E"; return token_type::parse_error; } case 0x0F: { error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F"; return token_type::parse_error; } case 0x10: { error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010"; return token_type::parse_error; } case 0x11: { error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011"; return token_type::parse_error; } case 0x12: { error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012"; return token_type::parse_error; } case 0x13: { error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013"; return token_type::parse_error; } case 0x14: { error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014"; return token_type::parse_error; } case 0x15: { error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015"; return token_type::parse_error; } case 0x16: { error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016"; return token_type::parse_error; } case 0x17: { error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017"; return token_type::parse_error; } case 0x18: { error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018"; return token_type::parse_error; } case 0x19: { error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019"; return token_type::parse_error; } case 0x1A: { error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A"; return token_type::parse_error; } case 0x1B: { error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B"; return token_type::parse_error; } case 0x1C: { error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C"; return token_type::parse_error; } case 0x1D: { error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D"; return token_type::parse_error; } case 0x1E: { error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E"; return token_type::parse_error; } case 0x1F: { error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F"; return token_type::parse_error; } // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace)) case 0x20: case 0x21: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27: case 0x28: case 0x29: case 0x2A: case 0x2B: case 0x2C: case 0x2D: case 0x2E: case 0x2F: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: case 0x3A: case 0x3B: case 0x3C: case 0x3D: case 0x3E: case 0x3F: case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4A: case 0x4B: case 0x4C: case 0x4D: case 0x4E: case 0x4F: case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: case 0x58: case 0x59: case 0x5A: case 0x5B: case 0x5D: case 0x5E: case 0x5F: case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6A: case 0x6B: case 0x6C: case 0x6D: case 0x6E: case 0x6F: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: case 0x78: case 0x79: case 0x7A: case 0x7B: case 0x7C: case 0x7D: case 0x7E: case 0x7F: { add(current); break; } // U+0080..U+07FF: bytes C2..DF 80..BF case 0xC2: case 0xC3: case 0xC4: case 0xC5: case 0xC6: case 0xC7: case 0xC8: case 0xC9: case 0xCA: case 0xCB: case 0xCC: case 0xCD: case 0xCE: case 0xCF: case 0xD0: case 0xD1: case 0xD2: case 0xD3: case 0xD4: case 0xD5: case 0xD6: case 0xD7: case 0xD8: case 0xD9: case 0xDA: case 0xDB: case 0xDC: case 0xDD: case 0xDE: case 0xDF: { if (JSON_HEDLEY_UNLIKELY(!next_byte_in_range({0x80, 0xBF}))) { return token_type::parse_error; } break; } // U+0800..U+0FFF: bytes E0 A0..BF 80..BF case 0xE0: { if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF case 0xE1: case 0xE2: case 0xE3: case 0xE4: case 0xE5: case 0xE6: case 0xE7: case 0xE8: case 0xE9: case 0xEA: case 0xEB: case 0xEC: case 0xEE: case 0xEF: { if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+D000..U+D7FF: bytes ED 80..9F 80..BF case 0xED: { if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x9F, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF case 0xF0: { if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF case 0xF1: case 0xF2: case 0xF3: { if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF case 0xF4: { if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // remaining bytes (80..C1 and F5..FF) are ill-formed default: { error_message = "invalid string: ill-formed UTF-8 byte"; return token_type::parse_error; } } } } /*! * @brief scan a comment * @return whether comment could be scanned successfully */ bool scan_comment() { switch (get()) { // single-line comments skip input until a newline or EOF is read case '/': { while (true) { switch (get()) { case '\n': case '\r': case std::char_traits::eof(): case '\0': return true; default: break; } } } // multi-line comments skip input until */ is read case '*': { while (true) { switch (get()) { case std::char_traits::eof(): case '\0': { error_message = "invalid comment; missing closing '*/'"; return false; } case '*': { switch (get()) { case '/': return true; default: { unget(); continue; } } } default: continue; } } } // unexpected character after reading '/' default: { error_message = "invalid comment; expecting '/' or '*' after '/'"; return false; } } } JSON_HEDLEY_NON_NULL(2) static void strtof(float& f, const char* str, char** endptr) noexcept { f = std::strtof(str, endptr); } JSON_HEDLEY_NON_NULL(2) static void strtof(double& f, const char* str, char** endptr) noexcept { f = std::strtod(str, endptr); } JSON_HEDLEY_NON_NULL(2) static void strtof(long double& f, const char* str, char** endptr) noexcept { f = std::strtold(str, endptr); } /*! @brief scan a number literal This function scans a string according to Sect. 6 of RFC 8259. The function is realized with a deterministic finite state machine derived from the grammar described in RFC 8259. Starting in state "init", the input is read and used to determined the next state. Only state "done" accepts the number. State "error" is a trap state to model errors. In the table below, "anything" means any character but the ones listed before. state | 0 | 1-9 | e E | + | - | . | anything ---------|----------|----------|----------|---------|---------|----------|----------- init | zero | any1 | [error] | [error] | minus | [error] | [error] minus | zero | any1 | [error] | [error] | [error] | [error] | [error] zero | done | done | exponent | done | done | decimal1 | done any1 | any1 | any1 | exponent | done | done | decimal1 | done decimal1 | decimal2 | decimal2 | [error] | [error] | [error] | [error] | [error] decimal2 | decimal2 | decimal2 | exponent | done | done | done | done exponent | any2 | any2 | [error] | sign | sign | [error] | [error] sign | any2 | any2 | [error] | [error] | [error] | [error] | [error] any2 | any2 | any2 | done | done | done | done | done The state machine is realized with one label per state (prefixed with "scan_number_") and `goto` statements between them. The state machine contains cycles, but any cycle can be left when EOF is read. Therefore, the function is guaranteed to terminate. During scanning, the read bytes are stored in token_buffer. This string is then converted to a signed integer, an unsigned integer, or a floating-point number. @return token_type::value_unsigned, token_type::value_integer, or token_type::value_float if number could be successfully scanned, token_type::parse_error otherwise @note The scanner is independent of the current locale. Internally, the locale's decimal point is used instead of `.` to work with the locale-dependent converters. */ token_type scan_number() // lgtm [cpp/use-of-goto] { // reset token_buffer to store the number's bytes reset(); // the type of the parsed number; initially set to unsigned; will be // changed if minus sign, decimal point or exponent is read token_type number_type = token_type::value_unsigned; // state (init): we just found out we need to scan a number switch (current) { case '-': { add(current); goto scan_number_minus; } case '0': { add(current); goto scan_number_zero; } case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any1; } // all other characters are rejected outside scan_number() default: // LCOV_EXCL_LINE JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE } scan_number_minus: // state: we just parsed a leading minus sign number_type = token_type::value_integer; switch (get()) { case '0': { add(current); goto scan_number_zero; } case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any1; } default: { error_message = "invalid number; expected digit after '-'"; return token_type::parse_error; } } scan_number_zero: // state: we just parse a zero (maybe with a leading minus sign) switch (get()) { case '.': { add(decimal_point_char); goto scan_number_decimal1; } case 'e': case 'E': { add(current); goto scan_number_exponent; } default: goto scan_number_done; } scan_number_any1: // state: we just parsed a number 0-9 (maybe with a leading minus sign) switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any1; } case '.': { add(decimal_point_char); goto scan_number_decimal1; } case 'e': case 'E': { add(current); goto scan_number_exponent; } default: goto scan_number_done; } scan_number_decimal1: // state: we just parsed a decimal point number_type = token_type::value_float; switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_decimal2; } default: { error_message = "invalid number; expected digit after '.'"; return token_type::parse_error; } } scan_number_decimal2: // we just parsed at least one number after a decimal point switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_decimal2; } case 'e': case 'E': { add(current); goto scan_number_exponent; } default: goto scan_number_done; } scan_number_exponent: // we just parsed an exponent number_type = token_type::value_float; switch (get()) { case '+': case '-': { add(current); goto scan_number_sign; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any2; } default: { error_message = "invalid number; expected '+', '-', or digit after exponent"; return token_type::parse_error; } } scan_number_sign: // we just parsed an exponent sign switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any2; } default: { error_message = "invalid number; expected digit after exponent sign"; return token_type::parse_error; } } scan_number_any2: // we just parsed a number after the exponent or exponent sign switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any2; } default: goto scan_number_done; } scan_number_done: // unget the character after the number (we only read it to know that // we are done scanning a number) unget(); char* endptr = nullptr; // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) errno = 0; // try to parse integers first and fall back to floats if (number_type == token_type::value_unsigned) { const auto x = std::strtoull(token_buffer.data(), &endptr, 10); // we checked the number format before JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); if (errno == 0) { value_unsigned = static_cast(x); if (value_unsigned == x) { return token_type::value_unsigned; } } } else if (number_type == token_type::value_integer) { const auto x = std::strtoll(token_buffer.data(), &endptr, 10); // we checked the number format before JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); if (errno == 0) { value_integer = static_cast(x); if (value_integer == x) { return token_type::value_integer; } } } // this code is reached if we parse a floating-point number or if an // integer conversion above failed strtof(value_float, token_buffer.data(), &endptr); // we checked the number format before JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); return token_type::value_float; } /*! @param[in] literal_text the literal text to expect @param[in] length the length of the passed literal text @param[in] return_type the token type to return on success */ JSON_HEDLEY_NON_NULL(2) token_type scan_literal(const char_type* literal_text, const std::size_t length, token_type return_type) { JSON_ASSERT(std::char_traits::to_char_type(current) == literal_text[0]); for (std::size_t i = 1; i < length; ++i) { if (JSON_HEDLEY_UNLIKELY(std::char_traits::to_char_type(get()) != literal_text[i])) { error_message = "invalid literal"; return token_type::parse_error; } } return return_type; } ///////////////////// // input management ///////////////////// /// reset token_buffer; current character is beginning of token void reset() noexcept { token_buffer.clear(); token_string.clear(); token_string.push_back(std::char_traits::to_char_type(current)); } /* @brief get next character from the input This function provides the interface to the used input adapter. It does not throw in case the input reached EOF, but returns a `std::char_traits::eof()` in that case. Stores the scanned characters for use in error messages. @return character read from the input */ char_int_type get() { ++position.chars_read_total; ++position.chars_read_current_line; if (next_unget) { // just reset the next_unget variable and work with current next_unget = false; } else { current = ia.get_character(); } if (JSON_HEDLEY_LIKELY(current != std::char_traits::eof())) { token_string.push_back(std::char_traits::to_char_type(current)); } if (current == '\n') { ++position.lines_read; position.chars_read_current_line = 0; } return current; } /*! @brief unget current character (read it again on next get) We implement unget by setting variable next_unget to true. The input is not changed - we just simulate ungetting by modifying chars_read_total, chars_read_current_line, and token_string. The next call to get() will behave as if the unget character is read again. */ void unget() { next_unget = true; --position.chars_read_total; // in case we "unget" a newline, we have to also decrement the lines_read if (position.chars_read_current_line == 0) { if (position.lines_read > 0) { --position.lines_read; } } else { --position.chars_read_current_line; } if (JSON_HEDLEY_LIKELY(current != std::char_traits::eof())) { JSON_ASSERT(!token_string.empty()); token_string.pop_back(); } } /// add a character to token_buffer void add(char_int_type c) { token_buffer.push_back(static_cast(c)); } public: ///////////////////// // value getters ///////////////////// /// return integer value constexpr number_integer_t get_number_integer() const noexcept { return value_integer; } /// return unsigned integer value constexpr number_unsigned_t get_number_unsigned() const noexcept { return value_unsigned; } /// return floating-point value constexpr number_float_t get_number_float() const noexcept { return value_float; } /// return current string value (implicitly resets the token; useful only once) string_t& get_string() { return token_buffer; } ///////////////////// // diagnostics ///////////////////// /// return position of last read token constexpr position_t get_position() const noexcept { return position; } /// return the last read token (for errors only). Will never contain EOF /// (an arbitrary value that is not a valid char value, often -1), because /// 255 may legitimately occur. May contain NUL, which should be escaped. std::string get_token_string() const { // escape control characters std::string result; for (const auto c : token_string) { if (static_cast(c) <= '\x1F') { // escape control characters std::array cs{{}}; static_cast((std::snprintf)(cs.data(), cs.size(), "", static_cast(c))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) result += cs.data(); } else { // add character as is result.push_back(static_cast(c)); } } return result; } /// return syntax error message JSON_HEDLEY_RETURNS_NON_NULL constexpr const char* get_error_message() const noexcept { return error_message; } ///////////////////// // actual scanner ///////////////////// /*! @brief skip the UTF-8 byte order mark @return true iff there is no BOM or the correct BOM has been skipped */ bool skip_bom() { if (get() == 0xEF) { // check if we completely parse the BOM return get() == 0xBB && get() == 0xBF; } // the first character is not the beginning of the BOM; unget it to // process is later unget(); return true; } void skip_whitespace() { do { get(); } while (current == ' ' || current == '\t' || current == '\n' || current == '\r'); } token_type scan() { // initially, skip the BOM if (position.chars_read_total == 0 && !skip_bom()) { error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given"; return token_type::parse_error; } // read next character and ignore whitespace skip_whitespace(); // ignore comments while (ignore_comments && current == '/') { if (!scan_comment()) { return token_type::parse_error; } // skip following whitespace skip_whitespace(); } switch (current) { // structural characters case '[': return token_type::begin_array; case ']': return token_type::end_array; case '{': return token_type::begin_object; case '}': return token_type::end_object; case ':': return token_type::name_separator; case ',': return token_type::value_separator; // literals case 't': { std::array true_literal = {{static_cast('t'), static_cast('r'), static_cast('u'), static_cast('e')}}; return scan_literal(true_literal.data(), true_literal.size(), token_type::literal_true); } case 'f': { std::array false_literal = {{static_cast('f'), static_cast('a'), static_cast('l'), static_cast('s'), static_cast('e')}}; return scan_literal(false_literal.data(), false_literal.size(), token_type::literal_false); } case 'n': { std::array null_literal = {{static_cast('n'), static_cast('u'), static_cast('l'), static_cast('l')}}; return scan_literal(null_literal.data(), null_literal.size(), token_type::literal_null); } // string case '\"': return scan_string(); // number case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return scan_number(); // end of input (the null byte is needed when parsing from // string literals) case '\0': case std::char_traits::eof(): return token_type::end_of_input; // error default: error_message = "invalid literal"; return token_type::parse_error; } } private: /// input adapter InputAdapterType ia; /// whether comments should be ignored (true) or signaled as errors (false) const bool ignore_comments = false; /// the current character char_int_type current = std::char_traits::eof(); /// whether the next get() call should just return current bool next_unget = false; /// the start position of the current token position_t position {}; /// raw input token string (for error messages) std::vector token_string {}; /// buffer for variable-length tokens (numbers, strings) string_t token_buffer {}; /// a description of occurred lexer errors const char* error_message = ""; // number values number_integer_t value_integer = 0; number_unsigned_t value_unsigned = 0; number_float_t value_float = 0; /// the decimal point const char_int_type decimal_point_char = '.'; }; } // namespace detail } // namespace nlohmann // #include // #include #include // size_t #include // declval #include // string // #include // #include namespace nlohmann { namespace detail { template using null_function_t = decltype(std::declval().null()); template using boolean_function_t = decltype(std::declval().boolean(std::declval())); template using number_integer_function_t = decltype(std::declval().number_integer(std::declval())); template using number_unsigned_function_t = decltype(std::declval().number_unsigned(std::declval())); template using number_float_function_t = decltype(std::declval().number_float( std::declval(), std::declval())); template using string_function_t = decltype(std::declval().string(std::declval())); template using binary_function_t = decltype(std::declval().binary(std::declval())); template using start_object_function_t = decltype(std::declval().start_object(std::declval())); template using key_function_t = decltype(std::declval().key(std::declval())); template using end_object_function_t = decltype(std::declval().end_object()); template using start_array_function_t = decltype(std::declval().start_array(std::declval())); template using end_array_function_t = decltype(std::declval().end_array()); template using parse_error_function_t = decltype(std::declval().parse_error( std::declval(), std::declval(), std::declval())); template struct is_sax { private: static_assert(is_basic_json::value, "BasicJsonType must be of type basic_json<...>"); using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; using exception_t = typename BasicJsonType::exception; public: static constexpr bool value = is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value; }; template struct is_sax_static_asserts { private: static_assert(is_basic_json::value, "BasicJsonType must be of type basic_json<...>"); using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; using exception_t = typename BasicJsonType::exception; public: static_assert(is_detected_exact::value, "Missing/invalid function: bool null()"); static_assert(is_detected_exact::value, "Missing/invalid function: bool boolean(bool)"); static_assert(is_detected_exact::value, "Missing/invalid function: bool boolean(bool)"); static_assert( is_detected_exact::value, "Missing/invalid function: bool number_integer(number_integer_t)"); static_assert( is_detected_exact::value, "Missing/invalid function: bool number_unsigned(number_unsigned_t)"); static_assert(is_detected_exact::value, "Missing/invalid function: bool number_float(number_float_t, const string_t&)"); static_assert( is_detected_exact::value, "Missing/invalid function: bool string(string_t&)"); static_assert( is_detected_exact::value, "Missing/invalid function: bool binary(binary_t&)"); static_assert(is_detected_exact::value, "Missing/invalid function: bool start_object(std::size_t)"); static_assert(is_detected_exact::value, "Missing/invalid function: bool key(string_t&)"); static_assert(is_detected_exact::value, "Missing/invalid function: bool end_object()"); static_assert(is_detected_exact::value, "Missing/invalid function: bool start_array(std::size_t)"); static_assert(is_detected_exact::value, "Missing/invalid function: bool end_array()"); static_assert( is_detected_exact::value, "Missing/invalid function: bool parse_error(std::size_t, const " "std::string&, const exception&)"); }; } // namespace detail } // namespace nlohmann // #include // #include namespace nlohmann { namespace detail { /// how to treat CBOR tags enum class cbor_tag_handler_t { error, ///< throw a parse_error exception in case of a tag ignore, ///< ignore tags store ///< store tags as binary type }; /*! @brief determine system byte order @return true if and only if system's byte order is little endian @note from https://stackoverflow.com/a/1001328/266378 */ static inline bool little_endianness(int num = 1) noexcept { return *reinterpret_cast(&num) == 1; } /////////////////// // binary reader // /////////////////// /*! @brief deserialization of CBOR, MessagePack, and UBJSON values */ template> class binary_reader { using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; using json_sax_t = SAX; using char_type = typename InputAdapterType::char_type; using char_int_type = typename std::char_traits::int_type; public: /*! @brief create a binary reader @param[in] adapter input adapter to read from */ explicit binary_reader(InputAdapterType&& adapter) noexcept : ia(std::move(adapter)) { (void)detail::is_sax_static_asserts {}; } // make class move-only binary_reader(const binary_reader&) = delete; binary_reader(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) binary_reader& operator=(const binary_reader&) = delete; binary_reader& operator=(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) ~binary_reader() = default; /*! @param[in] format the binary format to parse @param[in] sax_ a SAX event processor @param[in] strict whether to expect the input to be consumed completed @param[in] tag_handler how to treat CBOR tags @return whether parsing was successful */ JSON_HEDLEY_NON_NULL(3) bool sax_parse(const input_format_t format, json_sax_t* sax_, const bool strict = true, const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) { sax = sax_; bool result = false; switch (format) { case input_format_t::bson: result = parse_bson_internal(); break; case input_format_t::cbor: result = parse_cbor_internal(true, tag_handler); break; case input_format_t::msgpack: result = parse_msgpack_internal(); break; case input_format_t::ubjson: result = parse_ubjson_internal(); break; case input_format_t::json: // LCOV_EXCL_LINE default: // LCOV_EXCL_LINE JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE } // strict mode: next byte must be EOF if (result && strict) { if (format == input_format_t::ubjson) { get_ignore_noop(); } else { get(); } if (JSON_HEDLEY_UNLIKELY(current != std::char_traits::eof())) { return sax->parse_error(chars_read, get_token_string(), parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value"), BasicJsonType())); } } return result; } private: ////////// // BSON // ////////// /*! @brief Reads in a BSON-object and passes it to the SAX-parser. @return whether a valid BSON-value was passed to the SAX parser */ bool parse_bson_internal() { std::int32_t document_size{}; get_number(input_format_t::bson, document_size); if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast(-1)))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/false))) { return false; } return sax->end_object(); } /*! @brief Parses a C-style string from the BSON input. @param[in,out] result A reference to the string variable where the read string is to be stored. @return `true` if the \x00-byte indicating the end of the string was encountered before the EOF; false` indicates an unexpected EOF. */ bool get_bson_cstr(string_t& result) { auto out = std::back_inserter(result); while (true) { get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "cstring"))) { return false; } if (current == 0x00) { return true; } *out++ = static_cast(current); } } /*! @brief Parses a zero-terminated string of length @a len from the BSON input. @param[in] len The length (including the zero-byte at the end) of the string to be read. @param[in,out] result A reference to the string variable where the read string is to be stored. @tparam NumberType The type of the length @a len @pre len >= 1 @return `true` if the string was successfully parsed */ template bool get_bson_string(const NumberType len, string_t& result) { if (JSON_HEDLEY_UNLIKELY(len < 1)) { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "string length must be at least 1, is " + std::to_string(len), "string"), BasicJsonType())); } return get_string(input_format_t::bson, len - static_cast(1), result) && get() != std::char_traits::eof(); } /*! @brief Parses a byte array input of length @a len from the BSON input. @param[in] len The length of the byte array to be read. @param[in,out] result A reference to the binary variable where the read array is to be stored. @tparam NumberType The type of the length @a len @pre len >= 0 @return `true` if the byte array was successfully parsed */ template bool get_bson_binary(const NumberType len, binary_t& result) { if (JSON_HEDLEY_UNLIKELY(len < 0)) { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "byte array length cannot be negative, is " + std::to_string(len), "binary"), BasicJsonType())); } // All BSON binary values have a subtype std::uint8_t subtype{}; get_number(input_format_t::bson, subtype); result.set_subtype(subtype); return get_binary(input_format_t::bson, len, result); } /*! @brief Read a BSON document element of the given @a element_type. @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html @param[in] element_type_parse_position The position in the input stream, where the `element_type` was read. @warning Not all BSON element types are supported yet. An unsupported @a element_type will give rise to a parse_error.114: Unsupported BSON record type 0x... @return whether a valid BSON-object/array was passed to the SAX parser */ bool parse_bson_element_internal(const char_int_type element_type, const std::size_t element_type_parse_position) { switch (element_type) { case 0x01: // double { double number{}; return get_number(input_format_t::bson, number) && sax->number_float(static_cast(number), ""); } case 0x02: // string { std::int32_t len{}; string_t value; return get_number(input_format_t::bson, len) && get_bson_string(len, value) && sax->string(value); } case 0x03: // object { return parse_bson_internal(); } case 0x04: // array { return parse_bson_array(); } case 0x05: // binary { std::int32_t len{}; binary_t value; return get_number(input_format_t::bson, len) && get_bson_binary(len, value) && sax->binary(value); } case 0x08: // boolean { return sax->boolean(get() != 0); } case 0x0A: // null { return sax->null(); } case 0x10: // int32 { std::int32_t value{}; return get_number(input_format_t::bson, value) && sax->number_integer(value); } case 0x12: // int64 { std::int64_t value{}; return get_number(input_format_t::bson, value) && sax->number_integer(value); } default: // anything else not supported (yet) { std::array cr{{}}; static_cast((std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast(element_type))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) return sax->parse_error(element_type_parse_position, std::string(cr.data()), parse_error::create(114, element_type_parse_position, "Unsupported BSON record type 0x" + std::string(cr.data()), BasicJsonType())); } } } /*! @brief Read a BSON element list (as specified in the BSON-spec) The same binary layout is used for objects and arrays, hence it must be indicated with the argument @a is_array which one is expected (true --> array, false --> object). @param[in] is_array Determines if the element list being read is to be treated as an object (@a is_array == false), or as an array (@a is_array == true). @return whether a valid BSON-object/array was passed to the SAX parser */ bool parse_bson_element_list(const bool is_array) { string_t key; while (auto element_type = get()) { if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "element list"))) { return false; } const std::size_t element_type_parse_position = chars_read; if (JSON_HEDLEY_UNLIKELY(!get_bson_cstr(key))) { return false; } if (!is_array && !sax->key(key)) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_internal(element_type, element_type_parse_position))) { return false; } // get_bson_cstr only appends key.clear(); } return true; } /*! @brief Reads an array from the BSON input and passes it to the SAX-parser. @return whether a valid BSON-array was passed to the SAX parser */ bool parse_bson_array() { std::int32_t document_size{}; get_number(input_format_t::bson, document_size); if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast(-1)))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/true))) { return false; } return sax->end_array(); } ////////// // CBOR // ////////// /*! @param[in] get_char whether a new character should be retrieved from the input (true) or whether the last read character should be considered instead (false) @param[in] tag_handler how CBOR tags should be treated @return whether a valid CBOR value was passed to the SAX parser */ bool parse_cbor_internal(const bool get_char, const cbor_tag_handler_t tag_handler) { switch (get_char ? get() : current) { // EOF case std::char_traits::eof(): return unexpect_eof(input_format_t::cbor, "value"); // Integer 0x00..0x17 (0..23) case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case 0x09: case 0x0A: case 0x0B: case 0x0C: case 0x0D: case 0x0E: case 0x0F: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: return sax->number_unsigned(static_cast(current)); case 0x18: // Unsigned integer (one-byte uint8_t follows) { std::uint8_t number{}; return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); } case 0x19: // Unsigned integer (two-byte uint16_t follows) { std::uint16_t number{}; return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); } case 0x1A: // Unsigned integer (four-byte uint32_t follows) { std::uint32_t number{}; return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); } case 0x1B: // Unsigned integer (eight-byte uint64_t follows) { std::uint64_t number{}; return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); } // Negative integer -1-0x00..-1-0x17 (-1..-24) case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27: case 0x28: case 0x29: case 0x2A: case 0x2B: case 0x2C: case 0x2D: case 0x2E: case 0x2F: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37: return sax->number_integer(static_cast(0x20 - 1 - current)); case 0x38: // Negative integer (one-byte uint8_t follows) { std::uint8_t number{}; return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); } case 0x39: // Negative integer -1-n (two-byte uint16_t follows) { std::uint16_t number{}; return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); } case 0x3A: // Negative integer -1-n (four-byte uint32_t follows) { std::uint32_t number{}; return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); } case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows) { std::uint64_t number{}; return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - static_cast(number)); } // Binary data (0x00..0x17 bytes follow) case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4A: case 0x4B: case 0x4C: case 0x4D: case 0x4E: case 0x4F: case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: case 0x58: // Binary data (one-byte uint8_t for n follows) case 0x59: // Binary data (two-byte uint16_t for n follow) case 0x5A: // Binary data (four-byte uint32_t for n follow) case 0x5B: // Binary data (eight-byte uint64_t for n follow) case 0x5F: // Binary data (indefinite length) { binary_t b; return get_cbor_binary(b) && sax->binary(b); } // UTF-8 string (0x00..0x17 bytes follow) case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6A: case 0x6B: case 0x6C: case 0x6D: case 0x6E: case 0x6F: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: case 0x78: // UTF-8 string (one-byte uint8_t for n follows) case 0x79: // UTF-8 string (two-byte uint16_t for n follow) case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) case 0x7F: // UTF-8 string (indefinite length) { string_t s; return get_cbor_string(s) && sax->string(s); } // array (0x00..0x17 data items follow) case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: return get_cbor_array(static_cast(static_cast(current) & 0x1Fu), tag_handler); case 0x98: // array (one-byte uint8_t for n follows) { std::uint8_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); } case 0x99: // array (two-byte uint16_t for n follow) { std::uint16_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); } case 0x9A: // array (four-byte uint32_t for n follow) { std::uint32_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); } case 0x9B: // array (eight-byte uint64_t for n follow) { std::uint64_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_array(detail::conditional_static_cast(len), tag_handler); } case 0x9F: // array (indefinite length) return get_cbor_array(static_cast(-1), tag_handler); // map (0x00..0x17 pairs of data items follow) case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: return get_cbor_object(static_cast(static_cast(current) & 0x1Fu), tag_handler); case 0xB8: // map (one-byte uint8_t for n follows) { std::uint8_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); } case 0xB9: // map (two-byte uint16_t for n follow) { std::uint16_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); } case 0xBA: // map (four-byte uint32_t for n follow) { std::uint32_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); } case 0xBB: // map (eight-byte uint64_t for n follow) { std::uint64_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_object(detail::conditional_static_cast(len), tag_handler); } case 0xBF: // map (indefinite length) return get_cbor_object(static_cast(-1), tag_handler); case 0xC6: // tagged item case 0xC7: case 0xC8: case 0xC9: case 0xCA: case 0xCB: case 0xCC: case 0xCD: case 0xCE: case 0xCF: case 0xD0: case 0xD1: case 0xD2: case 0xD3: case 0xD4: case 0xD8: // tagged item (1 bytes follow) case 0xD9: // tagged item (2 bytes follow) case 0xDA: // tagged item (4 bytes follow) case 0xDB: // tagged item (8 bytes follow) { switch (tag_handler) { case cbor_tag_handler_t::error: { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); } case cbor_tag_handler_t::ignore: { // ignore binary subtype switch (current) { case 0xD8: { std::uint8_t subtype_to_ignore{}; get_number(input_format_t::cbor, subtype_to_ignore); break; } case 0xD9: { std::uint16_t subtype_to_ignore{}; get_number(input_format_t::cbor, subtype_to_ignore); break; } case 0xDA: { std::uint32_t subtype_to_ignore{}; get_number(input_format_t::cbor, subtype_to_ignore); break; } case 0xDB: { std::uint64_t subtype_to_ignore{}; get_number(input_format_t::cbor, subtype_to_ignore); break; } default: break; } return parse_cbor_internal(true, tag_handler); } case cbor_tag_handler_t::store: { binary_t b; // use binary subtype and store in binary container switch (current) { case 0xD8: { std::uint8_t subtype{}; get_number(input_format_t::cbor, subtype); b.set_subtype(detail::conditional_static_cast(subtype)); break; } case 0xD9: { std::uint16_t subtype{}; get_number(input_format_t::cbor, subtype); b.set_subtype(detail::conditional_static_cast(subtype)); break; } case 0xDA: { std::uint32_t subtype{}; get_number(input_format_t::cbor, subtype); b.set_subtype(detail::conditional_static_cast(subtype)); break; } case 0xDB: { std::uint64_t subtype{}; get_number(input_format_t::cbor, subtype); b.set_subtype(detail::conditional_static_cast(subtype)); break; } default: return parse_cbor_internal(true, tag_handler); } get(); return get_cbor_binary(b) && sax->binary(b); } default: // LCOV_EXCL_LINE JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE return false; // LCOV_EXCL_LINE } } case 0xF4: // false return sax->boolean(false); case 0xF5: // true return sax->boolean(true); case 0xF6: // null return sax->null(); case 0xF9: // Half-Precision Float (two-byte IEEE 754) { const auto byte1_raw = get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number"))) { return false; } const auto byte2_raw = get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number"))) { return false; } const auto byte1 = static_cast(byte1_raw); const auto byte2 = static_cast(byte2_raw); // code from RFC 7049, Appendix D, Figure 3: // As half-precision floating-point numbers were only added // to IEEE 754 in 2008, today's programming platforms often // still only have limited support for them. It is very // easy to include at least decoding support for them even // without such support. An example of a small decoder for // half-precision floating-point numbers in the C language // is shown in Fig. 3. const auto half = static_cast((byte1 << 8u) + byte2); const double val = [&half] { const int exp = (half >> 10u) & 0x1Fu; const unsigned int mant = half & 0x3FFu; JSON_ASSERT(0 <= exp&& exp <= 32); JSON_ASSERT(mant <= 1024); switch (exp) { case 0: return std::ldexp(mant, -24); case 31: return (mant == 0) ? std::numeric_limits::infinity() : std::numeric_limits::quiet_NaN(); default: return std::ldexp(mant + 1024, exp - 25); } }(); return sax->number_float((half & 0x8000u) != 0 ? static_cast(-val) : static_cast(val), ""); } case 0xFA: // Single-Precision Float (four-byte IEEE 754) { float number{}; return get_number(input_format_t::cbor, number) && sax->number_float(static_cast(number), ""); } case 0xFB: // Double-Precision Float (eight-byte IEEE 754) { double number{}; return get_number(input_format_t::cbor, number) && sax->number_float(static_cast(number), ""); } default: // anything else (0xFF is handled inside the other types) { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); } } } /*! @brief reads a CBOR string This function first reads starting bytes to determine the expected string length and then copies this number of bytes into a string. Additionally, CBOR's strings with indefinite lengths are supported. @param[out] result created string @return whether string creation completed */ bool get_cbor_string(string_t& result) { if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "string"))) { return false; } switch (current) { // UTF-8 string (0x00..0x17 bytes follow) case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6A: case 0x6B: case 0x6C: case 0x6D: case 0x6E: case 0x6F: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: { return get_string(input_format_t::cbor, static_cast(current) & 0x1Fu, result); } case 0x78: // UTF-8 string (one-byte uint8_t for n follows) { std::uint8_t len{}; return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); } case 0x79: // UTF-8 string (two-byte uint16_t for n follow) { std::uint16_t len{}; return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); } case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) { std::uint32_t len{}; return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); } case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) { std::uint64_t len{}; return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); } case 0x7F: // UTF-8 string (indefinite length) { while (get() != 0xFF) { string_t chunk; if (!get_cbor_string(chunk)) { return false; } result.append(chunk); } return true; } default: { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0x" + last_token, "string"), BasicJsonType())); } } } /*! @brief reads a CBOR byte array This function first reads starting bytes to determine the expected byte array length and then copies this number of bytes into the byte array. Additionally, CBOR's byte arrays with indefinite lengths are supported. @param[out] result created byte array @return whether byte array creation completed */ bool get_cbor_binary(binary_t& result) { if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "binary"))) { return false; } switch (current) { // Binary data (0x00..0x17 bytes follow) case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4A: case 0x4B: case 0x4C: case 0x4D: case 0x4E: case 0x4F: case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: { return get_binary(input_format_t::cbor, static_cast(current) & 0x1Fu, result); } case 0x58: // Binary data (one-byte uint8_t for n follows) { std::uint8_t len{}; return get_number(input_format_t::cbor, len) && get_binary(input_format_t::cbor, len, result); } case 0x59: // Binary data (two-byte uint16_t for n follow) { std::uint16_t len{}; return get_number(input_format_t::cbor, len) && get_binary(input_format_t::cbor, len, result); } case 0x5A: // Binary data (four-byte uint32_t for n follow) { std::uint32_t len{}; return get_number(input_format_t::cbor, len) && get_binary(input_format_t::cbor, len, result); } case 0x5B: // Binary data (eight-byte uint64_t for n follow) { std::uint64_t len{}; return get_number(input_format_t::cbor, len) && get_binary(input_format_t::cbor, len, result); } case 0x5F: // Binary data (indefinite length) { while (get() != 0xFF) { binary_t chunk; if (!get_cbor_binary(chunk)) { return false; } result.insert(result.end(), chunk.begin(), chunk.end()); } return true; } default: { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x40-0x5B) or indefinite binary array type (0x5F); last byte: 0x" + last_token, "binary"), BasicJsonType())); } } } /*! @param[in] len the length of the array or static_cast(-1) for an array of indefinite size @param[in] tag_handler how CBOR tags should be treated @return whether array creation completed */ bool get_cbor_array(const std::size_t len, const cbor_tag_handler_t tag_handler) { if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len))) { return false; } if (len != static_cast(-1)) { for (std::size_t i = 0; i < len; ++i) { if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) { return false; } } } else { while (get() != 0xFF) { if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(false, tag_handler))) { return false; } } } return sax->end_array(); } /*! @param[in] len the length of the object or static_cast(-1) for an object of indefinite size @param[in] tag_handler how CBOR tags should be treated @return whether object creation completed */ bool get_cbor_object(const std::size_t len, const cbor_tag_handler_t tag_handler) { if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len))) { return false; } if (len != 0) { string_t key; if (len != static_cast(-1)) { for (std::size_t i = 0; i < len; ++i) { get(); if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) { return false; } key.clear(); } } else { while (get() != 0xFF) { if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) { return false; } key.clear(); } } } return sax->end_object(); } ///////////// // MsgPack // ///////////// /*! @return whether a valid MessagePack value was passed to the SAX parser */ bool parse_msgpack_internal() { switch (get()) { // EOF case std::char_traits::eof(): return unexpect_eof(input_format_t::msgpack, "value"); // positive fixint case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case 0x09: case 0x0A: case 0x0B: case 0x0C: case 0x0D: case 0x0E: case 0x0F: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1A: case 0x1B: case 0x1C: case 0x1D: case 0x1E: case 0x1F: case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27: case 0x28: case 0x29: case 0x2A: case 0x2B: case 0x2C: case 0x2D: case 0x2E: case 0x2F: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: case 0x3A: case 0x3B: case 0x3C: case 0x3D: case 0x3E: case 0x3F: case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4A: case 0x4B: case 0x4C: case 0x4D: case 0x4E: case 0x4F: case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: case 0x58: case 0x59: case 0x5A: case 0x5B: case 0x5C: case 0x5D: case 0x5E: case 0x5F: case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6A: case 0x6B: case 0x6C: case 0x6D: case 0x6E: case 0x6F: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: case 0x78: case 0x79: case 0x7A: case 0x7B: case 0x7C: case 0x7D: case 0x7E: case 0x7F: return sax->number_unsigned(static_cast(current)); // fixmap case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: return get_msgpack_object(static_cast(static_cast(current) & 0x0Fu)); // fixarray case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: case 0x98: case 0x99: case 0x9A: case 0x9B: case 0x9C: case 0x9D: case 0x9E: case 0x9F: return get_msgpack_array(static_cast(static_cast(current) & 0x0Fu)); // fixstr case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: case 0xD9: // str 8 case 0xDA: // str 16 case 0xDB: // str 32 { string_t s; return get_msgpack_string(s) && sax->string(s); } case 0xC0: // nil return sax->null(); case 0xC2: // false return sax->boolean(false); case 0xC3: // true return sax->boolean(true); case 0xC4: // bin 8 case 0xC5: // bin 16 case 0xC6: // bin 32 case 0xC7: // ext 8 case 0xC8: // ext 16 case 0xC9: // ext 32 case 0xD4: // fixext 1 case 0xD5: // fixext 2 case 0xD6: // fixext 4 case 0xD7: // fixext 8 case 0xD8: // fixext 16 { binary_t b; return get_msgpack_binary(b) && sax->binary(b); } case 0xCA: // float 32 { float number{}; return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast(number), ""); } case 0xCB: // float 64 { double number{}; return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast(number), ""); } case 0xCC: // uint 8 { std::uint8_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); } case 0xCD: // uint 16 { std::uint16_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); } case 0xCE: // uint 32 { std::uint32_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); } case 0xCF: // uint 64 { std::uint64_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); } case 0xD0: // int 8 { std::int8_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_integer(number); } case 0xD1: // int 16 { std::int16_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_integer(number); } case 0xD2: // int 32 { std::int32_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_integer(number); } case 0xD3: // int 64 { std::int64_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_integer(number); } case 0xDC: // array 16 { std::uint16_t len{}; return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast(len)); } case 0xDD: // array 32 { std::uint32_t len{}; return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast(len)); } case 0xDE: // map 16 { std::uint16_t len{}; return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast(len)); } case 0xDF: // map 32 { std::uint32_t len{}; return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast(len)); } // negative fixint case 0xE0: case 0xE1: case 0xE2: case 0xE3: case 0xE4: case 0xE5: case 0xE6: case 0xE7: case 0xE8: case 0xE9: case 0xEA: case 0xEB: case 0xEC: case 0xED: case 0xEE: case 0xEF: case 0xF0: case 0xF1: case 0xF2: case 0xF3: case 0xF4: case 0xF5: case 0xF6: case 0xF7: case 0xF8: case 0xF9: case 0xFA: case 0xFB: case 0xFC: case 0xFD: case 0xFE: case 0xFF: return sax->number_integer(static_cast(current)); default: // anything else { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::msgpack, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); } } } /*! @brief reads a MessagePack string This function first reads starting bytes to determine the expected string length and then copies this number of bytes into a string. @param[out] result created string @return whether string creation completed */ bool get_msgpack_string(string_t& result) { if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::msgpack, "string"))) { return false; } switch (current) { // fixstr case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: { return get_string(input_format_t::msgpack, static_cast(current) & 0x1Fu, result); } case 0xD9: // str 8 { std::uint8_t len{}; return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); } case 0xDA: // str 16 { std::uint16_t len{}; return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); } case 0xDB: // str 32 { std::uint32_t len{}; return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); } default: { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::msgpack, "expected length specification (0xA0-0xBF, 0xD9-0xDB); last byte: 0x" + last_token, "string"), BasicJsonType())); } } } /*! @brief reads a MessagePack byte array This function first reads starting bytes to determine the expected byte array length and then copies this number of bytes into a byte array. @param[out] result created byte array @return whether byte array creation completed */ bool get_msgpack_binary(binary_t& result) { // helper function to set the subtype auto assign_and_return_true = [&result](std::int8_t subtype) { result.set_subtype(static_cast(subtype)); return true; }; switch (current) { case 0xC4: // bin 8 { std::uint8_t len{}; return get_number(input_format_t::msgpack, len) && get_binary(input_format_t::msgpack, len, result); } case 0xC5: // bin 16 { std::uint16_t len{}; return get_number(input_format_t::msgpack, len) && get_binary(input_format_t::msgpack, len, result); } case 0xC6: // bin 32 { std::uint32_t len{}; return get_number(input_format_t::msgpack, len) && get_binary(input_format_t::msgpack, len, result); } case 0xC7: // ext 8 { std::uint8_t len{}; std::int8_t subtype{}; return get_number(input_format_t::msgpack, len) && get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, len, result) && assign_and_return_true(subtype); } case 0xC8: // ext 16 { std::uint16_t len{}; std::int8_t subtype{}; return get_number(input_format_t::msgpack, len) && get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, len, result) && assign_and_return_true(subtype); } case 0xC9: // ext 32 { std::uint32_t len{}; std::int8_t subtype{}; return get_number(input_format_t::msgpack, len) && get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, len, result) && assign_and_return_true(subtype); } case 0xD4: // fixext 1 { std::int8_t subtype{}; return get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, 1, result) && assign_and_return_true(subtype); } case 0xD5: // fixext 2 { std::int8_t subtype{}; return get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, 2, result) && assign_and_return_true(subtype); } case 0xD6: // fixext 4 { std::int8_t subtype{}; return get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, 4, result) && assign_and_return_true(subtype); } case 0xD7: // fixext 8 { std::int8_t subtype{}; return get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, 8, result) && assign_and_return_true(subtype); } case 0xD8: // fixext 16 { std::int8_t subtype{}; return get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, 16, result) && assign_and_return_true(subtype); } default: // LCOV_EXCL_LINE return false; // LCOV_EXCL_LINE } } /*! @param[in] len the length of the array @return whether array creation completed */ bool get_msgpack_array(const std::size_t len) { if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len))) { return false; } for (std::size_t i = 0; i < len; ++i) { if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal())) { return false; } } return sax->end_array(); } /*! @param[in] len the length of the object @return whether object creation completed */ bool get_msgpack_object(const std::size_t len) { if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len))) { return false; } string_t key; for (std::size_t i = 0; i < len; ++i) { get(); if (JSON_HEDLEY_UNLIKELY(!get_msgpack_string(key) || !sax->key(key))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal())) { return false; } key.clear(); } return sax->end_object(); } //////////// // UBJSON // //////////// /*! @param[in] get_char whether a new character should be retrieved from the input (true, default) or whether the last read character should be considered instead @return whether a valid UBJSON value was passed to the SAX parser */ bool parse_ubjson_internal(const bool get_char = true) { return get_ubjson_value(get_char ? get_ignore_noop() : current); } /*! @brief reads a UBJSON string This function is either called after reading the 'S' byte explicitly indicating a string, or in case of an object key where the 'S' byte can be left out. @param[out] result created string @param[in] get_char whether a new character should be retrieved from the input (true, default) or whether the last read character should be considered instead @return whether string creation completed */ bool get_ubjson_string(string_t& result, const bool get_char = true) { if (get_char) { get(); // TODO(niels): may we ignore N here? } if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value"))) { return false; } switch (current) { case 'U': { std::uint8_t len{}; return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); } case 'i': { std::int8_t len{}; return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); } case 'I': { std::int16_t len{}; return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); } case 'l': { std::int32_t len{}; return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); } case 'L': { std::int64_t len{}; return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); } default: auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L); last byte: 0x" + last_token, "string"), BasicJsonType())); } } /*! @param[out] result determined size @return whether size determination completed */ bool get_ubjson_size_value(std::size_t& result) { switch (get_ignore_noop()) { case 'U': { std::uint8_t number{}; if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) { return false; } result = static_cast(number); return true; } case 'i': { std::int8_t number{}; if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) { return false; } result = static_cast(number); // NOLINT(bugprone-signed-char-misuse,cert-str34-c): number is not a char return true; } case 'I': { std::int16_t number{}; if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) { return false; } result = static_cast(number); return true; } case 'l': { std::int32_t number{}; if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) { return false; } result = static_cast(number); return true; } case 'L': { std::int64_t number{}; if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) { return false; } result = static_cast(number); return true; } default: { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L) after '#'; last byte: 0x" + last_token, "size"), BasicJsonType())); } } } /*! @brief determine the type and size for a container In the optimized UBJSON format, a type and a size can be provided to allow for a more compact representation. @param[out] result pair of the size and the type @return whether pair creation completed */ bool get_ubjson_size_type(std::pair& result) { result.first = string_t::npos; // size result.second = 0; // type get_ignore_noop(); if (current == '$') { result.second = get(); // must not ignore 'N', because 'N' maybe the type if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "type"))) { return false; } get_ignore_noop(); if (JSON_HEDLEY_UNLIKELY(current != '#')) { if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value"))) { return false; } auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "expected '#' after type information; last byte: 0x" + last_token, "size"), BasicJsonType())); } return get_ubjson_size_value(result.first); } if (current == '#') { return get_ubjson_size_value(result.first); } return true; } /*! @param prefix the previously read or set type prefix @return whether value creation completed */ bool get_ubjson_value(const char_int_type prefix) { switch (prefix) { case std::char_traits::eof(): // EOF return unexpect_eof(input_format_t::ubjson, "value"); case 'T': // true return sax->boolean(true); case 'F': // false return sax->boolean(false); case 'Z': // null return sax->null(); case 'U': { std::uint8_t number{}; return get_number(input_format_t::ubjson, number) && sax->number_unsigned(number); } case 'i': { std::int8_t number{}; return get_number(input_format_t::ubjson, number) && sax->number_integer(number); } case 'I': { std::int16_t number{}; return get_number(input_format_t::ubjson, number) && sax->number_integer(number); } case 'l': { std::int32_t number{}; return get_number(input_format_t::ubjson, number) && sax->number_integer(number); } case 'L': { std::int64_t number{}; return get_number(input_format_t::ubjson, number) && sax->number_integer(number); } case 'd': { float number{}; return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast(number), ""); } case 'D': { double number{}; return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast(number), ""); } case 'H': { return get_ubjson_high_precision_number(); } case 'C': // char { get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "char"))) { return false; } if (JSON_HEDLEY_UNLIKELY(current > 127)) { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "byte after 'C' must be in range 0x00..0x7F; last byte: 0x" + last_token, "char"), BasicJsonType())); } string_t s(1, static_cast(current)); return sax->string(s); } case 'S': // string { string_t s; return get_ubjson_string(s) && sax->string(s); } case '[': // array return get_ubjson_array(); case '{': // object return get_ubjson_object(); default: // anything else { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); } } } /*! @return whether array creation completed */ bool get_ubjson_array() { std::pair size_and_type; if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type))) { return false; } if (size_and_type.first != string_t::npos) { if (JSON_HEDLEY_UNLIKELY(!sax->start_array(size_and_type.first))) { return false; } if (size_and_type.second != 0) { if (size_and_type.second != 'N') { for (std::size_t i = 0; i < size_and_type.first; ++i) { if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second))) { return false; } } } } else { for (std::size_t i = 0; i < size_and_type.first; ++i) { if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) { return false; } } } } else { if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast(-1)))) { return false; } while (current != ']') { if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal(false))) { return false; } get_ignore_noop(); } } return sax->end_array(); } /*! @return whether object creation completed */ bool get_ubjson_object() { std::pair size_and_type; if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type))) { return false; } string_t key; if (size_and_type.first != string_t::npos) { if (JSON_HEDLEY_UNLIKELY(!sax->start_object(size_and_type.first))) { return false; } if (size_and_type.second != 0) { for (std::size_t i = 0; i < size_and_type.first; ++i) { if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key))) { return false; } if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second))) { return false; } key.clear(); } } else { for (std::size_t i = 0; i < size_and_type.first; ++i) { if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) { return false; } key.clear(); } } } else { if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast(-1)))) { return false; } while (current != '}') { if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key, false) || !sax->key(key))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) { return false; } get_ignore_noop(); key.clear(); } } return sax->end_object(); } // Note, no reader for UBJSON binary types is implemented because they do // not exist bool get_ubjson_high_precision_number() { // get size of following number string std::size_t size{}; auto res = get_ubjson_size_value(size); if (JSON_HEDLEY_UNLIKELY(!res)) { return res; } // get number string std::vector number_vector; for (std::size_t i = 0; i < size; ++i) { get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "number"))) { return false; } number_vector.push_back(static_cast(current)); } // parse number string using ia_type = decltype(detail::input_adapter(number_vector)); auto number_lexer = detail::lexer(detail::input_adapter(number_vector), false); const auto result_number = number_lexer.scan(); const auto number_string = number_lexer.get_token_string(); const auto result_remainder = number_lexer.scan(); using token_type = typename detail::lexer_base::token_type; if (JSON_HEDLEY_UNLIKELY(result_remainder != token_type::end_of_input)) { return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format_t::ubjson, "invalid number text: " + number_lexer.get_token_string(), "high-precision number"), BasicJsonType())); } switch (result_number) { case token_type::value_integer: return sax->number_integer(number_lexer.get_number_integer()); case token_type::value_unsigned: return sax->number_unsigned(number_lexer.get_number_unsigned()); case token_type::value_float: return sax->number_float(number_lexer.get_number_float(), std::move(number_string)); case token_type::uninitialized: case token_type::literal_true: case token_type::literal_false: case token_type::literal_null: case token_type::value_string: case token_type::begin_array: case token_type::begin_object: case token_type::end_array: case token_type::end_object: case token_type::name_separator: case token_type::value_separator: case token_type::parse_error: case token_type::end_of_input: case token_type::literal_or_value: default: return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format_t::ubjson, "invalid number text: " + number_lexer.get_token_string(), "high-precision number"), BasicJsonType())); } } /////////////////////// // Utility functions // /////////////////////// /*! @brief get next character from the input This function provides the interface to the used input adapter. It does not throw in case the input reached EOF, but returns a -'ve valued `std::char_traits::eof()` in that case. @return character read from the input */ char_int_type get() { ++chars_read; return current = ia.get_character(); } /*! @return character read from the input after ignoring all 'N' entries */ char_int_type get_ignore_noop() { do { get(); } while (current == 'N'); return current; } /* @brief read a number from the input @tparam NumberType the type of the number @param[in] format the current format (for diagnostics) @param[out] result number of type @a NumberType @return whether conversion completed @note This function needs to respect the system's endianness, because bytes in CBOR, MessagePack, and UBJSON are stored in network order (big endian) and therefore need reordering on little endian systems. */ template bool get_number(const input_format_t format, NumberType& result) { // step 1: read input into array with system's byte order std::array vec{}; for (std::size_t i = 0; i < sizeof(NumberType); ++i) { get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "number"))) { return false; } // reverse byte order prior to conversion if necessary if (is_little_endian != InputIsLittleEndian) { vec[sizeof(NumberType) - i - 1] = static_cast(current); } else { vec[i] = static_cast(current); // LCOV_EXCL_LINE } } // step 2: convert array into number of type T and return std::memcpy(&result, vec.data(), sizeof(NumberType)); return true; } /*! @brief create a string by reading characters from the input @tparam NumberType the type of the number @param[in] format the current format (for diagnostics) @param[in] len number of characters to read @param[out] result string created by reading @a len bytes @return whether string creation completed @note We can not reserve @a len bytes for the result, because @a len may be too large. Usually, @ref unexpect_eof() detects the end of the input before we run out of string memory. */ template bool get_string(const input_format_t format, const NumberType len, string_t& result) { bool success = true; for (NumberType i = 0; i < len; i++) { get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "string"))) { success = false; break; } result.push_back(static_cast(current)); } return success; } /*! @brief create a byte array by reading bytes from the input @tparam NumberType the type of the number @param[in] format the current format (for diagnostics) @param[in] len number of bytes to read @param[out] result byte array created by reading @a len bytes @return whether byte array creation completed @note We can not reserve @a len bytes for the result, because @a len may be too large. Usually, @ref unexpect_eof() detects the end of the input before we run out of memory. */ template bool get_binary(const input_format_t format, const NumberType len, binary_t& result) { bool success = true; for (NumberType i = 0; i < len; i++) { get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "binary"))) { success = false; break; } result.push_back(static_cast(current)); } return success; } /*! @param[in] format the current format (for diagnostics) @param[in] context further context information (for diagnostics) @return whether the last read character is not EOF */ JSON_HEDLEY_NON_NULL(3) bool unexpect_eof(const input_format_t format, const char* context) const { if (JSON_HEDLEY_UNLIKELY(current == std::char_traits::eof())) { return sax->parse_error(chars_read, "", parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context), BasicJsonType())); } return true; } /*! @return a string representation of the last read byte */ std::string get_token_string() const { std::array cr{{}}; static_cast((std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast(current))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) return std::string{cr.data()}; } /*! @param[in] format the current format @param[in] detail a detailed error message @param[in] context further context information @return a message string to use in the parse_error exceptions */ std::string exception_message(const input_format_t format, const std::string& detail, const std::string& context) const { std::string error_msg = "syntax error while parsing "; switch (format) { case input_format_t::cbor: error_msg += "CBOR"; break; case input_format_t::msgpack: error_msg += "MessagePack"; break; case input_format_t::ubjson: error_msg += "UBJSON"; break; case input_format_t::bson: error_msg += "BSON"; break; case input_format_t::json: // LCOV_EXCL_LINE default: // LCOV_EXCL_LINE JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE } return error_msg + " " + context + ": " + detail; } private: /// input adapter InputAdapterType ia; /// the current character char_int_type current = std::char_traits::eof(); /// the number of characters read std::size_t chars_read = 0; /// whether we can assume little endianness const bool is_little_endian = little_endianness(); /// the SAX parser json_sax_t* sax = nullptr; }; } // namespace detail } // namespace nlohmann // #include // #include // #include #include // isfinite #include // uint8_t #include // function #include // string #include // move #include // vector // #include // #include // #include // #include // #include // #include // #include namespace nlohmann { namespace detail { //////////// // parser // //////////// enum class parse_event_t : std::uint8_t { /// the parser read `{` and started to process a JSON object object_start, /// the parser read `}` and finished processing a JSON object object_end, /// the parser read `[` and started to process a JSON array array_start, /// the parser read `]` and finished processing a JSON array array_end, /// the parser read a key of a value in an object key, /// the parser finished reading a JSON value value }; template using parser_callback_t = std::function; /*! @brief syntax analysis This class implements a recursive descent parser. */ template class parser { using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using lexer_t = lexer; using token_type = typename lexer_t::token_type; public: /// a parser reading from an input adapter explicit parser(InputAdapterType&& adapter, const parser_callback_t cb = nullptr, const bool allow_exceptions_ = true, const bool skip_comments = false) : callback(cb) , m_lexer(std::move(adapter), skip_comments) , allow_exceptions(allow_exceptions_) { // read first token get_token(); } /*! @brief public parser interface @param[in] strict whether to expect the last token to be EOF @param[in,out] result parsed JSON value @throw parse_error.101 in case of an unexpected token @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails */ void parse(const bool strict, BasicJsonType& result) { if (callback) { json_sax_dom_callback_parser sdp(result, callback, allow_exceptions); sax_parse_internal(&sdp); // in strict mode, input must be completely read if (strict && (get_token() != token_type::end_of_input)) { sdp.parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType())); } // in case of an error, return discarded value if (sdp.is_errored()) { result = value_t::discarded; return; } // set top-level value to null if it was discarded by the callback // function if (result.is_discarded()) { result = nullptr; } } else { json_sax_dom_parser sdp(result, allow_exceptions); sax_parse_internal(&sdp); // in strict mode, input must be completely read if (strict && (get_token() != token_type::end_of_input)) { sdp.parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType())); } // in case of an error, return discarded value if (sdp.is_errored()) { result = value_t::discarded; return; } } result.assert_invariant(); } /*! @brief public accept interface @param[in] strict whether to expect the last token to be EOF @return whether the input is a proper JSON text */ bool accept(const bool strict = true) { json_sax_acceptor sax_acceptor; return sax_parse(&sax_acceptor, strict); } template JSON_HEDLEY_NON_NULL(2) bool sax_parse(SAX* sax, const bool strict = true) { (void)detail::is_sax_static_asserts {}; const bool result = sax_parse_internal(sax); // strict mode: next byte must be EOF if (result && strict && (get_token() != token_type::end_of_input)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType())); } return result; } private: template JSON_HEDLEY_NON_NULL(2) bool sax_parse_internal(SAX* sax) { // stack to remember the hierarchy of structured values we are parsing // true = array; false = object std::vector states; // value to avoid a goto (see comment where set to true) bool skip_to_state_evaluation = false; while (true) { if (!skip_to_state_evaluation) { // invariant: get_token() was called before each iteration switch (last_token) { case token_type::begin_object: { if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast(-1)))) { return false; } // closing } -> we are done if (get_token() == token_type::end_object) { if (JSON_HEDLEY_UNLIKELY(!sax->end_object())) { return false; } break; } // parse key if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), BasicJsonType())); } if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string()))) { return false; } // parse separator (:) if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), BasicJsonType())); } // remember we are now inside an object states.push_back(false); // parse values get_token(); continue; } case token_type::begin_array: { if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast(-1)))) { return false; } // closing ] -> we are done if (get_token() == token_type::end_array) { if (JSON_HEDLEY_UNLIKELY(!sax->end_array())) { return false; } break; } // remember we are now inside an array states.push_back(true); // parse values (no need to call get_token) continue; } case token_type::value_float: { const auto res = m_lexer.get_number_float(); if (JSON_HEDLEY_UNLIKELY(!std::isfinite(res))) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'", BasicJsonType())); } if (JSON_HEDLEY_UNLIKELY(!sax->number_float(res, m_lexer.get_string()))) { return false; } break; } case token_type::literal_false: { if (JSON_HEDLEY_UNLIKELY(!sax->boolean(false))) { return false; } break; } case token_type::literal_null: { if (JSON_HEDLEY_UNLIKELY(!sax->null())) { return false; } break; } case token_type::literal_true: { if (JSON_HEDLEY_UNLIKELY(!sax->boolean(true))) { return false; } break; } case token_type::value_integer: { if (JSON_HEDLEY_UNLIKELY(!sax->number_integer(m_lexer.get_number_integer()))) { return false; } break; } case token_type::value_string: { if (JSON_HEDLEY_UNLIKELY(!sax->string(m_lexer.get_string()))) { return false; } break; } case token_type::value_unsigned: { if (JSON_HEDLEY_UNLIKELY(!sax->number_unsigned(m_lexer.get_number_unsigned()))) { return false; } break; } case token_type::parse_error: { // using "uninitialized" to avoid "expected" message return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::uninitialized, "value"), BasicJsonType())); } case token_type::uninitialized: case token_type::end_array: case token_type::end_object: case token_type::name_separator: case token_type::value_separator: case token_type::end_of_input: case token_type::literal_or_value: default: // the last token was unexpected { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::literal_or_value, "value"), BasicJsonType())); } } } else { skip_to_state_evaluation = false; } // we reached this line after we successfully parsed a value if (states.empty()) { // empty stack: we reached the end of the hierarchy: done return true; } if (states.back()) // array { // comma -> next value if (get_token() == token_type::value_separator) { // parse a new value get_token(); continue; } // closing ] if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array)) { if (JSON_HEDLEY_UNLIKELY(!sax->end_array())) { return false; } // We are done with this array. Before we can parse a // new value, we need to evaluate the new state first. // By setting skip_to_state_evaluation to false, we // are effectively jumping to the beginning of this if. JSON_ASSERT(!states.empty()); states.pop_back(); skip_to_state_evaluation = true; continue; } return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_array, "array"), BasicJsonType())); } // states.back() is false -> object // comma -> next value if (get_token() == token_type::value_separator) { // parse key if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), BasicJsonType())); } if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string()))) { return false; } // parse separator (:) if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), BasicJsonType())); } // parse values get_token(); continue; } // closing } if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object)) { if (JSON_HEDLEY_UNLIKELY(!sax->end_object())) { return false; } // We are done with this object. Before we can parse a // new value, we need to evaluate the new state first. // By setting skip_to_state_evaluation to false, we // are effectively jumping to the beginning of this if. JSON_ASSERT(!states.empty()); states.pop_back(); skip_to_state_evaluation = true; continue; } return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_object, "object"), BasicJsonType())); } } /// get next token from lexer token_type get_token() { return last_token = m_lexer.scan(); } std::string exception_message(const token_type expected, const std::string& context) { std::string error_msg = "syntax error "; if (!context.empty()) { error_msg += "while parsing " + context + " "; } error_msg += "- "; if (last_token == token_type::parse_error) { error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" + m_lexer.get_token_string() + "'"; } else { error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token)); } if (expected != token_type::uninitialized) { error_msg += "; expected " + std::string(lexer_t::token_type_name(expected)); } return error_msg; } private: /// callback function const parser_callback_t callback = nullptr; /// the type of the last read token token_type last_token = token_type::uninitialized; /// the lexer lexer_t m_lexer; /// whether to throw exceptions in case of errors const bool allow_exceptions = true; }; } // namespace detail } // namespace nlohmann // #include // #include #include // ptrdiff_t #include // numeric_limits // #include namespace nlohmann { namespace detail { /* @brief an iterator for primitive JSON types This class models an iterator for primitive JSON types (boolean, number, string). It's only purpose is to allow the iterator/const_iterator classes to "iterate" over primitive values. Internally, the iterator is modeled by a `difference_type` variable. Value begin_value (`0`) models the begin, end_value (`1`) models past the end. */ class primitive_iterator_t { private: using difference_type = std::ptrdiff_t; static constexpr difference_type begin_value = 0; static constexpr difference_type end_value = begin_value + 1; JSON_PRIVATE_UNLESS_TESTED: /// iterator as signed integer type difference_type m_it = (std::numeric_limits::min)(); public: constexpr difference_type get_value() const noexcept { return m_it; } /// set iterator to a defined beginning void set_begin() noexcept { m_it = begin_value; } /// set iterator to a defined past the end void set_end() noexcept { m_it = end_value; } /// return whether the iterator can be dereferenced constexpr bool is_begin() const noexcept { return m_it == begin_value; } /// return whether the iterator is at end constexpr bool is_end() const noexcept { return m_it == end_value; } friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it == rhs.m_it; } friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it < rhs.m_it; } primitive_iterator_t operator+(difference_type n) noexcept { auto result = *this; result += n; return result; } friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it - rhs.m_it; } primitive_iterator_t& operator++() noexcept { ++m_it; return *this; } primitive_iterator_t const operator++(int) noexcept // NOLINT(readability-const-return-type) { auto result = *this; ++m_it; return result; } primitive_iterator_t& operator--() noexcept { --m_it; return *this; } primitive_iterator_t const operator--(int) noexcept // NOLINT(readability-const-return-type) { auto result = *this; --m_it; return result; } primitive_iterator_t& operator+=(difference_type n) noexcept { m_it += n; return *this; } primitive_iterator_t& operator-=(difference_type n) noexcept { m_it -= n; return *this; } }; } // namespace detail } // namespace nlohmann namespace nlohmann { namespace detail { /*! @brief an iterator value @note This structure could easily be a union, but MSVC currently does not allow unions members with complex constructors, see https://github.com/nlohmann/json/pull/105. */ template struct internal_iterator { /// iterator for JSON objects typename BasicJsonType::object_t::iterator object_iterator {}; /// iterator for JSON arrays typename BasicJsonType::array_t::iterator array_iterator {}; /// generic iterator for all other types primitive_iterator_t primitive_iterator {}; }; } // namespace detail } // namespace nlohmann // #include #include // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next #include // conditional, is_const, remove_const // #include // #include // #include // #include // #include // #include // #include namespace nlohmann { namespace detail { // forward declare, to be able to friend it later on template class iteration_proxy; template class iteration_proxy_value; /*! @brief a template for a bidirectional iterator for the @ref basic_json class This class implements a both iterators (iterator and const_iterator) for the @ref basic_json class. @note An iterator is called *initialized* when a pointer to a JSON value has been set (e.g., by a constructor or a copy assignment). If the iterator is default-constructed, it is *uninitialized* and most methods are undefined. **The library uses assertions to detect calls on uninitialized iterators.** @requirement The class satisfies the following concept requirements: - [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): The iterator that can be moved can be moved in both directions (i.e. incremented and decremented). @since version 1.0.0, simplified in version 2.0.9, change to bidirectional iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593) */ template class iter_impl // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions) { /// the iterator with BasicJsonType of different const-ness using other_iter_impl = iter_impl::value, typename std::remove_const::type, const BasicJsonType>::type>; /// allow basic_json to access private members friend other_iter_impl; friend BasicJsonType; friend iteration_proxy; friend iteration_proxy_value; using object_t = typename BasicJsonType::object_t; using array_t = typename BasicJsonType::array_t; // make sure BasicJsonType is basic_json or const basic_json static_assert(is_basic_json::type>::value, "iter_impl only accepts (const) basic_json"); public: /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17. /// The C++ Standard has never required user-defined iterators to derive from std::iterator. /// A user-defined iterator should provide publicly accessible typedefs named /// iterator_category, value_type, difference_type, pointer, and reference. /// Note that value_type is required to be non-const, even for constant iterators. using iterator_category = std::bidirectional_iterator_tag; /// the type of the values when the iterator is dereferenced using value_type = typename BasicJsonType::value_type; /// a type to represent differences between iterators using difference_type = typename BasicJsonType::difference_type; /// defines a pointer to the type iterated over (value_type) using pointer = typename std::conditional::value, typename BasicJsonType::const_pointer, typename BasicJsonType::pointer>::type; /// defines a reference to the type iterated over (value_type) using reference = typename std::conditional::value, typename BasicJsonType::const_reference, typename BasicJsonType::reference>::type; iter_impl() = default; ~iter_impl() = default; iter_impl(iter_impl&&) noexcept = default; iter_impl& operator=(iter_impl&&) noexcept = default; /*! @brief constructor for a given JSON instance @param[in] object pointer to a JSON object for this iterator @pre object != nullptr @post The iterator is initialized; i.e. `m_object != nullptr`. */ explicit iter_impl(pointer object) noexcept : m_object(object) { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { m_it.object_iterator = typename object_t::iterator(); break; } case value_t::array: { m_it.array_iterator = typename array_t::iterator(); break; } case value_t::null: case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: { m_it.primitive_iterator = primitive_iterator_t(); break; } } } /*! @note The conventional copy constructor and copy assignment are implicitly defined. Combined with the following converting constructor and assignment, they support: (1) copy from iterator to iterator, (2) copy from const iterator to const iterator, and (3) conversion from iterator to const iterator. However conversion from const iterator to iterator is not defined. */ /*! @brief const copy constructor @param[in] other const iterator to copy from @note This copy constructor had to be defined explicitly to circumvent a bug occurring on msvc v19.0 compiler (VS 2015) debug build. For more information refer to: https://github.com/nlohmann/json/issues/1608 */ iter_impl(const iter_impl& other) noexcept : m_object(other.m_object), m_it(other.m_it) {} /*! @brief converting assignment @param[in] other const iterator to copy from @return const/non-const iterator @note It is not checked whether @a other is initialized. */ iter_impl& operator=(const iter_impl& other) noexcept { if (&other != this) { m_object = other.m_object; m_it = other.m_it; } return *this; } /*! @brief converting constructor @param[in] other non-const iterator to copy from @note It is not checked whether @a other is initialized. */ iter_impl(const iter_impl::type>& other) noexcept : m_object(other.m_object), m_it(other.m_it) {} /*! @brief converting assignment @param[in] other non-const iterator to copy from @return const/non-const iterator @note It is not checked whether @a other is initialized. */ iter_impl& operator=(const iter_impl::type>& other) noexcept // NOLINT(cert-oop54-cpp) { m_object = other.m_object; m_it = other.m_it; return *this; } JSON_PRIVATE_UNLESS_TESTED: /*! @brief set the iterator to the first value @pre The iterator is initialized; i.e. `m_object != nullptr`. */ void set_begin() noexcept { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { m_it.object_iterator = m_object->m_value.object->begin(); break; } case value_t::array: { m_it.array_iterator = m_object->m_value.array->begin(); break; } case value_t::null: { // set to end so begin()==end() is true: null is empty m_it.primitive_iterator.set_end(); break; } case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: { m_it.primitive_iterator.set_begin(); break; } } } /*! @brief set the iterator past the last value @pre The iterator is initialized; i.e. `m_object != nullptr`. */ void set_end() noexcept { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { m_it.object_iterator = m_object->m_value.object->end(); break; } case value_t::array: { m_it.array_iterator = m_object->m_value.array->end(); break; } case value_t::null: case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: { m_it.primitive_iterator.set_end(); break; } } } public: /*! @brief return a reference to the value pointed to by the iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ reference operator*() const { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end()); return m_it.object_iterator->second; } case value_t::array: { JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end()); return *m_it.array_iterator; } case value_t::null: JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: { if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin())) { return *m_object; } JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); } } } /*! @brief dereference the iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ pointer operator->() const { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end()); return &(m_it.object_iterator->second); } case value_t::array: { JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end()); return &*m_it.array_iterator; } case value_t::null: case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: { if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin())) { return m_object; } JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); } } } /*! @brief post-increment (it++) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl const operator++(int) // NOLINT(readability-const-return-type) { auto result = *this; ++(*this); return result; } /*! @brief pre-increment (++it) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator++() { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { std::advance(m_it.object_iterator, 1); break; } case value_t::array: { std::advance(m_it.array_iterator, 1); break; } case value_t::null: case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: { ++m_it.primitive_iterator; break; } } return *this; } /*! @brief post-decrement (it--) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl const operator--(int) // NOLINT(readability-const-return-type) { auto result = *this; --(*this); return result; } /*! @brief pre-decrement (--it) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator--() { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { std::advance(m_it.object_iterator, -1); break; } case value_t::array: { std::advance(m_it.array_iterator, -1); break; } case value_t::null: case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: { --m_it.primitive_iterator; break; } } return *this; } /*! @brief comparison: equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ template < typename IterImpl, detail::enable_if_t < (std::is_same::value || std::is_same::value), std::nullptr_t > = nullptr > bool operator==(const IterImpl& other) const { // if objects are not the same, the comparison is undefined if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object)) { JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", *m_object)); } JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: return (m_it.object_iterator == other.m_it.object_iterator); case value_t::array: return (m_it.array_iterator == other.m_it.array_iterator); case value_t::null: case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: return (m_it.primitive_iterator == other.m_it.primitive_iterator); } } /*! @brief comparison: not equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ template < typename IterImpl, detail::enable_if_t < (std::is_same::value || std::is_same::value), std::nullptr_t > = nullptr > bool operator!=(const IterImpl& other) const { return !operator==(other); } /*! @brief comparison: smaller @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator<(const iter_impl& other) const { // if objects are not the same, the comparison is undefined if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object)) { JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", *m_object)); } JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators", *m_object)); case value_t::array: return (m_it.array_iterator < other.m_it.array_iterator); case value_t::null: case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: return (m_it.primitive_iterator < other.m_it.primitive_iterator); } } /*! @brief comparison: less than or equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator<=(const iter_impl& other) const { return !other.operator < (*this); } /*! @brief comparison: greater than @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator>(const iter_impl& other) const { return !operator<=(other); } /*! @brief comparison: greater than or equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator>=(const iter_impl& other) const { return !operator<(other); } /*! @brief add to iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator+=(difference_type i) { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", *m_object)); case value_t::array: { std::advance(m_it.array_iterator, i); break; } case value_t::null: case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: { m_it.primitive_iterator += i; break; } } return *this; } /*! @brief subtract from iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator-=(difference_type i) { return operator+=(-i); } /*! @brief add to iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl operator+(difference_type i) const { auto result = *this; result += i; return result; } /*! @brief addition of distance and iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ friend iter_impl operator+(difference_type i, const iter_impl& it) { auto result = it; result += i; return result; } /*! @brief subtract from iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl operator-(difference_type i) const { auto result = *this; result -= i; return result; } /*! @brief return difference @pre The iterator is initialized; i.e. `m_object != nullptr`. */ difference_type operator-(const iter_impl& other) const { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", *m_object)); case value_t::array: return m_it.array_iterator - other.m_it.array_iterator; case value_t::null: case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: return m_it.primitive_iterator - other.m_it.primitive_iterator; } } /*! @brief access to successor @pre The iterator is initialized; i.e. `m_object != nullptr`. */ reference operator[](difference_type n) const { JSON_ASSERT(m_object != nullptr); switch (m_object->m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators", *m_object)); case value_t::array: return *std::next(m_it.array_iterator, n); case value_t::null: JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: { if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n)) { return *m_object; } JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); } } } /*! @brief return the key of an object iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ const typename object_t::key_type& key() const { JSON_ASSERT(m_object != nullptr); if (JSON_HEDLEY_LIKELY(m_object->is_object())) { return m_it.object_iterator->first; } JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators", *m_object)); } /*! @brief return the value of an iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ reference value() const { return operator*(); } JSON_PRIVATE_UNLESS_TESTED: /// associated JSON instance pointer m_object = nullptr; /// the actual iterator of the associated instance internal_iterator::type> m_it {}; }; } // namespace detail } // namespace nlohmann // #include // #include #include // ptrdiff_t #include // reverse_iterator #include // declval namespace nlohmann { namespace detail { ////////////////////// // reverse_iterator // ////////////////////// /*! @brief a template for a reverse iterator class @tparam Base the base iterator type to reverse. Valid types are @ref iterator (to create @ref reverse_iterator) and @ref const_iterator (to create @ref const_reverse_iterator). @requirement The class satisfies the following concept requirements: - [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): The iterator that can be moved can be moved in both directions (i.e. incremented and decremented). - [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator): It is possible to write to the pointed-to element (only if @a Base is @ref iterator). @since version 1.0.0 */ template class json_reverse_iterator : public std::reverse_iterator { public: using difference_type = std::ptrdiff_t; /// shortcut to the reverse iterator adapter using base_iterator = std::reverse_iterator; /// the reference type for the pointed-to element using reference = typename Base::reference; /// create reverse iterator from iterator explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept : base_iterator(it) {} /// create reverse iterator from base class explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {} /// post-increment (it++) json_reverse_iterator const operator++(int) // NOLINT(readability-const-return-type) { return static_cast(base_iterator::operator++(1)); } /// pre-increment (++it) json_reverse_iterator& operator++() { return static_cast(base_iterator::operator++()); } /// post-decrement (it--) json_reverse_iterator const operator--(int) // NOLINT(readability-const-return-type) { return static_cast(base_iterator::operator--(1)); } /// pre-decrement (--it) json_reverse_iterator& operator--() { return static_cast(base_iterator::operator--()); } /// add to iterator json_reverse_iterator& operator+=(difference_type i) { return static_cast(base_iterator::operator+=(i)); } /// add to iterator json_reverse_iterator operator+(difference_type i) const { return static_cast(base_iterator::operator+(i)); } /// subtract from iterator json_reverse_iterator operator-(difference_type i) const { return static_cast(base_iterator::operator-(i)); } /// return difference difference_type operator-(const json_reverse_iterator& other) const { return base_iterator(*this) - base_iterator(other); } /// access to successor reference operator[](difference_type n) const { return *(this->operator+(n)); } /// return the key of an object iterator auto key() const -> decltype(std::declval().key()) { auto it = --this->base(); return it.key(); } /// return the value of an iterator reference value() const { auto it = --this->base(); return it.operator * (); } }; } // namespace detail } // namespace nlohmann // #include // #include #include // all_of #include // isdigit #include // max #include // accumulate #include // string #include // move #include // vector // #include // #include // #include // #include namespace nlohmann { /// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document /// @sa https://json.nlohmann.me/api/json_pointer/ template class json_pointer { // allow basic_json to access private members NLOHMANN_BASIC_JSON_TPL_DECLARATION friend class basic_json; public: /// @brief create JSON pointer /// @sa https://json.nlohmann.me/api/json_pointer/json_pointer/ explicit json_pointer(const std::string& s = "") : reference_tokens(split(s)) {} /// @brief return a string representation of the JSON pointer /// @sa https://json.nlohmann.me/api/json_pointer/to_string/ std::string to_string() const { return std::accumulate(reference_tokens.begin(), reference_tokens.end(), std::string{}, [](const std::string & a, const std::string & b) { return a + "/" + detail::escape(b); }); } /// @brief return a string representation of the JSON pointer /// @sa https://json.nlohmann.me/api/json_pointer/operator_string/ operator std::string() const { return to_string(); } /// @brief append another JSON pointer at the end of this JSON pointer /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/ json_pointer& operator/=(const json_pointer& ptr) { reference_tokens.insert(reference_tokens.end(), ptr.reference_tokens.begin(), ptr.reference_tokens.end()); return *this; } /// @brief append an unescaped reference token at the end of this JSON pointer /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/ json_pointer& operator/=(std::string token) { push_back(std::move(token)); return *this; } /// @brief append an array index at the end of this JSON pointer /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/ json_pointer& operator/=(std::size_t array_idx) { return *this /= std::to_string(array_idx); } /// @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/ friend json_pointer operator/(const json_pointer& lhs, const json_pointer& rhs) { return json_pointer(lhs) /= rhs; } /// @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/ friend json_pointer operator/(const json_pointer& lhs, std::string token) // NOLINT(performance-unnecessary-value-param) { return json_pointer(lhs) /= std::move(token); } /// @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/ friend json_pointer operator/(const json_pointer& lhs, std::size_t array_idx) { return json_pointer(lhs) /= array_idx; } /// @brief returns the parent of this JSON pointer /// @sa https://json.nlohmann.me/api/json_pointer/parent_pointer/ json_pointer parent_pointer() const { if (empty()) { return *this; } json_pointer res = *this; res.pop_back(); return res; } /// @brief remove last reference token /// @sa https://json.nlohmann.me/api/json_pointer/pop_back/ void pop_back() { if (JSON_HEDLEY_UNLIKELY(empty())) { JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType())); } reference_tokens.pop_back(); } /// @brief return last reference token /// @sa https://json.nlohmann.me/api/json_pointer/back/ const std::string& back() const { if (JSON_HEDLEY_UNLIKELY(empty())) { JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType())); } return reference_tokens.back(); } /// @brief append an unescaped token at the end of the reference pointer /// @sa https://json.nlohmann.me/api/json_pointer/push_back/ void push_back(const std::string& token) { reference_tokens.push_back(token); } /// @brief append an unescaped token at the end of the reference pointer /// @sa https://json.nlohmann.me/api/json_pointer/push_back/ void push_back(std::string&& token) { reference_tokens.push_back(std::move(token)); } /// @brief return whether pointer points to the root document /// @sa https://json.nlohmann.me/api/json_pointer/empty/ bool empty() const noexcept { return reference_tokens.empty(); } private: /*! @param[in] s reference token to be converted into an array index @return integer representation of @a s @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index begins not with a digit @throw out_of_range.404 if string @a s could not be converted to an integer @throw out_of_range.410 if an array index exceeds size_type */ static typename BasicJsonType::size_type array_index(const std::string& s) { using size_type = typename BasicJsonType::size_type; // error condition (cf. RFC 6901, Sect. 4) if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && s[0] == '0')) { JSON_THROW(detail::parse_error::create(106, 0, "array index '" + s + "' must not begin with '0'", BasicJsonType())); } // error condition (cf. RFC 6901, Sect. 4) if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && !(s[0] >= '1' && s[0] <= '9'))) { JSON_THROW(detail::parse_error::create(109, 0, "array index '" + s + "' is not a number", BasicJsonType())); } std::size_t processed_chars = 0; unsigned long long res = 0; // NOLINT(runtime/int) JSON_TRY { res = std::stoull(s, &processed_chars); } JSON_CATCH(std::out_of_range&) { JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType())); } // check if the string was completely read if (JSON_HEDLEY_UNLIKELY(processed_chars != s.size())) { JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType())); } // only triggered on special platforms (like 32bit), see also // https://github.com/nlohmann/json/pull/2203 if (res >= static_cast((std::numeric_limits::max)())) // NOLINT(runtime/int) { JSON_THROW(detail::out_of_range::create(410, "array index " + s + " exceeds size_type", BasicJsonType())); // LCOV_EXCL_LINE } return static_cast(res); } JSON_PRIVATE_UNLESS_TESTED: json_pointer top() const { if (JSON_HEDLEY_UNLIKELY(empty())) { JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType())); } json_pointer result = *this; result.reference_tokens = {reference_tokens[0]}; return result; } private: /*! @brief create and return a reference to the pointed to value @complexity Linear in the number of reference tokens. @throw parse_error.109 if array index is not a number @throw type_error.313 if value cannot be unflattened */ BasicJsonType& get_and_create(BasicJsonType& j) const { auto* result = &j; // in case no reference tokens exist, return a reference to the JSON value // j which will be overwritten by a primitive value for (const auto& reference_token : reference_tokens) { switch (result->type()) { case detail::value_t::null: { if (reference_token == "0") { // start a new array if reference token is 0 result = &result->operator[](0); } else { // start a new object otherwise result = &result->operator[](reference_token); } break; } case detail::value_t::object: { // create an entry in the object result = &result->operator[](reference_token); break; } case detail::value_t::array: { // create an entry in the array result = &result->operator[](array_index(reference_token)); break; } /* The following code is only reached if there exists a reference token _and_ the current value is primitive. In this case, we have an error situation, because primitive values may only occur as single value; that is, with an empty list of reference tokens. */ case detail::value_t::string: case detail::value_t::boolean: case detail::value_t::number_integer: case detail::value_t::number_unsigned: case detail::value_t::number_float: case detail::value_t::binary: case detail::value_t::discarded: default: JSON_THROW(detail::type_error::create(313, "invalid value to unflatten", j)); } } return *result; } /*! @brief return a reference to the pointed to value @note This version does not throw if a value is not present, but tries to create nested values instead. For instance, calling this function with pointer `"/this/that"` on a null value is equivalent to calling `operator[]("this").operator[]("that")` on that value, effectively changing the null value to an object. @param[in] ptr a JSON value @return reference to the JSON value pointed to by the JSON pointer @complexity Linear in the length of the JSON pointer. @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.404 if the JSON pointer can not be resolved */ BasicJsonType& get_unchecked(BasicJsonType* ptr) const { for (const auto& reference_token : reference_tokens) { // convert null values to arrays or objects before continuing if (ptr->is_null()) { // check if reference token is a number const bool nums = std::all_of(reference_token.begin(), reference_token.end(), [](const unsigned char x) { return std::isdigit(x); }); // change value to array for numbers or "-" or to object otherwise *ptr = (nums || reference_token == "-") ? detail::value_t::array : detail::value_t::object; } switch (ptr->type()) { case detail::value_t::object: { // use unchecked object access ptr = &ptr->operator[](reference_token); break; } case detail::value_t::array: { if (reference_token == "-") { // explicitly treat "-" as index beyond the end ptr = &ptr->operator[](ptr->m_value.array->size()); } else { // convert array index to number; unchecked access ptr = &ptr->operator[](array_index(reference_token)); } break; } case detail::value_t::null: case detail::value_t::string: case detail::value_t::boolean: case detail::value_t::number_integer: case detail::value_t::number_unsigned: case detail::value_t::number_float: case detail::value_t::binary: case detail::value_t::discarded: default: JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); } } return *ptr; } /*! @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved */ BasicJsonType& get_checked(BasicJsonType* ptr) const { for (const auto& reference_token : reference_tokens) { switch (ptr->type()) { case detail::value_t::object: { // note: at performs range check ptr = &ptr->at(reference_token); break; } case detail::value_t::array: { if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) { // "-" always fails the range check JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range", *ptr)); } // note: at performs range check ptr = &ptr->at(array_index(reference_token)); break; } case detail::value_t::null: case detail::value_t::string: case detail::value_t::boolean: case detail::value_t::number_integer: case detail::value_t::number_unsigned: case detail::value_t::number_float: case detail::value_t::binary: case detail::value_t::discarded: default: JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); } } return *ptr; } /*! @brief return a const reference to the pointed to value @param[in] ptr a JSON value @return const reference to the JSON value pointed to by the JSON pointer @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved */ const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const { for (const auto& reference_token : reference_tokens) { switch (ptr->type()) { case detail::value_t::object: { // use unchecked object access ptr = &ptr->operator[](reference_token); break; } case detail::value_t::array: { if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) { // "-" cannot be used for const access JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range", *ptr)); } // use unchecked array access ptr = &ptr->operator[](array_index(reference_token)); break; } case detail::value_t::null: case detail::value_t::string: case detail::value_t::boolean: case detail::value_t::number_integer: case detail::value_t::number_unsigned: case detail::value_t::number_float: case detail::value_t::binary: case detail::value_t::discarded: default: JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); } } return *ptr; } /*! @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved */ const BasicJsonType& get_checked(const BasicJsonType* ptr) const { for (const auto& reference_token : reference_tokens) { switch (ptr->type()) { case detail::value_t::object: { // note: at performs range check ptr = &ptr->at(reference_token); break; } case detail::value_t::array: { if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) { // "-" always fails the range check JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range", *ptr)); } // note: at performs range check ptr = &ptr->at(array_index(reference_token)); break; } case detail::value_t::null: case detail::value_t::string: case detail::value_t::boolean: case detail::value_t::number_integer: case detail::value_t::number_unsigned: case detail::value_t::number_float: case detail::value_t::binary: case detail::value_t::discarded: default: JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); } } return *ptr; } /*! @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number */ bool contains(const BasicJsonType* ptr) const { for (const auto& reference_token : reference_tokens) { switch (ptr->type()) { case detail::value_t::object: { if (!ptr->contains(reference_token)) { // we did not find the key in the object return false; } ptr = &ptr->operator[](reference_token); break; } case detail::value_t::array: { if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) { // "-" always fails the range check return false; } if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 && !("0" <= reference_token && reference_token <= "9"))) { // invalid char return false; } if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1)) { if (JSON_HEDLEY_UNLIKELY(!('1' <= reference_token[0] && reference_token[0] <= '9'))) { // first char should be between '1' and '9' return false; } for (std::size_t i = 1; i < reference_token.size(); i++) { if (JSON_HEDLEY_UNLIKELY(!('0' <= reference_token[i] && reference_token[i] <= '9'))) { // other char should be between '0' and '9' return false; } } } const auto idx = array_index(reference_token); if (idx >= ptr->size()) { // index out of range return false; } ptr = &ptr->operator[](idx); break; } case detail::value_t::null: case detail::value_t::string: case detail::value_t::boolean: case detail::value_t::number_integer: case detail::value_t::number_unsigned: case detail::value_t::number_float: case detail::value_t::binary: case detail::value_t::discarded: default: { // we do not expect primitive values if there is still a // reference token to process return false; } } } // no reference token left means we found a primitive value return true; } /*! @brief split the string input to reference tokens @note This function is only called by the json_pointer constructor. All exceptions below are documented there. @throw parse_error.107 if the pointer is not empty or begins with '/' @throw parse_error.108 if character '~' is not followed by '0' or '1' */ static std::vector split(const std::string& reference_string) { std::vector result; // special case: empty reference string -> no reference tokens if (reference_string.empty()) { return result; } // check if nonempty reference string begins with slash if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/')) { JSON_THROW(detail::parse_error::create(107, 1, "JSON pointer must be empty or begin with '/' - was: '" + reference_string + "'", BasicJsonType())); } // extract the reference tokens: // - slash: position of the last read slash (or end of string) // - start: position after the previous slash for ( // search for the first slash after the first character std::size_t slash = reference_string.find_first_of('/', 1), // set the beginning of the first reference token start = 1; // we can stop if start == 0 (if slash == std::string::npos) start != 0; // set the beginning of the next reference token // (will eventually be 0 if slash == std::string::npos) start = (slash == std::string::npos) ? 0 : slash + 1, // find next slash slash = reference_string.find_first_of('/', start)) { // use the text between the beginning of the reference token // (start) and the last slash (slash). auto reference_token = reference_string.substr(start, slash - start); // check reference tokens are properly escaped for (std::size_t pos = reference_token.find_first_of('~'); pos != std::string::npos; pos = reference_token.find_first_of('~', pos + 1)) { JSON_ASSERT(reference_token[pos] == '~'); // ~ must be followed by 0 or 1 if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 || (reference_token[pos + 1] != '0' && reference_token[pos + 1] != '1'))) { JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'", BasicJsonType())); } } // finally, store the reference token detail::unescape(reference_token); result.push_back(reference_token); } return result; } private: /*! @param[in] reference_string the reference string to the current value @param[in] value the value to consider @param[in,out] result the result object to insert values to @note Empty objects or arrays are flattened to `null`. */ static void flatten(const std::string& reference_string, const BasicJsonType& value, BasicJsonType& result) { switch (value.type()) { case detail::value_t::array: { if (value.m_value.array->empty()) { // flatten empty array as null result[reference_string] = nullptr; } else { // iterate array and use index as reference string for (std::size_t i = 0; i < value.m_value.array->size(); ++i) { flatten(reference_string + "/" + std::to_string(i), value.m_value.array->operator[](i), result); } } break; } case detail::value_t::object: { if (value.m_value.object->empty()) { // flatten empty object as null result[reference_string] = nullptr; } else { // iterate object and use keys as reference string for (const auto& element : *value.m_value.object) { flatten(reference_string + "/" + detail::escape(element.first), element.second, result); } } break; } case detail::value_t::null: case detail::value_t::string: case detail::value_t::boolean: case detail::value_t::number_integer: case detail::value_t::number_unsigned: case detail::value_t::number_float: case detail::value_t::binary: case detail::value_t::discarded: default: { // add primitive value with its reference string result[reference_string] = value; break; } } } /*! @param[in] value flattened JSON @return unflattened JSON @throw parse_error.109 if array index is not a number @throw type_error.314 if value is not an object @throw type_error.315 if object values are not primitive @throw type_error.313 if value cannot be unflattened */ static BasicJsonType unflatten(const BasicJsonType& value) { if (JSON_HEDLEY_UNLIKELY(!value.is_object())) { JSON_THROW(detail::type_error::create(314, "only objects can be unflattened", value)); } BasicJsonType result; // iterate the JSON object values for (const auto& element : *value.m_value.object) { if (JSON_HEDLEY_UNLIKELY(!element.second.is_primitive())) { JSON_THROW(detail::type_error::create(315, "values in object must be primitive", element.second)); } // assign value to reference pointed to by JSON pointer; Note that if // the JSON pointer is "" (i.e., points to the whole value), function // get_and_create returns a reference to result itself. An assignment // will then create a primitive value. json_pointer(element.first).get_and_create(result) = element.second; } return result; } /*! @brief compares two JSON pointers for equality @param[in] lhs JSON pointer to compare @param[in] rhs JSON pointer to compare @return whether @a lhs is equal to @a rhs @complexity Linear in the length of the JSON pointer @exceptionsafety No-throw guarantee: this function never throws exceptions. */ friend bool operator==(json_pointer const& lhs, json_pointer const& rhs) noexcept { return lhs.reference_tokens == rhs.reference_tokens; } /*! @brief compares two JSON pointers for inequality @param[in] lhs JSON pointer to compare @param[in] rhs JSON pointer to compare @return whether @a lhs is not equal @a rhs @complexity Linear in the length of the JSON pointer @exceptionsafety No-throw guarantee: this function never throws exceptions. */ friend bool operator!=(json_pointer const& lhs, json_pointer const& rhs) noexcept { return !(lhs == rhs); } /// the reference tokens std::vector reference_tokens; }; } // namespace nlohmann // #include #include #include // #include namespace nlohmann { namespace detail { template class json_ref { public: using value_type = BasicJsonType; json_ref(value_type&& value) : owned_value(std::move(value)) {} json_ref(const value_type& value) : value_ref(&value) {} json_ref(std::initializer_list init) : owned_value(init) {} template < class... Args, enable_if_t::value, int> = 0 > json_ref(Args && ... args) : owned_value(std::forward(args)...) {} // class should be movable only json_ref(json_ref&&) noexcept = default; json_ref(const json_ref&) = delete; json_ref& operator=(const json_ref&) = delete; json_ref& operator=(json_ref&&) = delete; ~json_ref() = default; value_type moved_or_copied() const { if (value_ref == nullptr) { return std::move(owned_value); } return *value_ref; } value_type const& operator*() const { return value_ref ? *value_ref : owned_value; } value_type const* operator->() const { return &** this; } private: mutable value_type owned_value = nullptr; value_type const* value_ref = nullptr; }; } // namespace detail } // namespace nlohmann // #include // #include // #include // #include // #include #include // reverse #include // array #include // isnan, isinf #include // uint8_t, uint16_t, uint32_t, uint64_t #include // memcpy #include // numeric_limits #include // string #include // move // #include // #include // #include #include // copy #include // size_t #include // back_inserter #include // shared_ptr, make_shared #include // basic_string #include // vector #ifndef JSON_NO_IO #include // streamsize #include // basic_ostream #endif // JSON_NO_IO // #include namespace nlohmann { namespace detail { /// abstract output adapter interface template struct output_adapter_protocol { virtual void write_character(CharType c) = 0; virtual void write_characters(const CharType* s, std::size_t length) = 0; virtual ~output_adapter_protocol() = default; output_adapter_protocol() = default; output_adapter_protocol(const output_adapter_protocol&) = default; output_adapter_protocol(output_adapter_protocol&&) noexcept = default; output_adapter_protocol& operator=(const output_adapter_protocol&) = default; output_adapter_protocol& operator=(output_adapter_protocol&&) noexcept = default; }; /// a type to simplify interfaces template using output_adapter_t = std::shared_ptr>; /// output adapter for byte vectors template> class output_vector_adapter : public output_adapter_protocol { public: explicit output_vector_adapter(std::vector& vec) noexcept : v(vec) {} void write_character(CharType c) override { v.push_back(c); } JSON_HEDLEY_NON_NULL(2) void write_characters(const CharType* s, std::size_t length) override { std::copy(s, s + length, std::back_inserter(v)); } private: std::vector& v; }; #ifndef JSON_NO_IO /// output adapter for output streams template class output_stream_adapter : public output_adapter_protocol { public: explicit output_stream_adapter(std::basic_ostream& s) noexcept : stream(s) {} void write_character(CharType c) override { stream.put(c); } JSON_HEDLEY_NON_NULL(2) void write_characters(const CharType* s, std::size_t length) override { stream.write(s, static_cast(length)); } private: std::basic_ostream& stream; }; #endif // JSON_NO_IO /// output adapter for basic_string template> class output_string_adapter : public output_adapter_protocol { public: explicit output_string_adapter(StringType& s) noexcept : str(s) {} void write_character(CharType c) override { str.push_back(c); } JSON_HEDLEY_NON_NULL(2) void write_characters(const CharType* s, std::size_t length) override { str.append(s, length); } private: StringType& str; }; template> class output_adapter { public: template> output_adapter(std::vector& vec) : oa(std::make_shared>(vec)) {} #ifndef JSON_NO_IO output_adapter(std::basic_ostream& s) : oa(std::make_shared>(s)) {} #endif // JSON_NO_IO output_adapter(StringType& s) : oa(std::make_shared>(s)) {} operator output_adapter_t() { return oa; } private: output_adapter_t oa = nullptr; }; } // namespace detail } // namespace nlohmann namespace nlohmann { namespace detail { /////////////////// // binary writer // /////////////////// /*! @brief serialization to CBOR and MessagePack values */ template class binary_writer { using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; using number_float_t = typename BasicJsonType::number_float_t; public: /*! @brief create a binary writer @param[in] adapter output adapter to write to */ explicit binary_writer(output_adapter_t adapter) : oa(std::move(adapter)) { JSON_ASSERT(oa); } /*! @param[in] j JSON value to serialize @pre j.type() == value_t::object */ void write_bson(const BasicJsonType& j) { switch (j.type()) { case value_t::object: { write_bson_object(*j.m_value.object); break; } case value_t::null: case value_t::array: case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: { JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name()), j)); } } } /*! @param[in] j JSON value to serialize */ void write_cbor(const BasicJsonType& j) { switch (j.type()) { case value_t::null: { oa->write_character(to_char_type(0xF6)); break; } case value_t::boolean: { oa->write_character(j.m_value.boolean ? to_char_type(0xF5) : to_char_type(0xF4)); break; } case value_t::number_integer: { if (j.m_value.number_integer >= 0) { // CBOR does not differentiate between positive signed // integers and unsigned integers. Therefore, we used the // code from the value_t::number_unsigned case here. if (j.m_value.number_integer <= 0x17) { write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_integer <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x18)); write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_integer <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x19)); write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_integer <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x1A)); write_number(static_cast(j.m_value.number_integer)); } else { oa->write_character(to_char_type(0x1B)); write_number(static_cast(j.m_value.number_integer)); } } else { // The conversions below encode the sign in the first // byte, and the value is converted to a positive number. const auto positive_number = -1 - j.m_value.number_integer; if (j.m_value.number_integer >= -24) { write_number(static_cast(0x20 + positive_number)); } else if (positive_number <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x38)); write_number(static_cast(positive_number)); } else if (positive_number <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x39)); write_number(static_cast(positive_number)); } else if (positive_number <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x3A)); write_number(static_cast(positive_number)); } else { oa->write_character(to_char_type(0x3B)); write_number(static_cast(positive_number)); } } break; } case value_t::number_unsigned: { if (j.m_value.number_unsigned <= 0x17) { write_number(static_cast(j.m_value.number_unsigned)); } else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x18)); write_number(static_cast(j.m_value.number_unsigned)); } else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x19)); write_number(static_cast(j.m_value.number_unsigned)); } else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x1A)); write_number(static_cast(j.m_value.number_unsigned)); } else { oa->write_character(to_char_type(0x1B)); write_number(static_cast(j.m_value.number_unsigned)); } break; } case value_t::number_float: { if (std::isnan(j.m_value.number_float)) { // NaN is 0xf97e00 in CBOR oa->write_character(to_char_type(0xF9)); oa->write_character(to_char_type(0x7E)); oa->write_character(to_char_type(0x00)); } else if (std::isinf(j.m_value.number_float)) { // Infinity is 0xf97c00, -Infinity is 0xf9fc00 oa->write_character(to_char_type(0xf9)); oa->write_character(j.m_value.number_float > 0 ? to_char_type(0x7C) : to_char_type(0xFC)); oa->write_character(to_char_type(0x00)); } else { write_compact_float(j.m_value.number_float, detail::input_format_t::cbor); } break; } case value_t::string: { // step 1: write control byte and the string length const auto N = j.m_value.string->size(); if (N <= 0x17) { write_number(static_cast(0x60 + N)); } else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x78)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x79)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x7A)); write_number(static_cast(N)); } // LCOV_EXCL_START else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x7B)); write_number(static_cast(N)); } // LCOV_EXCL_STOP // step 2: write the string oa->write_characters( reinterpret_cast(j.m_value.string->c_str()), j.m_value.string->size()); break; } case value_t::array: { // step 1: write control byte and the array size const auto N = j.m_value.array->size(); if (N <= 0x17) { write_number(static_cast(0x80 + N)); } else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x98)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x99)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x9A)); write_number(static_cast(N)); } // LCOV_EXCL_START else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x9B)); write_number(static_cast(N)); } // LCOV_EXCL_STOP // step 2: write each element for (const auto& el : *j.m_value.array) { write_cbor(el); } break; } case value_t::binary: { if (j.m_value.binary->has_subtype()) { if (j.m_value.binary->subtype() <= (std::numeric_limits::max)()) { write_number(static_cast(0xd8)); write_number(static_cast(j.m_value.binary->subtype())); } else if (j.m_value.binary->subtype() <= (std::numeric_limits::max)()) { write_number(static_cast(0xd9)); write_number(static_cast(j.m_value.binary->subtype())); } else if (j.m_value.binary->subtype() <= (std::numeric_limits::max)()) { write_number(static_cast(0xda)); write_number(static_cast(j.m_value.binary->subtype())); } else if (j.m_value.binary->subtype() <= (std::numeric_limits::max)()) { write_number(static_cast(0xdb)); write_number(static_cast(j.m_value.binary->subtype())); } } // step 1: write control byte and the binary array size const auto N = j.m_value.binary->size(); if (N <= 0x17) { write_number(static_cast(0x40 + N)); } else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x58)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x59)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x5A)); write_number(static_cast(N)); } // LCOV_EXCL_START else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0x5B)); write_number(static_cast(N)); } // LCOV_EXCL_STOP // step 2: write each element oa->write_characters( reinterpret_cast(j.m_value.binary->data()), N); break; } case value_t::object: { // step 1: write control byte and the object size const auto N = j.m_value.object->size(); if (N <= 0x17) { write_number(static_cast(0xA0 + N)); } else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0xB8)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0xB9)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0xBA)); write_number(static_cast(N)); } // LCOV_EXCL_START else if (N <= (std::numeric_limits::max)()) { oa->write_character(to_char_type(0xBB)); write_number(static_cast(N)); } // LCOV_EXCL_STOP // step 2: write each element for (const auto& el : *j.m_value.object) { write_cbor(el.first); write_cbor(el.second); } break; } case value_t::discarded: default: break; } } /*! @param[in] j JSON value to serialize */ void write_msgpack(const BasicJsonType& j) { switch (j.type()) { case value_t::null: // nil { oa->write_character(to_char_type(0xC0)); break; } case value_t::boolean: // true and false { oa->write_character(j.m_value.boolean ? to_char_type(0xC3) : to_char_type(0xC2)); break; } case value_t::number_integer: { if (j.m_value.number_integer >= 0) { // MessagePack does not differentiate between positive // signed integers and unsigned integers. Therefore, we used // the code from the value_t::number_unsigned case here. if (j.m_value.number_unsigned < 128) { // positive fixnum write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) { // uint 8 oa->write_character(to_char_type(0xCC)); write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) { // uint 16 oa->write_character(to_char_type(0xCD)); write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) { // uint 32 oa->write_character(to_char_type(0xCE)); write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) { // uint 64 oa->write_character(to_char_type(0xCF)); write_number(static_cast(j.m_value.number_integer)); } } else { if (j.m_value.number_integer >= -32) { // negative fixnum write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_integer >= (std::numeric_limits::min)() && j.m_value.number_integer <= (std::numeric_limits::max)()) { // int 8 oa->write_character(to_char_type(0xD0)); write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_integer >= (std::numeric_limits::min)() && j.m_value.number_integer <= (std::numeric_limits::max)()) { // int 16 oa->write_character(to_char_type(0xD1)); write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_integer >= (std::numeric_limits::min)() && j.m_value.number_integer <= (std::numeric_limits::max)()) { // int 32 oa->write_character(to_char_type(0xD2)); write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_integer >= (std::numeric_limits::min)() && j.m_value.number_integer <= (std::numeric_limits::max)()) { // int 64 oa->write_character(to_char_type(0xD3)); write_number(static_cast(j.m_value.number_integer)); } } break; } case value_t::number_unsigned: { if (j.m_value.number_unsigned < 128) { // positive fixnum write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) { // uint 8 oa->write_character(to_char_type(0xCC)); write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) { // uint 16 oa->write_character(to_char_type(0xCD)); write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) { // uint 32 oa->write_character(to_char_type(0xCE)); write_number(static_cast(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) { // uint 64 oa->write_character(to_char_type(0xCF)); write_number(static_cast(j.m_value.number_integer)); } break; } case value_t::number_float: { write_compact_float(j.m_value.number_float, detail::input_format_t::msgpack); break; } case value_t::string: { // step 1: write control byte and the string length const auto N = j.m_value.string->size(); if (N <= 31) { // fixstr write_number(static_cast(0xA0 | N)); } else if (N <= (std::numeric_limits::max)()) { // str 8 oa->write_character(to_char_type(0xD9)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { // str 16 oa->write_character(to_char_type(0xDA)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { // str 32 oa->write_character(to_char_type(0xDB)); write_number(static_cast(N)); } // step 2: write the string oa->write_characters( reinterpret_cast(j.m_value.string->c_str()), j.m_value.string->size()); break; } case value_t::array: { // step 1: write control byte and the array size const auto N = j.m_value.array->size(); if (N <= 15) { // fixarray write_number(static_cast(0x90 | N)); } else if (N <= (std::numeric_limits::max)()) { // array 16 oa->write_character(to_char_type(0xDC)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { // array 32 oa->write_character(to_char_type(0xDD)); write_number(static_cast(N)); } // step 2: write each element for (const auto& el : *j.m_value.array) { write_msgpack(el); } break; } case value_t::binary: { // step 0: determine if the binary type has a set subtype to // determine whether or not to use the ext or fixext types const bool use_ext = j.m_value.binary->has_subtype(); // step 1: write control byte and the byte string length const auto N = j.m_value.binary->size(); if (N <= (std::numeric_limits::max)()) { std::uint8_t output_type{}; bool fixed = true; if (use_ext) { switch (N) { case 1: output_type = 0xD4; // fixext 1 break; case 2: output_type = 0xD5; // fixext 2 break; case 4: output_type = 0xD6; // fixext 4 break; case 8: output_type = 0xD7; // fixext 8 break; case 16: output_type = 0xD8; // fixext 16 break; default: output_type = 0xC7; // ext 8 fixed = false; break; } } else { output_type = 0xC4; // bin 8 fixed = false; } oa->write_character(to_char_type(output_type)); if (!fixed) { write_number(static_cast(N)); } } else if (N <= (std::numeric_limits::max)()) { std::uint8_t output_type = use_ext ? 0xC8 // ext 16 : 0xC5; // bin 16 oa->write_character(to_char_type(output_type)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { std::uint8_t output_type = use_ext ? 0xC9 // ext 32 : 0xC6; // bin 32 oa->write_character(to_char_type(output_type)); write_number(static_cast(N)); } // step 1.5: if this is an ext type, write the subtype if (use_ext) { write_number(static_cast(j.m_value.binary->subtype())); } // step 2: write the byte string oa->write_characters( reinterpret_cast(j.m_value.binary->data()), N); break; } case value_t::object: { // step 1: write control byte and the object size const auto N = j.m_value.object->size(); if (N <= 15) { // fixmap write_number(static_cast(0x80 | (N & 0xF))); } else if (N <= (std::numeric_limits::max)()) { // map 16 oa->write_character(to_char_type(0xDE)); write_number(static_cast(N)); } else if (N <= (std::numeric_limits::max)()) { // map 32 oa->write_character(to_char_type(0xDF)); write_number(static_cast(N)); } // step 2: write each element for (const auto& el : *j.m_value.object) { write_msgpack(el.first); write_msgpack(el.second); } break; } case value_t::discarded: default: break; } } /*! @param[in] j JSON value to serialize @param[in] use_count whether to use '#' prefixes (optimized format) @param[in] use_type whether to use '$' prefixes (optimized format) @param[in] add_prefix whether prefixes need to be used for this value */ void write_ubjson(const BasicJsonType& j, const bool use_count, const bool use_type, const bool add_prefix = true) { switch (j.type()) { case value_t::null: { if (add_prefix) { oa->write_character(to_char_type('Z')); } break; } case value_t::boolean: { if (add_prefix) { oa->write_character(j.m_value.boolean ? to_char_type('T') : to_char_type('F')); } break; } case value_t::number_integer: { write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix); break; } case value_t::number_unsigned: { write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix); break; } case value_t::number_float: { write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix); break; } case value_t::string: { if (add_prefix) { oa->write_character(to_char_type('S')); } write_number_with_ubjson_prefix(j.m_value.string->size(), true); oa->write_characters( reinterpret_cast(j.m_value.string->c_str()), j.m_value.string->size()); break; } case value_t::array: { if (add_prefix) { oa->write_character(to_char_type('[')); } bool prefix_required = true; if (use_type && !j.m_value.array->empty()) { JSON_ASSERT(use_count); const CharType first_prefix = ubjson_prefix(j.front()); const bool same_prefix = std::all_of(j.begin() + 1, j.end(), [this, first_prefix](const BasicJsonType & v) { return ubjson_prefix(v) == first_prefix; }); if (same_prefix) { prefix_required = false; oa->write_character(to_char_type('$')); oa->write_character(first_prefix); } } if (use_count) { oa->write_character(to_char_type('#')); write_number_with_ubjson_prefix(j.m_value.array->size(), true); } for (const auto& el : *j.m_value.array) { write_ubjson(el, use_count, use_type, prefix_required); } if (!use_count) { oa->write_character(to_char_type(']')); } break; } case value_t::binary: { if (add_prefix) { oa->write_character(to_char_type('[')); } if (use_type && !j.m_value.binary->empty()) { JSON_ASSERT(use_count); oa->write_character(to_char_type('$')); oa->write_character('U'); } if (use_count) { oa->write_character(to_char_type('#')); write_number_with_ubjson_prefix(j.m_value.binary->size(), true); } if (use_type) { oa->write_characters( reinterpret_cast(j.m_value.binary->data()), j.m_value.binary->size()); } else { for (size_t i = 0; i < j.m_value.binary->size(); ++i) { oa->write_character(to_char_type('U')); oa->write_character(j.m_value.binary->data()[i]); } } if (!use_count) { oa->write_character(to_char_type(']')); } break; } case value_t::object: { if (add_prefix) { oa->write_character(to_char_type('{')); } bool prefix_required = true; if (use_type && !j.m_value.object->empty()) { JSON_ASSERT(use_count); const CharType first_prefix = ubjson_prefix(j.front()); const bool same_prefix = std::all_of(j.begin(), j.end(), [this, first_prefix](const BasicJsonType & v) { return ubjson_prefix(v) == first_prefix; }); if (same_prefix) { prefix_required = false; oa->write_character(to_char_type('$')); oa->write_character(first_prefix); } } if (use_count) { oa->write_character(to_char_type('#')); write_number_with_ubjson_prefix(j.m_value.object->size(), true); } for (const auto& el : *j.m_value.object) { write_number_with_ubjson_prefix(el.first.size(), true); oa->write_characters( reinterpret_cast(el.first.c_str()), el.first.size()); write_ubjson(el.second, use_count, use_type, prefix_required); } if (!use_count) { oa->write_character(to_char_type('}')); } break; } case value_t::discarded: default: break; } } private: ////////// // BSON // ////////// /*! @return The size of a BSON document entry header, including the id marker and the entry name size (and its null-terminator). */ static std::size_t calc_bson_entry_header_size(const string_t& name, const BasicJsonType& j) { const auto it = name.find(static_cast(0)); if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos)) { JSON_THROW(out_of_range::create(409, "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")", j)); static_cast(j); } return /*id*/ 1ul + name.size() + /*zero-terminator*/1u; } /*! @brief Writes the given @a element_type and @a name to the output adapter */ void write_bson_entry_header(const string_t& name, const std::uint8_t element_type) { oa->write_character(to_char_type(element_type)); // boolean oa->write_characters( reinterpret_cast(name.c_str()), name.size() + 1u); } /*! @brief Writes a BSON element with key @a name and boolean value @a value */ void write_bson_boolean(const string_t& name, const bool value) { write_bson_entry_header(name, 0x08); oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00)); } /*! @brief Writes a BSON element with key @a name and double value @a value */ void write_bson_double(const string_t& name, const double value) { write_bson_entry_header(name, 0x01); write_number(value); } /*! @return The size of the BSON-encoded string in @a value */ static std::size_t calc_bson_string_size(const string_t& value) { return sizeof(std::int32_t) + value.size() + 1ul; } /*! @brief Writes a BSON element with key @a name and string value @a value */ void write_bson_string(const string_t& name, const string_t& value) { write_bson_entry_header(name, 0x02); write_number(static_cast(value.size() + 1ul)); oa->write_characters( reinterpret_cast(value.c_str()), value.size() + 1); } /*! @brief Writes a BSON element with key @a name and null value */ void write_bson_null(const string_t& name) { write_bson_entry_header(name, 0x0A); } /*! @return The size of the BSON-encoded integer @a value */ static std::size_t calc_bson_integer_size(const std::int64_t value) { return (std::numeric_limits::min)() <= value && value <= (std::numeric_limits::max)() ? sizeof(std::int32_t) : sizeof(std::int64_t); } /*! @brief Writes a BSON element with key @a name and integer @a value */ void write_bson_integer(const string_t& name, const std::int64_t value) { if ((std::numeric_limits::min)() <= value && value <= (std::numeric_limits::max)()) { write_bson_entry_header(name, 0x10); // int32 write_number(static_cast(value)); } else { write_bson_entry_header(name, 0x12); // int64 write_number(static_cast(value)); } } /*! @return The size of the BSON-encoded unsigned integer in @a j */ static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept { return (value <= static_cast((std::numeric_limits::max)())) ? sizeof(std::int32_t) : sizeof(std::int64_t); } /*! @brief Writes a BSON element with key @a name and unsigned @a value */ void write_bson_unsigned(const string_t& name, const BasicJsonType& j) { if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) { write_bson_entry_header(name, 0x10 /* int32 */); write_number(static_cast(j.m_value.number_unsigned)); } else if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) { write_bson_entry_header(name, 0x12 /* int64 */); write_number(static_cast(j.m_value.number_unsigned)); } else { JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(j.m_value.number_unsigned) + " cannot be represented by BSON as it does not fit int64", j)); } } /*! @brief Writes a BSON element with key @a name and object @a value */ void write_bson_object_entry(const string_t& name, const typename BasicJsonType::object_t& value) { write_bson_entry_header(name, 0x03); // object write_bson_object(value); } /*! @return The size of the BSON-encoded array @a value */ static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value) { std::size_t array_index = 0ul; const std::size_t embedded_document_size = std::accumulate(std::begin(value), std::end(value), static_cast(0), [&array_index](std::size_t result, const typename BasicJsonType::array_t::value_type & el) { return result + calc_bson_element_size(std::to_string(array_index++), el); }); return sizeof(std::int32_t) + embedded_document_size + 1ul; } /*! @return The size of the BSON-encoded binary array @a value */ static std::size_t calc_bson_binary_size(const typename BasicJsonType::binary_t& value) { return sizeof(std::int32_t) + value.size() + 1ul; } /*! @brief Writes a BSON element with key @a name and array @a value */ void write_bson_array(const string_t& name, const typename BasicJsonType::array_t& value) { write_bson_entry_header(name, 0x04); // array write_number(static_cast(calc_bson_array_size(value))); std::size_t array_index = 0ul; for (const auto& el : value) { write_bson_element(std::to_string(array_index++), el); } oa->write_character(to_char_type(0x00)); } /*! @brief Writes a BSON element with key @a name and binary value @a value */ void write_bson_binary(const string_t& name, const binary_t& value) { write_bson_entry_header(name, 0x05); write_number(static_cast(value.size())); write_number(value.has_subtype() ? static_cast(value.subtype()) : static_cast(0x00)); oa->write_characters(reinterpret_cast(value.data()), value.size()); } /*! @brief Calculates the size necessary to serialize the JSON value @a j with its @a name @return The calculated size for the BSON document entry for @a j with the given @a name. */ static std::size_t calc_bson_element_size(const string_t& name, const BasicJsonType& j) { const auto header_size = calc_bson_entry_header_size(name, j); switch (j.type()) { case value_t::object: return header_size + calc_bson_object_size(*j.m_value.object); case value_t::array: return header_size + calc_bson_array_size(*j.m_value.array); case value_t::binary: return header_size + calc_bson_binary_size(*j.m_value.binary); case value_t::boolean: return header_size + 1ul; case value_t::number_float: return header_size + 8ul; case value_t::number_integer: return header_size + calc_bson_integer_size(j.m_value.number_integer); case value_t::number_unsigned: return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned); case value_t::string: return header_size + calc_bson_string_size(*j.m_value.string); case value_t::null: return header_size + 0ul; // LCOV_EXCL_START case value_t::discarded: default: JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) return 0ul; // LCOV_EXCL_STOP } } /*! @brief Serializes the JSON value @a j to BSON and associates it with the key @a name. @param name The name to associate with the JSON entity @a j within the current BSON document */ void write_bson_element(const string_t& name, const BasicJsonType& j) { switch (j.type()) { case value_t::object: return write_bson_object_entry(name, *j.m_value.object); case value_t::array: return write_bson_array(name, *j.m_value.array); case value_t::binary: return write_bson_binary(name, *j.m_value.binary); case value_t::boolean: return write_bson_boolean(name, j.m_value.boolean); case value_t::number_float: return write_bson_double(name, j.m_value.number_float); case value_t::number_integer: return write_bson_integer(name, j.m_value.number_integer); case value_t::number_unsigned: return write_bson_unsigned(name, j); case value_t::string: return write_bson_string(name, *j.m_value.string); case value_t::null: return write_bson_null(name); // LCOV_EXCL_START case value_t::discarded: default: JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) return; // LCOV_EXCL_STOP } } /*! @brief Calculates the size of the BSON serialization of the given JSON-object @a j. @param[in] value JSON value to serialize @pre value.type() == value_t::object */ static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value) { std::size_t document_size = std::accumulate(value.begin(), value.end(), static_cast(0), [](size_t result, const typename BasicJsonType::object_t::value_type & el) { return result += calc_bson_element_size(el.first, el.second); }); return sizeof(std::int32_t) + document_size + 1ul; } /*! @param[in] value JSON value to serialize @pre value.type() == value_t::object */ void write_bson_object(const typename BasicJsonType::object_t& value) { write_number(static_cast(calc_bson_object_size(value))); for (const auto& el : value) { write_bson_element(el.first, el.second); } oa->write_character(to_char_type(0x00)); } ////////// // CBOR // ////////// static constexpr CharType get_cbor_float_prefix(float /*unused*/) { return to_char_type(0xFA); // Single-Precision Float } static constexpr CharType get_cbor_float_prefix(double /*unused*/) { return to_char_type(0xFB); // Double-Precision Float } ///////////// // MsgPack // ///////////// static constexpr CharType get_msgpack_float_prefix(float /*unused*/) { return to_char_type(0xCA); // float 32 } static constexpr CharType get_msgpack_float_prefix(double /*unused*/) { return to_char_type(0xCB); // float 64 } //////////// // UBJSON // //////////// // UBJSON: write number (floating point) template::value, int>::type = 0> void write_number_with_ubjson_prefix(const NumberType n, const bool add_prefix) { if (add_prefix) { oa->write_character(get_ubjson_float_prefix(n)); } write_number(n); } // UBJSON: write number (unsigned integer) template::value, int>::type = 0> void write_number_with_ubjson_prefix(const NumberType n, const bool add_prefix) { if (n <= static_cast((std::numeric_limits::max)())) { if (add_prefix) { oa->write_character(to_char_type('i')); // int8 } write_number(static_cast(n)); } else if (n <= (std::numeric_limits::max)()) { if (add_prefix) { oa->write_character(to_char_type('U')); // uint8 } write_number(static_cast(n)); } else if (n <= static_cast((std::numeric_limits::max)())) { if (add_prefix) { oa->write_character(to_char_type('I')); // int16 } write_number(static_cast(n)); } else if (n <= static_cast((std::numeric_limits::max)())) { if (add_prefix) { oa->write_character(to_char_type('l')); // int32 } write_number(static_cast(n)); } else if (n <= static_cast((std::numeric_limits::max)())) { if (add_prefix) { oa->write_character(to_char_type('L')); // int64 } write_number(static_cast(n)); } else { if (add_prefix) { oa->write_character(to_char_type('H')); // high-precision number } const auto number = BasicJsonType(n).dump(); write_number_with_ubjson_prefix(number.size(), true); for (std::size_t i = 0; i < number.size(); ++i) { oa->write_character(to_char_type(static_cast(number[i]))); } } } // UBJSON: write number (signed integer) template < typename NumberType, typename std::enable_if < std::is_signed::value&& !std::is_floating_point::value, int >::type = 0 > void write_number_with_ubjson_prefix(const NumberType n, const bool add_prefix) { if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) { if (add_prefix) { oa->write_character(to_char_type('i')); // int8 } write_number(static_cast(n)); } else if (static_cast((std::numeric_limits::min)()) <= n && n <= static_cast((std::numeric_limits::max)())) { if (add_prefix) { oa->write_character(to_char_type('U')); // uint8 } write_number(static_cast(n)); } else if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) { if (add_prefix) { oa->write_character(to_char_type('I')); // int16 } write_number(static_cast(n)); } else if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) { if (add_prefix) { oa->write_character(to_char_type('l')); // int32 } write_number(static_cast(n)); } else if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) { if (add_prefix) { oa->write_character(to_char_type('L')); // int64 } write_number(static_cast(n)); } // LCOV_EXCL_START else { if (add_prefix) { oa->write_character(to_char_type('H')); // high-precision number } const auto number = BasicJsonType(n).dump(); write_number_with_ubjson_prefix(number.size(), true); for (std::size_t i = 0; i < number.size(); ++i) { oa->write_character(to_char_type(static_cast(number[i]))); } } // LCOV_EXCL_STOP } /*! @brief determine the type prefix of container values */ CharType ubjson_prefix(const BasicJsonType& j) const noexcept { switch (j.type()) { case value_t::null: return 'Z'; case value_t::boolean: return j.m_value.boolean ? 'T' : 'F'; case value_t::number_integer: { if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) { return 'i'; } if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) { return 'U'; } if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) { return 'I'; } if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) { return 'l'; } if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) { return 'L'; } // anything else is treated as high-precision number return 'H'; // LCOV_EXCL_LINE } case value_t::number_unsigned: { if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) { return 'i'; } if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) { return 'U'; } if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) { return 'I'; } if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) { return 'l'; } if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) { return 'L'; } // anything else is treated as high-precision number return 'H'; // LCOV_EXCL_LINE } case value_t::number_float: return get_ubjson_float_prefix(j.m_value.number_float); case value_t::string: return 'S'; case value_t::array: // fallthrough case value_t::binary: return '['; case value_t::object: return '{'; case value_t::discarded: default: // discarded values return 'N'; } } static constexpr CharType get_ubjson_float_prefix(float /*unused*/) { return 'd'; // float 32 } static constexpr CharType get_ubjson_float_prefix(double /*unused*/) { return 'D'; // float 64 } /////////////////////// // Utility functions // /////////////////////// /* @brief write a number to output input @param[in] n number of type @a NumberType @tparam NumberType the type of the number @tparam OutputIsLittleEndian Set to true if output data is required to be little endian @note This function needs to respect the system's endianness, because bytes in CBOR, MessagePack, and UBJSON are stored in network order (big endian) and therefore need reordering on little endian systems. */ template void write_number(const NumberType n) { // step 1: write number to array of length NumberType std::array vec{}; std::memcpy(vec.data(), &n, sizeof(NumberType)); // step 2: write array to output (with possible reordering) if (is_little_endian != OutputIsLittleEndian) { // reverse byte order prior to conversion if necessary std::reverse(vec.begin(), vec.end()); } oa->write_characters(vec.data(), sizeof(NumberType)); } void write_compact_float(const number_float_t n, detail::input_format_t format) { #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wfloat-equal" #endif if (static_cast(n) >= static_cast(std::numeric_limits::lowest()) && static_cast(n) <= static_cast((std::numeric_limits::max)()) && static_cast(static_cast(n)) == static_cast(n)) { oa->write_character(format == detail::input_format_t::cbor ? get_cbor_float_prefix(static_cast(n)) : get_msgpack_float_prefix(static_cast(n))); write_number(static_cast(n)); } else { oa->write_character(format == detail::input_format_t::cbor ? get_cbor_float_prefix(n) : get_msgpack_float_prefix(n)); write_number(n); } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif } public: // The following to_char_type functions are implement the conversion // between uint8_t and CharType. In case CharType is not unsigned, // such a conversion is required to allow values greater than 128. // See for a discussion. template < typename C = CharType, enable_if_t < std::is_signed::value && std::is_signed::value > * = nullptr > static constexpr CharType to_char_type(std::uint8_t x) noexcept { return *reinterpret_cast(&x); } template < typename C = CharType, enable_if_t < std::is_signed::value && std::is_unsigned::value > * = nullptr > static CharType to_char_type(std::uint8_t x) noexcept { static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t"); static_assert(std::is_trivial::value, "CharType must be trivial"); CharType result; std::memcpy(&result, &x, sizeof(x)); return result; } template::value>* = nullptr> static constexpr CharType to_char_type(std::uint8_t x) noexcept { return x; } template < typename InputCharType, typename C = CharType, enable_if_t < std::is_signed::value && std::is_signed::value && std::is_same::type>::value > * = nullptr > static constexpr CharType to_char_type(InputCharType x) noexcept { return x; } private: /// whether we can assume little endianness const bool is_little_endian = little_endianness(); /// the output output_adapter_t oa = nullptr; }; } // namespace detail } // namespace nlohmann // #include // #include #include // reverse, remove, fill, find, none_of #include // array #include // localeconv, lconv #include // labs, isfinite, isnan, signbit #include // size_t, ptrdiff_t #include // uint8_t #include // snprintf #include // numeric_limits #include // string, char_traits #include // setfill, setw #include // stringstream #include // is_same #include // move // #include #include // array #include // signbit, isfinite #include // intN_t, uintN_t #include // memcpy, memmove #include // numeric_limits #include // conditional // #include namespace nlohmann { namespace detail { /*! @brief implements the Grisu2 algorithm for binary to decimal floating-point conversion. This implementation is a slightly modified version of the reference implementation which may be obtained from http://florian.loitsch.com/publications (bench.tar.gz). The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch. For a detailed description of the algorithm see: [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming Language Design and Implementation, PLDI 2010 [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately", Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language Design and Implementation, PLDI 1996 */ namespace dtoa_impl { template Target reinterpret_bits(const Source source) { static_assert(sizeof(Target) == sizeof(Source), "size mismatch"); Target target; std::memcpy(&target, &source, sizeof(Source)); return target; } struct diyfp // f * 2^e { static constexpr int kPrecision = 64; // = q std::uint64_t f = 0; int e = 0; constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {} /*! @brief returns x - y @pre x.e == y.e and x.f >= y.f */ static diyfp sub(const diyfp& x, const diyfp& y) noexcept { JSON_ASSERT(x.e == y.e); JSON_ASSERT(x.f >= y.f); return {x.f - y.f, x.e}; } /*! @brief returns x * y @note The result is rounded. (Only the upper q bits are returned.) */ static diyfp mul(const diyfp& x, const diyfp& y) noexcept { static_assert(kPrecision == 64, "internal error"); // Computes: // f = round((x.f * y.f) / 2^q) // e = x.e + y.e + q // Emulate the 64-bit * 64-bit multiplication: // // p = u * v // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi) // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi ) // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 ) // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 ) // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3) // = (p0_lo ) + 2^32 (Q ) + 2^64 (H ) // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H ) // // (Since Q might be larger than 2^32 - 1) // // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H) // // (Q_hi + H does not overflow a 64-bit int) // // = p_lo + 2^64 p_hi const std::uint64_t u_lo = x.f & 0xFFFFFFFFu; const std::uint64_t u_hi = x.f >> 32u; const std::uint64_t v_lo = y.f & 0xFFFFFFFFu; const std::uint64_t v_hi = y.f >> 32u; const std::uint64_t p0 = u_lo * v_lo; const std::uint64_t p1 = u_lo * v_hi; const std::uint64_t p2 = u_hi * v_lo; const std::uint64_t p3 = u_hi * v_hi; const std::uint64_t p0_hi = p0 >> 32u; const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu; const std::uint64_t p1_hi = p1 >> 32u; const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu; const std::uint64_t p2_hi = p2 >> 32u; std::uint64_t Q = p0_hi + p1_lo + p2_lo; // The full product might now be computed as // // p_hi = p3 + p2_hi + p1_hi + (Q >> 32) // p_lo = p0_lo + (Q << 32) // // But in this particular case here, the full p_lo is not required. // Effectively we only need to add the highest bit in p_lo to p_hi (and // Q_hi + 1 does not overflow). Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u); return {h, x.e + y.e + 64}; } /*! @brief normalize x such that the significand is >= 2^(q-1) @pre x.f != 0 */ static diyfp normalize(diyfp x) noexcept { JSON_ASSERT(x.f != 0); while ((x.f >> 63u) == 0) { x.f <<= 1u; x.e--; } return x; } /*! @brief normalize x such that the result has the exponent E @pre e >= x.e and the upper e - x.e bits of x.f must be zero. */ static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept { const int delta = x.e - target_exponent; JSON_ASSERT(delta >= 0); JSON_ASSERT(((x.f << delta) >> delta) == x.f); return {x.f << delta, target_exponent}; } }; struct boundaries { diyfp w; diyfp minus; diyfp plus; }; /*! Compute the (normalized) diyfp representing the input number 'value' and its boundaries. @pre value must be finite and positive */ template boundaries compute_boundaries(FloatType value) { JSON_ASSERT(std::isfinite(value)); JSON_ASSERT(value > 0); // Convert the IEEE representation into a diyfp. // // If v is denormal: // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1)) // If v is normalized: // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1)) static_assert(std::numeric_limits::is_iec559, "internal error: dtoa_short requires an IEEE-754 floating-point implementation"); constexpr int kPrecision = std::numeric_limits::digits; // = p (includes the hidden bit) constexpr int kBias = std::numeric_limits::max_exponent - 1 + (kPrecision - 1); constexpr int kMinExp = 1 - kBias; constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1) using bits_type = typename std::conditional::type; const auto bits = static_cast(reinterpret_bits(value)); const std::uint64_t E = bits >> (kPrecision - 1); const std::uint64_t F = bits & (kHiddenBit - 1); const bool is_denormal = E == 0; const diyfp v = is_denormal ? diyfp(F, kMinExp) : diyfp(F + kHiddenBit, static_cast(E) - kBias); // Compute the boundaries m- and m+ of the floating-point value // v = f * 2^e. // // Determine v- and v+, the floating-point predecessor and successor if v, // respectively. // // v- = v - 2^e if f != 2^(p-1) or e == e_min (A) // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B) // // v+ = v + 2^e // // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_ // between m- and m+ round to v, regardless of how the input rounding // algorithm breaks ties. // // ---+-------------+-------------+-------------+-------------+--- (A) // v- m- v m+ v+ // // -----------------+------+------+-------------+-------------+--- (B) // v- m- v m+ v+ const bool lower_boundary_is_closer = F == 0 && E > 1; const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1); const diyfp m_minus = lower_boundary_is_closer ? diyfp(4 * v.f - 1, v.e - 2) // (B) : diyfp(2 * v.f - 1, v.e - 1); // (A) // Determine the normalized w+ = m+. const diyfp w_plus = diyfp::normalize(m_plus); // Determine w- = m- such that e_(w-) = e_(w+). const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e); return {diyfp::normalize(v), w_minus, w_plus}; } // Given normalized diyfp w, Grisu needs to find a (normalized) cached // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies // within a certain range [alpha, gamma] (Definition 3.2 from [1]) // // alpha <= e = e_c + e_w + q <= gamma // // or // // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q // <= f_c * f_w * 2^gamma // // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies // // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma // // or // // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma) // // The choice of (alpha,gamma) determines the size of the table and the form of // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well // in practice: // // The idea is to cut the number c * w = f * 2^e into two parts, which can be // processed independently: An integral part p1, and a fractional part p2: // // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e // = (f div 2^-e) + (f mod 2^-e) * 2^e // = p1 + p2 * 2^e // // The conversion of p1 into decimal form requires a series of divisions and // modulos by (a power of) 10. These operations are faster for 32-bit than for // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be // achieved by choosing // // -e >= 32 or e <= -32 := gamma // // In order to convert the fractional part // // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ... // // into decimal form, the fraction is repeatedly multiplied by 10 and the digits // d[-i] are extracted in order: // // (10 * p2) div 2^-e = d[-1] // (10 * p2) mod 2^-e = d[-2] / 10^1 + ... // // The multiplication by 10 must not overflow. It is sufficient to choose // // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64. // // Since p2 = f mod 2^-e < 2^-e, // // -e <= 60 or e >= -60 := alpha constexpr int kAlpha = -60; constexpr int kGamma = -32; struct cached_power // c = f * 2^e ~= 10^k { std::uint64_t f; int e; int k; }; /*! For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c satisfies (Definition 3.2 from [1]) alpha <= e_c + e + q <= gamma. */ inline cached_power get_cached_power_for_binary_exponent(int e) { // Now // // alpha <= e_c + e + q <= gamma (1) // ==> f_c * 2^alpha <= c * 2^e * 2^q // // and since the c's are normalized, 2^(q-1) <= f_c, // // ==> 2^(q - 1 + alpha) <= c * 2^(e + q) // ==> 2^(alpha - e - 1) <= c // // If c were an exact power of ten, i.e. c = 10^k, one may determine k as // // k = ceil( log_10( 2^(alpha - e - 1) ) ) // = ceil( (alpha - e - 1) * log_10(2) ) // // From the paper: // "In theory the result of the procedure could be wrong since c is rounded, // and the computation itself is approximated [...]. In practice, however, // this simple function is sufficient." // // For IEEE double precision floating-point numbers converted into // normalized diyfp's w = f * 2^e, with q = 64, // // e >= -1022 (min IEEE exponent) // -52 (p - 1) // -52 (p - 1, possibly normalize denormal IEEE numbers) // -11 (normalize the diyfp) // = -1137 // // and // // e <= +1023 (max IEEE exponent) // -52 (p - 1) // -11 (normalize the diyfp) // = 960 // // This binary exponent range [-1137,960] results in a decimal exponent // range [-307,324]. One does not need to store a cached power for each // k in this range. For each such k it suffices to find a cached power // such that the exponent of the product lies in [alpha,gamma]. // This implies that the difference of the decimal exponents of adjacent // table entries must be less than or equal to // // floor( (gamma - alpha) * log_10(2) ) = 8. // // (A smaller distance gamma-alpha would require a larger table.) // NB: // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34. constexpr int kCachedPowersMinDecExp = -300; constexpr int kCachedPowersDecStep = 8; static constexpr std::array kCachedPowers = { { { 0xAB70FE17C79AC6CA, -1060, -300 }, { 0xFF77B1FCBEBCDC4F, -1034, -292 }, { 0xBE5691EF416BD60C, -1007, -284 }, { 0x8DD01FAD907FFC3C, -980, -276 }, { 0xD3515C2831559A83, -954, -268 }, { 0x9D71AC8FADA6C9B5, -927, -260 }, { 0xEA9C227723EE8BCB, -901, -252 }, { 0xAECC49914078536D, -874, -244 }, { 0x823C12795DB6CE57, -847, -236 }, { 0xC21094364DFB5637, -821, -228 }, { 0x9096EA6F3848984F, -794, -220 }, { 0xD77485CB25823AC7, -768, -212 }, { 0xA086CFCD97BF97F4, -741, -204 }, { 0xEF340A98172AACE5, -715, -196 }, { 0xB23867FB2A35B28E, -688, -188 }, { 0x84C8D4DFD2C63F3B, -661, -180 }, { 0xC5DD44271AD3CDBA, -635, -172 }, { 0x936B9FCEBB25C996, -608, -164 }, { 0xDBAC6C247D62A584, -582, -156 }, { 0xA3AB66580D5FDAF6, -555, -148 }, { 0xF3E2F893DEC3F126, -529, -140 }, { 0xB5B5ADA8AAFF80B8, -502, -132 }, { 0x87625F056C7C4A8B, -475, -124 }, { 0xC9BCFF6034C13053, -449, -116 }, { 0x964E858C91BA2655, -422, -108 }, { 0xDFF9772470297EBD, -396, -100 }, { 0xA6DFBD9FB8E5B88F, -369, -92 }, { 0xF8A95FCF88747D94, -343, -84 }, { 0xB94470938FA89BCF, -316, -76 }, { 0x8A08F0F8BF0F156B, -289, -68 }, { 0xCDB02555653131B6, -263, -60 }, { 0x993FE2C6D07B7FAC, -236, -52 }, { 0xE45C10C42A2B3B06, -210, -44 }, { 0xAA242499697392D3, -183, -36 }, { 0xFD87B5F28300CA0E, -157, -28 }, { 0xBCE5086492111AEB, -130, -20 }, { 0x8CBCCC096F5088CC, -103, -12 }, { 0xD1B71758E219652C, -77, -4 }, { 0x9C40000000000000, -50, 4 }, { 0xE8D4A51000000000, -24, 12 }, { 0xAD78EBC5AC620000, 3, 20 }, { 0x813F3978F8940984, 30, 28 }, { 0xC097CE7BC90715B3, 56, 36 }, { 0x8F7E32CE7BEA5C70, 83, 44 }, { 0xD5D238A4ABE98068, 109, 52 }, { 0x9F4F2726179A2245, 136, 60 }, { 0xED63A231D4C4FB27, 162, 68 }, { 0xB0DE65388CC8ADA8, 189, 76 }, { 0x83C7088E1AAB65DB, 216, 84 }, { 0xC45D1DF942711D9A, 242, 92 }, { 0x924D692CA61BE758, 269, 100 }, { 0xDA01EE641A708DEA, 295, 108 }, { 0xA26DA3999AEF774A, 322, 116 }, { 0xF209787BB47D6B85, 348, 124 }, { 0xB454E4A179DD1877, 375, 132 }, { 0x865B86925B9BC5C2, 402, 140 }, { 0xC83553C5C8965D3D, 428, 148 }, { 0x952AB45CFA97A0B3, 455, 156 }, { 0xDE469FBD99A05FE3, 481, 164 }, { 0xA59BC234DB398C25, 508, 172 }, { 0xF6C69A72A3989F5C, 534, 180 }, { 0xB7DCBF5354E9BECE, 561, 188 }, { 0x88FCF317F22241E2, 588, 196 }, { 0xCC20CE9BD35C78A5, 614, 204 }, { 0x98165AF37B2153DF, 641, 212 }, { 0xE2A0B5DC971F303A, 667, 220 }, { 0xA8D9D1535CE3B396, 694, 228 }, { 0xFB9B7CD9A4A7443C, 720, 236 }, { 0xBB764C4CA7A44410, 747, 244 }, { 0x8BAB8EEFB6409C1A, 774, 252 }, { 0xD01FEF10A657842C, 800, 260 }, { 0x9B10A4E5E9913129, 827, 268 }, { 0xE7109BFBA19C0C9D, 853, 276 }, { 0xAC2820D9623BF429, 880, 284 }, { 0x80444B5E7AA7CF85, 907, 292 }, { 0xBF21E44003ACDD2D, 933, 300 }, { 0x8E679C2F5E44FF8F, 960, 308 }, { 0xD433179D9C8CB841, 986, 316 }, { 0x9E19DB92B4E31BA9, 1013, 324 }, } }; // This computation gives exactly the same results for k as // k = ceil((kAlpha - e - 1) * 0.30102999566398114) // for |e| <= 1500, but doesn't require floating-point operations. // NB: log_10(2) ~= 78913 / 2^18 JSON_ASSERT(e >= -1500); JSON_ASSERT(e <= 1500); const int f = kAlpha - e - 1; const int k = (f * 78913) / (1 << 18) + static_cast(f > 0); const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep; JSON_ASSERT(index >= 0); JSON_ASSERT(static_cast(index) < kCachedPowers.size()); const cached_power cached = kCachedPowers[static_cast(index)]; JSON_ASSERT(kAlpha <= cached.e + e + 64); JSON_ASSERT(kGamma >= cached.e + e + 64); return cached; } /*! For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k. For n == 0, returns 1 and sets pow10 := 1. */ inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10) { // LCOV_EXCL_START if (n >= 1000000000) { pow10 = 1000000000; return 10; } // LCOV_EXCL_STOP if (n >= 100000000) { pow10 = 100000000; return 9; } if (n >= 10000000) { pow10 = 10000000; return 8; } if (n >= 1000000) { pow10 = 1000000; return 7; } if (n >= 100000) { pow10 = 100000; return 6; } if (n >= 10000) { pow10 = 10000; return 5; } if (n >= 1000) { pow10 = 1000; return 4; } if (n >= 100) { pow10 = 100; return 3; } if (n >= 10) { pow10 = 10; return 2; } pow10 = 1; return 1; } inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta, std::uint64_t rest, std::uint64_t ten_k) { JSON_ASSERT(len >= 1); JSON_ASSERT(dist <= delta); JSON_ASSERT(rest <= delta); JSON_ASSERT(ten_k > 0); // <--------------------------- delta ----> // <---- dist ---------> // --------------[------------------+-------------------]-------------- // M- w M+ // // ten_k // <------> // <---- rest ----> // --------------[------------------+----+--------------]-------------- // w V // = buf * 10^k // // ten_k represents a unit-in-the-last-place in the decimal representation // stored in buf. // Decrement buf by ten_k while this takes buf closer to w. // The tests are written in this order to avoid overflow in unsigned // integer arithmetic. while (rest < dist && delta - rest >= ten_k && (rest + ten_k < dist || dist - rest > rest + ten_k - dist)) { JSON_ASSERT(buf[len - 1] != '0'); buf[len - 1]--; rest += ten_k; } } /*! Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+. M- and M+ must be normalized and share the same exponent -60 <= e <= -32. */ inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent, diyfp M_minus, diyfp w, diyfp M_plus) { static_assert(kAlpha >= -60, "internal error"); static_assert(kGamma <= -32, "internal error"); // Generates the digits (and the exponent) of a decimal floating-point // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma. // // <--------------------------- delta ----> // <---- dist ---------> // --------------[------------------+-------------------]-------------- // M- w M+ // // Grisu2 generates the digits of M+ from left to right and stops as soon as // V is in [M-,M+]. JSON_ASSERT(M_plus.e >= kAlpha); JSON_ASSERT(M_plus.e <= kGamma); std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e) std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e) // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0): // // M+ = f * 2^e // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e // = ((p1 ) * 2^-e + (p2 )) * 2^e // = p1 + p2 * 2^e const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e); auto p1 = static_cast(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.) std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e // 1) // // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0] JSON_ASSERT(p1 > 0); std::uint32_t pow10{}; const int k = find_largest_pow10(p1, pow10); // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1) // // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1)) // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1)) // // M+ = p1 + p2 * 2^e // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e // = d[k-1] * 10^(k-1) + ( rest) * 2^e // // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0) // // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0] // // but stop as soon as // // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e int n = k; while (n > 0) { // Invariants: // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k) // pow10 = 10^(n-1) <= p1 < 10^n // const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1) const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1) // // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e) // JSON_ASSERT(d <= 9); buffer[length++] = static_cast('0' + d); // buffer := buffer * 10 + d // // M+ = buffer * 10^(n-1) + (r + p2 * 2^e) // p1 = r; n--; // // M+ = buffer * 10^n + (p1 + p2 * 2^e) // pow10 = 10^n // // Now check if enough digits have been generated. // Compute // // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e // // Note: // Since rest and delta share the same exponent e, it suffices to // compare the significands. const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2; if (rest <= delta) { // V = buffer * 10^n, with M- <= V <= M+. decimal_exponent += n; // We may now just stop. But instead look if the buffer could be // decremented to bring V closer to w. // // pow10 = 10^n is now 1 ulp in the decimal representation V. // The rounding procedure works with diyfp's with an implicit // exponent of e. // // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e // const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e; grisu2_round(buffer, length, dist, delta, rest, ten_n); return; } pow10 /= 10; // // pow10 = 10^(n-1) <= p1 < 10^n // Invariants restored. } // 2) // // The digits of the integral part have been generated: // // M+ = d[k-1]...d[1]d[0] + p2 * 2^e // = buffer + p2 * 2^e // // Now generate the digits of the fractional part p2 * 2^e. // // Note: // No decimal point is generated: the exponent is adjusted instead. // // p2 actually represents the fraction // // p2 * 2^e // = p2 / 2^-e // = d[-1] / 10^1 + d[-2] / 10^2 + ... // // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...) // // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...) // // using // // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e) // = ( d) * 2^-e + ( r) // // or // 10^m * p2 * 2^e = d + r * 2^e // // i.e. // // M+ = buffer + p2 * 2^e // = buffer + 10^-m * (d + r * 2^e) // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e // // and stop as soon as 10^-m * r * 2^e <= delta * 2^e JSON_ASSERT(p2 > delta); int m = 0; for (;;) { // Invariant: // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e // = buffer * 10^-m + 10^-m * (p2 ) * 2^e // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e // JSON_ASSERT(p2 <= (std::numeric_limits::max)() / 10); p2 *= 10; const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e // // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e)) // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e // JSON_ASSERT(d <= 9); buffer[length++] = static_cast('0' + d); // buffer := buffer * 10 + d // // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e // p2 = r; m++; // // M+ = buffer * 10^-m + 10^-m * p2 * 2^e // Invariant restored. // Check if enough digits have been generated. // // 10^-m * p2 * 2^e <= delta * 2^e // p2 * 2^e <= 10^m * delta * 2^e // p2 <= 10^m * delta delta *= 10; dist *= 10; if (p2 <= delta) { break; } } // V = buffer * 10^-m, with M- <= V <= M+. decimal_exponent -= m; // 1 ulp in the decimal representation is now 10^-m. // Since delta and dist are now scaled by 10^m, we need to do the // same with ulp in order to keep the units in sync. // // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e // const std::uint64_t ten_m = one.f; grisu2_round(buffer, length, dist, delta, p2, ten_m); // By construction this algorithm generates the shortest possible decimal // number (Loitsch, Theorem 6.2) which rounds back to w. // For an input number of precision p, at least // // N = 1 + ceil(p * log_10(2)) // // decimal digits are sufficient to identify all binary floating-point // numbers (Matula, "In-and-Out conversions"). // This implies that the algorithm does not produce more than N decimal // digits. // // N = 17 for p = 53 (IEEE double precision) // N = 9 for p = 24 (IEEE single precision) } /*! v = buf * 10^decimal_exponent len is the length of the buffer (number of decimal digits) The buffer must be large enough, i.e. >= max_digits10. */ JSON_HEDLEY_NON_NULL(1) inline void grisu2(char* buf, int& len, int& decimal_exponent, diyfp m_minus, diyfp v, diyfp m_plus) { JSON_ASSERT(m_plus.e == m_minus.e); JSON_ASSERT(m_plus.e == v.e); // --------(-----------------------+-----------------------)-------- (A) // m- v m+ // // --------------------(-----------+-----------------------)-------- (B) // m- v m+ // // First scale v (and m- and m+) such that the exponent is in the range // [alpha, gamma]. const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e); const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma] const diyfp w = diyfp::mul(v, c_minus_k); const diyfp w_minus = diyfp::mul(m_minus, c_minus_k); const diyfp w_plus = diyfp::mul(m_plus, c_minus_k); // ----(---+---)---------------(---+---)---------------(---+---)---- // w- w w+ // = c*m- = c*v = c*m+ // // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and // w+ are now off by a small amount. // In fact: // // w - v * 10^k < 1 ulp // // To account for this inaccuracy, add resp. subtract 1 ulp. // // --------+---[---------------(---+---)---------------]---+-------- // w- M- w M+ w+ // // Now any number in [M-, M+] (bounds included) will round to w when input, // regardless of how the input rounding algorithm breaks ties. // // And digit_gen generates the shortest possible such number in [M-, M+]. // Note that this does not mean that Grisu2 always generates the shortest // possible number in the interval (m-, m+). const diyfp M_minus(w_minus.f + 1, w_minus.e); const diyfp M_plus (w_plus.f - 1, w_plus.e ); decimal_exponent = -cached.k; // = -(-k) = k grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus); } /*! v = buf * 10^decimal_exponent len is the length of the buffer (number of decimal digits) The buffer must be large enough, i.e. >= max_digits10. */ template JSON_HEDLEY_NON_NULL(1) void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value) { static_assert(diyfp::kPrecision >= std::numeric_limits::digits + 3, "internal error: not enough precision"); JSON_ASSERT(std::isfinite(value)); JSON_ASSERT(value > 0); // If the neighbors (and boundaries) of 'value' are always computed for double-precision // numbers, all float's can be recovered using strtod (and strtof). However, the resulting // decimal representations are not exactly "short". // // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars) // says "value is converted to a string as if by std::sprintf in the default ("C") locale" // and since sprintf promotes floats to doubles, I think this is exactly what 'std::to_chars' // does. // On the other hand, the documentation for 'std::to_chars' requires that "parsing the // representation using the corresponding std::from_chars function recovers value exactly". That // indicates that single precision floating-point numbers should be recovered using // 'std::strtof'. // // NB: If the neighbors are computed for single-precision numbers, there is a single float // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision // value is off by 1 ulp. #if 0 const boundaries w = compute_boundaries(static_cast(value)); #else const boundaries w = compute_boundaries(value); #endif grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus); } /*! @brief appends a decimal representation of e to buf @return a pointer to the element following the exponent. @pre -1000 < e < 1000 */ JSON_HEDLEY_NON_NULL(1) JSON_HEDLEY_RETURNS_NON_NULL inline char* append_exponent(char* buf, int e) { JSON_ASSERT(e > -1000); JSON_ASSERT(e < 1000); if (e < 0) { e = -e; *buf++ = '-'; } else { *buf++ = '+'; } auto k = static_cast(e); if (k < 10) { // Always print at least two digits in the exponent. // This is for compatibility with printf("%g"). *buf++ = '0'; *buf++ = static_cast('0' + k); } else if (k < 100) { *buf++ = static_cast('0' + k / 10); k %= 10; *buf++ = static_cast('0' + k); } else { *buf++ = static_cast('0' + k / 100); k %= 100; *buf++ = static_cast('0' + k / 10); k %= 10; *buf++ = static_cast('0' + k); } return buf; } /*! @brief prettify v = buf * 10^decimal_exponent If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point notation. Otherwise it will be printed in exponential notation. @pre min_exp < 0 @pre max_exp > 0 */ JSON_HEDLEY_NON_NULL(1) JSON_HEDLEY_RETURNS_NON_NULL inline char* format_buffer(char* buf, int len, int decimal_exponent, int min_exp, int max_exp) { JSON_ASSERT(min_exp < 0); JSON_ASSERT(max_exp > 0); const int k = len; const int n = len + decimal_exponent; // v = buf * 10^(n-k) // k is the length of the buffer (number of decimal digits) // n is the position of the decimal point relative to the start of the buffer. if (k <= n && n <= max_exp) { // digits[000] // len <= max_exp + 2 std::memset(buf + k, '0', static_cast(n) - static_cast(k)); // Make it look like a floating-point number (#362, #378) buf[n + 0] = '.'; buf[n + 1] = '0'; return buf + (static_cast(n) + 2); } if (0 < n && n <= max_exp) { // dig.its // len <= max_digits10 + 1 JSON_ASSERT(k > n); std::memmove(buf + (static_cast(n) + 1), buf + n, static_cast(k) - static_cast(n)); buf[n] = '.'; return buf + (static_cast(k) + 1U); } if (min_exp < n && n <= 0) { // 0.[000]digits // len <= 2 + (-min_exp - 1) + max_digits10 std::memmove(buf + (2 + static_cast(-n)), buf, static_cast(k)); buf[0] = '0'; buf[1] = '.'; std::memset(buf + 2, '0', static_cast(-n)); return buf + (2U + static_cast(-n) + static_cast(k)); } if (k == 1) { // dE+123 // len <= 1 + 5 buf += 1; } else { // d.igitsE+123 // len <= max_digits10 + 1 + 5 std::memmove(buf + 2, buf + 1, static_cast(k) - 1); buf[1] = '.'; buf += 1 + static_cast(k); } *buf++ = 'e'; return append_exponent(buf, n - 1); } } // namespace dtoa_impl /*! @brief generates a decimal representation of the floating-point number value in [first, last). The format of the resulting decimal representation is similar to printf's %g format. Returns an iterator pointing past-the-end of the decimal representation. @note The input number must be finite, i.e. NaN's and Inf's are not supported. @note The buffer must be large enough. @note The result is NOT null-terminated. */ template JSON_HEDLEY_NON_NULL(1, 2) JSON_HEDLEY_RETURNS_NON_NULL char* to_chars(char* first, const char* last, FloatType value) { static_cast(last); // maybe unused - fix warning JSON_ASSERT(std::isfinite(value)); // Use signbit(value) instead of (value < 0) since signbit works for -0. if (std::signbit(value)) { value = -value; *first++ = '-'; } #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wfloat-equal" #endif if (value == 0) // +-0 { *first++ = '0'; // Make it look like a floating-point number (#362, #378) *first++ = '.'; *first++ = '0'; return first; } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif JSON_ASSERT(last - first >= std::numeric_limits::max_digits10); // Compute v = buffer * 10^decimal_exponent. // The decimal digits are stored in the buffer, which needs to be interpreted // as an unsigned decimal integer. // len is the length of the buffer, i.e. the number of decimal digits. int len = 0; int decimal_exponent = 0; dtoa_impl::grisu2(first, len, decimal_exponent, value); JSON_ASSERT(len <= std::numeric_limits::max_digits10); // Format the buffer like printf("%.*g", prec, value) constexpr int kMinExp = -4; // Use digits10 here to increase compatibility with version 2. constexpr int kMaxExp = std::numeric_limits::digits10; JSON_ASSERT(last - first >= kMaxExp + 2); JSON_ASSERT(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits::max_digits10); JSON_ASSERT(last - first >= std::numeric_limits::max_digits10 + 6); return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp); } } // namespace detail } // namespace nlohmann // #include // #include // #include // #include // #include // #include namespace nlohmann { namespace detail { /////////////////// // serialization // /////////////////// /// how to treat decoding errors enum class error_handler_t { strict, ///< throw a type_error exception in case of invalid UTF-8 replace, ///< replace invalid UTF-8 sequences with U+FFFD ignore ///< ignore invalid UTF-8 sequences }; template class serializer { using string_t = typename BasicJsonType::string_t; using number_float_t = typename BasicJsonType::number_float_t; using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using binary_char_t = typename BasicJsonType::binary_t::value_type; static constexpr std::uint8_t UTF8_ACCEPT = 0; static constexpr std::uint8_t UTF8_REJECT = 1; public: /*! @param[in] s output stream to serialize to @param[in] ichar indentation character to use @param[in] error_handler_ how to react on decoding errors */ serializer(output_adapter_t s, const char ichar, error_handler_t error_handler_ = error_handler_t::strict) : o(std::move(s)) , loc(std::localeconv()) , thousands_sep(loc->thousands_sep == nullptr ? '\0' : std::char_traits::to_char_type(* (loc->thousands_sep))) , decimal_point(loc->decimal_point == nullptr ? '\0' : std::char_traits::to_char_type(* (loc->decimal_point))) , indent_char(ichar) , indent_string(512, indent_char) , error_handler(error_handler_) {} // delete because of pointer members serializer(const serializer&) = delete; serializer& operator=(const serializer&) = delete; serializer(serializer&&) = delete; serializer& operator=(serializer&&) = delete; ~serializer() = default; /*! @brief internal implementation of the serialization function This function is called by the public member function dump and organizes the serialization internally. The indentation level is propagated as additional parameter. In case of arrays and objects, the function is called recursively. - strings and object keys are escaped using `escape_string()` - integer numbers are converted implicitly via `operator<<` - floating-point numbers are converted to a string using `"%g"` format - binary values are serialized as objects containing the subtype and the byte array @param[in] val value to serialize @param[in] pretty_print whether the output shall be pretty-printed @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters in the output are escaped with `\uXXXX` sequences, and the result consists of ASCII characters only. @param[in] indent_step the indent level @param[in] current_indent the current indent level (only used internally) */ void dump(const BasicJsonType& val, const bool pretty_print, const bool ensure_ascii, const unsigned int indent_step, const unsigned int current_indent = 0) { switch (val.m_type) { case value_t::object: { if (val.m_value.object->empty()) { o->write_characters("{}", 2); return; } if (pretty_print) { o->write_characters("{\n", 2); // variable to hold indentation for recursive calls const auto new_indent = current_indent + indent_step; if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) { indent_string.resize(indent_string.size() * 2, ' '); } // first n-1 elements auto i = val.m_value.object->cbegin(); for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) { o->write_characters(indent_string.c_str(), new_indent); o->write_character('\"'); dump_escaped(i->first, ensure_ascii); o->write_characters("\": ", 3); dump(i->second, true, ensure_ascii, indent_step, new_indent); o->write_characters(",\n", 2); } // last element JSON_ASSERT(i != val.m_value.object->cend()); JSON_ASSERT(std::next(i) == val.m_value.object->cend()); o->write_characters(indent_string.c_str(), new_indent); o->write_character('\"'); dump_escaped(i->first, ensure_ascii); o->write_characters("\": ", 3); dump(i->second, true, ensure_ascii, indent_step, new_indent); o->write_character('\n'); o->write_characters(indent_string.c_str(), current_indent); o->write_character('}'); } else { o->write_character('{'); // first n-1 elements auto i = val.m_value.object->cbegin(); for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) { o->write_character('\"'); dump_escaped(i->first, ensure_ascii); o->write_characters("\":", 2); dump(i->second, false, ensure_ascii, indent_step, current_indent); o->write_character(','); } // last element JSON_ASSERT(i != val.m_value.object->cend()); JSON_ASSERT(std::next(i) == val.m_value.object->cend()); o->write_character('\"'); dump_escaped(i->first, ensure_ascii); o->write_characters("\":", 2); dump(i->second, false, ensure_ascii, indent_step, current_indent); o->write_character('}'); } return; } case value_t::array: { if (val.m_value.array->empty()) { o->write_characters("[]", 2); return; } if (pretty_print) { o->write_characters("[\n", 2); // variable to hold indentation for recursive calls const auto new_indent = current_indent + indent_step; if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) { indent_string.resize(indent_string.size() * 2, ' '); } // first n-1 elements for (auto i = val.m_value.array->cbegin(); i != val.m_value.array->cend() - 1; ++i) { o->write_characters(indent_string.c_str(), new_indent); dump(*i, true, ensure_ascii, indent_step, new_indent); o->write_characters(",\n", 2); } // last element JSON_ASSERT(!val.m_value.array->empty()); o->write_characters(indent_string.c_str(), new_indent); dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent); o->write_character('\n'); o->write_characters(indent_string.c_str(), current_indent); o->write_character(']'); } else { o->write_character('['); // first n-1 elements for (auto i = val.m_value.array->cbegin(); i != val.m_value.array->cend() - 1; ++i) { dump(*i, false, ensure_ascii, indent_step, current_indent); o->write_character(','); } // last element JSON_ASSERT(!val.m_value.array->empty()); dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent); o->write_character(']'); } return; } case value_t::string: { o->write_character('\"'); dump_escaped(*val.m_value.string, ensure_ascii); o->write_character('\"'); return; } case value_t::binary: { if (pretty_print) { o->write_characters("{\n", 2); // variable to hold indentation for recursive calls const auto new_indent = current_indent + indent_step; if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) { indent_string.resize(indent_string.size() * 2, ' '); } o->write_characters(indent_string.c_str(), new_indent); o->write_characters("\"bytes\": [", 10); if (!val.m_value.binary->empty()) { for (auto i = val.m_value.binary->cbegin(); i != val.m_value.binary->cend() - 1; ++i) { dump_integer(*i); o->write_characters(", ", 2); } dump_integer(val.m_value.binary->back()); } o->write_characters("],\n", 3); o->write_characters(indent_string.c_str(), new_indent); o->write_characters("\"subtype\": ", 11); if (val.m_value.binary->has_subtype()) { dump_integer(val.m_value.binary->subtype()); } else { o->write_characters("null", 4); } o->write_character('\n'); o->write_characters(indent_string.c_str(), current_indent); o->write_character('}'); } else { o->write_characters("{\"bytes\":[", 10); if (!val.m_value.binary->empty()) { for (auto i = val.m_value.binary->cbegin(); i != val.m_value.binary->cend() - 1; ++i) { dump_integer(*i); o->write_character(','); } dump_integer(val.m_value.binary->back()); } o->write_characters("],\"subtype\":", 12); if (val.m_value.binary->has_subtype()) { dump_integer(val.m_value.binary->subtype()); o->write_character('}'); } else { o->write_characters("null}", 5); } } return; } case value_t::boolean: { if (val.m_value.boolean) { o->write_characters("true", 4); } else { o->write_characters("false", 5); } return; } case value_t::number_integer: { dump_integer(val.m_value.number_integer); return; } case value_t::number_unsigned: { dump_integer(val.m_value.number_unsigned); return; } case value_t::number_float: { dump_float(val.m_value.number_float); return; } case value_t::discarded: { o->write_characters("", 11); return; } case value_t::null: { o->write_characters("null", 4); return; } default: // LCOV_EXCL_LINE JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE } } JSON_PRIVATE_UNLESS_TESTED: /*! @brief dump escaped string Escape a string by replacing certain special characters by a sequence of an escape character (backslash) and another character and other control characters by a sequence of "\u" followed by a four-digit hex representation. The escaped string is written to output stream @a o. @param[in] s the string to escape @param[in] ensure_ascii whether to escape non-ASCII characters with \uXXXX sequences @complexity Linear in the length of string @a s. */ void dump_escaped(const string_t& s, const bool ensure_ascii) { std::uint32_t codepoint{}; std::uint8_t state = UTF8_ACCEPT; std::size_t bytes = 0; // number of bytes written to string_buffer // number of bytes written at the point of the last valid byte std::size_t bytes_after_last_accept = 0; std::size_t undumped_chars = 0; for (std::size_t i = 0; i < s.size(); ++i) { const auto byte = static_cast(s[i]); switch (decode(state, codepoint, byte)) { case UTF8_ACCEPT: // decode found a new code point { switch (codepoint) { case 0x08: // backspace { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = 'b'; break; } case 0x09: // horizontal tab { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = 't'; break; } case 0x0A: // newline { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = 'n'; break; } case 0x0C: // formfeed { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = 'f'; break; } case 0x0D: // carriage return { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = 'r'; break; } case 0x22: // quotation mark { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = '\"'; break; } case 0x5C: // reverse solidus { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = '\\'; break; } default: { // escape control characters (0x00..0x1F) or, if // ensure_ascii parameter is used, non-ASCII characters if ((codepoint <= 0x1F) || (ensure_ascii && (codepoint >= 0x7F))) { if (codepoint <= 0xFFFF) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) static_cast((std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x", static_cast(codepoint))); bytes += 6; } else { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) static_cast((std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x", static_cast(0xD7C0u + (codepoint >> 10u)), static_cast(0xDC00u + (codepoint & 0x3FFu)))); bytes += 12; } } else { // copy byte to buffer (all previous bytes // been copied have in default case above) string_buffer[bytes++] = s[i]; } break; } } // write buffer and reset index; there must be 13 bytes // left, as this is the maximal number of bytes to be // written ("\uxxxx\uxxxx\0") for one code point if (string_buffer.size() - bytes < 13) { o->write_characters(string_buffer.data(), bytes); bytes = 0; } // remember the byte position of this accept bytes_after_last_accept = bytes; undumped_chars = 0; break; } case UTF8_REJECT: // decode found invalid UTF-8 byte { switch (error_handler) { case error_handler_t::strict: { std::stringstream ss; ss << std::uppercase << std::setfill('0') << std::setw(2) << std::hex << (byte | 0); JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + ss.str(), BasicJsonType())); } case error_handler_t::ignore: case error_handler_t::replace: { // in case we saw this character the first time, we // would like to read it again, because the byte // may be OK for itself, but just not OK for the // previous sequence if (undumped_chars > 0) { --i; } // reset length buffer to the last accepted index; // thus removing/ignoring the invalid characters bytes = bytes_after_last_accept; if (error_handler == error_handler_t::replace) { // add a replacement character if (ensure_ascii) { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = 'u'; string_buffer[bytes++] = 'f'; string_buffer[bytes++] = 'f'; string_buffer[bytes++] = 'f'; string_buffer[bytes++] = 'd'; } else { string_buffer[bytes++] = detail::binary_writer::to_char_type('\xEF'); string_buffer[bytes++] = detail::binary_writer::to_char_type('\xBF'); string_buffer[bytes++] = detail::binary_writer::to_char_type('\xBD'); } // write buffer and reset index; there must be 13 bytes // left, as this is the maximal number of bytes to be // written ("\uxxxx\uxxxx\0") for one code point if (string_buffer.size() - bytes < 13) { o->write_characters(string_buffer.data(), bytes); bytes = 0; } bytes_after_last_accept = bytes; } undumped_chars = 0; // continue processing the string state = UTF8_ACCEPT; break; } default: // LCOV_EXCL_LINE JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE } break; } default: // decode found yet incomplete multi-byte code point { if (!ensure_ascii) { // code point will not be escaped - copy byte to buffer string_buffer[bytes++] = s[i]; } ++undumped_chars; break; } } } // we finished processing the string if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT)) { // write buffer if (bytes > 0) { o->write_characters(string_buffer.data(), bytes); } } else { // we finish reading, but do not accept: string was incomplete switch (error_handler) { case error_handler_t::strict: { std::stringstream ss; ss << std::uppercase << std::setfill('0') << std::setw(2) << std::hex << (static_cast(s.back()) | 0); JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + ss.str(), BasicJsonType())); } case error_handler_t::ignore: { // write all accepted bytes o->write_characters(string_buffer.data(), bytes_after_last_accept); break; } case error_handler_t::replace: { // write all accepted bytes o->write_characters(string_buffer.data(), bytes_after_last_accept); // add a replacement character if (ensure_ascii) { o->write_characters("\\ufffd", 6); } else { o->write_characters("\xEF\xBF\xBD", 3); } break; } default: // LCOV_EXCL_LINE JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE } } } private: /*! @brief count digits Count the number of decimal (base 10) digits for an input unsigned integer. @param[in] x unsigned integer number to count its digits @return number of decimal digits */ inline unsigned int count_digits(number_unsigned_t x) noexcept { unsigned int n_digits = 1; for (;;) { if (x < 10) { return n_digits; } if (x < 100) { return n_digits + 1; } if (x < 1000) { return n_digits + 2; } if (x < 10000) { return n_digits + 3; } x = x / 10000u; n_digits += 4; } } // templates to avoid warnings about useless casts template ::value, int> = 0> bool is_negative_number(NumberType x) { return x < 0; } template < typename NumberType, enable_if_t ::value, int > = 0 > bool is_negative_number(NumberType /*unused*/) { return false; } /*! @brief dump an integer Dump a given integer to output stream @a o. Works internally with @a number_buffer. @param[in] x integer number (signed or unsigned) to dump @tparam NumberType either @a number_integer_t or @a number_unsigned_t */ template < typename NumberType, detail::enable_if_t < std::is_integral::value || std::is_same::value || std::is_same::value || std::is_same::value, int > = 0 > void dump_integer(NumberType x) { static constexpr std::array, 100> digits_to_99 { { {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}}, {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}}, {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}}, {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}}, {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}}, {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}}, {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}}, {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}}, {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}}, {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}}, } }; // special case for "0" if (x == 0) { o->write_character('0'); return; } // use a pointer to fill the buffer auto buffer_ptr = number_buffer.begin(); // NOLINT(llvm-qualified-auto,readability-qualified-auto,cppcoreguidelines-pro-type-vararg,hicpp-vararg) number_unsigned_t abs_value; unsigned int n_chars{}; if (is_negative_number(x)) { *buffer_ptr = '-'; abs_value = remove_sign(static_cast(x)); // account one more byte for the minus sign n_chars = 1 + count_digits(abs_value); } else { abs_value = static_cast(x); n_chars = count_digits(abs_value); } // spare 1 byte for '\0' JSON_ASSERT(n_chars < number_buffer.size() - 1); // jump to the end to generate the string from backward, // so we later avoid reversing the result buffer_ptr += n_chars; // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu // See: https://www.youtube.com/watch?v=o4-CwDo2zpg while (abs_value >= 100) { const auto digits_index = static_cast((abs_value % 100)); abs_value /= 100; *(--buffer_ptr) = digits_to_99[digits_index][1]; *(--buffer_ptr) = digits_to_99[digits_index][0]; } if (abs_value >= 10) { const auto digits_index = static_cast(abs_value); *(--buffer_ptr) = digits_to_99[digits_index][1]; *(--buffer_ptr) = digits_to_99[digits_index][0]; } else { *(--buffer_ptr) = static_cast('0' + abs_value); } o->write_characters(number_buffer.data(), n_chars); } /*! @brief dump a floating-point number Dump a given floating-point number to output stream @a o. Works internally with @a number_buffer. @param[in] x floating-point number to dump */ void dump_float(number_float_t x) { // NaN / inf if (!std::isfinite(x)) { o->write_characters("null", 4); return; } // If number_float_t is an IEEE-754 single or double precision number, // use the Grisu2 algorithm to produce short numbers which are // guaranteed to round-trip, using strtof and strtod, resp. // // NB: The test below works if == . static constexpr bool is_ieee_single_or_double = (std::numeric_limits::is_iec559 && std::numeric_limits::digits == 24 && std::numeric_limits::max_exponent == 128) || (std::numeric_limits::is_iec559 && std::numeric_limits::digits == 53 && std::numeric_limits::max_exponent == 1024); dump_float(x, std::integral_constant()); } void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/) { auto* begin = number_buffer.data(); auto* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x); o->write_characters(begin, static_cast(end - begin)); } void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/) { // get number of digits for a float -> text -> float round-trip static constexpr auto d = std::numeric_limits::max_digits10; // the actual conversion // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x); // negative value indicates an error JSON_ASSERT(len > 0); // check if buffer was large enough JSON_ASSERT(static_cast(len) < number_buffer.size()); // erase thousands separator if (thousands_sep != '\0') { // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::remove returns an iterator, see https://github.com/nlohmann/json/issues/3081 const auto end = std::remove(number_buffer.begin(), number_buffer.begin() + len, thousands_sep); std::fill(end, number_buffer.end(), '\0'); JSON_ASSERT((end - number_buffer.begin()) <= len); len = (end - number_buffer.begin()); } // convert decimal point to '.' if (decimal_point != '\0' && decimal_point != '.') { // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::find returns an iterator, see https://github.com/nlohmann/json/issues/3081 const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point); if (dec_pos != number_buffer.end()) { *dec_pos = '.'; } } o->write_characters(number_buffer.data(), static_cast(len)); // determine if we need to append ".0" const bool value_is_int_like = std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1, [](char c) { return c == '.' || c == 'e'; }); if (value_is_int_like) { o->write_characters(".0", 2); } } /*! @brief check whether a string is UTF-8 encoded The function checks each byte of a string whether it is UTF-8 encoded. The result of the check is stored in the @a state parameter. The function must be called initially with state 0 (accept). State 1 means the string must be rejected, because the current byte is not allowed. If the string is completely processed, but the state is non-zero, the string ended prematurely; that is, the last byte indicated more bytes should have followed. @param[in,out] state the state of the decoding @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT) @param[in] byte next byte to decode @return new state @note The function has been edited: a std::array is used. @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ */ static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept { static const std::array utf8d = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40..5F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60..7F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9F 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // A0..BF 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C0..DF 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // s7..s8 } }; JSON_ASSERT(byte < utf8d.size()); const std::uint8_t type = utf8d[byte]; codep = (state != UTF8_ACCEPT) ? (byte & 0x3fu) | (codep << 6u) : (0xFFu >> type) & (byte); std::size_t index = 256u + static_cast(state) * 16u + static_cast(type); JSON_ASSERT(index < 400); state = utf8d[index]; return state; } /* * Overload to make the compiler happy while it is instantiating * dump_integer for number_unsigned_t. * Must never be called. */ number_unsigned_t remove_sign(number_unsigned_t x) { JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE return x; // LCOV_EXCL_LINE } /* * Helper function for dump_integer * * This function takes a negative signed integer and returns its absolute * value as unsigned integer. The plus/minus shuffling is necessary as we can * not directly remove the sign of an arbitrary signed integer as the * absolute values of INT_MIN and INT_MAX are usually not the same. See * #1708 for details. */ inline number_unsigned_t remove_sign(number_integer_t x) noexcept { JSON_ASSERT(x < 0 && x < (std::numeric_limits::max)()); // NOLINT(misc-redundant-expression) return static_cast(-(x + 1)) + 1; } private: /// the output of the serializer output_adapter_t o = nullptr; /// a (hopefully) large enough character buffer std::array number_buffer{{}}; /// the locale const std::lconv* loc = nullptr; /// the locale's thousand separator character const char thousands_sep = '\0'; /// the locale's decimal point character const char decimal_point = '\0'; /// string buffer std::array string_buffer{{}}; /// the indentation character const char indent_char; /// the indentation string string_t indent_string; /// error_handler how to react on decoding errors const error_handler_t error_handler; }; } // namespace detail } // namespace nlohmann // #include // #include // #include #include // less #include // initializer_list #include // input_iterator_tag, iterator_traits #include // allocator #include // for out_of_range #include // enable_if, is_convertible #include // pair #include // vector // #include namespace nlohmann { /// ordered_map: a minimal map-like container that preserves insertion order /// for use within nlohmann::basic_json template , class Allocator = std::allocator>> struct ordered_map : std::vector, Allocator> { using key_type = Key; using mapped_type = T; using Container = std::vector, Allocator>; using iterator = typename Container::iterator; using const_iterator = typename Container::const_iterator; using size_type = typename Container::size_type; using value_type = typename Container::value_type; // Explicit constructors instead of `using Container::Container` // otherwise older compilers choke on it (GCC <= 5.5, xcode <= 9.4) ordered_map(const Allocator& alloc = Allocator()) : Container{alloc} {} template ordered_map(It first, It last, const Allocator& alloc = Allocator()) : Container{first, last, alloc} {} ordered_map(std::initializer_list init, const Allocator& alloc = Allocator() ) : Container{init, alloc} {} std::pair emplace(const key_type& key, T&& t) { for (auto it = this->begin(); it != this->end(); ++it) { if (it->first == key) { return {it, false}; } } Container::emplace_back(key, t); return {--this->end(), true}; } T& operator[](const Key& key) { return emplace(key, T{}).first->second; } const T& operator[](const Key& key) const { return at(key); } T& at(const Key& key) { for (auto it = this->begin(); it != this->end(); ++it) { if (it->first == key) { return it->second; } } JSON_THROW(std::out_of_range("key not found")); } const T& at(const Key& key) const { for (auto it = this->begin(); it != this->end(); ++it) { if (it->first == key) { return it->second; } } JSON_THROW(std::out_of_range("key not found")); } size_type erase(const Key& key) { for (auto it = this->begin(); it != this->end(); ++it) { if (it->first == key) { // Since we cannot move const Keys, re-construct them in place for (auto next = it; ++next != this->end(); ++it) { it->~value_type(); // Destroy but keep allocation new (&*it) value_type{std::move(*next)}; } Container::pop_back(); return 1; } } return 0; } iterator erase(iterator pos) { return erase(pos, std::next(pos)); } iterator erase(iterator first, iterator last) { const auto elements_affected = std::distance(first, last); const auto offset = std::distance(Container::begin(), first); // This is the start situation. We need to delete elements_affected // elements (3 in this example: e, f, g), and need to return an // iterator past the last deleted element (h in this example). // Note that offset is the distance from the start of the vector // to first. We will need this later. // [ a, b, c, d, e, f, g, h, i, j ] // ^ ^ // first last // Since we cannot move const Keys, we re-construct them in place. // We start at first and re-construct (viz. copy) the elements from // the back of the vector. Example for first iteration: // ,--------. // v | destroy e and re-construct with h // [ a, b, c, d, e, f, g, h, i, j ] // ^ ^ // it it + elements_affected for (auto it = first; std::next(it, elements_affected) != Container::end(); ++it) { it->~value_type(); // destroy but keep allocation new (&*it) value_type{std::move(*std::next(it, elements_affected))}; // "move" next element to it } // [ a, b, c, d, h, i, j, h, i, j ] // ^ ^ // first last // remove the unneeded elements at the end of the vector Container::resize(this->size() - static_cast(elements_affected)); // [ a, b, c, d, h, i, j ] // ^ ^ // first last // first is now pointing past the last deleted element, but we cannot // use this iterator, because it may have been invalidated by the // resize call. Instead, we can return begin() + offset. return Container::begin() + offset; } size_type count(const Key& key) const { for (auto it = this->begin(); it != this->end(); ++it) { if (it->first == key) { return 1; } } return 0; } iterator find(const Key& key) { for (auto it = this->begin(); it != this->end(); ++it) { if (it->first == key) { return it; } } return Container::end(); } const_iterator find(const Key& key) const { for (auto it = this->begin(); it != this->end(); ++it) { if (it->first == key) { return it; } } return Container::end(); } std::pair insert( value_type&& value ) { return emplace(value.first, std::move(value.second)); } std::pair insert( const value_type& value ) { for (auto it = this->begin(); it != this->end(); ++it) { if (it->first == value.first) { return {it, false}; } } Container::push_back(value); return {--this->end(), true}; } template using require_input_iter = typename std::enable_if::iterator_category, std::input_iterator_tag>::value>::type; template> void insert(InputIt first, InputIt last) { for (auto it = first; it != last; ++it) { insert(*it); } } }; } // namespace nlohmann #if defined(JSON_HAS_CPP_17) #include #endif /*! @brief namespace for Niels Lohmann @see https://github.com/nlohmann @since version 1.0.0 */ namespace nlohmann { /*! @brief a class to store JSON values @internal @invariant The member variables @a m_value and @a m_type have the following relationship: - If `m_type == value_t::object`, then `m_value.object != nullptr`. - If `m_type == value_t::array`, then `m_value.array != nullptr`. - If `m_type == value_t::string`, then `m_value.string != nullptr`. The invariants are checked by member function assert_invariant(). @note ObjectType trick from https://stackoverflow.com/a/9860911 @endinternal @since version 1.0.0 @nosubgrouping */ NLOHMANN_BASIC_JSON_TPL_DECLARATION class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions) { private: template friend struct detail::external_constructor; friend ::nlohmann::json_pointer; template friend class ::nlohmann::detail::parser; friend ::nlohmann::detail::serializer; template friend class ::nlohmann::detail::iter_impl; template friend class ::nlohmann::detail::binary_writer; template friend class ::nlohmann::detail::binary_reader; template friend class ::nlohmann::detail::json_sax_dom_parser; template friend class ::nlohmann::detail::json_sax_dom_callback_parser; friend class ::nlohmann::detail::exception; /// workaround type for MSVC using basic_json_t = NLOHMANN_BASIC_JSON_TPL; JSON_PRIVATE_UNLESS_TESTED: // convenience aliases for types residing in namespace detail; using lexer = ::nlohmann::detail::lexer_base; template static ::nlohmann::detail::parser parser( InputAdapterType adapter, detail::parser_callback_tcb = nullptr, const bool allow_exceptions = true, const bool ignore_comments = false ) { return ::nlohmann::detail::parser(std::move(adapter), std::move(cb), allow_exceptions, ignore_comments); } private: using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t; template using internal_iterator = ::nlohmann::detail::internal_iterator; template using iter_impl = ::nlohmann::detail::iter_impl; template using iteration_proxy = ::nlohmann::detail::iteration_proxy; template using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator; template using output_adapter_t = ::nlohmann::detail::output_adapter_t; template using binary_reader = ::nlohmann::detail::binary_reader; template using binary_writer = ::nlohmann::detail::binary_writer; JSON_PRIVATE_UNLESS_TESTED: using serializer = ::nlohmann::detail::serializer; public: using value_t = detail::value_t; /// JSON Pointer, see @ref nlohmann::json_pointer using json_pointer = ::nlohmann::json_pointer; template using json_serializer = JSONSerializer; /// how to treat decoding errors using error_handler_t = detail::error_handler_t; /// how to treat CBOR tags using cbor_tag_handler_t = detail::cbor_tag_handler_t; /// helper type for initializer lists of basic_json values using initializer_list_t = std::initializer_list>; using input_format_t = detail::input_format_t; /// SAX interface type, see @ref nlohmann::json_sax using json_sax_t = json_sax; //////////////// // exceptions // //////////////// /// @name exceptions /// Classes to implement user-defined exceptions. /// @{ using exception = detail::exception; using parse_error = detail::parse_error; using invalid_iterator = detail::invalid_iterator; using type_error = detail::type_error; using out_of_range = detail::out_of_range; using other_error = detail::other_error; /// @} ///////////////////// // container types // ///////////////////// /// @name container types /// The canonic container types to use @ref basic_json like any other STL /// container. /// @{ /// the type of elements in a basic_json container using value_type = basic_json; /// the type of an element reference using reference = value_type&; /// the type of an element const reference using const_reference = const value_type&; /// a type to represent differences between iterators using difference_type = std::ptrdiff_t; /// a type to represent container sizes using size_type = std::size_t; /// the allocator type using allocator_type = AllocatorType; /// the type of an element pointer using pointer = typename std::allocator_traits::pointer; /// the type of an element const pointer using const_pointer = typename std::allocator_traits::const_pointer; /// an iterator for a basic_json container using iterator = iter_impl; /// a const iterator for a basic_json container using const_iterator = iter_impl; /// a reverse iterator for a basic_json container using reverse_iterator = json_reverse_iterator; /// a const reverse iterator for a basic_json container using const_reverse_iterator = json_reverse_iterator; /// @} /// @brief returns the allocator associated with the container /// @sa https://json.nlohmann.me/api/basic_json/get_allocator/ static allocator_type get_allocator() { return allocator_type(); } /// @brief returns version information on the library /// @sa https://json.nlohmann.me/api/basic_json/meta/ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json meta() { basic_json result; result["copyright"] = "(C) 2013-2022 Niels Lohmann"; result["name"] = "JSON for Modern C++"; result["url"] = "https://github.com/nlohmann/json"; result["version"]["string"] = std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." + std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." + std::to_string(NLOHMANN_JSON_VERSION_PATCH); result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR; result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR; result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH; #ifdef _WIN32 result["platform"] = "win32"; #elif defined __linux__ result["platform"] = "linux"; #elif defined __APPLE__ result["platform"] = "apple"; #elif defined __unix__ result["platform"] = "unix"; #else result["platform"] = "unknown"; #endif #if defined(__ICC) || defined(__INTEL_COMPILER) result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}}; #elif defined(__clang__) result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}}; #elif defined(__GNUC__) || defined(__GNUG__) result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}}; #elif defined(__HP_cc) || defined(__HP_aCC) result["compiler"] = "hp" #elif defined(__IBMCPP__) result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}}; #elif defined(_MSC_VER) result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}}; #elif defined(__PGI) result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}}; #elif defined(__SUNPRO_CC) result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}}; #else result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}}; #endif #ifdef __cplusplus result["compiler"]["c++"] = std::to_string(__cplusplus); #else result["compiler"]["c++"] = "unknown"; #endif return result; } /////////////////////////// // JSON value data types // /////////////////////////// /// @name JSON value data types /// The data types to store a JSON value. These types are derived from /// the template arguments passed to class @ref basic_json. /// @{ /// @brief object key comparator type /// @sa https://json.nlohmann.me/api/basic_json/object_comparator_t/ #if defined(JSON_HAS_CPP_14) // Use transparent comparator if possible, combined with perfect forwarding // on find() and count() calls prevents unnecessary string construction. using object_comparator_t = std::less<>; #else using object_comparator_t = std::less; #endif /// @brief a type for an object /// @sa https://json.nlohmann.me/api/basic_json/object_t/ using object_t = ObjectType>>; /// @brief a type for an array /// @sa https://json.nlohmann.me/api/basic_json/array_t/ using array_t = ArrayType>; /// @brief a type for a string /// @sa https://json.nlohmann.me/api/basic_json/string_t/ using string_t = StringType; /// @brief a type for a boolean /// @sa https://json.nlohmann.me/api/basic_json/boolean_t/ using boolean_t = BooleanType; /// @brief a type for a number (integer) /// @sa https://json.nlohmann.me/api/basic_json/number_integer_t/ using number_integer_t = NumberIntegerType; /// @brief a type for a number (unsigned) /// @sa https://json.nlohmann.me/api/basic_json/number_unsigned_t/ using number_unsigned_t = NumberUnsignedType; /// @brief a type for a number (floating-point) /// @sa https://json.nlohmann.me/api/basic_json/number_float_t/ using number_float_t = NumberFloatType; /// @brief a type for a packed binary type /// @sa https://json.nlohmann.me/api/basic_json/binary_t/ using binary_t = nlohmann::byte_container_with_subtype; /// @} private: /// helper for exception-safe object creation template JSON_HEDLEY_RETURNS_NON_NULL static T* create(Args&& ... args) { AllocatorType alloc; using AllocatorTraits = std::allocator_traits>; auto deleter = [&](T * obj) { AllocatorTraits::deallocate(alloc, obj, 1); }; std::unique_ptr obj(AllocatorTraits::allocate(alloc, 1), deleter); AllocatorTraits::construct(alloc, obj.get(), std::forward(args)...); JSON_ASSERT(obj != nullptr); return obj.release(); } //////////////////////// // JSON value storage // //////////////////////// JSON_PRIVATE_UNLESS_TESTED: /*! @brief a JSON value The actual storage for a JSON value of the @ref basic_json class. This union combines the different storage types for the JSON value types defined in @ref value_t. JSON type | value_t type | used type --------- | --------------- | ------------------------ object | object | pointer to @ref object_t array | array | pointer to @ref array_t string | string | pointer to @ref string_t boolean | boolean | @ref boolean_t number | number_integer | @ref number_integer_t number | number_unsigned | @ref number_unsigned_t number | number_float | @ref number_float_t binary | binary | pointer to @ref binary_t null | null | *no value is stored* @note Variable-length types (objects, arrays, and strings) are stored as pointers. The size of the union should not exceed 64 bits if the default value types are used. @since version 1.0.0 */ union json_value { /// object (stored with pointer to save storage) object_t* object; /// array (stored with pointer to save storage) array_t* array; /// string (stored with pointer to save storage) string_t* string; /// binary (stored with pointer to save storage) binary_t* binary; /// boolean boolean_t boolean; /// number (integer) number_integer_t number_integer; /// number (unsigned integer) number_unsigned_t number_unsigned; /// number (floating-point) number_float_t number_float; /// default constructor (for null values) json_value() = default; /// constructor for booleans json_value(boolean_t v) noexcept : boolean(v) {} /// constructor for numbers (integer) json_value(number_integer_t v) noexcept : number_integer(v) {} /// constructor for numbers (unsigned) json_value(number_unsigned_t v) noexcept : number_unsigned(v) {} /// constructor for numbers (floating-point) json_value(number_float_t v) noexcept : number_float(v) {} /// constructor for empty values of a given type json_value(value_t t) { switch (t) { case value_t::object: { object = create(); break; } case value_t::array: { array = create(); break; } case value_t::string: { string = create(""); break; } case value_t::binary: { binary = create(); break; } case value_t::boolean: { boolean = static_cast(false); break; } case value_t::number_integer: { number_integer = static_cast(0); break; } case value_t::number_unsigned: { number_unsigned = static_cast(0); break; } case value_t::number_float: { number_float = static_cast(0.0); break; } case value_t::null: { object = nullptr; // silence warning, see #821 break; } case value_t::discarded: default: { object = nullptr; // silence warning, see #821 if (JSON_HEDLEY_UNLIKELY(t == value_t::null)) { JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.10.5", basic_json())); // LCOV_EXCL_LINE } break; } } } /// constructor for strings json_value(const string_t& value) : string(create(value)) {} /// constructor for rvalue strings json_value(string_t&& value) : string(create(std::move(value))) {} /// constructor for objects json_value(const object_t& value) : object(create(value)) {} /// constructor for rvalue objects json_value(object_t&& value) : object(create(std::move(value))) {} /// constructor for arrays json_value(const array_t& value) : array(create(value)) {} /// constructor for rvalue arrays json_value(array_t&& value) : array(create(std::move(value))) {} /// constructor for binary arrays json_value(const typename binary_t::container_type& value) : binary(create(value)) {} /// constructor for rvalue binary arrays json_value(typename binary_t::container_type&& value) : binary(create(std::move(value))) {} /// constructor for binary arrays (internal type) json_value(const binary_t& value) : binary(create(value)) {} /// constructor for rvalue binary arrays (internal type) json_value(binary_t&& value) : binary(create(std::move(value))) {} void destroy(value_t t) { if (t == value_t::array || t == value_t::object) { // flatten the current json_value to a heap-allocated stack std::vector stack; // move the top-level items to stack if (t == value_t::array) { stack.reserve(array->size()); std::move(array->begin(), array->end(), std::back_inserter(stack)); } else { stack.reserve(object->size()); for (auto&& it : *object) { stack.push_back(std::move(it.second)); } } while (!stack.empty()) { // move the last item to local variable to be processed basic_json current_item(std::move(stack.back())); stack.pop_back(); // if current_item is array/object, move // its children to the stack to be processed later if (current_item.is_array()) { std::move(current_item.m_value.array->begin(), current_item.m_value.array->end(), std::back_inserter(stack)); current_item.m_value.array->clear(); } else if (current_item.is_object()) { for (auto&& it : *current_item.m_value.object) { stack.push_back(std::move(it.second)); } current_item.m_value.object->clear(); } // it's now safe that current_item get destructed // since it doesn't have any children } } switch (t) { case value_t::object: { AllocatorType alloc; std::allocator_traits::destroy(alloc, object); std::allocator_traits::deallocate(alloc, object, 1); break; } case value_t::array: { AllocatorType alloc; std::allocator_traits::destroy(alloc, array); std::allocator_traits::deallocate(alloc, array, 1); break; } case value_t::string: { AllocatorType alloc; std::allocator_traits::destroy(alloc, string); std::allocator_traits::deallocate(alloc, string, 1); break; } case value_t::binary: { AllocatorType alloc; std::allocator_traits::destroy(alloc, binary); std::allocator_traits::deallocate(alloc, binary, 1); break; } case value_t::null: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::discarded: default: { break; } } } }; private: /*! @brief checks the class invariants This function asserts the class invariants. It needs to be called at the end of every constructor to make sure that created objects respect the invariant. Furthermore, it has to be called each time the type of a JSON value is changed, because the invariant expresses a relationship between @a m_type and @a m_value. Furthermore, the parent relation is checked for arrays and objects: If @a check_parents true and the value is an array or object, then the container's elements must have the current value as parent. @param[in] check_parents whether the parent relation should be checked. The value is true by default and should only be set to false during destruction of objects when the invariant does not need to hold. */ void assert_invariant(bool check_parents = true) const noexcept { JSON_ASSERT(m_type != value_t::object || m_value.object != nullptr); JSON_ASSERT(m_type != value_t::array || m_value.array != nullptr); JSON_ASSERT(m_type != value_t::string || m_value.string != nullptr); JSON_ASSERT(m_type != value_t::binary || m_value.binary != nullptr); #if JSON_DIAGNOSTICS JSON_TRY { // cppcheck-suppress assertWithSideEffect JSON_ASSERT(!check_parents || !is_structured() || std::all_of(begin(), end(), [this](const basic_json & j) { return j.m_parent == this; })); } JSON_CATCH(...) {} // LCOV_EXCL_LINE #endif static_cast(check_parents); } void set_parents() { #if JSON_DIAGNOSTICS switch (m_type) { case value_t::array: { for (auto& element : *m_value.array) { element.m_parent = this; } break; } case value_t::object: { for (auto& element : *m_value.object) { element.second.m_parent = this; } break; } case value_t::null: case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: break; } #endif } iterator set_parents(iterator it, typename iterator::difference_type count_set_parents) { #if JSON_DIAGNOSTICS for (typename iterator::difference_type i = 0; i < count_set_parents; ++i) { (it + i)->m_parent = this; } #else static_cast(count_set_parents); #endif return it; } reference set_parent(reference j, std::size_t old_capacity = static_cast(-1)) { #if JSON_DIAGNOSTICS if (old_capacity != static_cast(-1)) { // see https://github.com/nlohmann/json/issues/2838 JSON_ASSERT(type() == value_t::array); if (JSON_HEDLEY_UNLIKELY(m_value.array->capacity() != old_capacity)) { // capacity has changed: update all parents set_parents(); return j; } } // ordered_json uses a vector internally, so pointers could have // been invalidated; see https://github.com/nlohmann/json/issues/2962 #ifdef JSON_HEDLEY_MSVC_VERSION #pragma warning(push ) #pragma warning(disable : 4127) // ignore warning to replace if with if constexpr #endif if (detail::is_ordered_map::value) { set_parents(); return j; } #ifdef JSON_HEDLEY_MSVC_VERSION #pragma warning( pop ) #endif j.m_parent = this; #else static_cast(j); static_cast(old_capacity); #endif return j; } public: ////////////////////////// // JSON parser callback // ////////////////////////// /// @brief parser event types /// @sa https://json.nlohmann.me/api/basic_json/parse_event_t/ using parse_event_t = detail::parse_event_t; /// @brief per-element parser callback type /// @sa https://json.nlohmann.me/api/basic_json/parser_callback_t/ using parser_callback_t = detail::parser_callback_t; ////////////////// // constructors // ////////////////// /// @name constructors and destructors /// Constructors of class @ref basic_json, copy/move constructor, copy /// assignment, static functions creating objects, and the destructor. /// @{ /// @brief create an empty value with a given type /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ basic_json(const value_t v) : m_type(v), m_value(v) { assert_invariant(); } /// @brief create a null object /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ basic_json(std::nullptr_t = nullptr) noexcept : basic_json(value_t::null) { assert_invariant(); } /// @brief create a JSON value from compatible types /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ template < typename CompatibleType, typename U = detail::uncvref_t, detail::enable_if_t < !detail::is_basic_json::value && detail::is_compatible_type::value, int > = 0 > basic_json(CompatibleType && val) noexcept(noexcept( // NOLINT(bugprone-forwarding-reference-overload,bugprone-exception-escape) JSONSerializer::to_json(std::declval(), std::forward(val)))) { JSONSerializer::to_json(*this, std::forward(val)); set_parents(); assert_invariant(); } /// @brief create a JSON value from an existing one /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ template < typename BasicJsonType, detail::enable_if_t < detail::is_basic_json::value&& !std::is_same::value, int > = 0 > basic_json(const BasicJsonType& val) { using other_boolean_t = typename BasicJsonType::boolean_t; using other_number_float_t = typename BasicJsonType::number_float_t; using other_number_integer_t = typename BasicJsonType::number_integer_t; using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t; using other_string_t = typename BasicJsonType::string_t; using other_object_t = typename BasicJsonType::object_t; using other_array_t = typename BasicJsonType::array_t; using other_binary_t = typename BasicJsonType::binary_t; switch (val.type()) { case value_t::boolean: JSONSerializer::to_json(*this, val.template get()); break; case value_t::number_float: JSONSerializer::to_json(*this, val.template get()); break; case value_t::number_integer: JSONSerializer::to_json(*this, val.template get()); break; case value_t::number_unsigned: JSONSerializer::to_json(*this, val.template get()); break; case value_t::string: JSONSerializer::to_json(*this, val.template get_ref()); break; case value_t::object: JSONSerializer::to_json(*this, val.template get_ref()); break; case value_t::array: JSONSerializer::to_json(*this, val.template get_ref()); break; case value_t::binary: JSONSerializer::to_json(*this, val.template get_ref()); break; case value_t::null: *this = nullptr; break; case value_t::discarded: m_type = value_t::discarded; break; default: // LCOV_EXCL_LINE JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE } set_parents(); assert_invariant(); } /// @brief create a container (array or object) from an initializer list /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ basic_json(initializer_list_t init, bool type_deduction = true, value_t manual_type = value_t::array) { // check if each element is an array with two elements whose first // element is a string bool is_an_object = std::all_of(init.begin(), init.end(), [](const detail::json_ref& element_ref) { return element_ref->is_array() && element_ref->size() == 2 && (*element_ref)[0].is_string(); }); // adjust type if type deduction is not wanted if (!type_deduction) { // if array is wanted, do not create an object though possible if (manual_type == value_t::array) { is_an_object = false; } // if object is wanted but impossible, throw an exception if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object && !is_an_object)) { JSON_THROW(type_error::create(301, "cannot create object from initializer list", basic_json())); } } if (is_an_object) { // the initializer list is a list of pairs -> create object m_type = value_t::object; m_value = value_t::object; for (auto& element_ref : init) { auto element = element_ref.moved_or_copied(); m_value.object->emplace( std::move(*((*element.m_value.array)[0].m_value.string)), std::move((*element.m_value.array)[1])); } } else { // the initializer list describes an array -> create array m_type = value_t::array; m_value.array = create(init.begin(), init.end()); } set_parents(); assert_invariant(); } /// @brief explicitly create a binary array (without subtype) /// @sa https://json.nlohmann.me/api/basic_json/binary/ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json binary(const typename binary_t::container_type& init) { auto res = basic_json(); res.m_type = value_t::binary; res.m_value = init; return res; } /// @brief explicitly create a binary array (with subtype) /// @sa https://json.nlohmann.me/api/basic_json/binary/ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json binary(const typename binary_t::container_type& init, typename binary_t::subtype_type subtype) { auto res = basic_json(); res.m_type = value_t::binary; res.m_value = binary_t(init, subtype); return res; } /// @brief explicitly create a binary array /// @sa https://json.nlohmann.me/api/basic_json/binary/ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json binary(typename binary_t::container_type&& init) { auto res = basic_json(); res.m_type = value_t::binary; res.m_value = std::move(init); return res; } /// @brief explicitly create a binary array (with subtype) /// @sa https://json.nlohmann.me/api/basic_json/binary/ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json binary(typename binary_t::container_type&& init, typename binary_t::subtype_type subtype) { auto res = basic_json(); res.m_type = value_t::binary; res.m_value = binary_t(std::move(init), subtype); return res; } /// @brief explicitly create an array from an initializer list /// @sa https://json.nlohmann.me/api/basic_json/array/ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json array(initializer_list_t init = {}) { return basic_json(init, false, value_t::array); } /// @brief explicitly create an object from an initializer list /// @sa https://json.nlohmann.me/api/basic_json/object/ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json object(initializer_list_t init = {}) { return basic_json(init, false, value_t::object); } /// @brief construct an array with count copies of given value /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ basic_json(size_type cnt, const basic_json& val) : m_type(value_t::array) { m_value.array = create(cnt, val); set_parents(); assert_invariant(); } /// @brief construct a JSON container given an iterator range /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ template < class InputIT, typename std::enable_if < std::is_same::value || std::is_same::value, int >::type = 0 > basic_json(InputIT first, InputIT last) { JSON_ASSERT(first.m_object != nullptr); JSON_ASSERT(last.m_object != nullptr); // make sure iterator fits the current value if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) { JSON_THROW(invalid_iterator::create(201, "iterators are not compatible", basic_json())); } // copy type from first iterator m_type = first.m_object->m_type; // check if iterator range is complete for primitive values switch (m_type) { case value_t::boolean: case value_t::number_float: case value_t::number_integer: case value_t::number_unsigned: case value_t::string: { if (JSON_HEDLEY_UNLIKELY(!first.m_it.primitive_iterator.is_begin() || !last.m_it.primitive_iterator.is_end())) { JSON_THROW(invalid_iterator::create(204, "iterators out of range", *first.m_object)); } break; } case value_t::null: case value_t::object: case value_t::array: case value_t::binary: case value_t::discarded: default: break; } switch (m_type) { case value_t::number_integer: { m_value.number_integer = first.m_object->m_value.number_integer; break; } case value_t::number_unsigned: { m_value.number_unsigned = first.m_object->m_value.number_unsigned; break; } case value_t::number_float: { m_value.number_float = first.m_object->m_value.number_float; break; } case value_t::boolean: { m_value.boolean = first.m_object->m_value.boolean; break; } case value_t::string: { m_value = *first.m_object->m_value.string; break; } case value_t::object: { m_value.object = create(first.m_it.object_iterator, last.m_it.object_iterator); break; } case value_t::array: { m_value.array = create(first.m_it.array_iterator, last.m_it.array_iterator); break; } case value_t::binary: { m_value = *first.m_object->m_value.binary; break; } case value_t::null: case value_t::discarded: default: JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " + std::string(first.m_object->type_name()), *first.m_object)); } set_parents(); assert_invariant(); } /////////////////////////////////////// // other constructors and destructor // /////////////////////////////////////// template, std::is_same>::value, int> = 0 > basic_json(const JsonRef& ref) : basic_json(ref.moved_or_copied()) {} /// @brief copy constructor /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ basic_json(const basic_json& other) : m_type(other.m_type) { // check of passed value is valid other.assert_invariant(); switch (m_type) { case value_t::object: { m_value = *other.m_value.object; break; } case value_t::array: { m_value = *other.m_value.array; break; } case value_t::string: { m_value = *other.m_value.string; break; } case value_t::boolean: { m_value = other.m_value.boolean; break; } case value_t::number_integer: { m_value = other.m_value.number_integer; break; } case value_t::number_unsigned: { m_value = other.m_value.number_unsigned; break; } case value_t::number_float: { m_value = other.m_value.number_float; break; } case value_t::binary: { m_value = *other.m_value.binary; break; } case value_t::null: case value_t::discarded: default: break; } set_parents(); assert_invariant(); } /// @brief move constructor /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ basic_json(basic_json&& other) noexcept : m_type(std::move(other.m_type)), m_value(std::move(other.m_value)) { // check that passed value is valid other.assert_invariant(false); // invalidate payload other.m_type = value_t::null; other.m_value = {}; set_parents(); assert_invariant(); } /// @brief copy assignment /// @sa https://json.nlohmann.me/api/basic_json/operator=/ basic_json& operator=(basic_json other) noexcept ( std::is_nothrow_move_constructible::value&& std::is_nothrow_move_assignable::value&& std::is_nothrow_move_constructible::value&& std::is_nothrow_move_assignable::value ) { // check that passed value is valid other.assert_invariant(); using std::swap; swap(m_type, other.m_type); swap(m_value, other.m_value); set_parents(); assert_invariant(); return *this; } /// @brief destructor /// @sa https://json.nlohmann.me/api/basic_json/~basic_json/ ~basic_json() noexcept { assert_invariant(false); m_value.destroy(m_type); } /// @} public: /////////////////////// // object inspection // /////////////////////// /// @name object inspection /// Functions to inspect the type of a JSON value. /// @{ /// @brief serialization /// @sa https://json.nlohmann.me/api/basic_json/dump/ string_t dump(const int indent = -1, const char indent_char = ' ', const bool ensure_ascii = false, const error_handler_t error_handler = error_handler_t::strict) const { string_t result; serializer s(detail::output_adapter(result), indent_char, error_handler); if (indent >= 0) { s.dump(*this, true, ensure_ascii, static_cast(indent)); } else { s.dump(*this, false, ensure_ascii, 0); } return result; } /// @brief return the type of the JSON value (explicit) /// @sa https://json.nlohmann.me/api/basic_json/type/ constexpr value_t type() const noexcept { return m_type; } /// @brief return whether type is primitive /// @sa https://json.nlohmann.me/api/basic_json/is_primitive/ constexpr bool is_primitive() const noexcept { return is_null() || is_string() || is_boolean() || is_number() || is_binary(); } /// @brief return whether type is structured /// @sa https://json.nlohmann.me/api/basic_json/is_structured/ constexpr bool is_structured() const noexcept { return is_array() || is_object(); } /// @brief return whether value is null /// @sa https://json.nlohmann.me/api/basic_json/is_null/ constexpr bool is_null() const noexcept { return m_type == value_t::null; } /// @brief return whether value is a boolean /// @sa https://json.nlohmann.me/api/basic_json/is_boolean/ constexpr bool is_boolean() const noexcept { return m_type == value_t::boolean; } /// @brief return whether value is a number /// @sa https://json.nlohmann.me/api/basic_json/is_number/ constexpr bool is_number() const noexcept { return is_number_integer() || is_number_float(); } /// @brief return whether value is an integer number /// @sa https://json.nlohmann.me/api/basic_json/is_number_integer/ constexpr bool is_number_integer() const noexcept { return m_type == value_t::number_integer || m_type == value_t::number_unsigned; } /// @brief return whether value is an unsigned integer number /// @sa https://json.nlohmann.me/api/basic_json/is_number_unsigned/ constexpr bool is_number_unsigned() const noexcept { return m_type == value_t::number_unsigned; } /// @brief return whether value is a floating-point number /// @sa https://json.nlohmann.me/api/basic_json/is_number_float/ constexpr bool is_number_float() const noexcept { return m_type == value_t::number_float; } /// @brief return whether value is an object /// @sa https://json.nlohmann.me/api/basic_json/is_object/ constexpr bool is_object() const noexcept { return m_type == value_t::object; } /// @brief return whether value is an array /// @sa https://json.nlohmann.me/api/basic_json/is_array/ constexpr bool is_array() const noexcept { return m_type == value_t::array; } /// @brief return whether value is a string /// @sa https://json.nlohmann.me/api/basic_json/is_string/ constexpr bool is_string() const noexcept { return m_type == value_t::string; } /// @brief return whether value is a binary array /// @sa https://json.nlohmann.me/api/basic_json/is_binary/ constexpr bool is_binary() const noexcept { return m_type == value_t::binary; } /// @brief return whether value is discarded /// @sa https://json.nlohmann.me/api/basic_json/is_discarded/ constexpr bool is_discarded() const noexcept { return m_type == value_t::discarded; } /// @brief return the type of the JSON value (implicit) /// @sa https://json.nlohmann.me/api/basic_json/operator_value_t/ constexpr operator value_t() const noexcept { return m_type; } /// @} private: ////////////////// // value access // ////////////////// /// get a boolean (explicit) boolean_t get_impl(boolean_t* /*unused*/) const { if (JSON_HEDLEY_LIKELY(is_boolean())) { return m_value.boolean; } JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name()), *this)); } /// get a pointer to the value (object) object_t* get_impl_ptr(object_t* /*unused*/) noexcept { return is_object() ? m_value.object : nullptr; } /// get a pointer to the value (object) constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept { return is_object() ? m_value.object : nullptr; } /// get a pointer to the value (array) array_t* get_impl_ptr(array_t* /*unused*/) noexcept { return is_array() ? m_value.array : nullptr; } /// get a pointer to the value (array) constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept { return is_array() ? m_value.array : nullptr; } /// get a pointer to the value (string) string_t* get_impl_ptr(string_t* /*unused*/) noexcept { return is_string() ? m_value.string : nullptr; } /// get a pointer to the value (string) constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept { return is_string() ? m_value.string : nullptr; } /// get a pointer to the value (boolean) boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept { return is_boolean() ? &m_value.boolean : nullptr; } /// get a pointer to the value (boolean) constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept { return is_boolean() ? &m_value.boolean : nullptr; } /// get a pointer to the value (integer number) number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept { return is_number_integer() ? &m_value.number_integer : nullptr; } /// get a pointer to the value (integer number) constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept { return is_number_integer() ? &m_value.number_integer : nullptr; } /// get a pointer to the value (unsigned number) number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept { return is_number_unsigned() ? &m_value.number_unsigned : nullptr; } /// get a pointer to the value (unsigned number) constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept { return is_number_unsigned() ? &m_value.number_unsigned : nullptr; } /// get a pointer to the value (floating-point number) number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept { return is_number_float() ? &m_value.number_float : nullptr; } /// get a pointer to the value (floating-point number) constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept { return is_number_float() ? &m_value.number_float : nullptr; } /// get a pointer to the value (binary) binary_t* get_impl_ptr(binary_t* /*unused*/) noexcept { return is_binary() ? m_value.binary : nullptr; } /// get a pointer to the value (binary) constexpr const binary_t* get_impl_ptr(const binary_t* /*unused*/) const noexcept { return is_binary() ? m_value.binary : nullptr; } /*! @brief helper function to implement get_ref() This function helps to implement get_ref() without code duplication for const and non-const overloads @tparam ThisType will be deduced as `basic_json` or `const basic_json` @throw type_error.303 if ReferenceType does not match underlying value type of the current JSON */ template static ReferenceType get_ref_impl(ThisType& obj) { // delegate the call to get_ptr<>() auto* ptr = obj.template get_ptr::type>(); if (JSON_HEDLEY_LIKELY(ptr != nullptr)) { return *ptr; } JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name()), obj)); } public: /// @name value access /// Direct access to the stored value of a JSON value. /// @{ /// @brief get a pointer value (implicit) /// @sa https://json.nlohmann.me/api/basic_json/get_ptr/ template::value, int>::type = 0> auto get_ptr() noexcept -> decltype(std::declval().get_impl_ptr(std::declval())) { // delegate the call to get_impl_ptr<>() return get_impl_ptr(static_cast(nullptr)); } /// @brief get a pointer value (implicit) /// @sa https://json.nlohmann.me/api/basic_json/get_ptr/ template < typename PointerType, typename std::enable_if < std::is_pointer::value&& std::is_const::type>::value, int >::type = 0 > constexpr auto get_ptr() const noexcept -> decltype(std::declval().get_impl_ptr(std::declval())) { // delegate the call to get_impl_ptr<>() const return get_impl_ptr(static_cast(nullptr)); } private: /*! @brief get a value (explicit) Explicit type conversion between the JSON value and a compatible value which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible) and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). The value is converted by calling the @ref json_serializer `from_json()` method. The function is equivalent to executing @code {.cpp} ValueType ret; JSONSerializer::from_json(*this, ret); return ret; @endcode This overloads is chosen if: - @a ValueType is not @ref basic_json, - @ref json_serializer has a `from_json()` method of the form `void from_json(const basic_json&, ValueType&)`, and - @ref json_serializer does not have a `from_json()` method of the form `ValueType from_json(const basic_json&)` @tparam ValueType the returned value type @return copy of the JSON value, converted to @a ValueType @throw what @ref json_serializer `from_json()` method throws @liveexample{The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers\, (2) A JSON array can be converted to a standard `std::vector`\, (3) A JSON object can be converted to C++ associative containers such as `std::unordered_map`.,get__ValueType_const} @since version 2.1.0 */ template < typename ValueType, detail::enable_if_t < detail::is_default_constructible::value&& detail::has_from_json::value, int > = 0 > ValueType get_impl(detail::priority_tag<0> /*unused*/) const noexcept(noexcept( JSONSerializer::from_json(std::declval(), std::declval()))) { auto ret = ValueType(); JSONSerializer::from_json(*this, ret); return ret; } /*! @brief get a value (explicit); special case Explicit type conversion between the JSON value and a compatible value which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible) and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). The value is converted by calling the @ref json_serializer `from_json()` method. The function is equivalent to executing @code {.cpp} return JSONSerializer::from_json(*this); @endcode This overloads is chosen if: - @a ValueType is not @ref basic_json and - @ref json_serializer has a `from_json()` method of the form `ValueType from_json(const basic_json&)` @note If @ref json_serializer has both overloads of `from_json()`, this one is chosen. @tparam ValueType the returned value type @return copy of the JSON value, converted to @a ValueType @throw what @ref json_serializer `from_json()` method throws @since version 2.1.0 */ template < typename ValueType, detail::enable_if_t < detail::has_non_default_from_json::value, int > = 0 > ValueType get_impl(detail::priority_tag<1> /*unused*/) const noexcept(noexcept( JSONSerializer::from_json(std::declval()))) { return JSONSerializer::from_json(*this); } /*! @brief get special-case overload This overloads converts the current @ref basic_json in a different @ref basic_json type @tparam BasicJsonType == @ref basic_json @return a copy of *this, converted into @a BasicJsonType @complexity Depending on the implementation of the called `from_json()` method. @since version 3.2.0 */ template < typename BasicJsonType, detail::enable_if_t < detail::is_basic_json::value, int > = 0 > BasicJsonType get_impl(detail::priority_tag<2> /*unused*/) const { return *this; } /*! @brief get special-case overload This overloads avoids a lot of template boilerplate, it can be seen as the identity method @tparam BasicJsonType == @ref basic_json @return a copy of *this @complexity Constant. @since version 2.1.0 */ template::value, int> = 0> basic_json get_impl(detail::priority_tag<3> /*unused*/) const { return *this; } /*! @brief get a pointer value (explicit) @copydoc get() */ template::value, int> = 0> constexpr auto get_impl(detail::priority_tag<4> /*unused*/) const noexcept -> decltype(std::declval().template get_ptr()) { // delegate the call to get_ptr return get_ptr(); } public: /*! @brief get a (pointer) value (explicit) Performs explicit type conversion between the JSON value and a compatible value if required. - If the requested type is a pointer to the internally stored JSON value that pointer is returned. No copies are made. - If the requested type is the current @ref basic_json, or a different @ref basic_json convertible from the current @ref basic_json. - Otherwise the value is converted by calling the @ref json_serializer `from_json()` method. @tparam ValueTypeCV the provided value type @tparam ValueType the returned value type @return copy of the JSON value, converted to @tparam ValueType if necessary @throw what @ref json_serializer `from_json()` method throws if conversion is required @since version 2.1.0 */ template < typename ValueTypeCV, typename ValueType = detail::uncvref_t> #if defined(JSON_HAS_CPP_14) constexpr #endif auto get() const noexcept( noexcept(std::declval().template get_impl(detail::priority_tag<4> {}))) -> decltype(std::declval().template get_impl(detail::priority_tag<4> {})) { // we cannot static_assert on ValueTypeCV being non-const, because // there is support for get(), which is why we // still need the uncvref static_assert(!std::is_reference::value, "get() cannot be used with reference types, you might want to use get_ref()"); return get_impl(detail::priority_tag<4> {}); } /*! @brief get a pointer value (explicit) Explicit pointer access to the internally stored JSON value. No copies are made. @warning The pointer becomes invalid if the underlying JSON object changes. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, @ref number_unsigned_t, or @ref number_float_t. @return pointer to the internally stored JSON value if the requested pointer type @a PointerType fits to the JSON value; `nullptr` otherwise @complexity Constant. @liveexample{The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a `nullptr` is returned if the value and the requested pointer type does not match.,get__PointerType} @sa see @ref get_ptr() for explicit pointer-member access @since version 1.0.0 */ template::value, int>::type = 0> auto get() noexcept -> decltype(std::declval().template get_ptr()) { // delegate the call to get_ptr return get_ptr(); } /// @brief get a value (explicit) /// @sa https://json.nlohmann.me/api/basic_json/get_to/ template < typename ValueType, detail::enable_if_t < !detail::is_basic_json::value&& detail::has_from_json::value, int > = 0 > ValueType & get_to(ValueType& v) const noexcept(noexcept( JSONSerializer::from_json(std::declval(), v))) { JSONSerializer::from_json(*this, v); return v; } // specialization to allow calling get_to with a basic_json value // see https://github.com/nlohmann/json/issues/2175 template::value, int> = 0> ValueType & get_to(ValueType& v) const { v = *this; return v; } template < typename T, std::size_t N, typename Array = T (&)[N], // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) detail::enable_if_t < detail::has_from_json::value, int > = 0 > Array get_to(T (&v)[N]) const // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) noexcept(noexcept(JSONSerializer::from_json( std::declval(), v))) { JSONSerializer::from_json(*this, v); return v; } /// @brief get a reference value (implicit) /// @sa https://json.nlohmann.me/api/basic_json/get_ref/ template::value, int>::type = 0> ReferenceType get_ref() { // delegate call to get_ref_impl return get_ref_impl(*this); } /// @brief get a reference value (implicit) /// @sa https://json.nlohmann.me/api/basic_json/get_ref/ template < typename ReferenceType, typename std::enable_if < std::is_reference::value&& std::is_const::type>::value, int >::type = 0 > ReferenceType get_ref() const { // delegate call to get_ref_impl return get_ref_impl(*this); } /*! @brief get a value (implicit) Implicit type conversion between the JSON value and a compatible value. The call is realized by calling @ref get() const. @tparam ValueType non-pointer type compatible to the JSON value, for instance `int` for JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for JSON arrays. The character type of @ref string_t as well as an initializer list of this type is excluded to avoid ambiguities as these types implicitly convert to `std::string`. @return copy of the JSON value, converted to type @a ValueType @throw type_error.302 in case passed type @a ValueType is incompatible to the JSON value type (e.g., the JSON value is of type boolean, but a string is requested); see example below @complexity Linear in the size of the JSON value. @liveexample{The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers\, (2) A JSON array can be converted to a standard `std::vector`\, (3) A JSON object can be converted to C++ associative containers such as `std::unordered_map`.,operator__ValueType} @since version 1.0.0 */ template < typename ValueType, typename std::enable_if < detail::conjunction < detail::negation>, detail::negation>>, detail::negation>, detail::negation>, detail::negation>>, #if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) && _MSC_VER >= 1910 && _MSC_VER <= 1914)) detail::negation>, #endif detail::is_detected_lazy >::value, int >::type = 0 > JSON_EXPLICIT operator ValueType() const { // delegate the call to get<>() const return get(); } /// @brief get a binary value /// @sa https://json.nlohmann.me/api/basic_json/get_binary/ binary_t& get_binary() { if (!is_binary()) { JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()), *this)); } return *get_ptr(); } /// @brief get a binary value /// @sa https://json.nlohmann.me/api/basic_json/get_binary/ const binary_t& get_binary() const { if (!is_binary()) { JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()), *this)); } return *get_ptr(); } /// @} //////////////////// // element access // //////////////////// /// @name element access /// Access to the JSON value. /// @{ /// @brief access specified array element with bounds checking /// @sa https://json.nlohmann.me/api/basic_json/at/ reference at(size_type idx) { // at only works for arrays if (JSON_HEDLEY_LIKELY(is_array())) { JSON_TRY { return set_parent(m_value.array->at(idx)); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this)); } } else { JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); } } /// @brief access specified array element with bounds checking /// @sa https://json.nlohmann.me/api/basic_json/at/ const_reference at(size_type idx) const { // at only works for arrays if (JSON_HEDLEY_LIKELY(is_array())) { JSON_TRY { return m_value.array->at(idx); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this)); } } else { JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); } } /// @brief access specified object element with bounds checking /// @sa https://json.nlohmann.me/api/basic_json/at/ reference at(const typename object_t::key_type& key) { // at only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { JSON_TRY { return set_parent(m_value.object->at(key)); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(out_of_range::create(403, "key '" + key + "' not found", *this)); } } else { JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); } } /// @brief access specified object element with bounds checking /// @sa https://json.nlohmann.me/api/basic_json/at/ const_reference at(const typename object_t::key_type& key) const { // at only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { JSON_TRY { return m_value.object->at(key); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(out_of_range::create(403, "key '" + key + "' not found", *this)); } } else { JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); } } /// @brief access specified array element /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ reference operator[](size_type idx) { // implicitly convert null value to an empty array if (is_null()) { m_type = value_t::array; m_value.array = create(); assert_invariant(); } // operator[] only works for arrays if (JSON_HEDLEY_LIKELY(is_array())) { // fill up array with null values if given idx is outside range if (idx >= m_value.array->size()) { #if JSON_DIAGNOSTICS // remember array size & capacity before resizing const auto old_size = m_value.array->size(); const auto old_capacity = m_value.array->capacity(); #endif m_value.array->resize(idx + 1); #if JSON_DIAGNOSTICS if (JSON_HEDLEY_UNLIKELY(m_value.array->capacity() != old_capacity)) { // capacity has changed: update all parents set_parents(); } else { // set parent for values added above set_parents(begin() + static_cast(old_size), static_cast(idx + 1 - old_size)); } #endif assert_invariant(); } return m_value.array->operator[](idx); } JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()), *this)); } /// @brief access specified array element /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ const_reference operator[](size_type idx) const { // const operator[] only works for arrays if (JSON_HEDLEY_LIKELY(is_array())) { return m_value.array->operator[](idx); } JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()), *this)); } /// @brief access specified object element /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ reference operator[](const typename object_t::key_type& key) { // implicitly convert null value to an empty object if (is_null()) { m_type = value_t::object; m_value.object = create(); assert_invariant(); } // operator[] only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { return set_parent(m_value.object->operator[](key)); } JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); } /// @brief access specified object element /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ const_reference operator[](const typename object_t::key_type& key) const { // const operator[] only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { JSON_ASSERT(m_value.object->find(key) != m_value.object->end()); return m_value.object->find(key)->second; } JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); } /// @brief access specified object element /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ template JSON_HEDLEY_NON_NULL(2) reference operator[](T* key) { // implicitly convert null to object if (is_null()) { m_type = value_t::object; m_value = value_t::object; assert_invariant(); } // at only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { return set_parent(m_value.object->operator[](key)); } JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); } /// @brief access specified object element /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ template JSON_HEDLEY_NON_NULL(2) const_reference operator[](T* key) const { // at only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { JSON_ASSERT(m_value.object->find(key) != m_value.object->end()); return m_value.object->find(key)->second; } JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); } /// @brief access specified object element with default value /// @sa https://json.nlohmann.me/api/basic_json/value/ /// using std::is_convertible in a std::enable_if will fail when using explicit conversions template < class ValueType, typename std::enable_if < detail::is_getable::value && !std::is_same::value, int >::type = 0 > ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const { // at only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { // if key is found, return value and given default value otherwise const auto it = find(key); if (it != end()) { return it->template get(); } return default_value; } JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()), *this)); } /// @brief access specified object element with default value /// @sa https://json.nlohmann.me/api/basic_json/value/ /// overload for a default value of type const char* string_t value(const typename object_t::key_type& key, const char* default_value) const { return value(key, string_t(default_value)); } /// @brief access specified object element via JSON Pointer with default value /// @sa https://json.nlohmann.me/api/basic_json/value/ template::value, int>::type = 0> ValueType value(const json_pointer& ptr, const ValueType& default_value) const { // at only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { // if pointer resolves a value, return it or use default value JSON_TRY { return ptr.get_checked(this).template get(); } JSON_INTERNAL_CATCH (out_of_range&) { return default_value; } } JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()), *this)); } /// @brief access specified object element via JSON Pointer with default value /// @sa https://json.nlohmann.me/api/basic_json/value/ /// overload for a default value of type const char* JSON_HEDLEY_NON_NULL(3) string_t value(const json_pointer& ptr, const char* default_value) const { return value(ptr, string_t(default_value)); } /// @brief access the first element /// @sa https://json.nlohmann.me/api/basic_json/front/ reference front() { return *begin(); } /// @brief access the first element /// @sa https://json.nlohmann.me/api/basic_json/front/ const_reference front() const { return *cbegin(); } /// @brief access the last element /// @sa https://json.nlohmann.me/api/basic_json/back/ reference back() { auto tmp = end(); --tmp; return *tmp; } /// @brief access the last element /// @sa https://json.nlohmann.me/api/basic_json/back/ const_reference back() const { auto tmp = cend(); --tmp; return *tmp; } /// @brief remove element given an iterator /// @sa https://json.nlohmann.me/api/basic_json/erase/ template < class IteratorType, typename std::enable_if < std::is_same::value || std::is_same::value, int >::type = 0 > IteratorType erase(IteratorType pos) { // make sure iterator fits the current value if (JSON_HEDLEY_UNLIKELY(this != pos.m_object)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); } IteratorType result = end(); switch (m_type) { case value_t::boolean: case value_t::number_float: case value_t::number_integer: case value_t::number_unsigned: case value_t::string: case value_t::binary: { if (JSON_HEDLEY_UNLIKELY(!pos.m_it.primitive_iterator.is_begin())) { JSON_THROW(invalid_iterator::create(205, "iterator out of range", *this)); } if (is_string()) { AllocatorType alloc; std::allocator_traits::destroy(alloc, m_value.string); std::allocator_traits::deallocate(alloc, m_value.string, 1); m_value.string = nullptr; } else if (is_binary()) { AllocatorType alloc; std::allocator_traits::destroy(alloc, m_value.binary); std::allocator_traits::deallocate(alloc, m_value.binary, 1); m_value.binary = nullptr; } m_type = value_t::null; assert_invariant(); break; } case value_t::object: { result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator); break; } case value_t::array: { result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator); break; } case value_t::null: case value_t::discarded: default: JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); } return result; } /// @brief remove elements given an iterator range /// @sa https://json.nlohmann.me/api/basic_json/erase/ template < class IteratorType, typename std::enable_if < std::is_same::value || std::is_same::value, int >::type = 0 > IteratorType erase(IteratorType first, IteratorType last) { // make sure iterator fits the current value if (JSON_HEDLEY_UNLIKELY(this != first.m_object || this != last.m_object)) { JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value", *this)); } IteratorType result = end(); switch (m_type) { case value_t::boolean: case value_t::number_float: case value_t::number_integer: case value_t::number_unsigned: case value_t::string: case value_t::binary: { if (JSON_HEDLEY_LIKELY(!first.m_it.primitive_iterator.is_begin() || !last.m_it.primitive_iterator.is_end())) { JSON_THROW(invalid_iterator::create(204, "iterators out of range", *this)); } if (is_string()) { AllocatorType alloc; std::allocator_traits::destroy(alloc, m_value.string); std::allocator_traits::deallocate(alloc, m_value.string, 1); m_value.string = nullptr; } else if (is_binary()) { AllocatorType alloc; std::allocator_traits::destroy(alloc, m_value.binary); std::allocator_traits::deallocate(alloc, m_value.binary, 1); m_value.binary = nullptr; } m_type = value_t::null; assert_invariant(); break; } case value_t::object: { result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator, last.m_it.object_iterator); break; } case value_t::array: { result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator, last.m_it.array_iterator); break; } case value_t::null: case value_t::discarded: default: JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); } return result; } /// @brief remove element from a JSON object given a key /// @sa https://json.nlohmann.me/api/basic_json/erase/ size_type erase(const typename object_t::key_type& key) { // this erase only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { return m_value.object->erase(key); } JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); } /// @brief remove element from a JSON array given an index /// @sa https://json.nlohmann.me/api/basic_json/erase/ void erase(const size_type idx) { // this erase only works for arrays if (JSON_HEDLEY_LIKELY(is_array())) { if (JSON_HEDLEY_UNLIKELY(idx >= size())) { JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this)); } m_value.array->erase(m_value.array->begin() + static_cast(idx)); } else { JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); } } /// @} //////////// // lookup // //////////// /// @name lookup /// @{ /// @brief find an element in a JSON object /// @sa https://json.nlohmann.me/api/basic_json/find/ template iterator find(KeyT&& key) { auto result = end(); if (is_object()) { result.m_it.object_iterator = m_value.object->find(std::forward(key)); } return result; } /// @brief find an element in a JSON object /// @sa https://json.nlohmann.me/api/basic_json/find/ template const_iterator find(KeyT&& key) const { auto result = cend(); if (is_object()) { result.m_it.object_iterator = m_value.object->find(std::forward(key)); } return result; } /// @brief returns the number of occurrences of a key in a JSON object /// @sa https://json.nlohmann.me/api/basic_json/count/ template size_type count(KeyT&& key) const { // return 0 for all nonobject types return is_object() ? m_value.object->count(std::forward(key)) : 0; } /// @brief check the existence of an element in a JSON object /// @sa https://json.nlohmann.me/api/basic_json/contains/ template < typename KeyT, typename std::enable_if < !std::is_same::type, json_pointer>::value, int >::type = 0 > bool contains(KeyT && key) const { return is_object() && m_value.object->find(std::forward(key)) != m_value.object->end(); } /// @brief check the existence of an element in a JSON object given a JSON pointer /// @sa https://json.nlohmann.me/api/basic_json/contains/ bool contains(const json_pointer& ptr) const { return ptr.contains(this); } /// @} /////////////// // iterators // /////////////// /// @name iterators /// @{ /// @brief returns an iterator to the first element /// @sa https://json.nlohmann.me/api/basic_json/begin/ iterator begin() noexcept { iterator result(this); result.set_begin(); return result; } /// @brief returns an iterator to the first element /// @sa https://json.nlohmann.me/api/basic_json/begin/ const_iterator begin() const noexcept { return cbegin(); } /// @brief returns a const iterator to the first element /// @sa https://json.nlohmann.me/api/basic_json/cbegin/ const_iterator cbegin() const noexcept { const_iterator result(this); result.set_begin(); return result; } /// @brief returns an iterator to one past the last element /// @sa https://json.nlohmann.me/api/basic_json/end/ iterator end() noexcept { iterator result(this); result.set_end(); return result; } /// @brief returns an iterator to one past the last element /// @sa https://json.nlohmann.me/api/basic_json/end/ const_iterator end() const noexcept { return cend(); } /// @brief returns an iterator to one past the last element /// @sa https://json.nlohmann.me/api/basic_json/cend/ const_iterator cend() const noexcept { const_iterator result(this); result.set_end(); return result; } /// @brief returns an iterator to the reverse-beginning /// @sa https://json.nlohmann.me/api/basic_json/rbegin/ reverse_iterator rbegin() noexcept { return reverse_iterator(end()); } /// @brief returns an iterator to the reverse-beginning /// @sa https://json.nlohmann.me/api/basic_json/rbegin/ const_reverse_iterator rbegin() const noexcept { return crbegin(); } /// @brief returns an iterator to the reverse-end /// @sa https://json.nlohmann.me/api/basic_json/rend/ reverse_iterator rend() noexcept { return reverse_iterator(begin()); } /// @brief returns an iterator to the reverse-end /// @sa https://json.nlohmann.me/api/basic_json/rend/ const_reverse_iterator rend() const noexcept { return crend(); } /// @brief returns a const reverse iterator to the last element /// @sa https://json.nlohmann.me/api/basic_json/crbegin/ const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(cend()); } /// @brief returns a const reverse iterator to one before the first /// @sa https://json.nlohmann.me/api/basic_json/crend/ const_reverse_iterator crend() const noexcept { return const_reverse_iterator(cbegin()); } public: /// @brief wrapper to access iterator member functions in range-based for /// @sa https://json.nlohmann.me/api/basic_json/items/ /// @deprecated This function is deprecated since 3.1.0 and will be removed in /// version 4.0.0 of the library. Please use @ref items() instead; /// that is, replace `json::iterator_wrapper(j)` with `j.items()`. JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items()) static iteration_proxy iterator_wrapper(reference ref) noexcept { return ref.items(); } /// @brief wrapper to access iterator member functions in range-based for /// @sa https://json.nlohmann.me/api/basic_json/items/ /// @deprecated This function is deprecated since 3.1.0 and will be removed in /// version 4.0.0 of the library. Please use @ref items() instead; /// that is, replace `json::iterator_wrapper(j)` with `j.items()`. JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items()) static iteration_proxy iterator_wrapper(const_reference ref) noexcept { return ref.items(); } /// @brief helper to access iterator member functions in range-based for /// @sa https://json.nlohmann.me/api/basic_json/items/ iteration_proxy items() noexcept { return iteration_proxy(*this); } /// @brief helper to access iterator member functions in range-based for /// @sa https://json.nlohmann.me/api/basic_json/items/ iteration_proxy items() const noexcept { return iteration_proxy(*this); } /// @} ////////////// // capacity // ////////////// /// @name capacity /// @{ /// @brief checks whether the container is empty. /// @sa https://json.nlohmann.me/api/basic_json/empty/ bool empty() const noexcept { switch (m_type) { case value_t::null: { // null values are empty return true; } case value_t::array: { // delegate call to array_t::empty() return m_value.array->empty(); } case value_t::object: { // delegate call to object_t::empty() return m_value.object->empty(); } case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: { // all other types are nonempty return false; } } } /// @brief returns the number of elements /// @sa https://json.nlohmann.me/api/basic_json/size/ size_type size() const noexcept { switch (m_type) { case value_t::null: { // null values are empty return 0; } case value_t::array: { // delegate call to array_t::size() return m_value.array->size(); } case value_t::object: { // delegate call to object_t::size() return m_value.object->size(); } case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: { // all other types have size 1 return 1; } } } /// @brief returns the maximum possible number of elements /// @sa https://json.nlohmann.me/api/basic_json/max_size/ size_type max_size() const noexcept { switch (m_type) { case value_t::array: { // delegate call to array_t::max_size() return m_value.array->max_size(); } case value_t::object: { // delegate call to object_t::max_size() return m_value.object->max_size(); } case value_t::null: case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: { // all other types have max_size() == size() return size(); } } } /// @} /////////////// // modifiers // /////////////// /// @name modifiers /// @{ /// @brief clears the contents /// @sa https://json.nlohmann.me/api/basic_json/clear/ void clear() noexcept { switch (m_type) { case value_t::number_integer: { m_value.number_integer = 0; break; } case value_t::number_unsigned: { m_value.number_unsigned = 0; break; } case value_t::number_float: { m_value.number_float = 0.0; break; } case value_t::boolean: { m_value.boolean = false; break; } case value_t::string: { m_value.string->clear(); break; } case value_t::binary: { m_value.binary->clear(); break; } case value_t::array: { m_value.array->clear(); break; } case value_t::object: { m_value.object->clear(); break; } case value_t::null: case value_t::discarded: default: break; } } /// @brief add an object to an array /// @sa https://json.nlohmann.me/api/basic_json/push_back/ void push_back(basic_json&& val) { // push_back only works for null objects or arrays if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) { JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this)); } // transform null object into an array if (is_null()) { m_type = value_t::array; m_value = value_t::array; assert_invariant(); } // add element to array (move semantics) const auto old_capacity = m_value.array->capacity(); m_value.array->push_back(std::move(val)); set_parent(m_value.array->back(), old_capacity); // if val is moved from, basic_json move constructor marks it null, so we do not call the destructor } /// @brief add an object to an array /// @sa https://json.nlohmann.me/api/basic_json/operator+=/ reference operator+=(basic_json&& val) { push_back(std::move(val)); return *this; } /// @brief add an object to an array /// @sa https://json.nlohmann.me/api/basic_json/push_back/ void push_back(const basic_json& val) { // push_back only works for null objects or arrays if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) { JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this)); } // transform null object into an array if (is_null()) { m_type = value_t::array; m_value = value_t::array; assert_invariant(); } // add element to array const auto old_capacity = m_value.array->capacity(); m_value.array->push_back(val); set_parent(m_value.array->back(), old_capacity); } /// @brief add an object to an array /// @sa https://json.nlohmann.me/api/basic_json/operator+=/ reference operator+=(const basic_json& val) { push_back(val); return *this; } /// @brief add an object to an object /// @sa https://json.nlohmann.me/api/basic_json/push_back/ void push_back(const typename object_t::value_type& val) { // push_back only works for null objects or objects if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object()))) { JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this)); } // transform null object into an object if (is_null()) { m_type = value_t::object; m_value = value_t::object; assert_invariant(); } // add element to object auto res = m_value.object->insert(val); set_parent(res.first->second); } /// @brief add an object to an object /// @sa https://json.nlohmann.me/api/basic_json/operator+=/ reference operator+=(const typename object_t::value_type& val) { push_back(val); return *this; } /// @brief add an object to an object /// @sa https://json.nlohmann.me/api/basic_json/push_back/ void push_back(initializer_list_t init) { if (is_object() && init.size() == 2 && (*init.begin())->is_string()) { basic_json&& key = init.begin()->moved_or_copied(); push_back(typename object_t::value_type( std::move(key.get_ref()), (init.begin() + 1)->moved_or_copied())); } else { push_back(basic_json(init)); } } /// @brief add an object to an object /// @sa https://json.nlohmann.me/api/basic_json/operator+=/ reference operator+=(initializer_list_t init) { push_back(init); return *this; } /// @brief add an object to an array /// @sa https://json.nlohmann.me/api/basic_json/emplace_back/ template reference emplace_back(Args&& ... args) { // emplace_back only works for null objects or arrays if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) { JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name()), *this)); } // transform null object into an array if (is_null()) { m_type = value_t::array; m_value = value_t::array; assert_invariant(); } // add element to array (perfect forwarding) const auto old_capacity = m_value.array->capacity(); m_value.array->emplace_back(std::forward(args)...); return set_parent(m_value.array->back(), old_capacity); } /// @brief add an object to an object if key does not exist /// @sa https://json.nlohmann.me/api/basic_json/emplace/ template std::pair emplace(Args&& ... args) { // emplace only works for null objects or arrays if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object()))) { JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name()), *this)); } // transform null object into an object if (is_null()) { m_type = value_t::object; m_value = value_t::object; assert_invariant(); } // add element to array (perfect forwarding) auto res = m_value.object->emplace(std::forward(args)...); set_parent(res.first->second); // create result iterator and set iterator to the result of emplace auto it = begin(); it.m_it.object_iterator = res.first; // return pair of iterator and boolean return {it, res.second}; } /// Helper for insertion of an iterator /// @note: This uses std::distance to support GCC 4.8, /// see https://github.com/nlohmann/json/pull/1257 template iterator insert_iterator(const_iterator pos, Args&& ... args) { iterator result(this); JSON_ASSERT(m_value.array != nullptr); auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator); m_value.array->insert(pos.m_it.array_iterator, std::forward(args)...); result.m_it.array_iterator = m_value.array->begin() + insert_pos; // This could have been written as: // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val); // but the return value of insert is missing in GCC 4.8, so it is written this way instead. set_parents(); return result; } /// @brief inserts element into array /// @sa https://json.nlohmann.me/api/basic_json/insert/ iterator insert(const_iterator pos, const basic_json& val) { // insert only works for arrays if (JSON_HEDLEY_LIKELY(is_array())) { // check if iterator pos fits to this JSON value if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); } // insert to array and return iterator return insert_iterator(pos, val); } JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); } /// @brief inserts element into array /// @sa https://json.nlohmann.me/api/basic_json/insert/ iterator insert(const_iterator pos, basic_json&& val) { return insert(pos, val); } /// @brief inserts copies of element into array /// @sa https://json.nlohmann.me/api/basic_json/insert/ iterator insert(const_iterator pos, size_type cnt, const basic_json& val) { // insert only works for arrays if (JSON_HEDLEY_LIKELY(is_array())) { // check if iterator pos fits to this JSON value if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); } // insert to array and return iterator return insert_iterator(pos, cnt, val); } JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); } /// @brief inserts range of elements into array /// @sa https://json.nlohmann.me/api/basic_json/insert/ iterator insert(const_iterator pos, const_iterator first, const_iterator last) { // insert only works for arrays if (JSON_HEDLEY_UNLIKELY(!is_array())) { JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); } // check if iterator pos fits to this JSON value if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); } // check if range iterators belong to the same JSON object if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) { JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this)); } if (JSON_HEDLEY_UNLIKELY(first.m_object == this)) { JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container", *this)); } // insert to array and return iterator return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator); } /// @brief inserts elements from initializer list into array /// @sa https://json.nlohmann.me/api/basic_json/insert/ iterator insert(const_iterator pos, initializer_list_t ilist) { // insert only works for arrays if (JSON_HEDLEY_UNLIKELY(!is_array())) { JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); } // check if iterator pos fits to this JSON value if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); } // insert to array and return iterator return insert_iterator(pos, ilist.begin(), ilist.end()); } /// @brief inserts range of elements into object /// @sa https://json.nlohmann.me/api/basic_json/insert/ void insert(const_iterator first, const_iterator last) { // insert only works for objects if (JSON_HEDLEY_UNLIKELY(!is_object())) { JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); } // check if range iterators belong to the same JSON object if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) { JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this)); } // passed iterators must belong to objects if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object())) { JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects", *this)); } m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator); } /// @brief updates a JSON object from another object, overwriting existing keys /// @sa https://json.nlohmann.me/api/basic_json/update/ void update(const_reference j, bool merge_objects = false) { update(j.begin(), j.end(), merge_objects); } /// @brief updates a JSON object from another object, overwriting existing keys /// @sa https://json.nlohmann.me/api/basic_json/update/ void update(const_iterator first, const_iterator last, bool merge_objects = false) { // implicitly convert null value to an empty object if (is_null()) { m_type = value_t::object; m_value.object = create(); assert_invariant(); } if (JSON_HEDLEY_UNLIKELY(!is_object())) { JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()), *this)); } // check if range iterators belong to the same JSON object if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) { JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this)); } // passed iterators must belong to objects if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object())) { JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(first.m_object->type_name()), *first.m_object)); } for (auto it = first; it != last; ++it) { if (merge_objects && it.value().is_object()) { auto it2 = m_value.object->find(it.key()); if (it2 != m_value.object->end()) { it2->second.update(it.value(), true); continue; } } m_value.object->operator[](it.key()) = it.value(); #if JSON_DIAGNOSTICS m_value.object->operator[](it.key()).m_parent = this; #endif } } /// @brief exchanges the values /// @sa https://json.nlohmann.me/api/basic_json/swap/ void swap(reference other) noexcept ( std::is_nothrow_move_constructible::value&& std::is_nothrow_move_assignable::value&& std::is_nothrow_move_constructible::value&& std::is_nothrow_move_assignable::value ) { std::swap(m_type, other.m_type); std::swap(m_value, other.m_value); set_parents(); other.set_parents(); assert_invariant(); } /// @brief exchanges the values /// @sa https://json.nlohmann.me/api/basic_json/swap/ friend void swap(reference left, reference right) noexcept ( std::is_nothrow_move_constructible::value&& std::is_nothrow_move_assignable::value&& std::is_nothrow_move_constructible::value&& std::is_nothrow_move_assignable::value ) { left.swap(right); } /// @brief exchanges the values /// @sa https://json.nlohmann.me/api/basic_json/swap/ void swap(array_t& other) // NOLINT(bugprone-exception-escape) { // swap only works for arrays if (JSON_HEDLEY_LIKELY(is_array())) { std::swap(*(m_value.array), other); } else { JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); } } /// @brief exchanges the values /// @sa https://json.nlohmann.me/api/basic_json/swap/ void swap(object_t& other) // NOLINT(bugprone-exception-escape) { // swap only works for objects if (JSON_HEDLEY_LIKELY(is_object())) { std::swap(*(m_value.object), other); } else { JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); } } /// @brief exchanges the values /// @sa https://json.nlohmann.me/api/basic_json/swap/ void swap(string_t& other) // NOLINT(bugprone-exception-escape) { // swap only works for strings if (JSON_HEDLEY_LIKELY(is_string())) { std::swap(*(m_value.string), other); } else { JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); } } /// @brief exchanges the values /// @sa https://json.nlohmann.me/api/basic_json/swap/ void swap(binary_t& other) // NOLINT(bugprone-exception-escape) { // swap only works for strings if (JSON_HEDLEY_LIKELY(is_binary())) { std::swap(*(m_value.binary), other); } else { JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); } } /// @brief exchanges the values /// @sa https://json.nlohmann.me/api/basic_json/swap/ void swap(typename binary_t::container_type& other) // NOLINT(bugprone-exception-escape) { // swap only works for strings if (JSON_HEDLEY_LIKELY(is_binary())) { std::swap(*(m_value.binary), other); } else { JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); } } /// @} public: ////////////////////////////////////////// // lexicographical comparison operators // ////////////////////////////////////////// /// @name lexicographical comparison operators /// @{ /// @brief comparison: equal /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/ friend bool operator==(const_reference lhs, const_reference rhs) noexcept { #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wfloat-equal" #endif const auto lhs_type = lhs.type(); const auto rhs_type = rhs.type(); if (lhs_type == rhs_type) { switch (lhs_type) { case value_t::array: return *lhs.m_value.array == *rhs.m_value.array; case value_t::object: return *lhs.m_value.object == *rhs.m_value.object; case value_t::null: return true; case value_t::string: return *lhs.m_value.string == *rhs.m_value.string; case value_t::boolean: return lhs.m_value.boolean == rhs.m_value.boolean; case value_t::number_integer: return lhs.m_value.number_integer == rhs.m_value.number_integer; case value_t::number_unsigned: return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned; case value_t::number_float: return lhs.m_value.number_float == rhs.m_value.number_float; case value_t::binary: return *lhs.m_value.binary == *rhs.m_value.binary; case value_t::discarded: default: return false; } } else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float) { return static_cast(lhs.m_value.number_integer) == rhs.m_value.number_float; } else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer) { return lhs.m_value.number_float == static_cast(rhs.m_value.number_integer); } else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float) { return static_cast(lhs.m_value.number_unsigned) == rhs.m_value.number_float; } else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned) { return lhs.m_value.number_float == static_cast(rhs.m_value.number_unsigned); } else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer) { return static_cast(lhs.m_value.number_unsigned) == rhs.m_value.number_integer; } else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned) { return lhs.m_value.number_integer == static_cast(rhs.m_value.number_unsigned); } return false; #ifdef __GNUC__ #pragma GCC diagnostic pop #endif } /// @brief comparison: equal /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/ template::value, int>::type = 0> friend bool operator==(const_reference lhs, ScalarType rhs) noexcept { return lhs == basic_json(rhs); } /// @brief comparison: equal /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/ template::value, int>::type = 0> friend bool operator==(ScalarType lhs, const_reference rhs) noexcept { return basic_json(lhs) == rhs; } /// @brief comparison: not equal /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/ friend bool operator!=(const_reference lhs, const_reference rhs) noexcept { return !(lhs == rhs); } /// @brief comparison: not equal /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/ template::value, int>::type = 0> friend bool operator!=(const_reference lhs, ScalarType rhs) noexcept { return lhs != basic_json(rhs); } /// @brief comparison: not equal /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/ template::value, int>::type = 0> friend bool operator!=(ScalarType lhs, const_reference rhs) noexcept { return basic_json(lhs) != rhs; } /// @brief comparison: less than /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/ friend bool operator<(const_reference lhs, const_reference rhs) noexcept { const auto lhs_type = lhs.type(); const auto rhs_type = rhs.type(); if (lhs_type == rhs_type) { switch (lhs_type) { case value_t::array: // note parentheses are necessary, see // https://github.com/nlohmann/json/issues/1530 return (*lhs.m_value.array) < (*rhs.m_value.array); case value_t::object: return (*lhs.m_value.object) < (*rhs.m_value.object); case value_t::null: return false; case value_t::string: return (*lhs.m_value.string) < (*rhs.m_value.string); case value_t::boolean: return (lhs.m_value.boolean) < (rhs.m_value.boolean); case value_t::number_integer: return (lhs.m_value.number_integer) < (rhs.m_value.number_integer); case value_t::number_unsigned: return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned); case value_t::number_float: return (lhs.m_value.number_float) < (rhs.m_value.number_float); case value_t::binary: return (*lhs.m_value.binary) < (*rhs.m_value.binary); case value_t::discarded: default: return false; } } else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float) { return static_cast(lhs.m_value.number_integer) < rhs.m_value.number_float; } else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer) { return lhs.m_value.number_float < static_cast(rhs.m_value.number_integer); } else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float) { return static_cast(lhs.m_value.number_unsigned) < rhs.m_value.number_float; } else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned) { return lhs.m_value.number_float < static_cast(rhs.m_value.number_unsigned); } else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned) { return lhs.m_value.number_integer < static_cast(rhs.m_value.number_unsigned); } else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer) { return static_cast(lhs.m_value.number_unsigned) < rhs.m_value.number_integer; } // We only reach this line if we cannot compare values. In that case, // we compare types. Note we have to call the operator explicitly, // because MSVC has problems otherwise. return operator<(lhs_type, rhs_type); } /// @brief comparison: less than /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/ template::value, int>::type = 0> friend bool operator<(const_reference lhs, ScalarType rhs) noexcept { return lhs < basic_json(rhs); } /// @brief comparison: less than /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/ template::value, int>::type = 0> friend bool operator<(ScalarType lhs, const_reference rhs) noexcept { return basic_json(lhs) < rhs; } /// @brief comparison: less than or equal /// @sa https://json.nlohmann.me/api/basic_json/operator_le/ friend bool operator<=(const_reference lhs, const_reference rhs) noexcept { return !(rhs < lhs); } /// @brief comparison: less than or equal /// @sa https://json.nlohmann.me/api/basic_json/operator_le/ template::value, int>::type = 0> friend bool operator<=(const_reference lhs, ScalarType rhs) noexcept { return lhs <= basic_json(rhs); } /// @brief comparison: less than or equal /// @sa https://json.nlohmann.me/api/basic_json/operator_le/ template::value, int>::type = 0> friend bool operator<=(ScalarType lhs, const_reference rhs) noexcept { return basic_json(lhs) <= rhs; } /// @brief comparison: greater than /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/ friend bool operator>(const_reference lhs, const_reference rhs) noexcept { return !(lhs <= rhs); } /// @brief comparison: greater than /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/ template::value, int>::type = 0> friend bool operator>(const_reference lhs, ScalarType rhs) noexcept { return lhs > basic_json(rhs); } /// @brief comparison: greater than /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/ template::value, int>::type = 0> friend bool operator>(ScalarType lhs, const_reference rhs) noexcept { return basic_json(lhs) > rhs; } /// @brief comparison: greater than or equal /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/ friend bool operator>=(const_reference lhs, const_reference rhs) noexcept { return !(lhs < rhs); } /// @brief comparison: greater than or equal /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/ template::value, int>::type = 0> friend bool operator>=(const_reference lhs, ScalarType rhs) noexcept { return lhs >= basic_json(rhs); } /// @brief comparison: greater than or equal /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/ template::value, int>::type = 0> friend bool operator>=(ScalarType lhs, const_reference rhs) noexcept { return basic_json(lhs) >= rhs; } /// @} /////////////////// // serialization // /////////////////// /// @name serialization /// @{ #ifndef JSON_NO_IO /// @brief serialize to stream /// @sa https://json.nlohmann.me/api/basic_json/operator_ltlt/ friend std::ostream& operator<<(std::ostream& o, const basic_json& j) { // read width member and use it as indentation parameter if nonzero const bool pretty_print = o.width() > 0; const auto indentation = pretty_print ? o.width() : 0; // reset width to 0 for subsequent calls to this stream o.width(0); // do the actual serialization serializer s(detail::output_adapter(o), o.fill()); s.dump(j, pretty_print, false, static_cast(indentation)); return o; } /// @brief serialize to stream /// @sa https://json.nlohmann.me/api/basic_json/operator_ltlt/ /// @deprecated This function is deprecated since 3.0.0 and will be removed in /// version 4.0.0 of the library. Please use /// operator<<(std::ostream&, const basic_json&) instead; that is, /// replace calls like `j >> o;` with `o << j;`. JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator<<(std::ostream&, const basic_json&)) friend std::ostream& operator>>(const basic_json& j, std::ostream& o) { return o << j; } #endif // JSON_NO_IO /// @} ///////////////////// // deserialization // ///////////////////// /// @name deserialization /// @{ /// @brief deserialize from a compatible input /// @sa https://json.nlohmann.me/api/basic_json/parse/ template JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json parse(InputType&& i, const parser_callback_t cb = nullptr, const bool allow_exceptions = true, const bool ignore_comments = false) { basic_json result; parser(detail::input_adapter(std::forward(i)), cb, allow_exceptions, ignore_comments).parse(true, result); return result; } /// @brief deserialize from a pair of character iterators /// @sa https://json.nlohmann.me/api/basic_json/parse/ template JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json parse(IteratorType first, IteratorType last, const parser_callback_t cb = nullptr, const bool allow_exceptions = true, const bool ignore_comments = false) { basic_json result; parser(detail::input_adapter(std::move(first), std::move(last)), cb, allow_exceptions, ignore_comments).parse(true, result); return result; } JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, parse(ptr, ptr + len)) static basic_json parse(detail::span_input_adapter&& i, const parser_callback_t cb = nullptr, const bool allow_exceptions = true, const bool ignore_comments = false) { basic_json result; parser(i.get(), cb, allow_exceptions, ignore_comments).parse(true, result); return result; } /// @brief check if the input is valid JSON /// @sa https://json.nlohmann.me/api/basic_json/accept/ template static bool accept(InputType&& i, const bool ignore_comments = false) { return parser(detail::input_adapter(std::forward(i)), nullptr, false, ignore_comments).accept(true); } /// @brief check if the input is valid JSON /// @sa https://json.nlohmann.me/api/basic_json/accept/ template static bool accept(IteratorType first, IteratorType last, const bool ignore_comments = false) { return parser(detail::input_adapter(std::move(first), std::move(last)), nullptr, false, ignore_comments).accept(true); } JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, accept(ptr, ptr + len)) static bool accept(detail::span_input_adapter&& i, const bool ignore_comments = false) { return parser(i.get(), nullptr, false, ignore_comments).accept(true); } /// @brief generate SAX events /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/ template JSON_HEDLEY_NON_NULL(2) static bool sax_parse(InputType&& i, SAX* sax, input_format_t format = input_format_t::json, const bool strict = true, const bool ignore_comments = false) { auto ia = detail::input_adapter(std::forward(i)); return format == input_format_t::json ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) : detail::binary_reader(std::move(ia)).sax_parse(format, sax, strict); } /// @brief generate SAX events /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/ template JSON_HEDLEY_NON_NULL(3) static bool sax_parse(IteratorType first, IteratorType last, SAX* sax, input_format_t format = input_format_t::json, const bool strict = true, const bool ignore_comments = false) { auto ia = detail::input_adapter(std::move(first), std::move(last)); return format == input_format_t::json ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) : detail::binary_reader(std::move(ia)).sax_parse(format, sax, strict); } /// @brief generate SAX events /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/ /// @deprecated This function is deprecated since 3.8.0 and will be removed in /// version 4.0.0 of the library. Please use /// sax_parse(ptr, ptr + len) instead. template JSON_HEDLEY_DEPRECATED_FOR(3.8.0, sax_parse(ptr, ptr + len, ...)) JSON_HEDLEY_NON_NULL(2) static bool sax_parse(detail::span_input_adapter&& i, SAX* sax, input_format_t format = input_format_t::json, const bool strict = true, const bool ignore_comments = false) { auto ia = i.get(); return format == input_format_t::json // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) : detail::binary_reader(std::move(ia)).sax_parse(format, sax, strict); } #ifndef JSON_NO_IO /// @brief deserialize from stream /// @sa https://json.nlohmann.me/api/basic_json/operator_gtgt/ /// @deprecated This stream operator is deprecated since 3.0.0 and will be removed in /// version 4.0.0 of the library. Please use /// operator>>(std::istream&, basic_json&) instead; that is, /// replace calls like `j << i;` with `i >> j;`. JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator>>(std::istream&, basic_json&)) friend std::istream& operator<<(basic_json& j, std::istream& i) { return operator>>(i, j); } /// @brief deserialize from stream /// @sa https://json.nlohmann.me/api/basic_json/operator_gtgt/ friend std::istream& operator>>(std::istream& i, basic_json& j) { parser(detail::input_adapter(i)).parse(false, j); return i; } #endif // JSON_NO_IO /// @} /////////////////////////// // convenience functions // /////////////////////////// /// @brief return the type as string /// @sa https://json.nlohmann.me/api/basic_json/type_name/ JSON_HEDLEY_RETURNS_NON_NULL const char* type_name() const noexcept { switch (m_type) { case value_t::null: return "null"; case value_t::object: return "object"; case value_t::array: return "array"; case value_t::string: return "string"; case value_t::boolean: return "boolean"; case value_t::binary: return "binary"; case value_t::discarded: return "discarded"; case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: default: return "number"; } } JSON_PRIVATE_UNLESS_TESTED: ////////////////////// // member variables // ////////////////////// /// the type of the current element value_t m_type = value_t::null; /// the value of the current element json_value m_value = {}; #if JSON_DIAGNOSTICS /// a pointer to a parent value (for debugging purposes) basic_json* m_parent = nullptr; #endif ////////////////////////////////////////// // binary serialization/deserialization // ////////////////////////////////////////// /// @name binary serialization/deserialization support /// @{ public: /// @brief create a CBOR serialization of a given JSON value /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/ static std::vector to_cbor(const basic_json& j) { std::vector result; to_cbor(j, result); return result; } /// @brief create a CBOR serialization of a given JSON value /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/ static void to_cbor(const basic_json& j, detail::output_adapter o) { binary_writer(o).write_cbor(j); } /// @brief create a CBOR serialization of a given JSON value /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/ static void to_cbor(const basic_json& j, detail::output_adapter o) { binary_writer(o).write_cbor(j); } /// @brief create a MessagePack serialization of a given JSON value /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/ static std::vector to_msgpack(const basic_json& j) { std::vector result; to_msgpack(j, result); return result; } /// @brief create a MessagePack serialization of a given JSON value /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/ static void to_msgpack(const basic_json& j, detail::output_adapter o) { binary_writer(o).write_msgpack(j); } /// @brief create a MessagePack serialization of a given JSON value /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/ static void to_msgpack(const basic_json& j, detail::output_adapter o) { binary_writer(o).write_msgpack(j); } /// @brief create a UBJSON serialization of a given JSON value /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/ static std::vector to_ubjson(const basic_json& j, const bool use_size = false, const bool use_type = false) { std::vector result; to_ubjson(j, result, use_size, use_type); return result; } /// @brief create a UBJSON serialization of a given JSON value /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/ static void to_ubjson(const basic_json& j, detail::output_adapter o, const bool use_size = false, const bool use_type = false) { binary_writer(o).write_ubjson(j, use_size, use_type); } /// @brief create a UBJSON serialization of a given JSON value /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/ static void to_ubjson(const basic_json& j, detail::output_adapter o, const bool use_size = false, const bool use_type = false) { binary_writer(o).write_ubjson(j, use_size, use_type); } /// @brief create a BSON serialization of a given JSON value /// @sa https://json.nlohmann.me/api/basic_json/to_bson/ static std::vector to_bson(const basic_json& j) { std::vector result; to_bson(j, result); return result; } /// @brief create a BSON serialization of a given JSON value /// @sa https://json.nlohmann.me/api/basic_json/to_bson/ static void to_bson(const basic_json& j, detail::output_adapter o) { binary_writer(o).write_bson(j); } /// @brief create a BSON serialization of a given JSON value /// @sa https://json.nlohmann.me/api/basic_json/to_bson/ static void to_bson(const basic_json& j, detail::output_adapter o) { binary_writer(o).write_bson(j); } /// @brief create a JSON value from an input in CBOR format /// @sa https://json.nlohmann.me/api/basic_json/from_cbor/ template JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json from_cbor(InputType&& i, const bool strict = true, const bool allow_exceptions = true, const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) { basic_json result; detail::json_sax_dom_parser sdp(result, allow_exceptions); auto ia = detail::input_adapter(std::forward(i)); const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); return res ? result : basic_json(value_t::discarded); } /// @brief create a JSON value from an input in CBOR format /// @sa https://json.nlohmann.me/api/basic_json/from_cbor/ template JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json from_cbor(IteratorType first, IteratorType last, const bool strict = true, const bool allow_exceptions = true, const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) { basic_json result; detail::json_sax_dom_parser sdp(result, allow_exceptions); auto ia = detail::input_adapter(std::move(first), std::move(last)); const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); return res ? result : basic_json(value_t::discarded); } template JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len)) static basic_json from_cbor(const T* ptr, std::size_t len, const bool strict = true, const bool allow_exceptions = true, const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) { return from_cbor(ptr, ptr + len, strict, allow_exceptions, tag_handler); } JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len)) static basic_json from_cbor(detail::span_input_adapter&& i, const bool strict = true, const bool allow_exceptions = true, const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) { basic_json result; detail::json_sax_dom_parser sdp(result, allow_exceptions); auto ia = i.get(); // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); return res ? result : basic_json(value_t::discarded); } /// @brief create a JSON value from an input in MessagePack format /// @sa https://json.nlohmann.me/api/basic_json/from_msgpack/ template JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json from_msgpack(InputType&& i, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser sdp(result, allow_exceptions); auto ia = detail::input_adapter(std::forward(i)); const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /// @brief create a JSON value from an input in MessagePack format /// @sa https://json.nlohmann.me/api/basic_json/from_msgpack/ template JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json from_msgpack(IteratorType first, IteratorType last, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser sdp(result, allow_exceptions); auto ia = detail::input_adapter(std::move(first), std::move(last)); const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); return res ? result : basic_json(value_t::discarded); } template JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len)) static basic_json from_msgpack(const T* ptr, std::size_t len, const bool strict = true, const bool allow_exceptions = true) { return from_msgpack(ptr, ptr + len, strict, allow_exceptions); } JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len)) static basic_json from_msgpack(detail::span_input_adapter&& i, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser sdp(result, allow_exceptions); auto ia = i.get(); // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /// @brief create a JSON value from an input in UBJSON format /// @sa https://json.nlohmann.me/api/basic_json/from_ubjson/ template JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json from_ubjson(InputType&& i, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser sdp(result, allow_exceptions); auto ia = detail::input_adapter(std::forward(i)); const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /// @brief create a JSON value from an input in UBJSON format /// @sa https://json.nlohmann.me/api/basic_json/from_ubjson/ template JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json from_ubjson(IteratorType first, IteratorType last, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser sdp(result, allow_exceptions); auto ia = detail::input_adapter(std::move(first), std::move(last)); const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); return res ? result : basic_json(value_t::discarded); } template JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len)) static basic_json from_ubjson(const T* ptr, std::size_t len, const bool strict = true, const bool allow_exceptions = true) { return from_ubjson(ptr, ptr + len, strict, allow_exceptions); } JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len)) static basic_json from_ubjson(detail::span_input_adapter&& i, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser sdp(result, allow_exceptions); auto ia = i.get(); // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /// @brief create a JSON value from an input in BSON format /// @sa https://json.nlohmann.me/api/basic_json/from_bson/ template JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json from_bson(InputType&& i, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser sdp(result, allow_exceptions); auto ia = detail::input_adapter(std::forward(i)); const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /// @brief create a JSON value from an input in BSON format /// @sa https://json.nlohmann.me/api/basic_json/from_bson/ template JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json from_bson(IteratorType first, IteratorType last, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser sdp(result, allow_exceptions); auto ia = detail::input_adapter(std::move(first), std::move(last)); const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); return res ? result : basic_json(value_t::discarded); } template JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len)) static basic_json from_bson(const T* ptr, std::size_t len, const bool strict = true, const bool allow_exceptions = true) { return from_bson(ptr, ptr + len, strict, allow_exceptions); } JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len)) static basic_json from_bson(detail::span_input_adapter&& i, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser sdp(result, allow_exceptions); auto ia = i.get(); // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /// @} ////////////////////////// // JSON Pointer support // ////////////////////////// /// @name JSON Pointer functions /// @{ /// @brief access specified element via JSON Pointer /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ reference operator[](const json_pointer& ptr) { return ptr.get_unchecked(this); } /// @brief access specified element via JSON Pointer /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ const_reference operator[](const json_pointer& ptr) const { return ptr.get_unchecked(this); } /// @brief access specified element via JSON Pointer /// @sa https://json.nlohmann.me/api/basic_json/at/ reference at(const json_pointer& ptr) { return ptr.get_checked(this); } /// @brief access specified element via JSON Pointer /// @sa https://json.nlohmann.me/api/basic_json/at/ const_reference at(const json_pointer& ptr) const { return ptr.get_checked(this); } /// @brief return flattened JSON value /// @sa https://json.nlohmann.me/api/basic_json/flatten/ basic_json flatten() const { basic_json result(value_t::object); json_pointer::flatten("", *this, result); return result; } /// @brief unflatten a previously flattened JSON value /// @sa https://json.nlohmann.me/api/basic_json/unflatten/ basic_json unflatten() const { return json_pointer::unflatten(*this); } /// @} ////////////////////////// // JSON Patch functions // ////////////////////////// /// @name JSON Patch functions /// @{ /// @brief applies a JSON patch /// @sa https://json.nlohmann.me/api/basic_json/patch/ basic_json patch(const basic_json& json_patch) const { // make a working copy to apply the patch to basic_json result = *this; // the valid JSON Patch operations enum class patch_operations {add, remove, replace, move, copy, test, invalid}; const auto get_op = [](const std::string & op) { if (op == "add") { return patch_operations::add; } if (op == "remove") { return patch_operations::remove; } if (op == "replace") { return patch_operations::replace; } if (op == "move") { return patch_operations::move; } if (op == "copy") { return patch_operations::copy; } if (op == "test") { return patch_operations::test; } return patch_operations::invalid; }; // wrapper for "add" operation; add value at ptr const auto operation_add = [&result](json_pointer & ptr, basic_json val) { // adding to the root of the target document means replacing it if (ptr.empty()) { result = val; return; } // make sure the top element of the pointer exists json_pointer top_pointer = ptr.top(); if (top_pointer != ptr) { result.at(top_pointer); } // get reference to parent of JSON pointer ptr const auto last_path = ptr.back(); ptr.pop_back(); basic_json& parent = result[ptr]; switch (parent.m_type) { case value_t::null: case value_t::object: { // use operator[] to add value parent[last_path] = val; break; } case value_t::array: { if (last_path == "-") { // special case: append to back parent.push_back(val); } else { const auto idx = json_pointer::array_index(last_path); if (JSON_HEDLEY_UNLIKELY(idx > parent.size())) { // avoid undefined behavior JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", parent)); } // default case: insert add offset parent.insert(parent.begin() + static_cast(idx), val); } break; } // if there exists a parent it cannot be primitive case value_t::string: // LCOV_EXCL_LINE case value_t::boolean: // LCOV_EXCL_LINE case value_t::number_integer: // LCOV_EXCL_LINE case value_t::number_unsigned: // LCOV_EXCL_LINE case value_t::number_float: // LCOV_EXCL_LINE case value_t::binary: // LCOV_EXCL_LINE case value_t::discarded: // LCOV_EXCL_LINE default: // LCOV_EXCL_LINE JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE } }; // wrapper for "remove" operation; remove value at ptr const auto operation_remove = [this, &result](json_pointer & ptr) { // get reference to parent of JSON pointer ptr const auto last_path = ptr.back(); ptr.pop_back(); basic_json& parent = result.at(ptr); // remove child if (parent.is_object()) { // perform range check auto it = parent.find(last_path); if (JSON_HEDLEY_LIKELY(it != parent.end())) { parent.erase(it); } else { JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found", *this)); } } else if (parent.is_array()) { // note erase performs range check parent.erase(json_pointer::array_index(last_path)); } }; // type check: top level value must be an array if (JSON_HEDLEY_UNLIKELY(!json_patch.is_array())) { JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", json_patch)); } // iterate and apply the operations for (const auto& val : json_patch) { // wrapper to get a value for an operation const auto get_value = [&val](const std::string & op, const std::string & member, bool string_type) -> basic_json & { // find value auto it = val.m_value.object->find(member); // context-sensitive error message const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'"; // check if desired value is present if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end())) { // NOLINTNEXTLINE(performance-inefficient-string-concatenation) JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'", val)); } // check if result is of type string if (JSON_HEDLEY_UNLIKELY(string_type && !it->second.is_string())) { // NOLINTNEXTLINE(performance-inefficient-string-concatenation) JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'", val)); } // no error: return value return it->second; }; // type check: every element of the array must be an object if (JSON_HEDLEY_UNLIKELY(!val.is_object())) { JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", val)); } // collect mandatory members const auto op = get_value("op", "op", true).template get(); const auto path = get_value(op, "path", true).template get(); json_pointer ptr(path); switch (get_op(op)) { case patch_operations::add: { operation_add(ptr, get_value("add", "value", false)); break; } case patch_operations::remove: { operation_remove(ptr); break; } case patch_operations::replace: { // the "path" location must exist - use at() result.at(ptr) = get_value("replace", "value", false); break; } case patch_operations::move: { const auto from_path = get_value("move", "from", true).template get(); json_pointer from_ptr(from_path); // the "from" location must exist - use at() basic_json v = result.at(from_ptr); // The move operation is functionally identical to a // "remove" operation on the "from" location, followed // immediately by an "add" operation at the target // location with the value that was just removed. operation_remove(from_ptr); operation_add(ptr, v); break; } case patch_operations::copy: { const auto from_path = get_value("copy", "from", true).template get(); const json_pointer from_ptr(from_path); // the "from" location must exist - use at() basic_json v = result.at(from_ptr); // The copy is functionally identical to an "add" // operation at the target location using the value // specified in the "from" member. operation_add(ptr, v); break; } case patch_operations::test: { bool success = false; JSON_TRY { // check if "value" matches the one at "path" // the "path" location must exist - use at() success = (result.at(ptr) == get_value("test", "value", false)); } JSON_INTERNAL_CATCH (out_of_range&) { // ignore out of range errors: success remains false } // throw an exception if test fails if (JSON_HEDLEY_UNLIKELY(!success)) { JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump(), val)); } break; } case patch_operations::invalid: default: { // op must be "add", "remove", "replace", "move", "copy", or // "test" JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid", val)); } } } return result; } /// @brief creates a diff as a JSON patch /// @sa https://json.nlohmann.me/api/basic_json/diff/ JSON_HEDLEY_WARN_UNUSED_RESULT static basic_json diff(const basic_json& source, const basic_json& target, const std::string& path = "") { // the patch basic_json result(value_t::array); // if the values are the same, return empty patch if (source == target) { return result; } if (source.type() != target.type()) { // different types: replace value result.push_back( { {"op", "replace"}, {"path", path}, {"value", target} }); return result; } switch (source.type()) { case value_t::array: { // first pass: traverse common elements std::size_t i = 0; while (i < source.size() && i < target.size()) { // recursive call to compare array values at index i auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i)); result.insert(result.end(), temp_diff.begin(), temp_diff.end()); ++i; } // We now reached the end of at least one array // in a second pass, traverse the remaining elements // remove my remaining elements const auto end_index = static_cast(result.size()); while (i < source.size()) { // add operations in reverse order to avoid invalid // indices result.insert(result.begin() + end_index, object( { {"op", "remove"}, {"path", path + "/" + std::to_string(i)} })); ++i; } // add other remaining elements while (i < target.size()) { result.push_back( { {"op", "add"}, {"path", path + "/-"}, {"value", target[i]} }); ++i; } break; } case value_t::object: { // first pass: traverse this object's elements for (auto it = source.cbegin(); it != source.cend(); ++it) { // escape the key name to be used in a JSON patch const auto path_key = path + "/" + detail::escape(it.key()); if (target.find(it.key()) != target.end()) { // recursive call to compare object values at key it auto temp_diff = diff(it.value(), target[it.key()], path_key); result.insert(result.end(), temp_diff.begin(), temp_diff.end()); } else { // found a key that is not in o -> remove it result.push_back(object( { {"op", "remove"}, {"path", path_key} })); } } // second pass: traverse other object's elements for (auto it = target.cbegin(); it != target.cend(); ++it) { if (source.find(it.key()) == source.end()) { // found a key that is not in this -> add it const auto path_key = path + "/" + detail::escape(it.key()); result.push_back( { {"op", "add"}, {"path", path_key}, {"value", it.value()} }); } } break; } case value_t::null: case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: { // both primitive type: replace value result.push_back( { {"op", "replace"}, {"path", path}, {"value", target} }); break; } } return result; } /// @} //////////////////////////////// // JSON Merge Patch functions // //////////////////////////////// /// @name JSON Merge Patch functions /// @{ /// @brief applies a JSON Merge Patch /// @sa https://json.nlohmann.me/api/basic_json/merge_patch/ void merge_patch(const basic_json& apply_patch) { if (apply_patch.is_object()) { if (!is_object()) { *this = object(); } for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it) { if (it.value().is_null()) { erase(it.key()); } else { operator[](it.key()).merge_patch(it.value()); } } } else { *this = apply_patch; } } /// @} }; /// @brief user-defined to_string function for JSON values /// @sa https://json.nlohmann.me/api/basic_json/to_string/ NLOHMANN_BASIC_JSON_TPL_DECLARATION std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j) { return j.dump(); } } // namespace nlohmann /////////////////////// // nonmember support // /////////////////////// namespace std // NOLINT(cert-dcl58-cpp) { /// @brief hash value for JSON objects /// @sa https://json.nlohmann.me/api/basic_json/std_hash/ NLOHMANN_BASIC_JSON_TPL_DECLARATION struct hash { std::size_t operator()(const nlohmann::NLOHMANN_BASIC_JSON_TPL& j) const { return nlohmann::detail::hash(j); } }; // specialization for std::less template<> struct less< ::nlohmann::detail::value_t> // do not remove the space after '<', see https://github.com/nlohmann/json/pull/679 { /*! @brief compare two value_t enum values @since version 3.0.0 */ bool operator()(nlohmann::detail::value_t lhs, nlohmann::detail::value_t rhs) const noexcept { return nlohmann::detail::operator<(lhs, rhs); } }; // C++20 prohibit function specialization in the std namespace. #ifndef JSON_HAS_CPP_20 /// @brief exchanges the values of two JSON objects /// @sa https://json.nlohmann.me/api/basic_json/std_swap/ NLOHMANN_BASIC_JSON_TPL_DECLARATION inline void swap(nlohmann::NLOHMANN_BASIC_JSON_TPL& j1, nlohmann::NLOHMANN_BASIC_JSON_TPL& j2) noexcept( // NOLINT(readability-inconsistent-declaration-parameter-name) is_nothrow_move_constructible::value&& // NOLINT(misc-redundant-expression) is_nothrow_move_assignable::value) { j1.swap(j2); } #endif } // namespace std /// @brief user-defined string literal for JSON values /// @sa https://json.nlohmann.me/api/basic_json/operator_literal_json/ JSON_HEDLEY_NON_NULL(1) inline nlohmann::json operator "" _json(const char* s, std::size_t n) { return nlohmann::json::parse(s, s + n); } /// @brief user-defined string literal for JSON pointer /// @sa https://json.nlohmann.me/api/basic_json/operator_literal_json_pointer/ JSON_HEDLEY_NON_NULL(1) inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n) { return nlohmann::json::json_pointer(std::string(s, n)); } // #include // restore clang diagnostic settings #if defined(__clang__) #pragma clang diagnostic pop #endif // clean up #undef JSON_ASSERT #undef JSON_INTERNAL_CATCH #undef JSON_CATCH #undef JSON_THROW #undef JSON_TRY #undef JSON_PRIVATE_UNLESS_TESTED #undef JSON_HAS_CPP_11 #undef JSON_HAS_CPP_14 #undef JSON_HAS_CPP_17 #undef JSON_HAS_CPP_20 #undef JSON_HAS_FILESYSTEM #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION #undef NLOHMANN_BASIC_JSON_TPL #undef JSON_EXPLICIT #undef NLOHMANN_CAN_CALL_STD_FUNC_IMPL // #include #undef JSON_HEDLEY_ALWAYS_INLINE #undef JSON_HEDLEY_ARM_VERSION #undef JSON_HEDLEY_ARM_VERSION_CHECK #undef JSON_HEDLEY_ARRAY_PARAM #undef JSON_HEDLEY_ASSUME #undef JSON_HEDLEY_BEGIN_C_DECLS #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE #undef JSON_HEDLEY_CLANG_HAS_BUILTIN #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE #undef JSON_HEDLEY_CLANG_HAS_EXTENSION #undef JSON_HEDLEY_CLANG_HAS_FEATURE #undef JSON_HEDLEY_CLANG_HAS_WARNING #undef JSON_HEDLEY_COMPCERT_VERSION #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK #undef JSON_HEDLEY_CONCAT #undef JSON_HEDLEY_CONCAT3 #undef JSON_HEDLEY_CONCAT3_EX #undef JSON_HEDLEY_CONCAT_EX #undef JSON_HEDLEY_CONST #undef JSON_HEDLEY_CONSTEXPR #undef JSON_HEDLEY_CONST_CAST #undef JSON_HEDLEY_CPP_CAST #undef JSON_HEDLEY_CRAY_VERSION #undef JSON_HEDLEY_CRAY_VERSION_CHECK #undef JSON_HEDLEY_C_DECL #undef JSON_HEDLEY_DEPRECATED #undef JSON_HEDLEY_DEPRECATED_FOR #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION #undef JSON_HEDLEY_DIAGNOSTIC_POP #undef JSON_HEDLEY_DIAGNOSTIC_PUSH #undef JSON_HEDLEY_DMC_VERSION #undef JSON_HEDLEY_DMC_VERSION_CHECK #undef JSON_HEDLEY_EMPTY_BASES #undef JSON_HEDLEY_EMSCRIPTEN_VERSION #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK #undef JSON_HEDLEY_END_C_DECLS #undef JSON_HEDLEY_FLAGS #undef JSON_HEDLEY_FLAGS_CAST #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE #undef JSON_HEDLEY_GCC_HAS_BUILTIN #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE #undef JSON_HEDLEY_GCC_HAS_EXTENSION #undef JSON_HEDLEY_GCC_HAS_FEATURE #undef JSON_HEDLEY_GCC_HAS_WARNING #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK #undef JSON_HEDLEY_GCC_VERSION #undef JSON_HEDLEY_GCC_VERSION_CHECK #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE #undef JSON_HEDLEY_GNUC_HAS_BUILTIN #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE #undef JSON_HEDLEY_GNUC_HAS_EXTENSION #undef JSON_HEDLEY_GNUC_HAS_FEATURE #undef JSON_HEDLEY_GNUC_HAS_WARNING #undef JSON_HEDLEY_GNUC_VERSION #undef JSON_HEDLEY_GNUC_VERSION_CHECK #undef JSON_HEDLEY_HAS_ATTRIBUTE #undef JSON_HEDLEY_HAS_BUILTIN #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE #undef JSON_HEDLEY_HAS_EXTENSION #undef JSON_HEDLEY_HAS_FEATURE #undef JSON_HEDLEY_HAS_WARNING #undef JSON_HEDLEY_IAR_VERSION #undef JSON_HEDLEY_IAR_VERSION_CHECK #undef JSON_HEDLEY_IBM_VERSION #undef JSON_HEDLEY_IBM_VERSION_CHECK #undef JSON_HEDLEY_IMPORT #undef JSON_HEDLEY_INLINE #undef JSON_HEDLEY_INTEL_CL_VERSION #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK #undef JSON_HEDLEY_INTEL_VERSION #undef JSON_HEDLEY_INTEL_VERSION_CHECK #undef JSON_HEDLEY_IS_CONSTANT #undef JSON_HEDLEY_IS_CONSTEXPR_ #undef JSON_HEDLEY_LIKELY #undef JSON_HEDLEY_MALLOC #undef JSON_HEDLEY_MCST_LCC_VERSION #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK #undef JSON_HEDLEY_MESSAGE #undef JSON_HEDLEY_MSVC_VERSION #undef JSON_HEDLEY_MSVC_VERSION_CHECK #undef JSON_HEDLEY_NEVER_INLINE #undef JSON_HEDLEY_NON_NULL #undef JSON_HEDLEY_NO_ESCAPE #undef JSON_HEDLEY_NO_RETURN #undef JSON_HEDLEY_NO_THROW #undef JSON_HEDLEY_NULL #undef JSON_HEDLEY_PELLES_VERSION #undef JSON_HEDLEY_PELLES_VERSION_CHECK #undef JSON_HEDLEY_PGI_VERSION #undef JSON_HEDLEY_PGI_VERSION_CHECK #undef JSON_HEDLEY_PREDICT #undef JSON_HEDLEY_PRINTF_FORMAT #undef JSON_HEDLEY_PRIVATE #undef JSON_HEDLEY_PUBLIC #undef JSON_HEDLEY_PURE #undef JSON_HEDLEY_REINTERPRET_CAST #undef JSON_HEDLEY_REQUIRE #undef JSON_HEDLEY_REQUIRE_CONSTEXPR #undef JSON_HEDLEY_REQUIRE_MSG #undef JSON_HEDLEY_RESTRICT #undef JSON_HEDLEY_RETURNS_NON_NULL #undef JSON_HEDLEY_SENTINEL #undef JSON_HEDLEY_STATIC_ASSERT #undef JSON_HEDLEY_STATIC_CAST #undef JSON_HEDLEY_STRINGIFY #undef JSON_HEDLEY_STRINGIFY_EX #undef JSON_HEDLEY_SUNPRO_VERSION #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK #undef JSON_HEDLEY_TINYC_VERSION #undef JSON_HEDLEY_TINYC_VERSION_CHECK #undef JSON_HEDLEY_TI_ARMCL_VERSION #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK #undef JSON_HEDLEY_TI_CL2000_VERSION #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK #undef JSON_HEDLEY_TI_CL430_VERSION #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK #undef JSON_HEDLEY_TI_CL6X_VERSION #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK #undef JSON_HEDLEY_TI_CL7X_VERSION #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK #undef JSON_HEDLEY_TI_CLPRU_VERSION #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK #undef JSON_HEDLEY_TI_VERSION #undef JSON_HEDLEY_TI_VERSION_CHECK #undef JSON_HEDLEY_UNAVAILABLE #undef JSON_HEDLEY_UNLIKELY #undef JSON_HEDLEY_UNPREDICTABLE #undef JSON_HEDLEY_UNREACHABLE #undef JSON_HEDLEY_UNREACHABLE_RETURN #undef JSON_HEDLEY_VERSION #undef JSON_HEDLEY_VERSION_DECODE_MAJOR #undef JSON_HEDLEY_VERSION_DECODE_MINOR #undef JSON_HEDLEY_VERSION_DECODE_REVISION #undef JSON_HEDLEY_VERSION_ENCODE #undef JSON_HEDLEY_WARNING #undef JSON_HEDLEY_WARN_UNUSED_RESULT #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG #undef JSON_HEDLEY_FALL_THROUGH #endif // INCLUDE_NLOHMANN_JSON_HPP_ ================================================ FILE: macloader.vcxproj ================================================ Debug Win32 Release Win32 Debug x64 Release x64 17.0 Win32Proj {6d6ac860-ba16-4be7-9169-21787f21cb6f} macloader 10.0 Application true v143 Unicode Application false v143 true Unicode Application true v143 Unicode Application false v143 true Unicode $(ProjectName)64 $(ProjectName)64 Level3 true WIN32;_DEBUG;_WINDOWS;USE_DETOURS;_GDIPP_EXE;%(PreprocessorDefinitions) Default MultiThreadedDebugDLL Windows true Level3 true true true WIN32;NDEBUG;_WINDOWS;USE_DETOURS;_GDIPP_EXE;%(PreprocessorDefinitions) Default MultiThreaded Windows true true true Level3 true _DEBUG;_WINDOWS;USE_DETOURS;_GDIPP_EXE;_WIN64;%(PreprocessorDefinitions) Default Windows true Level3 true true true NDEBUG;_WINDOWS;USE_DETOURS;_GDIPP_EXE;_WIN64;%(PreprocessorDefinitions) Default MultiThreaded Windows true true true ================================================ FILE: makelib.cmd ================================================ @echo off cl /c /MD /GA /GF /Gy /O2 /arch:SSE optimize/memcpy__amd.cpp optimize/memcpy_amd.c lib /machine:ix86 /out:memcpy_amd.lib memcpy__amd.obj memcpy_amd.obj ================================================ FILE: misc.cpp ================================================ #include "common.h" #include "settings.h" CRITICAL_SECTION CCriticalSectionLock::m_cs[20]; OWNED_CRITIAL_SECTION COwnedCriticalSectionLock::m_cs[2]; LONG CThreadCounter::interlock; //snowie!! C++还需要额外申明,汗 TCHAR CGdippSettings::m_szexeName[MAX_PATH+1] = {0}; #ifdef _UNICODE #undef CharPrev #define CharPrev(s, c) ((c) - 1) #endif //手抜きのパス操作関数群 BOOL WINAPI PathIsRelative(LPCTSTR pszPath) { if (!pszPath || !*pszPath) { return FALSE; } const TCHAR ch1 = pszPath[0]; const TCHAR ch2 = pszPath[1]; if (ch1 == _T('\\') && ch2 == _T('\\')) { //UNC return FALSE; } if (ch1 == _T('\\') || (ch1 && ch2 == _T(':'))) { //絶対パス return FALSE; } return TRUE; } BOOL WINAPI PathRemoveFileSpec(LPTSTR pszPath) { if (!pszPath) { return FALSE; } LPTSTR p = pszPath + _tcslen(pszPath); while (p >= pszPath) { switch (*p) { case _T('\\'): case _T('/'): if (p > pszPath) { //c:\aaa -> c:\ < //c:\ -> c:\ < switch (*(p - 1)) { case _T('\\'): case _T('/'): case _T(':'): break; default: goto END; } } case _T(':'): // c:aaa -> c: p++; goto END; } if (p <= pszPath) { break; } p = CharPrev(NULL, p); } END: if (*p) { *p = _T('\0'); return TRUE; } return FALSE; } LPTSTR WINAPI PathFindExtension(LPCTSTR pszPath) { if (!pszPath) { return NULL; } LPCTSTR p, pszEnd; p = pszEnd = pszPath + _tcslen(pszPath); while (p > pszPath) { switch (*p) { case _T('.'): return (LPTSTR)p; case _T('\\'): case _T('/'): case _T(':'): return (LPTSTR)pszEnd; } p = CharPrev(pszPath, p); } return (LPTSTR)pszEnd; } LPTSTR WINAPI PathAddBackslash(LPTSTR pszPath) { if (!pszPath) { return NULL; } int cch = _tcslen(pszPath); if (cch + 1 >= MAX_PATH) { return NULL; } LPTSTR p = pszPath + cch; switch (*CharPrev(pszPath, p)) { case _T('\\'): case _T('/'): break; default: p[0] = _T('\\'); p[1] = _T('\0'); break; } return pszPath; } LPTSTR WINAPI PathCombine(LPTSTR pszDest, LPCTSTR pszDir, LPCTSTR pszFile) { if (!pszDest || !pszDir || !pszFile) { return NULL; } //かなり手抜き TCHAR szCurDir[MAX_PATH], szDir[MAX_PATH+1]; GetCurrentDirectory(MAX_PATH, szCurDir); _tcsncpy(szDir, pszDir, MAX_PATH - 1); szDir[MAX_PATH - 1] = _T('\0'); PathAddBackslash(szDir); if (!SetCurrentDirectory(szDir)) { *pszDest = _T('\0'); return NULL; } TCHAR szFile[MAX_PATH]; _tcsncpy(szFile, pszFile, MAX_PATH - 1); szFile[MAX_PATH - 1] = _T('\0'); GetFullPathName(szFile, MAX_PATH, pszDest, NULL); SetCurrentDirectory(szCurDir); TRACE(_T("PathCombine: %s\n"), pszDest); return pszDest; } LPWSTR _StrDupExAtoW(LPCSTR pszMB, int cchMB /*= -1*/, LPWSTR pszStack /*= NULL*/, int cchStack /*= 0*/, int* pcchWC /*= NULL*/, int nACP) { int _cchWC; if (!pcchWC) { pcchWC = &_cchWC; } *pcchWC = 0; if (!pszMB) { return NULL; } if (cchMB == -1) { cchMB = strlen(pszMB); } const int cchWC = MultiByteToWideChar(nACP, 0, pszMB, cchMB, NULL, 0); if(cchWC < 0) { return NULL; } LPWSTR pszWC; if(cchWC < cchStack && pszStack) { pszWC = pszStack; ZeroMemory(pszWC, sizeof(WCHAR) * (cchWC + 1)); } else { pszWC = (LPWSTR)calloc(sizeof(WCHAR), cchWC + 1); if (!pszWC) { return NULL; } } MultiByteToWideChar(nACP, 0, pszMB, cchMB, pszWC, cchWC); pszWC[cchWC] = L'\0'; *pcchWC = cchWC; return pszWC; } #ifdef _DEBUG typedef struct { LPCSTR name; UINT flag; UINT mask; UINT xor; } FLAG_NAME_MAP; #define DEF_FLAG_NAME(f,m,x) { #f, f, m, x } #define END_FLAG() { NULL } LPCSTR Dbg_GetFlagNames(UINT flags, const FLAG_NAME_MAP* p, LPSTR worker) { if (!worker) return ""; if (!flags || !p) return "0"; LPSTR wk = worker; *wk = '\0'; while (p->name) { if (((flags & p->mask) ^ p->xor) == p->flag) { if (wk != worker) { memcpy(wk, " | ", 4); wk += 3; } strcpy(wk, p->name); wk += strlen(p->name); flags &= ~p->mask; } p++; } if (flags) { if (wk != worker) { memcpy(wk, " | ", 4); wk += 3; } sprintf(wk, "%04X", flags); } return *worker ? worker : "0"; } void Dbg_TraceExtTextOutW(int nXStart, int nYStart, UINT fuOptions, LPCWSTR lpString, int cbString, const int* lpDx) { LPWSTR p; if (fuOptions & ETO_GLYPH_INDEX) { p = (LPWSTR)_alloca((cbString * 5 + 1) * sizeof(WCHAR)); LPWSTR q = p; for (int i = 0; i < cbString; ++i) { q += wsprintf(q, _T(" %04X"), lpString[i]); } } else { p = (LPWSTR)_alloca((cbString + 1) * sizeof(WCHAR)); memcpy(p, lpString, cbString * sizeof(WCHAR)); p[cbString] = 0; } static const FLAG_NAME_MAP c_map[] = { DEF_FLAG_NAME(ETO_OPAQUE, ETO_OPAQUE, 0), DEF_FLAG_NAME(ETO_CLIPPED, ETO_CLIPPED, 0), DEF_FLAG_NAME(ETO_GLYPH_INDEX, ETO_GLYPH_INDEX, 0), DEF_FLAG_NAME(ETO_RTLREADING, ETO_RTLREADING, 0), DEF_FLAG_NAME(ETO_NUMERICSLOCAL, ETO_NUMERICSLOCAL, 0), DEF_FLAG_NAME(ETO_NUMERICSLATIN, ETO_NUMERICSLATIN, 0), DEF_FLAG_NAME(ETO_IGNORELANGUAGE, ETO_IGNORELANGUAGE, 0), DEF_FLAG_NAME(ETO_PDY, ETO_PDY, 0), END_FLAG(), }; CHAR wk[1024]; TRACE(_T("ExtTextOutW(%d, %d, %hs, \"%ls\", %d, %hs)\n") , nXStart, nYStart, Dbg_GetFlagNames(fuOptions, c_map, wk), p, cbString, lpDx ? "{...}" : "NULL"); } void Dbg_TraceScriptItemize(const WCHAR* pwcInChars, int cInChars) { LPWSTR p = (LPWSTR)_alloca((cInChars + 1) * sizeof(WCHAR)); memcpy(p, pwcInChars, cInChars * sizeof(WCHAR)); p[cInChars] = 0; TRACE(_T("ScriptItemize(\"%ls\", %d)\n"), p, cInChars); } void Dbg_TraceScriptShape(const WCHAR* pwcChars, int cChars, const SCRIPT_ANALYSIS* psa, const WORD* pwOutGlyphs, int cGlyphs) { LPWSTR pc = (LPWSTR)_alloca((cChars + 1) * sizeof(WCHAR)); memcpy(pc, pwcChars, cChars * sizeof(WCHAR)); pc[cChars] = 0; LPWSTR pg; if (pwOutGlyphs) { if (psa->fNoGlyphIndex) { pg = (LPWSTR)_alloca((cGlyphs + 1) * sizeof(WCHAR)); memcpy(pg, pwOutGlyphs, cGlyphs * sizeof(WCHAR)); pg[cGlyphs] = 0; } else { pg = (LPWSTR)_alloca((cGlyphs * 5 + 1) * sizeof(WCHAR)); LPWSTR q = pg; for (int i = 0; i < cGlyphs; ++i) { q += wsprintf(q, _T(" %04X"), pwOutGlyphs[i]); } } } TRACE(_T("ScriptShape(\"%ls\", %d, Script=%d%S%S%S%S%S%S, BidiLevel=%d%S%S%S%S%S%S%S%S"), pc, cChars, psa->eScript, psa->fRTL ? ", RTL" : "", psa->fLayoutRTL ? ", LayoutRTL" : "", psa->fLinkBefore ? ", LinkBefore" : "", psa->fLinkAfter ? ", LinkAfter" : "", psa->fLogicalOrder ? ", LogicalOrder" : "", psa->fNoGlyphIndex ? ", NoGlyphIndex" : "", psa->s.uBidiLevel, psa->s.fOverrideDirection ? ", OverrideDirection" : "", psa->s.fInhibitSymSwap ? ", InhibitSymSwap" : "", psa->s.fCharShape ? ", CharShape" : "", psa->s.fDigitSubstitute ? ", DigitSubstitute" : "", psa->s.fInhibitLigate ? ", InhibitLigate" : "", psa->s.fDisplayZWG ? ", DisplayZWG" : "", psa->s.fArabicNumContext ? ", ArabicNumContext" : "", psa->s.fGcpClusters ? ", GcpClusters" : "" ); if (pwOutGlyphs) { TRACE(_T(", \"%ls\", %d"), pg, cGlyphs); } TRACE(_T(")\n")); } void Dbg_TractGetTextExtent(LPCSTR lpString, int cbString, LPSIZE lpSize) { LPSTR p = (LPSTR)_alloca((cbString + 1) * sizeof(CHAR)); memcpy(p, lpString, cbString * sizeof(CHAR)); p[cbString] = 0; TRACE(_T("GetTextExtentA(\"%hs\", %d) = { %d, %d }\n") , p, cbString, lpSize->cx, lpSize->cy); } void Dbg_TractGetTextExtent(LPCWSTR lpString, int cbString, LPSIZE lpSize) { LPWSTR p = (LPWSTR)_alloca((cbString + 1) * sizeof(WCHAR)); memcpy(p, lpString, cbString * sizeof(WCHAR)); p[cbString] = 0; TRACE(_T("GetTextExtentW(\"%ls\", %d) = { %d, %d }\n") , p, cbString, lpSize->cx, lpSize->cy); } #endif ================================================ FILE: optimize/UpgradeLog.XML ================================================ ================================================ FILE: optimize/UpgradeLog2.XML ================================================ ================================================ FILE: optimize/_UpgradeReport_Files/UpgradeReport.css ================================================ BODY { BACKGROUND-COLOR: white; FONT-FAMILY: "Verdana", sans-serif; FONT-SIZE: 100%; MARGIN-LEFT: 0px; MARGIN-TOP: 0px } P { FONT-FAMILY: "Verdana", sans-serif; FONT-SIZE: 70%; LINE-HEIGHT: 12pt; MARGIN-BOTTOM: 0px; MARGIN-LEFT: 10px; MARGIN-TOP: 10px } .note { BACKGROUND-COLOR: #ffffff; COLOR: #336699; FONT-FAMILY: "Verdana", sans-serif; FONT-SIZE: 100%; MARGIN-BOTTOM: 0px; MARGIN-LEFT: 0px; MARGIN-TOP: 0px; PADDING-RIGHT: 10px } .infotable { BACKGROUND-COLOR: #f0f0e0; BORDER-BOTTOM: #ffffff 0px solid; BORDER-COLLAPSE: collapse; BORDER-LEFT: #ffffff 0px solid; BORDER-RIGHT: #ffffff 0px solid; BORDER-TOP: #ffffff 0px solid; FONT-SIZE: 70%; MARGIN-LEFT: 10px } .issuetable { BACKGROUND-COLOR: #ffffe8; BORDER-COLLAPSE: collapse; COLOR: #000000; FONT-SIZE: 100%; MARGIN-BOTTOM: 10px; MARGIN-LEFT: 13px; MARGIN-TOP: 0px } .issuetitle { BACKGROUND-COLOR: #ffffff; BORDER-BOTTOM: #dcdcdc 1px solid; BORDER-TOP: #dcdcdc 1px; COLOR: #003366; FONT-WEIGHT: normal } .header { BACKGROUND-COLOR: #cecf9c; BORDER-BOTTOM: #ffffff 1px solid; BORDER-LEFT: #ffffff 1px solid; BORDER-RIGHT: #ffffff 1px solid; BORDER-TOP: #ffffff 1px solid; COLOR: #000000; FONT-WEIGHT: bold } .issuehdr { BACKGROUND-COLOR: #E0EBF5; BORDER-BOTTOM: #dcdcdc 1px solid; BORDER-TOP: #dcdcdc 1px solid; COLOR: #000000; FONT-WEIGHT: normal } .issuenone { BACKGROUND-COLOR: #ffffff; BORDER-BOTTOM: 0px; BORDER-LEFT: 0px; BORDER-RIGHT: 0px; BORDER-TOP: 0px; COLOR: #000000; FONT-WEIGHT: normal } .content { BACKGROUND-COLOR: #e7e7ce; BORDER-BOTTOM: #ffffff 1px solid; BORDER-LEFT: #ffffff 1px solid; BORDER-RIGHT: #ffffff 1px solid; BORDER-TOP: #ffffff 1px solid; PADDING-LEFT: 3px } .issuecontent { BACKGROUND-COLOR: #ffffff; BORDER-BOTTOM: #dcdcdc 1px solid; BORDER-TOP: #dcdcdc 1px solid; PADDING-LEFT: 3px } A:link { COLOR: #cc6633; TEXT-DECORATION: underline } A:visited { COLOR: #cc6633; } A:active { COLOR: #cc6633; } A:hover { COLOR: #cc3300; TEXT-DECORATION: underline } H1 { BACKGROUND-COLOR: #003366; BORDER-BOTTOM: #336699 6px solid; COLOR: #ffffff; FONT-SIZE: 130%; FONT-WEIGHT: normal; MARGIN: 0em 0em 0em -20px; PADDING-BOTTOM: 8px; PADDING-LEFT: 30px; PADDING-TOP: 16px } H2 { COLOR: #000000; FONT-SIZE: 80%; FONT-WEIGHT: bold; MARGIN-BOTTOM: 3px; MARGIN-LEFT: 10px; MARGIN-TOP: 20px; PADDING-LEFT: 0px } H3 { COLOR: #000000; FONT-SIZE: 80%; FONT-WEIGHT: bold; MARGIN-BOTTOM: -5px; MARGIN-LEFT: 10px; MARGIN-TOP: 20px } H4 { COLOR: #000000; FONT-SIZE: 70%; FONT-WEIGHT: bold; MARGIN-BOTTOM: 0px; MARGIN-TOP: 15px; PADDING-BOTTOM: 0px } UL { COLOR: #000000; FONT-SIZE: 70%; LIST-STYLE: square; MARGIN-BOTTOM: 0pt; MARGIN-TOP: 0pt } OL { COLOR: #000000; FONT-SIZE: 70%; LIST-STYLE: square; MARGIN-BOTTOM: 0pt; MARGIN-TOP: 0pt } LI { LIST-STYLE: square; MARGIN-LEFT: 0px } .expandable { CURSOR: hand } .expanded { color: black } .collapsed { DISPLAY: none } .foot { BACKGROUND-COLOR: #ffffff; BORDER-BOTTOM: #cecf9c 1px solid; BORDER-TOP: #cecf9c 2px solid } .settings { MARGIN-LEFT: 25PX; } .help { TEXT-ALIGN: right; margin-right: 10px; } ================================================ FILE: optimize/_UpgradeReport_Files/UpgradeReport.xslt ================================================

解决方案: 项目:

src
文件名 状态 错误 警告
javascript:document.images[''].click()src 已转换 已转换
个文件 1 个文件 已转换:
未转换:
: 转换报告 <xsl:if test="Properties/Property[@Name='LogNumber']"> <xsl:value-of select="Properties/Property[@Name='LogNumber']/@Value"/> </xsl:if>

转换报告 -

转换时间:

转换设置

================================================ FILE: optimize/mem_amd.icproj ================================================ ================================================ FILE: optimize/mem_amd.sln ================================================ Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mem_amd", "mem_amd.vcproj", "{40F90B68-74C8-4F1D-B302-0EB968CC271D}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 Release|Win32 = Release|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {40F90B68-74C8-4F1D-B302-0EB968CC271D}.Debug|Win32.ActiveCfg = Debug|Win32 {40F90B68-74C8-4F1D-B302-0EB968CC271D}.Debug|Win32.Build.0 = Debug|Win32 {40F90B68-74C8-4F1D-B302-0EB968CC271D}.Release|Win32.ActiveCfg = Release|Win32 {40F90B68-74C8-4F1D-B302-0EB968CC271D}.Release|Win32.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ================================================ FILE: optimize/mem_amd.sln_old ================================================ Microsoft Visual Studio Solution File, Format Version 8.00 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "mem_amd", "mem_amd.vcproj", "{40F90B68-74C8-4F1D-B302-0EB968CC271D}" ProjectSection(ProjectDependencies) = postProject EndProjectSection EndProject Global GlobalSection(SolutionConfiguration) = preSolution Debug = Debug Release = Release EndGlobalSection GlobalSection(ProjectDependencies) = postSolution EndGlobalSection GlobalSection(ProjectConfiguration) = postSolution {40F90B68-74C8-4F1D-B302-0EB968CC271D}.Debug.ActiveCfg = Debug|Win32 {40F90B68-74C8-4F1D-B302-0EB968CC271D}.Debug.Build.0 = Debug|Win32 {40F90B68-74C8-4F1D-B302-0EB968CC271D}.Release.ActiveCfg = Release|Win32 {40F90B68-74C8-4F1D-B302-0EB968CC271D}.Release.Build.0 = Release|Win32 EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution EndGlobalSection GlobalSection(ExtensibilityAddIns) = postSolution EndGlobalSection EndGlobal ================================================ FILE: optimize/mem_amd.vcproj ================================================ ================================================ FILE: optimize/memcpy__amd.cpp ================================================ /****************************************************************************** Copyright (c) 2001 Advanced Micro Devices, Inc. LIMITATION OF LIABILITY: THE MATERIALS ARE PROVIDED *AS IS* WITHOUT ANY EXPRESS OR IMPLIED WARRANTY OF ANY KIND INCLUDING WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT OF THIRD-PARTY INTELLECTUAL PROPERTY, OR FITNESS FOR ANY PARTICULAR PURPOSE. IN NO EVENT SHALL AMD OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF PROFITS, BUSINESS INTERRUPTION, LOSS OF INFORMATION) ARISING OUT OF THE USE OF OR INABILITY TO USE THE MATERIALS, EVEN IF AMD HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. BECAUSE SOME JURISDICTIONS PROHIBIT THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES, THE ABOVE LIMITATION MAY NOT APPLY TO YOU. AMD does not assume any responsibility for any errors which may appear in the Materials nor any responsibility to support or update the Materials. AMD retains the right to make changes to its test specifications at any time, without notice. NO SUPPORT OBLIGATION: AMD is not obligated to furnish, support, or make any further information, software, technical information, know-how, or show-how available to you. So that all may benefit from your experience, please report any problems or suggestions about this software to 3dsdk.support@amd.com AMD Developer Technologies, M/S 585 Advanced Micro Devices, Inc. 5900 E. Ben White Blvd. Austin, TX 78741 3dsdk.support@amd.com ******************************************************************************/ #pragma once #include "memcpy_amd.h" /***************************************************************************** MEMCPY_AMD.CPP ******************************************************************************/ // Very optimized memcpy() routine for all AMD Athlon and Duron family. // This code uses any of FOUR different basic copy methods, depending // on the transfer size. // NOTE: Since this code uses MOVNTQ (also known as "Non-Temporal MOV" or // "Streaming Store"), and also uses the software prefetchnta instructions, // be sure you're running on Athlon/Duron or other recent CPU before calling! #define IN_CACHE_COPY 64 * 1024 // upper limit for movq/movq copy w/SW prefetch // Next is a copy that uses the MMX registers to copy 8 bytes at a time, // also using the "unrolled loop" optimization. This code uses // the software prefetch instruction to get the data into the cache. #define UNCACHED_COPY 197 * 1024 // upper limit for movq/movntq w/SW prefetch // For larger blocks, which will spill beyond the cache, it's faster to // use the Streaming Store instruction MOVNTQ. This write instruction // bypasses the cache and writes straight to main memory. This code also // uses the software prefetch instruction to pre-read the data. // USE 64 * 1024 FOR THIS VALUE IF YOU'RE ALWAYS FILLING A "CLEAN CACHE" #define BLOCK_PREFETCH_COPY infinity // no limit for movq/movntq w/block prefetch #define CACHEBLOCK 80h // number of 64-byte blocks (cache lines) for block prefetch // For the largest size blocks, a special technique called Block Prefetch // can be used to accelerate the read operations. Block Prefetch reads // one address per cache line, for a series of cache lines, in a short loop. // This is faster than using software prefetch. The technique is great for // getting maximum read bandwidth, especially in DDR memory systems. // Inline assembly syntax for use with Visual C++ ///////////////////////////////////////////////////////////////////////////////////// // katsyonak: Added MMX & SSE optimized memcpy - October 8, 2003 // // // // katsyonak: Added AMD, MMX & SSE optimized memset - October 12, 2003 // // // // Aw3/katsyonak: Added AMD, MMX & SSE optimized memzero - February 11, 2004 // /////////////////////////////////////////////////////////////////////////////// static unsigned long CPU_Type = 0; // 0 = CPU check not performed yet (Auto detect) // 1 = No optimization // 2 = MMX // 3 = MMX2 for AMD Athlon/Duron and above (might also work on MMX2 (KATMAI) Intel machines) // 4 = SSE // 5 = SSE2 (only for Pentium 4 detection, the optimization used is SSE) unsigned long get_cpu_type() { __asm { mov eax, [CPU_Type] cmp eax, 5 ja do_detect or eax, eax jne ret_eax do_detect: xor eax, eax cpuid or eax, eax mov eax, 1 ;No optimization je cpu_done xor esi, esi cmp ebx, 68747541h ;Auth jne not_amd cmp edx, 69746E65h ;enti jne not_amd cmp ecx, 444D4163h ;cAMD jne not_amd inc esi not_amd: ;mov eax,1 cpuid mov al, 1 ;No optimization bt edx, 23 ;MMX Feature Bit jnb ret_al or esi, esi je check_sse and ah, 1111b cmp ah, 6 ;model 6 (K7) = Athlon, Duron jb cpu_mmx mov eax, 80000000h cpuid cmp eax, 80000000h jbe cpu_mmx mov eax, 80000001h cpuid bt edx, 31 ;AMD Feature Bit jnb cpu_mmx mov al, 3 ;AMD jmp ret_al check_sse: bt edx, 25 ;SSE Feature Bit jb cpu_sse cpu_mmx: mov al, 2 jmp ret_al cpu_sse: mov al, 4 ;SSE bt edx, 26 ;SSE2 Feature Bit adc al, 0 ret_al: movzx eax,al cpu_done: mov [CPU_Type], eax ret_eax: } } static unsigned long memcpyProc = 0; static unsigned long memsetProc = 0; static unsigned long memzeroProc = 0; void * _stdcall memcpy_optimized(void *dest, const void *src, size_t n) { __asm { mov ebx, [n] ; number of bytes to copy mov edi, [dest] ; destination mov esi, [src] ; source push edi mov ecx, [memcpyProc] jecxz $memcpy_detect jmp ecx $memcpy_detect: push ebx push esi push edi call get_cpu_type mov ecx, offset copy_sse cmp al, 3 ja addr_done mov ecx, offset copy_amd je addr_done mov ecx, offset copy_mmx cmp al, 1 ja addr_done mov ecx, offset copy_rep addr_done: mov [memcpyProc], ecx pop edi pop esi pop ebx jmp ecx align 16 copy_sse: cmp ebx, 512 jb copy_mmx ; tiny? skip optimized copy mov ecx, 16 ; a trick that's faster than rep movsb... sub ecx, edi ; align destination to qword and ecx, 1111b ; get the low bits sub ebx, ecx ; update copy count neg ecx ; set up to jump into the array add ecx, offset $memcpy_sse_align_done jmp ecx ; jump to array of movsb's align 16 $memcpy_sse_ic_1_a: ; 64-byte block copies, in-cache copy prefetchnta [esi + 320] ; start reading ahead movaps xmm0, [esi] ; read 128 bits movaps xmm1, [esi+16] movaps xmm2, [esi+32] movaps xmm3, [esi+48] add esi, 64 ; update source pointer movntps [edi], xmm0 ; write 128 bits movntps [edi+16], xmm1 movntps [edi+32], xmm2 movntps [edi+48], xmm3 add edi, 64 ; update destination pointer dec ecx ; count down jnz $memcpy_sse_ic_1_a ; last 64-byte block? sfence ; flush the write buffer mov ecx, ebx ; has valid low 6 bits of the byte count shr ecx, 2 ; dword count and ecx, 1111b ; only look at the "remainder" bits neg ecx ; set up to jump into the array add ecx, offset $memcpy_last_few jmp ecx ; jump to array of movsd's align 4 movsb movsb movsb movsb movsb movsb movsb movsb movsb movsb movsb movsb movsb movsb movsb movsb $memcpy_sse_align_done: ; destination is double quadword aligned mov ecx, ebx ; number of bytes left to copy shr ecx, 6 ; get 64-byte block count test esi, 1111b ; Is the source address aligned? je $memcpy_sse_ic_1_a // This is small block copy that uses the SSE registers to copy 16 bytes // at a time. It uses the "unrolled loop" optimization, and also uses // the software prefetch instruction to get the data into the cache. align 16 $memcpy_sse_ic_1: ; 64-byte block copies, in-cache copy prefetchnta [esi + 320] ; start reading ahead movups xmm0, [esi] ; read 128 bits movups xmm1, [esi+16] movups xmm2, [esi+32] movups xmm3, [esi+48] add esi, 64 ; update source pointer movntps [edi], xmm0 ; write 128 bits movntps [edi+16], xmm1 movntps [edi+32], xmm2 movntps [edi+48], xmm3 add edi, 64 ; update destination pointer dec ecx ; count down jnz $memcpy_sse_ic_1 ; last 64-byte block? sfence ; flush the write buffer mov ecx, ebx ; has valid low 6 bits of the byte count shr ecx, 2 ; dword count and ecx, 1111b ; only look at the "remainder" bits neg ecx ; set up to jump into the array add ecx, offset $memcpy_last_few jmp ecx ; jump to array of movsd's align 16 copy_amd: cmp ebx, 128 jb copy_rep ; tiny? skip optimized copy cmp ebx, 32*1024 ; don't align between 32k-64k because jbe $memcpy_amd_do_align ; it appears to be slower cmp ebx, 64*1024 jbe $memcpy_amd_align_done $memcpy_amd_do_align: mov ecx, 8 ; a trick that's faster than rep movsb... sub ecx, edi ; align destination to qword and ecx, 111b ; get the low bits sub ebx, ecx ; update copy count neg ecx ; set up to jump into the array add ecx, offset $memcpy_amd_align_done jmp ecx ; jump to array of movsb's $memcpy_amd_uc_test: cmp ecx, UNCACHED_COPY/64 ; big enough? use block prefetch copy jae $memcpy_amd_bp_1 // For larger blocks, which will spill beyond the cache, it's faster to // use the Streaming Store instruction MOVNTQ. This write instruction // bypasses the cache and writes straight to main memory. This code also // uses the software prefetch instruction to pre-read the data. align 16 $memcpy_amd_uc_1: ; 64-byte blocks, uncached copy prefetchnta [esi + (200*64/34+192)] ; start reading ahead movq mm0, [esi] ; read 64 bits add edi, 64 ; update destination pointer movq mm1, [esi+8] add esi, 64 ; update source pointer movq mm2, [esi-48] movntq [edi-64], mm0 ; write 64 bits, bypassing the cache movq mm0, [esi-40] ; note: movntq also prevents the CPU movntq [edi-56], mm1 ; from READING the destination address movq mm1, [esi-32] ; into the cache, only to be over-written movntq [edi-48], mm2 ; so that also helps performance movq mm2, [esi-24] movntq [edi-40], mm0 movq mm0, [esi-16] movntq [edi-32], mm1 movq mm1, [esi-8] movntq [edi-24], mm2 movntq [edi-16], mm0 dec ecx movntq [edi-8], mm1 jnz $memcpy_amd_uc_1 ; last 64-byte block? sfence ; flush the write buffer mov ecx, ebx ; has valid low 6 bits of the byte count shr ecx, 2 ; dword count and ecx, 1111b ; only look at the "remainder" bits neg ecx ; set up to jump into the array add ecx, offset $memcpy_last_few jmp ecx ; jump to array of movsd's // For the largest size blocks, a special technique called Block Prefetch // can be used to accelerate the read operations. Block Prefetch reads // one address per cache line, for a series of cache lines, in a short loop. // This is faster than using software prefetch, in this case. // The technique is great for getting maximum read bandwidth, // especially in DDR memory systems. $memcpy_amd_bp_1: ; large blocks, block prefetch copy mov eax, CACHEBLOCK / 2 ; block prefetch loop, unrolled 2X add esi, CACHEBLOCK * 64 ; move to the top of the block align 16 $memcpy_amd_bp_2: mov edx, [esi-64] ; grab one address per cache line mov edx, [esi-128] ; grab one address per cache line sub esi, 128 ; go reverse order dec eax ; count down the cache lines jnz $memcpy_amd_bp_2 ; keep grabbing more lines into cache mov eax, CACHEBLOCK ; now that it's in cache, do the copy align 16 $memcpy_amd_bp_3: movq mm0, [esi] ; read 64 bits movq mm1, [esi+8] movq mm2, [esi+16] movq mm3, [esi+24] movq mm4, [esi+32] movq mm5, [esi+40] movq mm6, [esi+48] movq mm7, [esi+56] add esi, 64 ; update source pointer movntq [edi], mm0 ; write 64 bits, bypassing cache movntq [edi+8], mm1 ; note: movntq also prevents the CPU movntq [edi+16], mm2 ; from READING the destination address movntq [edi+24], mm3 ; into the cache, only to be over-written, movntq [edi+32], mm4 ; so that also helps performance movntq [edi+40], mm5 movntq [edi+48], mm6 movntq [edi+56], mm7 add edi, 64 ; update dest pointer dec eax ; count down jnz $memcpy_amd_bp_3 ; keep copying sub ecx, CACHEBLOCK ; update the 64-byte block count jbe $memcpy_done ; no more 64-byte blocks left cmp ecx, CACHEBLOCK ; big enough to run another prefetch loop? jae $memcpy_amd_bp_1 ; yes, keep processing chunks jmp $memcpy_amd_uc_1 ; 64-byte blocks, uncached copy align 4 movsb movsb movsb movsb movsb movsb movsb movsb $memcpy_amd_align_done: ; destination is dword aligned mov ecx, ebx ; number of bytes left to copy shr ecx, 6 ; get 64-byte block count cmp ecx, IN_CACHE_COPY/64 ; too big 4 cache? use uncached copy jae $memcpy_amd_uc_test // This is small block copy that uses the MMX registers to copy 8 bytes // at a time. It uses the "unrolled loop" optimization, and also uses // the software prefetch instruction to get the data into the cache. align 16 $memcpy_amd_ic_1: ; 64-byte block copies, in-cache copy prefetchnta [esi + (200*64/34+192)] ; start reading ahead movq mm0, [esi] ; read 64 bits movq mm1, [esi+8] movq [edi], mm0 ; write 64 bits movq [edi+8], mm1 ; note: the normal movq writes the movq mm2, [esi+16] ; data to cache; a cache line will be movq mm3, [esi+24] ; allocated as needed, to store the data movq [edi+16], mm2 movq [edi+24], mm3 movq mm0, [esi+32] movq mm1, [esi+40] movq [edi+32], mm0 movq [edi+40], mm1 movq mm2, [esi+48] movq mm3, [esi+56] movq [edi+48], mm2 movq [edi+56], mm3 add esi, 64 ; update source pointer add edi, 64 ; update destination pointer dec ecx ; count down jnz $memcpy_amd_ic_1 ; last 64-byte block? $memcpy_done: sfence ; flush the write buffer mov ecx, ebx ; has valid low 6 bits of the byte count shr ecx, 2 ; dword count and ecx, 1111b ; only look at the "remainder" bits neg ecx ; set up to jump into the array add ecx, offset $memcpy_last_few jmp ecx ; jump to array of movsd's align 16 copy_mmx: cmp ebx, 128 jb copy_rep ; tiny? skip optimized copy mov ecx, 8 ; a trick that's faster than rep movsb... sub ecx, edi ; align destination to qword and ecx, 111b ; get the low bits sub ebx, ecx ; update copy count neg ecx ; set up to jump into the array add ecx, offset $memcpy_mmx_align_done jmp ecx ; jump to array of movsb's align 4 movsb movsb movsb movsb movsb movsb movsb movsb $memcpy_mmx_align_done: ; destination is dword aligned mov ecx, ebx ; number of bytes left to copy shr ecx, 6 ; get 64-byte block count align 16 $memcpy_mmx_ic_1: movq mm0, [esi] ; read 64 bits movq mm1, [esi+8] movq [edi], mm0 ; write 64 bits movq [edi+8], mm1 movq mm2, [esi+16] movq mm3, [esi+24] movq [edi+16], mm2 movq [edi+24], mm3 movq mm0, [esi+32] movq mm1, [esi+40] movq [edi+32], mm0 movq [edi+40], mm1 movq mm2, [esi+48] movq mm3, [esi+56] movq [edi+48], mm2 movq [edi+56], mm3 add esi, 64 ; update source pointer add edi, 64 ; update destination pointer dec ecx ; count down jnz $memcpy_mmx_ic_1 ; last 64-byte block? mov ecx, ebx ; has valid low 6 bits of the byte count shr ecx, 2 ; dword count and ecx, 1111b ; only look at the "remainder" bits neg ecx ; set up to jump into the array add ecx, offset $memcpy_last_few jmp ecx ; jump to array of movsd's align 16 copy_rep: mov ecx, ebx shr ecx, 2 and ebx, 11b ; ebx isn't required any more rep movsd mov ecx, ebx rep movsb jmp $memcpy_exit // The smallest copy uses the X86 "movsd" instruction, in an optimized // form which is an "unrolled loop". Then it handles the last few bytes. align 4 movsd movsd ; perform last 1-15 dword copies movsd movsd movsd movsd movsd movsd movsd movsd ; perform last 1-7 dword copies movsd movsd movsd movsd movsd movsd $memcpy_last_few: ; dword aligned from before movsd's mov ecx, ebx ; has valid low 2 bits of the byte count and ecx, 11b ; the last few cows must come home rep movsb ; the last 1, 2, or 3 bytes emms $memcpy_exit: pop eax // [dest] ; ret value = destination pointer } } void* _stdcall memset_optimized(void *dest, int c, size_t n) { __asm { mov ebx, [n] ; number of bytes to fill mov edi, [dest] ; destination movzx eax, [c] ; character mov ah, al mov ecx, eax shl ecx, 16 push edi or eax, ecx mov ecx,[memsetProc] jecxz $memset_detect jmp ecx $memset_detect: push eax push ebx push edi call get_cpu_type mov ecx, offset fill_sse cmp al, 3 ja addr_done mov ecx, offset fill_amd je addr_done mov ecx, offset fill_mmx cmp al, 1 ja addr_done mov ecx, offset fill_rep addr_done: mov [memsetProc], ecx pop edi pop ebx pop eax jmp ecx align 16 fill_sse: cmp ebx, 2048 jb fill_mmx ; tiny? skip optimized fill mov ecx, 16 ; a trick that's faster than rep stosb... sub ecx, edi ; align destination to qword and ecx, 1111b ; get the low bits sub ebx, ecx ; update copy count neg ecx ; set up to jump into the array add ecx, offset $memset_sse_align_done jmp ecx ; jump to array of stosb's align 4 stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb $memset_sse_align_done: ; destination is double quadword aligned mov ecx, ebx ; number of bytes left to fill shr ecx, 6 ; get 64-byte block count push eax push eax push eax push eax movups xmm0, [esp] add esp, 16 align 16 $memset_sse_ic_1: movntps [edi], xmm0 ; write 128 bits movntps [edi+16], xmm0 movntps [edi+32], xmm0 movntps [edi+48], xmm0 add edi, 64 ; update destination pointer dec ecx ; count down jnz $memset_sse_ic_1 ; last 64-byte block? sfence ; flush the write buffer mov ecx, ebx ; has valid low 6 bits of the byte count shr ecx, 2 ; dword count and ecx, 1111b ; only look at the "remainder" bits neg ecx ; set up to jump into the array add ecx, offset $memset_last_few jmp ecx ; jump to array of stosd's align 16 fill_amd: cmp ebx, 128 jb fill_rep ; tiny? skip optimized fill mov ecx, 8 ; a trick that's faster than rep stosb... sub ecx, edi ; align destination to qword and ecx, 111b ; get the low bits sub ebx, ecx ; update fill count neg ecx ; set up to jump into the array add ecx, offset $memset_amd_align_done jmp ecx ; jump to array of stosb's align 4 stosb stosb stosb stosb stosb stosb stosb stosb $memset_amd_align_done: ; destination is dword aligned mov ecx, ebx ; number of bytes left to fill shr ecx, 6 ; get 64-byte block count movd mm0, eax punpckldq mm0, mm0 align 16 $memset_amd_ic_1: movntq [edi], mm0 ; write 64 bits movntq [edi+8], mm0 movntq [edi+16], mm0 movntq [edi+24], mm0 movntq [edi+32], mm0 movntq [edi+40], mm0 movntq [edi+48], mm0 movntq [edi+56], mm0 add edi, 64 ; update destination pointer dec ecx ; count down jnz $memset_amd_ic_1 ; last 64-byte block? sfence ; flush the write buffer mov ecx, ebx ; has valid low 6 bits of the byte count shr ecx, 2 ; dword count and ecx, 1111b ; only look at the "remainder" bits neg ecx ; set up to jump into the array add ecx, offset $memset_last_few jmp ecx ; jump to array of stosd's align 16 fill_mmx: cmp ebx, 192 jb fill_rep ; tiny? skip optimized fill mov ecx, 8 ; a trick that's faster than rep stosb... sub ecx, edi ; align destination to qword and ecx, 111b ; get the low bits sub ebx, ecx ; update fill count neg ecx ; set up to jump into the array add ecx, offset $memset_mmx_align_done jmp ecx ; jump to array of stosb's align 4 stosb stosb stosb stosb stosb stosb stosb stosb $memset_mmx_align_done: ; destination is dword aligned mov ecx, ebx ; number of bytes left to fill shr ecx, 6 ; get 64-byte block count movd mm0, eax punpckldq mm0, mm0 align 16 $memset_mmx_ic_1: movq [edi], mm0 ; write 64 bits movq [edi+8], mm0 movq [edi+16], mm0 movq [edi+24], mm0 movq [edi+32], mm0 movq [edi+40], mm0 movq [edi+48], mm0 movq [edi+56], mm0 add edi, 64 ; update destination pointer dec ecx ; count down jnz $memset_mmx_ic_1 ; last 64-byte block? mov ecx, ebx ; has valid low 6 bits of the byte count shr ecx, 2 ; dword count and ecx, 1111b ; only look at the "remainder" bits neg ecx ; set up to jump into the array add ecx, offset $memset_last_few jmp ecx ; jump to array of stosd's align 16 fill_rep: mov ecx, ebx shr ecx, 2 and ebx, 11b ; ebx isn't required any more rep stosd mov ecx, ebx rep stosb jmp $memset_exit align 4 stosd stosd ; perform last 1-15 dword fills stosd stosd stosd stosd stosd stosd stosd stosd ; perform last 1-7 dword fills stosd stosd stosd stosd stosd stosd $memset_last_few: ; dword aligned from before stosd's mov ecx, ebx ; has valid low 2 bits of the byte count and ecx, 11b ; the last few cows must come home rep stosb ; the last 1, 2, or 3 bytes emms $memset_exit: pop eax // [dest] ; ret value = destination pointer } } void _stdcall memzero_optimized(void *dest, size_t n) { __asm { mov ebx, [n] ; number of bytes to fill mov edi, [dest] ; destination xor eax, eax mov ecx,[memzeroProc] jecxz $memzero_detect jmp ecx $memzero_detect: push ebx push edi call get_cpu_type mov ecx, offset fill_sse cmp al, 3 ja addr_done mov ecx, offset fill_amd je addr_done mov ecx, offset fill_mmx cmp al, 1 ja addr_done mov ecx, offset fill_rep addr_done: mov [memzeroProc], ecx pop edi pop ebx xor eax, eax jmp ecx align 16 fill_sse: cmp ebx, 2048 jb fill_mmx ; tiny? skip optimized fill mov ecx, 16 ; a trick that's faster than rep stosb... sub ecx, edi ; align destination to qword and ecx, 1111b ; get the low bits sub ebx, ecx ; update copy count neg ecx ; set up to jump into the array add ecx, offset $memzero_sse_align_done jmp ecx ; jump to array of stosb's align 4 stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb $memzero_sse_align_done: ; destination is double quadword aligned mov ecx, ebx ; number of bytes left to fill shr ecx, 6 ; get 64-byte block count xorps xmm0, xmm0 align 16 $memzero_sse_ic_1: movntps [edi], xmm0 ; write 128 bits movntps [edi+16], xmm0 movntps [edi+32], xmm0 movntps [edi+48], xmm0 add edi, 64 ; update destination pointer dec ecx ; count down jnz $memzero_sse_ic_1 ; last 64-byte block? sfence ; flush the write buffer mov ecx, ebx ; has valid low 6 bits of the byte count shr ecx, 2 ; dword count and ecx, 1111b ; only look at the "remainder" bits neg ecx ; set up to jump into the array add ecx, offset $memzero_last_few jmp ecx ; jump to array of stosd's align 16 fill_amd: cmp ebx, 128 jb fill_rep ; tiny? skip optimized fill mov ecx, 8 ; a trick that's faster than rep stosb... sub ecx, edi ; align destination to qword and ecx, 111b ; get the low bits sub ebx, ecx ; update fill count neg ecx ; set up to jump into the array add ecx, offset $memzero_amd_align_done jmp ecx ; jump to array of stosb's align 4 stosb stosb stosb stosb stosb stosb stosb stosb $memzero_amd_align_done: ; destination is dword aligned mov ecx, ebx ; number of bytes left to fill shr ecx, 6 ; get 64-byte block count pxor mm0, mm0 align 16 $memzero_amd_ic_1: movntq [edi], mm0 ; write 64 bits movntq [edi+8], mm0 movntq [edi+16], mm0 movntq [edi+24], mm0 movntq [edi+32], mm0 movntq [edi+40], mm0 movntq [edi+48], mm0 movntq [edi+56], mm0 add edi, 64 ; update destination pointer dec ecx ; count down jnz $memzero_amd_ic_1 ; last 64-byte block? sfence ; flush the write buffer mov ecx, ebx ; has valid low 6 bits of the byte count shr ecx, 2 ; dword count and ecx, 1111b ; only look at the "remainder" bits neg ecx ; set up to jump into the array add ecx, offset $memzero_last_few jmp ecx ; jump to array of stosd's align 16 fill_mmx: cmp ebx, 192 jb fill_rep ; tiny? skip optimized fill mov ecx, 8 ; a trick that's faster than rep stosb... sub ecx, edi ; align destination to qword and ecx, 111b ; get the low bits sub ebx, ecx ; update fill count neg ecx ; set up to jump into the array add ecx, offset $memzero_mmx_align_done jmp ecx ; jump to array of stosb's align 4 stosb stosb stosb stosb stosb stosb stosb stosb $memzero_mmx_align_done: ; destination is dword aligned mov ecx, ebx ; number of bytes left to fill shr ecx, 6 ; get 64-byte block count pxor mm0, mm0 align 16 $memzero_mmx_ic_1: movq [edi], mm0 ; write 64 bits movq [edi+8], mm0 movq [edi+16], mm0 movq [edi+24], mm0 movq [edi+32], mm0 movq [edi+40], mm0 movq [edi+48], mm0 movq [edi+56], mm0 add edi, 64 ; update destination pointer dec ecx ; count down jnz $memzero_mmx_ic_1 ; last 64-byte block? mov ecx, ebx ; has valid low 6 bits of the byte count shr ecx, 2 ; dword count and ecx, 1111b ; only look at the "remainder" bits neg ecx ; set up to jump into the array add ecx, offset $memzero_last_few jmp ecx ; jump to array of stosd's align 16 fill_rep: mov ecx, ebx shr ecx, 2 and ebx, 11b ; ebx isn't required any more rep stosd mov ecx, ebx rep stosb jmp $memzero_exit align 4 stosd stosd ; perform last 1-15 dword fills stosd stosd stosd stosd stosd stosd stosd stosd ; perform last 1-7 dword fills stosd stosd stosd stosd stosd stosd $memzero_last_few: ; dword aligned from before stosd's mov ecx, ebx ; has valid low 2 bits of the byte count and ecx, 11b ; the last few cows must come home rep stosb ; the last 1, 2, or 3 bytes emms $memzero_exit: } } ================================================ FILE: optimize/memcpy_amd.c ================================================ /****************************************************************************** Copyright (c) 2001 Advanced Micro Devices, Inc. LIMITATION OF LIABILITY: THE MATERIALS ARE PROVIDED *AS IS* WITHOUT ANY EXPRESS OR IMPLIED WARRANTY OF ANY KIND INCLUDING WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT OF THIRD-PARTY INTELLECTUAL PROPERTY, OR FITNESS FOR ANY PARTICULAR PURPOSE. IN NO EVENT SHALL AMD OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF PROFITS, BUSINESS INTERRUPTION, LOSS OF INFORMATION) ARISING OUT OF THE USE OF OR INABILITY TO USE THE MATERIALS, EVEN IF AMD HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. BECAUSE SOME JURISDICTIONS PROHIBIT THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES, THE ABOVE LIMITATION MAY NOT APPLY TO YOU. AMD does not assume any responsibility for any errors which may appear in the Materials nor any responsibility to support or update the Materials. AMD retains the right to make changes to its test specifications at any time, without notice. NO SUPPORT OBLIGATION: AMD is not obligated to furnish, support, or make any further information, software, technical information, know-how, or show-how available to you. So that all may benefit from your experience, please report any problems or suggestions about this software to 3dsdk.support@amd.com AMD Developer Technologies, M/S 585 Advanced Micro Devices, Inc. 5900 E. Ben White Blvd. Austin, TX 78741 3dsdk.support@amd.com ******************************************************************************/ #pragma once #include "memcpy_amd.h" /***************************************************************************** MEMCPY_AMD.CPP ******************************************************************************/ // Very optimized memcpy() routine for all AMD Athlon and Duron family. // This code uses any of FOUR different basic copy methods, depending // on the transfer size. // NOTE: Since this code uses MOVNTQ (also known as "Non-Temporal MOV" or // "Streaming Store"), and also uses the software prefetchnta instructions, // be sure you're running on Athlon/Duron or other recent CPU before calling! #define IN_CACHE_COPY 64 * 1024 // upper limit for movq/movq copy w/SW prefetch // Next is a copy that uses the MMX registers to copy 8 bytes at a time, // also using the "unrolled loop" optimization. This code uses // the software prefetch instruction to get the data into the cache. #define UNCACHED_COPY 197 * 1024 // upper limit for movq/movntq w/SW prefetch // For larger blocks, which will spill beyond the cache, it's faster to // use the Streaming Store instruction MOVNTQ. This write instruction // bypasses the cache and writes straight to main memory. This code also // uses the software prefetch instruction to pre-read the data. // USE 64 * 1024 FOR THIS VALUE IF YOU'RE ALWAYS FILLING A "CLEAN CACHE" #define BLOCK_PREFETCH_COPY infinity // no limit for movq/movntq w/block prefetch #define CACHEBLOCK 80h // number of 64-byte blocks (cache lines) for block prefetch // For the largest size blocks, a special technique called Block Prefetch // can be used to accelerate the read operations. Block Prefetch reads // one address per cache line, for a series of cache lines, in a short loop. // This is faster than using software prefetch. The technique is great for // getting maximum read bandwidth, especially in DDR memory systems. // Inline assembly syntax for use with Visual C++ ///////////////////////////////////////////////////////////////////////////////////// // katsyonak: Added MMX & SSE optimized memcpy - October 8, 2003 // // // // katsyonak: Added AMD, MMX & SSE optimized memset - October 12, 2003 // // // // Aw3/katsyonak: Added AMD, MMX & SSE optimized memzero - February 11, 2004 // /////////////////////////////////////////////////////////////////////////////// static unsigned long CPU_Type = 0; // 0 = CPU check not performed yet (Auto detect) // 1 = No optimization // 2 = MMX // 3 = MMX2 for AMD Athlon/Duron and above (might also work on MMX2 (KATMAI) Intel machines) // 4 = SSE // 5 = SSE2 (only for Pentium 4 detection, the optimization used is SSE) unsigned long get_cpu_type() { __asm { mov eax, [CPU_Type] cmp eax, 5 ja do_detect or eax, eax jne ret_eax do_detect: xor eax, eax cpuid or eax, eax mov eax, 1 ;No optimization je cpu_done xor esi, esi cmp ebx, 68747541h ;Auth jne not_amd cmp edx, 69746E65h ;enti jne not_amd cmp ecx, 444D4163h ;cAMD jne not_amd inc esi not_amd: ;mov eax,1 cpuid mov al, 1 ;No optimization bt edx, 23 ;MMX Feature Bit jnb ret_al or esi, esi je check_sse and ah, 1111b cmp ah, 6 ;model 6 (K7) = Athlon, Duron jb cpu_mmx mov eax, 80000000h cpuid cmp eax, 80000000h jbe cpu_mmx mov eax, 80000001h cpuid bt edx, 31 ;AMD Feature Bit jnb cpu_mmx mov al, 3 ;AMD jmp ret_al check_sse: bt edx, 25 ;SSE Feature Bit jb cpu_sse cpu_mmx: mov al, 2 jmp ret_al cpu_sse: mov al, 4 ;SSE bt edx, 26 ;SSE2 Feature Bit adc al, 0 ret_al: movzx eax,al cpu_done: mov [CPU_Type], eax ret_eax: } } static unsigned long memcpyProc = 0; static unsigned long memsetProc = 0; static unsigned long memzeroProc = 0; void * _stdcall memcpy_optimized(void *dest, const void *src, size_t n) { __asm { mov ebx, [n] ; number of bytes to copy mov edi, [dest] ; destination mov esi, [src] ; source push edi mov ecx, [memcpyProc] jecxz $memcpy_detect jmp ecx $memcpy_detect: push ebx push esi push edi call get_cpu_type mov ecx, offset copy_sse cmp al, 3 ja addr_done mov ecx, offset copy_amd je addr_done mov ecx, offset copy_mmx cmp al, 1 ja addr_done mov ecx, offset copy_rep addr_done: mov [memcpyProc], ecx pop edi pop esi pop ebx jmp ecx align 16 copy_sse: cmp ebx, 512 jb copy_mmx ; tiny? skip optimized copy mov ecx, 16 ; a trick that's faster than rep movsb... sub ecx, edi ; align destination to qword and ecx, 1111b ; get the low bits sub ebx, ecx ; update copy count neg ecx ; set up to jump into the array add ecx, offset $memcpy_sse_align_done jmp ecx ; jump to array of movsb's align 16 $memcpy_sse_ic_1_a: ; 64-byte block copies, in-cache copy prefetchnta [esi + 320] ; start reading ahead movaps xmm0, [esi] ; read 128 bits movaps xmm1, [esi+16] movaps xmm2, [esi+32] movaps xmm3, [esi+48] add esi, 64 ; update source pointer movntps [edi], xmm0 ; write 128 bits movntps [edi+16], xmm1 movntps [edi+32], xmm2 movntps [edi+48], xmm3 add edi, 64 ; update destination pointer dec ecx ; count down jnz $memcpy_sse_ic_1_a ; last 64-byte block? sfence ; flush the write buffer mov ecx, ebx ; has valid low 6 bits of the byte count shr ecx, 2 ; dword count and ecx, 1111b ; only look at the "remainder" bits neg ecx ; set up to jump into the array add ecx, offset $memcpy_last_few jmp ecx ; jump to array of movsd's align 4 movsb movsb movsb movsb movsb movsb movsb movsb movsb movsb movsb movsb movsb movsb movsb movsb $memcpy_sse_align_done: ; destination is double quadword aligned mov ecx, ebx ; number of bytes left to copy shr ecx, 6 ; get 64-byte block count test esi, 1111b ; Is the source address aligned? je $memcpy_sse_ic_1_a // This is small block copy that uses the SSE registers to copy 16 bytes // at a time. It uses the "unrolled loop" optimization, and also uses // the software prefetch instruction to get the data into the cache. align 16 $memcpy_sse_ic_1: ; 64-byte block copies, in-cache copy prefetchnta [esi + 320] ; start reading ahead movups xmm0, [esi] ; read 128 bits movups xmm1, [esi+16] movups xmm2, [esi+32] movups xmm3, [esi+48] add esi, 64 ; update source pointer movntps [edi], xmm0 ; write 128 bits movntps [edi+16], xmm1 movntps [edi+32], xmm2 movntps [edi+48], xmm3 add edi, 64 ; update destination pointer dec ecx ; count down jnz $memcpy_sse_ic_1 ; last 64-byte block? sfence ; flush the write buffer mov ecx, ebx ; has valid low 6 bits of the byte count shr ecx, 2 ; dword count and ecx, 1111b ; only look at the "remainder" bits neg ecx ; set up to jump into the array add ecx, offset $memcpy_last_few jmp ecx ; jump to array of movsd's align 16 copy_amd: cmp ebx, 128 jb copy_rep ; tiny? skip optimized copy cmp ebx, 32*1024 ; don't align between 32k-64k because jbe $memcpy_amd_do_align ; it appears to be slower cmp ebx, 64*1024 jbe $memcpy_amd_align_done $memcpy_amd_do_align: mov ecx, 8 ; a trick that's faster than rep movsb... sub ecx, edi ; align destination to qword and ecx, 111b ; get the low bits sub ebx, ecx ; update copy count neg ecx ; set up to jump into the array add ecx, offset $memcpy_amd_align_done jmp ecx ; jump to array of movsb's $memcpy_amd_uc_test: cmp ecx, UNCACHED_COPY/64 ; big enough? use block prefetch copy jae $memcpy_amd_bp_1 // For larger blocks, which will spill beyond the cache, it's faster to // use the Streaming Store instruction MOVNTQ. This write instruction // bypasses the cache and writes straight to main memory. This code also // uses the software prefetch instruction to pre-read the data. align 16 $memcpy_amd_uc_1: ; 64-byte blocks, uncached copy prefetchnta [esi + (200*64/34+192)] ; start reading ahead movq mm0, [esi] ; read 64 bits add edi, 64 ; update destination pointer movq mm1, [esi+8] add esi, 64 ; update source pointer movq mm2, [esi-48] movntq [edi-64], mm0 ; write 64 bits, bypassing the cache movq mm0, [esi-40] ; note: movntq also prevents the CPU movntq [edi-56], mm1 ; from READING the destination address movq mm1, [esi-32] ; into the cache, only to be over-written movntq [edi-48], mm2 ; so that also helps performance movq mm2, [esi-24] movntq [edi-40], mm0 movq mm0, [esi-16] movntq [edi-32], mm1 movq mm1, [esi-8] movntq [edi-24], mm2 movntq [edi-16], mm0 dec ecx movntq [edi-8], mm1 jnz $memcpy_amd_uc_1 ; last 64-byte block? sfence ; flush the write buffer mov ecx, ebx ; has valid low 6 bits of the byte count shr ecx, 2 ; dword count and ecx, 1111b ; only look at the "remainder" bits neg ecx ; set up to jump into the array add ecx, offset $memcpy_last_few jmp ecx ; jump to array of movsd's // For the largest size blocks, a special technique called Block Prefetch // can be used to accelerate the read operations. Block Prefetch reads // one address per cache line, for a series of cache lines, in a short loop. // This is faster than using software prefetch, in this case. // The technique is great for getting maximum read bandwidth, // especially in DDR memory systems. $memcpy_amd_bp_1: ; large blocks, block prefetch copy mov eax, CACHEBLOCK / 2 ; block prefetch loop, unrolled 2X add esi, CACHEBLOCK * 64 ; move to the top of the block align 16 $memcpy_amd_bp_2: mov edx, [esi-64] ; grab one address per cache line mov edx, [esi-128] ; grab one address per cache line sub esi, 128 ; go reverse order dec eax ; count down the cache lines jnz $memcpy_amd_bp_2 ; keep grabbing more lines into cache mov eax, CACHEBLOCK ; now that it's in cache, do the copy align 16 $memcpy_amd_bp_3: movq mm0, [esi] ; read 64 bits movq mm1, [esi+8] movq mm2, [esi+16] movq mm3, [esi+24] movq mm4, [esi+32] movq mm5, [esi+40] movq mm6, [esi+48] movq mm7, [esi+56] add esi, 64 ; update source pointer movntq [edi], mm0 ; write 64 bits, bypassing cache movntq [edi+8], mm1 ; note: movntq also prevents the CPU movntq [edi+16], mm2 ; from READING the destination address movntq [edi+24], mm3 ; into the cache, only to be over-written, movntq [edi+32], mm4 ; so that also helps performance movntq [edi+40], mm5 movntq [edi+48], mm6 movntq [edi+56], mm7 add edi, 64 ; update dest pointer dec eax ; count down jnz $memcpy_amd_bp_3 ; keep copying sub ecx, CACHEBLOCK ; update the 64-byte block count jbe $memcpy_done ; no more 64-byte blocks left cmp ecx, CACHEBLOCK ; big enough to run another prefetch loop? jae $memcpy_amd_bp_1 ; yes, keep processing chunks jmp $memcpy_amd_uc_1 ; 64-byte blocks, uncached copy align 4 movsb movsb movsb movsb movsb movsb movsb movsb $memcpy_amd_align_done: ; destination is dword aligned mov ecx, ebx ; number of bytes left to copy shr ecx, 6 ; get 64-byte block count cmp ecx, IN_CACHE_COPY/64 ; too big 4 cache? use uncached copy jae $memcpy_amd_uc_test // This is small block copy that uses the MMX registers to copy 8 bytes // at a time. It uses the "unrolled loop" optimization, and also uses // the software prefetch instruction to get the data into the cache. align 16 $memcpy_amd_ic_1: ; 64-byte block copies, in-cache copy prefetchnta [esi + (200*64/34+192)] ; start reading ahead movq mm0, [esi] ; read 64 bits movq mm1, [esi+8] movq [edi], mm0 ; write 64 bits movq [edi+8], mm1 ; note: the normal movq writes the movq mm2, [esi+16] ; data to cache; a cache line will be movq mm3, [esi+24] ; allocated as needed, to store the data movq [edi+16], mm2 movq [edi+24], mm3 movq mm0, [esi+32] movq mm1, [esi+40] movq [edi+32], mm0 movq [edi+40], mm1 movq mm2, [esi+48] movq mm3, [esi+56] movq [edi+48], mm2 movq [edi+56], mm3 add esi, 64 ; update source pointer add edi, 64 ; update destination pointer dec ecx ; count down jnz $memcpy_amd_ic_1 ; last 64-byte block? $memcpy_done: sfence ; flush the write buffer mov ecx, ebx ; has valid low 6 bits of the byte count shr ecx, 2 ; dword count and ecx, 1111b ; only look at the "remainder" bits neg ecx ; set up to jump into the array add ecx, offset $memcpy_last_few jmp ecx ; jump to array of movsd's align 16 copy_mmx: cmp ebx, 128 jb copy_rep ; tiny? skip optimized copy mov ecx, 8 ; a trick that's faster than rep movsb... sub ecx, edi ; align destination to qword and ecx, 111b ; get the low bits sub ebx, ecx ; update copy count neg ecx ; set up to jump into the array add ecx, offset $memcpy_mmx_align_done jmp ecx ; jump to array of movsb's align 4 movsb movsb movsb movsb movsb movsb movsb movsb $memcpy_mmx_align_done: ; destination is dword aligned mov ecx, ebx ; number of bytes left to copy shr ecx, 6 ; get 64-byte block count align 16 $memcpy_mmx_ic_1: movq mm0, [esi] ; read 64 bits movq mm1, [esi+8] movq [edi], mm0 ; write 64 bits movq [edi+8], mm1 movq mm2, [esi+16] movq mm3, [esi+24] movq [edi+16], mm2 movq [edi+24], mm3 movq mm0, [esi+32] movq mm1, [esi+40] movq [edi+32], mm0 movq [edi+40], mm1 movq mm2, [esi+48] movq mm3, [esi+56] movq [edi+48], mm2 movq [edi+56], mm3 add esi, 64 ; update source pointer add edi, 64 ; update destination pointer dec ecx ; count down jnz $memcpy_mmx_ic_1 ; last 64-byte block? mov ecx, ebx ; has valid low 6 bits of the byte count shr ecx, 2 ; dword count and ecx, 1111b ; only look at the "remainder" bits neg ecx ; set up to jump into the array add ecx, offset $memcpy_last_few jmp ecx ; jump to array of movsd's align 16 copy_rep: mov ecx, ebx shr ecx, 2 and ebx, 11b ; ebx isn't required any more rep movsd mov ecx, ebx rep movsb jmp $memcpy_exit // The smallest copy uses the X86 "movsd" instruction, in an optimized // form which is an "unrolled loop". Then it handles the last few bytes. align 4 movsd movsd ; perform last 1-15 dword copies movsd movsd movsd movsd movsd movsd movsd movsd ; perform last 1-7 dword copies movsd movsd movsd movsd movsd movsd $memcpy_last_few: ; dword aligned from before movsd's mov ecx, ebx ; has valid low 2 bits of the byte count and ecx, 11b ; the last few cows must come home rep movsb ; the last 1, 2, or 3 bytes emms $memcpy_exit: pop eax // [dest] ; ret value = destination pointer } } void* _stdcall memset_optimized(void *dest, int c, size_t n) { __asm { mov ebx, [n] ; number of bytes to fill mov edi, [dest] ; destination movzx eax, [c] ; character mov ah, al mov ecx, eax shl ecx, 16 push edi or eax, ecx mov ecx,[memsetProc] jecxz $memset_detect jmp ecx $memset_detect: push eax push ebx push edi call get_cpu_type mov ecx, offset fill_sse cmp al, 3 ja addr_done mov ecx, offset fill_amd je addr_done mov ecx, offset fill_mmx cmp al, 1 ja addr_done mov ecx, offset fill_rep addr_done: mov [memsetProc], ecx pop edi pop ebx pop eax jmp ecx align 16 fill_sse: cmp ebx, 2048 jb fill_mmx ; tiny? skip optimized fill mov ecx, 16 ; a trick that's faster than rep stosb... sub ecx, edi ; align destination to qword and ecx, 1111b ; get the low bits sub ebx, ecx ; update copy count neg ecx ; set up to jump into the array add ecx, offset $memset_sse_align_done jmp ecx ; jump to array of stosb's align 4 stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb $memset_sse_align_done: ; destination is double quadword aligned mov ecx, ebx ; number of bytes left to fill shr ecx, 6 ; get 64-byte block count push eax push eax push eax push eax movups xmm0, [esp] add esp, 16 align 16 $memset_sse_ic_1: movntps [edi], xmm0 ; write 128 bits movntps [edi+16], xmm0 movntps [edi+32], xmm0 movntps [edi+48], xmm0 add edi, 64 ; update destination pointer dec ecx ; count down jnz $memset_sse_ic_1 ; last 64-byte block? sfence ; flush the write buffer mov ecx, ebx ; has valid low 6 bits of the byte count shr ecx, 2 ; dword count and ecx, 1111b ; only look at the "remainder" bits neg ecx ; set up to jump into the array add ecx, offset $memset_last_few jmp ecx ; jump to array of stosd's align 16 fill_amd: cmp ebx, 128 jb fill_rep ; tiny? skip optimized fill mov ecx, 8 ; a trick that's faster than rep stosb... sub ecx, edi ; align destination to qword and ecx, 111b ; get the low bits sub ebx, ecx ; update fill count neg ecx ; set up to jump into the array add ecx, offset $memset_amd_align_done jmp ecx ; jump to array of stosb's align 4 stosb stosb stosb stosb stosb stosb stosb stosb $memset_amd_align_done: ; destination is dword aligned mov ecx, ebx ; number of bytes left to fill shr ecx, 6 ; get 64-byte block count movd mm0, eax punpckldq mm0, mm0 align 16 $memset_amd_ic_1: movntq [edi], mm0 ; write 64 bits movntq [edi+8], mm0 movntq [edi+16], mm0 movntq [edi+24], mm0 movntq [edi+32], mm0 movntq [edi+40], mm0 movntq [edi+48], mm0 movntq [edi+56], mm0 add edi, 64 ; update destination pointer dec ecx ; count down jnz $memset_amd_ic_1 ; last 64-byte block? sfence ; flush the write buffer mov ecx, ebx ; has valid low 6 bits of the byte count shr ecx, 2 ; dword count and ecx, 1111b ; only look at the "remainder" bits neg ecx ; set up to jump into the array add ecx, offset $memset_last_few jmp ecx ; jump to array of stosd's align 16 fill_mmx: cmp ebx, 192 jb fill_rep ; tiny? skip optimized fill mov ecx, 8 ; a trick that's faster than rep stosb... sub ecx, edi ; align destination to qword and ecx, 111b ; get the low bits sub ebx, ecx ; update fill count neg ecx ; set up to jump into the array add ecx, offset $memset_mmx_align_done jmp ecx ; jump to array of stosb's align 4 stosb stosb stosb stosb stosb stosb stosb stosb $memset_mmx_align_done: ; destination is dword aligned mov ecx, ebx ; number of bytes left to fill shr ecx, 6 ; get 64-byte block count movd mm0, eax punpckldq mm0, mm0 align 16 $memset_mmx_ic_1: movq [edi], mm0 ; write 64 bits movq [edi+8], mm0 movq [edi+16], mm0 movq [edi+24], mm0 movq [edi+32], mm0 movq [edi+40], mm0 movq [edi+48], mm0 movq [edi+56], mm0 add edi, 64 ; update destination pointer dec ecx ; count down jnz $memset_mmx_ic_1 ; last 64-byte block? mov ecx, ebx ; has valid low 6 bits of the byte count shr ecx, 2 ; dword count and ecx, 1111b ; only look at the "remainder" bits neg ecx ; set up to jump into the array add ecx, offset $memset_last_few jmp ecx ; jump to array of stosd's align 16 fill_rep: mov ecx, ebx shr ecx, 2 and ebx, 11b ; ebx isn't required any more rep stosd mov ecx, ebx rep stosb jmp $memset_exit align 4 stosd stosd ; perform last 1-15 dword fills stosd stosd stosd stosd stosd stosd stosd stosd ; perform last 1-7 dword fills stosd stosd stosd stosd stosd stosd $memset_last_few: ; dword aligned from before stosd's mov ecx, ebx ; has valid low 2 bits of the byte count and ecx, 11b ; the last few cows must come home rep stosb ; the last 1, 2, or 3 bytes emms $memset_exit: pop eax // [dest] ; ret value = destination pointer } } void _stdcall memzero_optimized(void *dest, size_t n) { __asm { mov ebx, [n] ; number of bytes to fill mov edi, [dest] ; destination xor eax, eax mov ecx,[memzeroProc] jecxz $memzero_detect jmp ecx $memzero_detect: push ebx push edi call get_cpu_type mov ecx, offset fill_sse cmp al, 3 ja addr_done mov ecx, offset fill_amd je addr_done mov ecx, offset fill_mmx cmp al, 1 ja addr_done mov ecx, offset fill_rep addr_done: mov [memzeroProc], ecx pop edi pop ebx xor eax, eax jmp ecx align 16 fill_sse: cmp ebx, 2048 jb fill_mmx ; tiny? skip optimized fill mov ecx, 16 ; a trick that's faster than rep stosb... sub ecx, edi ; align destination to qword and ecx, 1111b ; get the low bits sub ebx, ecx ; update copy count neg ecx ; set up to jump into the array add ecx, offset $memzero_sse_align_done jmp ecx ; jump to array of stosb's align 4 stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb stosb $memzero_sse_align_done: ; destination is double quadword aligned mov ecx, ebx ; number of bytes left to fill shr ecx, 6 ; get 64-byte block count xorps xmm0, xmm0 align 16 $memzero_sse_ic_1: movntps [edi], xmm0 ; write 128 bits movntps [edi+16], xmm0 movntps [edi+32], xmm0 movntps [edi+48], xmm0 add edi, 64 ; update destination pointer dec ecx ; count down jnz $memzero_sse_ic_1 ; last 64-byte block? sfence ; flush the write buffer mov ecx, ebx ; has valid low 6 bits of the byte count shr ecx, 2 ; dword count and ecx, 1111b ; only look at the "remainder" bits neg ecx ; set up to jump into the array add ecx, offset $memzero_last_few jmp ecx ; jump to array of stosd's align 16 fill_amd: cmp ebx, 128 jb fill_rep ; tiny? skip optimized fill mov ecx, 8 ; a trick that's faster than rep stosb... sub ecx, edi ; align destination to qword and ecx, 111b ; get the low bits sub ebx, ecx ; update fill count neg ecx ; set up to jump into the array add ecx, offset $memzero_amd_align_done jmp ecx ; jump to array of stosb's align 4 stosb stosb stosb stosb stosb stosb stosb stosb $memzero_amd_align_done: ; destination is dword aligned mov ecx, ebx ; number of bytes left to fill shr ecx, 6 ; get 64-byte block count pxor mm0, mm0 align 16 $memzero_amd_ic_1: movntq [edi], mm0 ; write 64 bits movntq [edi+8], mm0 movntq [edi+16], mm0 movntq [edi+24], mm0 movntq [edi+32], mm0 movntq [edi+40], mm0 movntq [edi+48], mm0 movntq [edi+56], mm0 add edi, 64 ; update destination pointer dec ecx ; count down jnz $memzero_amd_ic_1 ; last 64-byte block? sfence ; flush the write buffer mov ecx, ebx ; has valid low 6 bits of the byte count shr ecx, 2 ; dword count and ecx, 1111b ; only look at the "remainder" bits neg ecx ; set up to jump into the array add ecx, offset $memzero_last_few jmp ecx ; jump to array of stosd's align 16 fill_mmx: cmp ebx, 192 jb fill_rep ; tiny? skip optimized fill mov ecx, 8 ; a trick that's faster than rep stosb... sub ecx, edi ; align destination to qword and ecx, 111b ; get the low bits sub ebx, ecx ; update fill count neg ecx ; set up to jump into the array add ecx, offset $memzero_mmx_align_done jmp ecx ; jump to array of stosb's align 4 stosb stosb stosb stosb stosb stosb stosb stosb $memzero_mmx_align_done: ; destination is dword aligned mov ecx, ebx ; number of bytes left to fill shr ecx, 6 ; get 64-byte block count pxor mm0, mm0 align 16 $memzero_mmx_ic_1: movq [edi], mm0 ; write 64 bits movq [edi+8], mm0 movq [edi+16], mm0 movq [edi+24], mm0 movq [edi+32], mm0 movq [edi+40], mm0 movq [edi+48], mm0 movq [edi+56], mm0 add edi, 64 ; update destination pointer dec ecx ; count down jnz $memzero_mmx_ic_1 ; last 64-byte block? mov ecx, ebx ; has valid low 6 bits of the byte count shr ecx, 2 ; dword count and ecx, 1111b ; only look at the "remainder" bits neg ecx ; set up to jump into the array add ecx, offset $memzero_last_few jmp ecx ; jump to array of stosd's align 16 fill_rep: mov ecx, ebx shr ecx, 2 and ebx, 11b ; ebx isn't required any more rep stosd mov ecx, ebx rep stosb jmp $memzero_exit align 4 stosd stosd ; perform last 1-15 dword fills stosd stosd stosd stosd stosd stosd stosd stosd ; perform last 1-7 dword fills stosd stosd stosd stosd stosd stosd $memzero_last_few: ; dword aligned from before stosd's mov ecx, ebx ; has valid low 2 bits of the byte count and ecx, 11b ; the last few cows must come home rep stosb ; the last 1, 2, or 3 bytes emms $memzero_exit: } } ================================================ FILE: optimize/memcpy_amd.h ================================================ /****************************************************************************** Copyright (c) 2001 Advanced Micro Devices, Inc. LIMITATION OF LIABILITY: THE MATERIALS ARE PROVIDED *AS IS* WITHOUT ANY EXPRESS OR IMPLIED WARRANTY OF ANY KIND INCLUDING WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT OF THIRD-PARTY INTELLECTUAL PROPERTY, OR FITNESS FOR ANY PARTICULAR PURPOSE. IN NO EVENT SHALL AMD OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF PROFITS, BUSINESS INTERRUPTION, LOSS OF INFORMATION) ARISING OUT OF THE USE OF OR INABILITY TO USE THE MATERIALS, EVEN IF AMD HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. BECAUSE SOME JURISDICTIONS PROHIBIT THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES, THE ABOVE LIMITATION MAY NOT APPLY TO YOU. AMD does not assume any responsibility for any errors which may appear in the Materials nor any responsibility to support or update the Materials. AMD retains the right to make changes to its test specifications at any time, without notice. NO SUPPORT OBLIGATION: AMD is not obligated to furnish, support, or make any further information, software, technical information, know-how, or show-how available to you. So that all may benefit from your experience, please report any problems or suggestions about this software to 3dsdk.support@amd.com AMD Developer Technologies, M/S 585 Advanced Micro Devices, Inc. 5900 E. Ben White Blvd. Austin, TX 78741 3dsdk.support@amd.com ******************************************************************************/ #pragma once #include void* _stdcall memcpy_optimized(void *dest, const void *src, size_t n); void* _stdcall memset_optimized(void *dest, int c, size_t n); void _stdcall memzero_optimized(void *dest, size_t n); unsigned long get_cpu_type(); ================================================ FILE: optimize/optimize.h ================================================ #include "memcpy_amd.h" #pragma comment (lib, "optimize/release/mem_amd.lib") #undef ZeroMemory #undef memzero #undef memset #undef memcpy #define ZeroMemory memzero_optimized #define memzero memzero_optimized #define memset memset_optimized #define memcpy memcpy_optimized //#ifndef _DEBUG //#endif ================================================ FILE: override.cpp ================================================ // override.cpp - キレイなTextOut // 2006/09/27 #include "override.h" #include "ft.h" #include "fteng.h" #include "supinfo.h" #include "undocAPI.h" //#include "lrucache.hpp" #include // _alloca #include // _getmbcp #pragma comment(lib, "Gdi32.lib") #pragma comment(lib, "User32.lib") #pragma comment(lib, "WindowsCodecs.lib") #pragma comment(lib, "dwrite.lib") #pragma comment(lib, "uxtheme.lib") #if defined(_DEBUG) void Dbg_TractGetTextExtent(LPCSTR lpString, int cbString, LPSIZE lpSize); void Dbg_TractGetTextExtent(LPCWSTR lpString, int cbString, LPSIZE lpSize); void Dbg_TraceExtTextOutW(int nXStart, int nYStart, UINT fuOptions, LPCWSTR lpString, int cbString, const int* lpDx); void Dbg_TraceScriptItemize(const WCHAR* pwcInChars, int cInChars); void Dbg_TraceScriptShape(const WCHAR* pwcChars, int cChars, const SCRIPT_ANALYSIS* psa, const WORD* pwOutGlyphs, int cGlyphs); #else #define Dbg_TraceExtTextOutW(x,y,f,s,c,p) #define Dbg_TractGetTextExtent(s,c,p) #define Dbg_TraceScriptItemize(s,c) #define Dbg_TraceScriptShape(s,c,p,g,o) #endif #define CCH_MAX_STACK 256 typedef HRESULT (WINAPI * __D2D1CreateFactory)( D2D1_FACTORY_TYPE factoryType, REFIID riid, const D2D1_FACTORY_OPTIONS *pFactoryOptions, void **ppIFactory); typedef HRESULT (WINAPI* __DWriteCreateFactory)( __in DWRITE_FACTORY_TYPE factoryType, __in REFIID iid, __out IUnknown **factory ); CFontCache FontCache; CDCArray DCArray; CDCRelationCache DCRelation; CDCHwndCache DCHwndCache; CDCRefCache DCRef; // HDC reference count //CPaintBufferCache PaintBufferCache; wstring nullstring; BOOL g_ccbRender = true; BOOL g_ccbCache = true; HFONT g_alterGUIFont = NULL; HFONT g_alterSysFont = NULL; //BOOL FreeTypeGetTextExtentPoint(HDC hdc, LPCSTR lpString, int cbString, LPSIZE lpSize, const FREETYPE_PARAMS* params); HFONT GetCurrentFont(HDC hdc) { HFONT hCurFont = (HFONT)GetCurrentObject(hdc, OBJ_FONT); if (!hCurFont) { // NULLの場合はSystemを設定しておく hCurFont = (HFONT)GetStockObject(SYSTEM_FONT); } return hCurFont; } //判断是否是有效普通显示DC,用于跳过字幕 BOOL IsValidDC(HDC hdc) { if (GetDeviceCaps(hdc, TECHNOLOGY) != DT_RASDISPLAY) { return FALSE; } return TRUE; } BOOL IsProcessExcluded() { // if (GetModuleHandle(NULL) == GetModuleHandle(_T("gdi++.exe"))) { // return TRUE; // } const CGdippSettings* pSettings = CGdippSettings::GetInstanceNoInit(); if (pSettings->IsInclude()) { if (pSettings->IsProcessIncluded()) { return FALSE; } return TRUE; } if (pSettings->IsProcessExcluded()) { return TRUE; } return FALSE; } BOOL IsProcessUnload() { // if (GetModuleHandle(NULL) == GetModuleHandle(_T("gdi++.exe"))) { // return TRUE; // } const CGdippSettings* pSettings = CGdippSettings::GetInstanceNoInit(); if (pSettings->IsInclude()) { if (pSettings->IsProcessIncluded()) { return FALSE; } return TRUE; } if (pSettings->IsProcessUnload()) { return TRUE; } return FALSE; } BOOL IsExeUnload(LPCTSTR lpApp) { const CGdippSettings* pSettings = CGdippSettings::GetInstanceNoInit(); if (pSettings->IsInclude()) { if (pSettings->IsExeInclude(lpApp)) { return FALSE; } return TRUE; } if (pSettings->IsExeUnload(lpApp)) { return TRUE; } return FALSE; } //切り上げ除算 int div_ceil(int a, int b) { if(a % b) return (a>0)? (a/b+1): (a/b-1); return a / b; } template //修改这个函数,使它在失败的时候返回false,由调用者负责调用Windows原函数,实现线程安全。 BOOL _GetTextExtentPoint32AorW(HDC hdc, _TCHAR* lpString, int cbString, LPSIZE lpSize) { const CGdippSettings* pSettings = CGdippSettings::GetInstance(); if (pSettings->WidthMode() == SETTING_WIDTHMODE_GDI32 || !IsValidDC(hdc) || !lpString || cbString <= 0) { return false; } FREETYPE_PARAMS params(0, hdc); if(FreeTypeGetTextExtentPoint(hdc, lpString, cbString, lpSize, ¶ms)) { Dbg_TractGetTextExtent(lpString, cbString, lpSize); return TRUE; } else return false; } //firefox /* BOOL WINAPI IMPL_GetTextExtentPoint32A(HDC hdc, LPCSTR lpString, int cbString, LPSIZE lpSize) { //CThreadCounter __counter; //CCriticalSectionLock __lock; return _GetTextExtentPoint32AorW(hdc, lpString, cbString, lpSize) || ORIG_GetTextExtentPoint32A(hdc, lpString, cbString, lpSize); } BOOL WINAPI IMPL_GetTextExtentPoint32W(HDC hdc, LPCWSTR lpString, int cbString, LPSIZE lpSize) { //CThreadCounter __counter; //CCriticalSectionLock __lock; return _GetTextExtentPoint32AorW(hdc, lpString, cbString, lpSize) || ORIG_GetTextExtentPoint32W(hdc, lpString, cbString, lpSize); } BOOL WINAPI IMPL_GetTextExtentPointA(HDC hdc, LPCSTR lpString, int cbString, LPSIZE lpSize) { //CThreadCounter __counter; //CCriticalSectionLock __lock; return _GetTextExtentPoint32AorW(hdc, lpString, cbString, lpSize) || ORIG_GetTextExtentPoint32A(hdc, lpString, cbString, lpSize); } BOOL WINAPI IMPL_GetTextExtentPointW(HDC hdc, LPCWSTR lpString, int cbString, LPSIZE lpSize) { //CThreadCounter __counter; //CCriticalSectionLock __lock; return _GetTextExtentPoint32AorW(hdc, lpString, cbString, lpSize) || ORIG_GetTextExtentPoint32W(hdc, lpString, cbString, lpSize); } BOOL WINAPI IMPL_GetCharWidthW(HDC hdc, UINT iFirstChar, UINT iLastChar, LPINT lpBuffer) { //CThreadCounter __counter; const CGdippSettings* pSettings = CGdippSettings::GetInstance(); if (pSettings->WidthMode() == SETTING_WIDTHMODE_GDI32 || !IsValidDC(hdc) || !lpBuffer || !FreeTypeGetCharWidth(hdc, iFirstChar, iLastChar, lpBuffer)) { return ORIG_GetCharWidthW(hdc, iFirstChar, iLastChar, lpBuffer); } return TRUE; } BOOL WINAPI IMPL_GetCharWidth32W(HDC hdc, UINT iFirstChar, UINT iLastChar, LPINT lpBuffer) { //CThreadCounter __counter; TRACE(_T("GetCharWidth32W(%u, %u, {...})\n"), iFirstChar, iLastChar); const CGdippSettings* pSettings = CGdippSettings::GetInstance(); if (pSettings->WidthMode() == SETTING_WIDTHMODE_GDI32 || !IsValidDC(hdc) || !lpBuffer || !FreeTypeGetCharWidth(hdc, iFirstChar, iLastChar, lpBuffer)) { return ORIG_GetCharWidth32W(hdc, iFirstChar, iLastChar, lpBuffer); } return TRUE; }*/ /* extern PFNLdrGetProcedureAddress LdrGetProcedureAddress; int MyGetProcAddress(HMODULE dll, LPSTR funcname) { ANSI_STRING dumy; dumy.Length = strlen(funcname); dumy.MaximumLength = strlen(funcname); dumy.Buffer = funcname; int nRet; LdrGetProcedureAddress(dll,&dumy,0,(void**)&nRet); return nRet; }*/ /* LONG WINAPI IMPL_LdrLoadDll(IN PWCHAR PathToFile OPTIONAL, IN ULONG Flags OPTIONAL, IN UNICODE_STRING2* ModuleFileName, OUT HANDLE* ModuleHandle) { static bool bFisrtTimeHook = GetModuleHandle(_T("d2d1.dll"))!=0; if (!bD2D1Loaded) { wstring filename = wstring(ModuleFileName->Buffer); int last_slash=filename.find_last_of('\\'); if (last_slash!=-1) filename.erase(0,last_slash+1); //删除路径 if (_wcsicmp(filename.c_str(), L"d2d1.dll")==0) //正在载入d2d1.dll { bD2D1Loaded = true; LONG result = ORIG_LdrLoadDll(PathToFile, Flags, ModuleFileName, ModuleHandle); HookD2D1((HMODULE)*ModuleHandle); return result; } if (bFisrtTimeHook) { bFisrtTimeHook = false; bD2D1Loaded = true; HookD2D1(GetModuleHandle(_T("d2d1.dll"))); } } return ORIG_LdrLoadDll(PathToFile, Flags, ModuleFileName, ModuleHandle); }*/ /* BOOL WINAPI IMPL_CreateProcessInternalW( HANDLE hToken, LPCTSTR lpApplicationName, LPTSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, \ DWORD dwCreationFlags, LPVOID lpEnvironment, LPCTSTR lpCurrentDirectory, LPSTARTUPINFO lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation , PHANDLE hNewToken) { //CThreadCounter __counter; CCriticalSectionLock __lock; return _CreateProcessInternalW(hToken, lpApplicationName, lpCommandLine, lpProcessAttributes, lpThreadAttributes, bInheritHandles, dwCreationFlags, lpEnvironment, lpCurrentDirectory, lpStartupInfo, lpProcessInformation, hNewToken, ORIG_CreateProcessInternalW); }*/ /* BOOL WINAPI IMPL_nCreateProcessA(LPCSTR lpApp, LPSTR lpCmd, LPSECURITY_ATTRIBUTES pa, LPSECURITY_ATTRIBUTES ta, BOOL bInherit, DWORD dwFlags, LPVOID lpEnv, LPCSTR lpDir, LPSTARTUPINFOA psi, LPPROCESS_INFORMATION ppi) { //CThreadCounter __counter; CCriticalSectionLock __lock; TRACE(_T("CreateProcessA(\"%hs\", \"%hs\", ...)\n"), lpApp, lpCmd); return _CreateProcessAorW(lpApp, lpCmd, pa, ta, bInherit, dwFlags, lpEnv, lpDir, psi, ppi, ORIG_nCreateProcessA); } BOOL WINAPI IMPL_nCreateProcessW(LPCWSTR lpApp, LPWSTR lpCmd, LPSECURITY_ATTRIBUTES pa, LPSECURITY_ATTRIBUTES ta, BOOL bInherit, DWORD dwFlags, LPVOID lpEnv, LPCWSTR lpDir, LPSTARTUPINFOW psi, LPPROCESS_INFORMATION ppi) { //CThreadCounter __counter; CCriticalSectionLock __lock; TRACE(_T("CreateProcessW(\"%ls\", \"%ls\", ...)\n"), lpApp, lpCmd); return _CreateProcessAorW(lpApp, lpCmd, pa, ta, bInherit, dwFlags, lpEnv, lpDir, psi, ppi, ORIG_nCreateProcessW); } BOOL WINAPI IMPL_CreateProcessAsUserA(HANDLE hToken, LPCSTR lpApp, LPSTR lpCmd, LPSECURITY_ATTRIBUTES pa, LPSECURITY_ATTRIBUTES ta, BOOL bInherit, DWORD dwFlags, LPVOID lpEnv, LPCSTR lpDir, LPSTARTUPINFOA psi, LPPROCESS_INFORMATION ppi) { //CThreadCounter __counter; CCriticalSectionLock __lock; TRACE(_T("CreateProcessA(\"%hs\", \"%hs\", ...)\n"), lpApp, lpCmd); return _CreateProcessAsUserAorW(hToken, lpApp, lpCmd, pa, ta, bInherit, dwFlags, lpEnv, lpDir, psi, ppi, ORIG_CreateProcessAsUserA); } BOOL WINAPI IMPL_CreateProcessAsUserW(HANDLE hToken, LPCWSTR lpApp, LPWSTR lpCmd, LPSECURITY_ATTRIBUTES pa, LPSECURITY_ATTRIBUTES ta, BOOL bInherit, DWORD dwFlags, LPVOID lpEnv, LPCWSTR lpDir, LPSTARTUPINFOW psi, LPPROCESS_INFORMATION ppi) { //CThreadCounter __counter; CCriticalSectionLock __lock; TRACE(_T("CreateProcessW(\"%ls\", \"%ls\", ...)\n"), lpApp, lpCmd); return _CreateProcessAsUserAorW(hToken, lpApp, lpCmd, pa, ta, bInherit, dwFlags, lpEnv, lpDir, psi, ppi, ORIG_CreateProcessAsUserW); }*/ /* HOOK_DEFINE(user32.dll, DWORD, GetTabbedTextExtentA, (HDC hdc, LPCSTR lpString, int nCount, int nTabPositions, CONST LPINT lpnTabStopPositions), (hdc, lpString, nCount, nTabPositions, lpnTabStopPositions)) HOOK_DEFINE(user32.dll, DWORD, GetTabbedTextExtentW, (HDC hdc, LPCWSTR lpString, int nCount, int nTabPositions, CONST LPINT lpnTabStopPositions), (hdc, lpString, nCount, nTabPositions, lpnTabStopPositions)) HOOK_DEFINE(gdi32.dll, BOOL, GetTextExtentExPointA, (HDC hdc, LPCSTR lpszStr, int cchString, int nMaxExtent, LPINT lpnFit, LPINT lpDx, LPSIZE lpSize), (hdc, lpszStr, cchString, nMaxExtent, lpnFit, lpDx, lpSize)) HOOK_DEFINE(gdi32.dll, BOOL, GetTextExtentExPointW, (HDC hdc, LPCWSTR lpszStr, int cchString, int nMaxExtent, LPINT lpnFit, LPINT lpDx, LPSIZE lpSize), (hdc, lpszStr, cchString, nMaxExtent, lpnFit, lpDx, lpSize)) HOOK_DEFINE(gdi32.dll, BOOL, GetTextExtentExPointI, (HDC hdc, LPWORD pgiIn, int cgi, int nMaxExtent, LPINT lpnFit, LPINT lpDx, LPSIZE lpSize), (hdc, pgiIn, cgi, nMaxExtent, lpnFit, lpDx, lpSize)) HOOK_DEFINE(gdi32.dll, BOOL, GetTextExtentPointA, (HDC hdc, LPCSTR lpString, int cbString, LPSIZE lpSize), (hdc, lpString, cbString, lpSize)) HOOK_DEFINE(gdi32.dll, BOOL, GetTextExtentPointW, (HDC hdc, LPCWSTR lpString, int cbString, LPSIZE lpSize), (hdc, lpString, cbString, lpSize)) HOOK_DEFINE(gdi32.dll, BOOL, GetTextExtentPointI, (HDC hdc, LPWORD pgiIn, int cgi, LPSIZE lpSize), (hdc, pgiIn, cgi, lpSize)) */ /* HFONT WINAPI IMPL_CreateFontA(int nHeight, int nWidth, int nEscapement, int nOrientation, int fnWeight, DWORD fdwItalic, DWORD fdwUnderline, DWORD fdwStrikeOut, DWORD fdwCharSet, DWORD fdwOutputPrecision, DWORD fdwClipPrecision, DWORD fdwQuality, DWORD fdwPitchAndFamily, LPCSTR lpszFace) { LOGFONTA lf = { nHeight, nWidth, nEscapement, nOrientation, fnWeight, !!fdwItalic, !!fdwUnderline, !!fdwStrikeOut, (BYTE)fdwCharSet, (BYTE)fdwOutputPrecision, (BYTE)fdwClipPrecision, (BYTE)fdwQuality, (BYTE)fdwPitchAndFamily, }; if (lpszFace) strncpy(lf.lfFaceName, lpszFace, LF_FACESIZE - 1); return IMPL_CreateFontIndirectA(&lf); } HFONT WINAPI IMPL_CreateFontW(int nHeight, int nWidth, int nEscapement, int nOrientation, int fnWeight, DWORD fdwItalic, DWORD fdwUnderline, DWORD fdwStrikeOut, DWORD fdwCharSet, DWORD fdwOutputPrecision, DWORD fdwClipPrecision, DWORD fdwQuality, DWORD fdwPitchAndFamily, LPCWSTR lpszFace) { LOGFONTW lf = { nHeight, nWidth, nEscapement, nOrientation, fnWeight, !!fdwItalic, !!fdwUnderline, !!fdwStrikeOut, (BYTE)fdwCharSet, (BYTE)fdwOutputPrecision, (BYTE)fdwClipPrecision, (BYTE)fdwQuality, (BYTE)fdwPitchAndFamily, }; if (lpszFace) wcsncpy(lf.lfFaceName, lpszFace, LF_FACESIZE - 1); return IMPL_CreateFontIndirectW(&lf); } HFONT WINAPI IMPL_CreateFontIndirectA(CONST LOGFONTA *lplfA) { if(!lplfA) { SetLastError(ERROR_INVALID_PARAMETER); return NULL; } const CGdippSettings* pSettings = CGdippSettings::GetInstance(); if (pSettings->IsFontExcluded(lplfA->lfFaceName)) { return ORIG_CreateFontIndirectA(lplfA); } LOGFONT lf = { lplfA->lfHeight, lplfA->lfWidth, lplfA->lfEscapement, lplfA->lfOrientation, lplfA->lfWeight, lplfA->lfItalic, lplfA->lfUnderline, lplfA->lfStrikeOut, lplfA->lfCharSet, lplfA->lfOutPrecision, lplfA->lfClipPrecision, lplfA->lfQuality, lplfA->lfPitchAndFamily, }; MultiByteToWideChar(CP_ACP, 0, lplfA->lfFaceName, LF_FACESIZE, lf.lfFaceName, LF_FACESIZE); LOGFONT* lplf = &lf; if (pSettings->CopyForceFont(lf, lf)) { lplf = &lf; } HFONT hf = IMPL_CreateFontIndirectW(lplf); // if(hf && lplf && !pSettings->LoadOnDemand()) { // AddFontToFT(lplf->lfFaceName, lplf->lfWeight, !!lplf->lfItalic); // } return hf; } */ //Snowie!! LPCWSTR GetCachedFont(HFONT lFont) { CFontCache::const_iterator it= FontCache.find(lFont); if (it==FontCache.end()) return NULL; else return it->second->lpRealName; } LPCWSTR GetCachedFontLocale(HFONT lFont) { CFontCache::const_iterator it= FontCache.find(lFont); if (it==FontCache.end()) return NULL; else return it->second->lpGDIName; } void AddToCachedFont(HFONT lfont, LPWSTR lpFaceName, LPWSTR lpGDIName) { if (!lfont) return; //不可以添加空节点 CCriticalSectionLock __lock(CCriticalSectionLock::CS_CACHEDFONT); if (GetCachedFont(lfont)) return; //已经存在的字体 FontCache[lfont] = new CFontSubResult(lpFaceName, lpGDIName); } void DeleteCachedFont(HFONT lfont) { if (!lfont) return; //不可以删除头结点 CCriticalSectionLock __lock(CCriticalSectionLock::CS_CACHEDFONT); CFontCache::iterator it= FontCache.find(lfont); if (it!=FontCache.end()) { delete it->second; FontCache.erase(it); } } int WINAPI IMPL_GetTextFaceAliasW(HDC hdc, int nLen, LPWSTR lpAliasW) { //CThreadCounter __counter; int bResult = ORIG_GetTextFaceAliasW(hdc, nLen, lpAliasW); //LOGFONT lf, lf2; //StringCchCopy(lf.lfFaceName, LF_FACESIZE, lpAliasW); //LOGFONT * lplf = &lf; LPCWSTR fontcache=GetCachedFont(GetCurrentFont(hdc)); if (fontcache){ if (lpAliasW) StringCchCopy(lpAliasW, LF_FACESIZE, fontcache); bResult = wcslen(fontcache)+1; } return bResult; } // Won't get any better for clipbox, obsolete. /* cache::lru_cache FontHeightCache(200); // cache 200 most frequently used fonts' height const WCHAR TEST_ALPHABET_SEQUENCE[] = L"ABCDEFGHIJKLMNOPQRSTUVWXYZ"; int GetFontMaxAlphabetHeight(HDC dc, MAT2 *lpmt2) { HFONT ft = GetCurrentFont(dc); if (FontHeightCache.exists(ft)) return FontHeightCache.get(ft); GLYPHMETRICS lppm = { 0 }; int nHeight = 0; for (int i = 0; i < 26; ++i) { ORIG_GetGlyphOutlineW(dc, TEST_ALPHABET_SEQUENCE[i], GGO_METRICS, &lppm, 0, 0, lpmt2); if (lppm.gmptGlyphOrigin.y>nHeight) nHeight = lppm.gmptGlyphOrigin.y; } FontHeightCache.put(ft, nHeight); return nHeight; }*/ DWORD WINAPI IMPL_GetGlyphOutlineW(__in HDC hdc, __in UINT uChar, __in UINT fuFormat, __out LPGLYPHMETRICS lpgm, __in DWORD cjBuffer, __out_bcount_opt(cjBuffer) LPVOID pvBuffer, __in CONST MAT2 *lpmat2) { const CGdippSettings* pSettings = CGdippSettings::GetInstance(); DWORD ret= ORIG_GetGlyphOutlineW(hdc, uChar, fuFormat, lpgm, cjBuffer, pvBuffer, lpmat2); if (pSettings->EnableClipBoxFix() && (!cjBuffer || !pvBuffer)) { if (!(fuFormat & (GGO_BITMAP | GGO_GRAY2_BITMAP | GGO_GRAY4_BITMAP | GGO_GRAY8_BITMAP | GGO_NATIVE))) { //lpgm->gmptGlyphOrigin.x -= 1; //lpgm->gmptGlyphOrigin.y += 1; //lpgm->gmBlackBoxX += 3; //lpgm->gmBlackBoxY += 2; static int n = (int)floor(1.5*pSettings->ScreenDpi() / 96); int nDeltaY = n, nDeltaBlackY = n; TEXTMETRIC tm = { 0 }; GetTextMetrics(hdc, &tm); if (lpgm->gmptGlyphOrigin.y < tm.tmAscent) { // origin out of the top of the box if (lpgm->gmptGlyphOrigin.y + nDeltaY>tm.tmAscent) { nDeltaY = tm.tmAscent - lpgm->gmptGlyphOrigin.y; // limit the top position of the origin } } else nDeltaY = 0; lpgm->gmptGlyphOrigin.y += nDeltaY; /*if (lpgm->gmptGlyphOrigin.x > 0) lpgm->gmBlackBoxX += n; // increase blackbox width if it's not a ligature if (lpgm->gmBlackBoxX > tm.tmMaxCharWidth) { lpgm->gmBlackBoxX = tm.tmMaxCharWidth; }*/ lpgm->gmBlackBoxY += nDeltaY; if (tm.tmAscent - lpgm->gmptGlyphOrigin.y + lpgm->gmBlackBoxY - 1 < tm.tmHeight) // still has some room to scale up { if (tm.tmAscent - lpgm->gmptGlyphOrigin.y + lpgm->gmBlackBoxY + 1 + nDeltaBlackY > tm.tmHeight) lpgm->gmBlackBoxY = tm.tmHeight - tm.tmAscent + lpgm->gmptGlyphOrigin.y + 1; else lpgm->gmBlackBoxY += nDeltaBlackY; } } } // TEXTMETRIC tm; // GetTextMetrics(hdc, &tm); return ret; } DWORD WINAPI IMPL_GetGlyphOutlineA(__in HDC hdc, __in UINT uChar, __in UINT fuFormat, __out LPGLYPHMETRICS lpgm, __in DWORD cjBuffer, __out_bcount_opt(cjBuffer) LPVOID pvBuffer, __in CONST MAT2 *lpmat2) { //fuFormat |= GGO_UNHINTED; const CGdippSettings* pSettings = CGdippSettings::GetInstance(); DWORD ret= ORIG_GetGlyphOutlineA(hdc, uChar, fuFormat, lpgm, cjBuffer, pvBuffer, lpmat2); // if (pSettings->EnableClipBoxFix()) // { // lpgm->gmptGlyphOrigin.y+=1; // lpgm->gmBlackBoxY+=1; // } if (pSettings->EnableClipBoxFix() && (!cjBuffer || !pvBuffer)) { if (!(fuFormat & (GGO_BITMAP | GGO_GRAY2_BITMAP | GGO_GRAY4_BITMAP | GGO_GRAY8_BITMAP | GGO_NATIVE))) { static int n = (int)floor(1.5*pSettings->ScreenDpi() / 96); int nDeltaY = n, nDeltaBlackY = n; TEXTMETRIC tm = { 0 }; GetTextMetrics(hdc, &tm); if (lpgm->gmptGlyphOrigin.y < tm.tmAscent) { // origin out of the top of the box if (lpgm->gmptGlyphOrigin.y + nDeltaY>tm.tmAscent) { nDeltaY = tm.tmAscent - lpgm->gmptGlyphOrigin.y; // limit the top position of the origin } } else nDeltaY = 0; /*if (lpgm->gmptGlyphOrigin.x > 0) lpgm->gmBlackBoxX += n; // increase blackbox width if it's not a ligature if (lpgm->gmBlackBoxX > tm.tmMaxCharWidth) { lpgm->gmBlackBoxX = tm.tmMaxCharWidth; }*/ lpgm->gmptGlyphOrigin.y += nDeltaY; lpgm->gmBlackBoxY += nDeltaY; if (tm.tmAscent - lpgm->gmptGlyphOrigin.y + lpgm->gmBlackBoxY - 1 < tm.tmHeight) { if (tm.tmAscent - lpgm->gmptGlyphOrigin.y + lpgm->gmBlackBoxY + 1 + nDeltaBlackY > tm.tmHeight) lpgm->gmBlackBoxY = tm.tmHeight - tm.tmAscent + lpgm->gmptGlyphOrigin.y + 1; else lpgm->gmBlackBoxY += nDeltaBlackY; } } } return ret; } int WINAPI IMPL_GetTextFaceW( __in HDC hdc, __in int c, __out_ecount_part_opt(c, return) LPWSTR lpName) { int nSize = ORIG_GetTextFaceW(hdc, c, lpName); LPCWSTR fontcache=GetCachedFontLocale(GetCurrentFont(hdc)); if (fontcache){ if (lpName) { int len = Min(LF_FACESIZE, c); StringCchCopy(lpName, len, fontcache); nSize = (int)wcslen(fontcache) > len ? len : wcslen(fontcache) + 1; } else { // a request for the size of font nSize = Min(LF_FACESIZE, (int)wcslen(fontcache)+1); } } return nSize; } int WINAPI IMPL_GetTextFaceA( __in HDC hdc, __in int c, __out_ecount_part_opt(c, return) LPSTR lpName) { int nSize = ORIG_GetTextFaceA(hdc, c, lpName); LPCWSTR fontcache=GetCachedFontLocale(GetCurrentFont(hdc)); if (fontcache){ //int len=Min(LF_FACESIZE, c); size_t _Dsize = 2 * wcslen(fontcache) + 1; char *_Dest = new char[_Dsize]; memset(_Dest,0,_Dsize); int len =wcstombs(_Dest, fontcache, _Dsize); if (lpName) StringCchCopyA(lpName, LF_FACESIZE, _Dest); delete[] _Dest; nSize = len+1; } return nSize; } HGDIOBJ WINAPI IMPL_GetStockObject(__in int i) { switch (i) { case DEFAULT_GUI_FONT: { static const CGdippSettings* pSetting = CGdippSettings::GetInstance(); if (g_alterGUIFont) return g_alterGUIFont; else return ORIG_GetStockObject(i); } /* case SYSTEM_FONT: { if (g_alterSysFont) return g_alterSysFont; break; }*/ default: return ORIG_GetStockObject(i); } return ORIG_GetStockObject(i); } BOOL WINAPI IMPL_BeginPath(HDC hdc) { //CThreadCounter __counter; BOOL ret=ORIG_BeginPath(hdc); if (ret) { DCArray.insert(hdc); } return ret; } BOOL WINAPI IMPL_EndPath(HDC hdc) { //CThreadCounter __counter; BOOL ret=ORIG_EndPath(hdc); if (ret) { DCArray.erase(hdc); } return ret; } BOOL WINAPI IMPL_AbortPath(HDC hdc) { //CThreadCounter __counter; BOOL ret=ORIG_AbortPath(hdc); if (ret) { DCArray.erase(hdc); } return ret; } int WINAPI IMPL_GetObjectA(__in HANDLE h, __in int c, __out_bcount_opt(c) LPVOID pv) { int ret = ORIG_GetObjectA(h, c, pv); if (ret==sizeof(LOGFONTA)) { LPCWSTR fontcache = GetCachedFont((HFONT)h); if (fontcache && pv) { size_t _Dsize = 2 * wcslen(fontcache) + 1; char *_Dest = new char[_Dsize]; memset(_Dest,0,_Dsize); wcstombs(_Dest,fontcache,_Dsize); StringCchCopyA(((LOGFONTA*)pv)->lfFaceName, LF_FACESIZE, _Dest); delete []_Dest; } } return ret; } int WINAPI IMPL_GetObjectW(__in HANDLE h, __in int c, __out_bcount_opt(c) LPVOID pv) { int ret = ORIG_GetObjectW(h, c, pv); if (ret==sizeof(LOGFONTW)) { LPCWSTR fontcache = GetCachedFont((HFONT)h); if (fontcache && pv) { StringCchCopyW(((LOGFONTW*)pv)->lfFaceName, LF_FACESIZE, fontcache); } } return ret; } HFONT WINAPI IMPL_CreateFontIndirectExW(CONST ENUMLOGFONTEXDV *penumlfex) { if (!penumlfex) return NULL; TRACE(L"Creating font \"%s\"\n", penumlfex->elfEnumLogfontEx.elfLogFont.lfFaceName); { if (penumlfex->elfEnumLogfontEx.elfLogFont.lfClipPrecision == FONT_MAGIC_NUMBER) { TRACE(L"Engine font, Ignored, "); ((ENUMLOGFONTEXDV *)penumlfex)->elfEnumLogfontEx.elfLogFont.lfClipPrecision = 0; return ORIG_CreateFontIndirectExW(penumlfex); } } /* GetEnvironmentVariableW(L"MACTYPE_FONTSUBSTITUTES_ENV", NULL, 0); if (GetLastError()!=ERROR_ENVVAR_NOT_FOUND) return ORIG_CreateFontIndirectExW(penumlfex);*/ if(!penumlfex) { SetLastError(ERROR_INVALID_PARAMETER); return NULL; } const CGdippSettings* pSettings = CGdippSettings::GetInstance(); if (pSettings->IsFontExcluded(penumlfex->elfEnumLogfontEx.elfLogFont.lfFaceName)) { TRACE(L"Font exception! "); return ORIG_CreateFontIndirectExW(penumlfex); //TRACE(L"Handle = %x\n" , (int)h); } ENUMLOGFONTEXDV mfont(*penumlfex); LOGFONT& lf = mfont.elfEnumLogfontEx.elfLogFont; LOGFONT lfOrg(lf); BOOL bForced = false; if (bForced = pSettings->CopyForceFont(lf, lfOrg)) { /* mfont->elfEnumLogfontEx.elfLogFont.lfHeight = lf.lfHeight; // mfont->elfEnumLogfontEx.elfLogFont.lfWidth = lfOrg.lfWidth; mfont->elfEnumLogfontEx.elfLogFont.lfWidth = lf.lfWidth; mfont->elfEnumLogfontEx.elfLogFont.lfEscapement = lf.lfEscapement; mfont->elfEnumLogfontEx.elfLogFont.lfOrientation = lf.lfOrientation; mfont->elfEnumLogfontEx.elfLogFont.lfWeight = lf.lfWeight; mfont->elfEnumLogfontEx.elfLogFont.lfItalic = lf.lfItalic; mfont->elfEnumLogfontEx.elfLogFont.lfUnderline = lf.lfUnderline; mfont->elfEnumLogfontEx.elfLogFont.lfStrikeOut = lf.lfStrikeOut; mfont->elfEnumLogfontEx.elfLogFont.lfCharSet = lf.lfCharSet; mfont->elfEnumLogfontEx.elfLogFont.lfOutPrecision = 0; mfont->elfEnumLogfontEx.elfLogFont.lfClipPrecision = 0; mfont->elfEnumLogfontEx.elfLogFont.lfQuality = 0; mfont->elfEnumLogfontEx.elfLogFont.lfPitchAndFamily = 0; StringCchCopy(mfont->elfEnumLogfontEx.elfLogFont.lfFaceName, LF_FACESIZE, lf.lfFaceName);*/ TRACE(L"Font substitutes to \"%s\"\n", lf.lfFaceName); } else TRACE(L"Normal font\n"); //bypass = true; HFONT hf = ORIG_CreateFontIndirectExW(&mfont); //ORIG_CreateFontIndirectExW( //if(hf && lplf && !pSettings->LoadOnDemand()) { // AddFontToFT(lplf->lfFaceName, lplf->lfWeight, !!lplf->lfItalic); //} if (hf && bForced) { AddToCachedFont(hf, (WCHAR*)penumlfex->elfEnumLogfontEx.elfLogFont.lfFaceName, (WCHAR *)lfOrg.lfFaceName); } //bypass = false; TRACE(L"Create font %s handle %x\n", lfOrg.lfFaceName, (int)hf); return hf; } BOOL WINAPI IMPL_DeleteObject(HGDIOBJ hObject) { //CThreadCounter __counter; if (hObject == g_alterGUIFont) //我的系统字体,不可以释放掉 return true; BOOL bResult = ORIG_DeleteObject(hObject); if (bResult) DeleteCachedFont((HFONT)hObject); return bResult; } HFONT WINAPI IMPL_CreateFontIndirectW(CONST LOGFONTW *lplf) //重新启用这个hook,只为兼容搜狗输入法 { ENUMLOGFONTEXDVW envlf = {0}; memcpy(&envlf.elfEnumLogfontEx.elfLogFont, lplf, sizeof(LOGFONTW)); return IMPL_CreateFontIndirectExW(&envlf); } /* BOOL WINAPI IMPL_DrawStateA(HDC hdc, HBRUSH hbr, DRAWSTATEPROC lpOutputFunc, LPARAM lData, WPARAM wData, int x, int y, int cx, int cy, UINT uFlags) { //CThreadCounter __counter; int cchW; LPWSTR lpStringW; if(lData && uFlags & DSS_DISABLED) { switch(uFlags & 0x0f) { case DST_TEXT: case DST_PREFIXTEXT: lpStringW = _StrDupAtoW((LPCSTR)lData, wData ? wData : -1, &cchW); if(lpStringW) { BOOL ret = IMPL_DrawStateW(hdc, hbr, lpOutputFunc, (LPARAM)lpStringW, cchW, x, y, cx, cy, uFlags); free(lpStringW); return ret; } break; } } return ORIG_DrawStateA(hdc, hbr, lpOutputFunc, lData, wData, x, y, cx, cy, uFlags); } //灰色描画をDrawTextへ投げる //DrawTextは内部でExtTextOutしてくれるので問題なし BOOL WINAPI IMPL_DrawStateW(HDC hdc, HBRUSH hbr, DRAWSTATEPROC lpOutputFunc, LPARAM lData, WPARAM wData, int x, int y, int cx, int cy, UINT uFlags) { //CThreadCounter __counter; if(lData && uFlags & DSS_DISABLED) { switch(uFlags & 0x0f) { case DST_TEXT: case DST_PREFIXTEXT: { //wData==0の時に文字数自動計算 //他のAPIと違って-1の時ではない if(wData == 0) { wData = wcslen((LPCWSTR)lData); } RECT rect = { x, y, x + 10000, y + 10000 }; //どうやら3DHighLightの上に1pxずらして3DShadowを重ねてるらしい int oldbm = SetBkMode(hdc, TRANSPARENT); COLORREF oldfg = SetTextColor(hdc, GetSysColor(COLOR_3DHIGHLIGHT)); //DrawStateとDrawTextではprefixのフラグが逆(APIの設計ダメすぎ) const UINT uDTFlags = DT_SINGLELINE | DT_NOCLIP | (uFlags & DST_PREFIXTEXT ? 0 : DT_NOPREFIX); OffsetRect(&rect, 1, 1); DrawTextW(hdc, (LPCWSTR)lData, wData, &rect, uDTFlags); SetTextColor(hdc, GetSysColor(COLOR_3DSHADOW)); OffsetRect(&rect, -1, -1); DrawTextW(hdc, (LPCWSTR)lData, wData, &rect, uDTFlags); SetTextColor(hdc, oldfg); SetBkMode(hdc, oldbm); } return TRUE; } } return ORIG_DrawStateW(hdc, hbr, lpOutputFunc, lData, wData, x, y, cx, cy, uFlags); }*/ class FreeTypeFontEngine; extern FreeTypeFontEngine* g_pFTEngine; BOOL __stdcall IMPL_RemoveFontResourceExW(__in LPCWSTR name, __in DWORD fl, __reserved PVOID pdv) { g_pFTEngine->RemoveFont(name); return ORIG_RemoveFontResourceExW(name, fl, pdv); } /* BOOL __stdcall IMPL_RemoveFontResourceW(__in LPCWSTR lpFileName) { g_pFTEngine->RemoveFont(lpFileName); return ORIG_RemoveFontResourceW(lpFileName); }*/ BOOL WINAPI IMPL_TextOutA(HDC hdc, int nXStart, int nYStart, LPCSTR lpString, int cbString) { //CThreadCounter __counter; return IMPL_ExtTextOutA(hdc, nXStart, nYStart, NULL, NULL, lpString, cbString, NULL); } BOOL WINAPI IMPL_TextOutW(HDC hdc, int nXStart, int nYStart, LPCWSTR lpString, int cbString) { //CThreadCounter __counter; return IMPL_ExtTextOutW(hdc, nXStart, nYStart, NULL, NULL, lpString, cbString, NULL); } void AnsiDxToUnicodeDx(LPCSTR lpStringA, int cbString, const int* lpDxA, int* lpDxW, int ACP) { LPCSTR lpEndA = lpStringA + cbString; while(lpStringA < lpEndA) { *lpDxW = *lpDxA++; if(IsDBCSLeadByteEx(ACP, *lpStringA)) { *lpDxW += *lpDxA++; lpStringA++; } lpDxW++; lpStringA++; } } // ANSI->Unicodeに変換してExtTextOutWに投げるExtTextOutA BOOL WINAPI IMPL_ExtTextOutA(HDC hdc, int nXStart, int nYStart, UINT fuOptions, CONST RECT *lprc, LPCSTR lpString, UINT cbString, CONST INT *lpDx) { //CThreadCounter __counter; if (!hdc || !lpString || !cbString || !g_ccbRender || !(fuOptions & ETO_IGNORELANGUAGE)) { return ORIG_ExtTextOutA(hdc, nXStart, nYStart, fuOptions, lprc, lpString, cbString, lpDx); } //However, if the ANSI version of ExtTextOut is called with ETO_GLYPH_INDEX, //the function returns TRUE even though the function does nothing. //とりあえずオリジナルに飛ばす if (fuOptions & ETO_GLYPH_INDEX) return ORIG_ExtTextOutA(hdc, nXStart, nYStart, fuOptions, lprc, lpString, cbString, lpDx); //HDBENCHチート // if (lpString && cbString == 7 && pSettings->IsHDBench() && (memcmp(lpString, "HDBENCH", 7) == 0 || memcmp(lpString, " ", 7) == 0)) // return ORIG_ExtTextOutA(hdc, nXStart, nYStart, fuOptions, lprc, lpString, cbString, lpDx); LPWSTR lpszUnicode; int bufferLength; BOOL result; WCHAR szStack[CCH_MAX_STACK]; int dxStack[CCH_MAX_STACK]; int nACP = GdiGetCodePage(hdc);//CP_ACP; //DWORD nCharset = GetTextCharsetInfo(hdc, NULL, 0); /* switch (nCharset) { case 0: { break; } case SYMBOL_CHARSET: { nACP = CP_SYMBOL; break; } case MAC_CHARSET: { nACP = CP_MACCP; break; } case OEM_CHARSET: { nACP = CP_OEMCP; break; } default: { CHARSETINFO Cs={0,CP_ACP,0}; TranslateCharsetInfo((DWORD*)nCharset, &Cs, TCI_SRCCHARSET); nACP = Cs.ciACP; } }*/ lpszUnicode = _StrDupExAtoW(lpString, cbString, szStack, CCH_MAX_STACK, &bufferLength, nACP); if(!lpszUnicode) { //メモリ不足: 一応オリジナルに投げとく return ORIG_ExtTextOutA(hdc, nXStart, nYStart, fuOptions, lprc, lpString, cbString, lpDx); } int* lpDxW = NULL; result = FALSE; if(lpDx && cbString && _getmbcp()) { if (cbString < CCH_MAX_STACK) { lpDxW = dxStack; ZeroMemory(lpDxW, sizeof(int) * cbString); } else { lpDxW = (int*)calloc(sizeof(int), cbString); if (!lpDxW) { goto CleanUp; } } if (nACP!=CP_SYMBOL) { AnsiDxToUnicodeDx(lpString, cbString, lpDx, lpDxW, nACP); lpDx = lpDxW; } } result = IMPL_ExtTextOutW(hdc, nXStart, nYStart, fuOptions, lprc, (LPCWSTR)lpszUnicode, bufferLength, lpDx); CleanUp: if (lpszUnicode != szStack) free(lpszUnicode); if (lpDxW != dxStack) free(lpDxW); return result; } typedef enum { ETOE_OK = 0, ETOE_CREATEDC = 1, ETOE_SETFONT = 2, ETOE_CREATEDIB = 3, ETOE_FREETYPE = 4, ETOE_INVALIDARG = 11, ETOE_ROTATION = 12, ETOE_LARGESIZE = 13, ETOE_INVALIDHDC = 14, ETOE_ROTATEFONT = 15, ETOE_NOAREA = 16, ETOE_GETTEXTEXTENT = 17, ETOE_MONO = 18, ETOE_GENERAL = 19, } ExtTextOut_ErrorCode; //例外モドキ #define ETO_TRY() ExtTextOut_ErrorCode error = ETOE_OK; { #define ETO_THROW(code) error = (code); goto _EXCEPTION_THRU #define ETO_CATCH() } _EXCEPTION_THRU: /* BOOL FreeTypeGetTextExtentPoint(HDC hdc, LPCSTR lpString, int cbString, LPSIZE lpSize, const FREETYPE_PARAMS* params) { WCHAR szStack[CCH_MAX_STACK]; int cchStringW; LPWSTR lpStringW = _StrDupExAtoW(lpString, cbString, szStack, CCH_MAX_STACK, &cchStringW); if(!lpStringW) { SetLastError(ERROR_NOT_ENOUGH_MEMORY); return FALSE; } BOOL ret = FreeTypeGetTextExtentPoint(hdc, lpStringW, cchStringW, lpSize, params); if (lpStringW != szStack) free(lpStringW); return ret; }*/ class CETOBitmap { private: CBitmapCache& m_cache; HDC m_hdc; HBITMAP m_hPrevBmp; HBITMAP m_hBmp; BYTE* m_lpPixels; public: CETOBitmap(CBitmapCache& cache) : m_cache(cache) , m_hdc(NULL) , m_hPrevBmp(NULL) , m_hBmp(NULL) , m_lpPixels(NULL) { } HDC CreateDC(HDC dc) { m_hdc = m_cache.CreateDC(dc); return m_hdc; } bool CreateDIBandSelect(int cx, int cy) { m_hBmp = m_cache.CreateDIB(cx, cy, &m_lpPixels); if (!m_hBmp) { return false; } m_hPrevBmp = SelectBitmap(m_hdc, m_hBmp); return true; } void RestoreBitmap() { if (m_hPrevBmp) { SelectBitmap(m_hdc, m_hPrevBmp); m_hPrevBmp = NULL; } } }; // extract the possibly largest integer from the string int StrToBestInt(const WCHAR* wstr) { int result = 0; const WCHAR* ptr = wstr; while ((*ptr < L'0' || *ptr > L'9') && *ptr != L'\0') ++ptr; // fast forward to the digits // Process digits while (*ptr >= L'0' && *ptr <= L'9') { int digit = *ptr - L'0'; // Overflow check if (result > (INT_MAX - digit) / 10) { return -1; // Overflow } result = result * 10 + digit; ++ptr; } return result; } int DisplayFromDC(HDC dc) { if (!dc) { return -1; } CCriticalSectionLock __lock(CCriticalSectionLock::CS_DCRELATION); // fetch realDC from memoryDC auto it = DCRelation.find(dc); if (it != DCRelation.end()) { dc = it->second; } HWND hwnd = NULL; auto dit = DCHwndCache.find(dc); if (dit != DCHwndCache.end()) { hwnd = dit->second; } else { hwnd = WindowFromDC(dc); } if (hwnd) { auto monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONULL); if (!monitor) return -1; // Minimized window? MONITORINFOEX mi; mi.cbSize = sizeof(MONITORINFOEX); GetMonitorInfo(monitor, &mi); TRACE(L"Display name: %s\n", mi.szDevice); return StrToBestInt(mi.szDevice); } else { TRACE(L"!! Display not found: %d -------------\n", dc); } return -1; } extern ControlIder CID; // 取代Windows的ExtTextOutW BOOL WINAPI IMPL_ExtTextOutW(HDC hdc, int nXStart, int nYStart, UINT fuOptions, CONST RECT *lprc, LPCWSTR lpString, UINT cbString, CONST INT *SyslpDx) { //CThreadCounter __counter; //用于安全退出的计数器 INT* lpDx = const_cast(SyslpDx); if (!hdc || !lpString || !cbString || !g_ccbRender || cbString>8192) { //no valid param or rendering is disabled from control center. return ORIG_ExtTextOutW(hdc, nXStart, nYStart, fuOptions, lprc, lpString, cbString, lpDx); } if (!(fuOptions & ETO_GLYPH_INDEX) && cbString==1 && *lpString==32) //空格 return ORIG_ExtTextOutW(hdc, nXStart, nYStart, fuOptions | ETO_IGNORELANGUAGE, lprc, lpString, cbString, lpDx); //空格就不用处理了。。。反正都一样 CThreadLocalInfo* pTLInfo = g_TLInfo.GetPtr(); if(!pTLInfo) { return ORIG_ExtTextOutW(hdc, nXStart, nYStart, fuOptions, lprc, lpString, cbString, lpDx); } if (DCArray.find(hdc)!=DCArray.end()) return ORIG_ExtTextOutW(hdc, nXStart, nYStart, fuOptions, lprc, lpString, cbString, lpDx); if (!(fuOptions & ETO_GLYPH_INDEX) && !(fuOptions & ETO_IGNORELANGUAGE) && !lpDx && CID.myiscomplexscript(lpString,cbString)) //complex script return ORIG_ExtTextOutW(hdc, nXStart, nYStart, fuOptions, lprc, lpString, cbString, lpDx); CGdippSettings* pSettings = CGdippSettings::GetInstance(); //获得一个配置文件实例 // check if per-display rendering is enabled if (pSettings->DisplayAffinity().size()) { set& aff = pSettings->DisplayAffinity(); int id = DisplayFromDC(hdc); if (id >= 0 && aff.find(id) == aff.end()) { // display is not in the list, we should drop rendering for it. return ORIG_ExtTextOutW(hdc, nXStart, nYStart, fuOptions, lprc, lpString, cbString, lpDx); } } CAutoVectorPtr newdx; if (!lpDx) { newdx.Allocate(cbString); SIZE p = { 0 }; BOOL r = false; if (fuOptions & ETO_GLYPH_INDEX) r = GetTextExtentExPointI(hdc, (LPWORD)lpString, cbString, 0, NULL, newdx, &p); else r = GetTextExtentExPointW(hdc, lpString, cbString, 0, NULL, newdx, &p); if (r) { for (int i = cbString - 1; i > 0; --i) { newdx[i] -= newdx[i - 1]; } lpDx = newdx; } else { newdx.Free(); } } /* #ifndef _DEBUG //debug模式下此参数有问题 if (pSettings->FontLoader()==SETTING_FONTLOADER_WIN32) { if (!(fuOptions & ETO_GLYPH_INDEX) //复杂文件,不进行渲染 && !(fuOptions & ETO_IGNORELANGUAGE) && ScriptIsComplex(lpString, cbString, SIC_COMPLEX) == S_OK) { return ORIG_ExtTextOutW(hdc, nXStart, nYStart, fuOptions, lprc, lpString, cbString, lpDx); } } else if (!(fuOptions & ETO_GLYPH_INDEX) && / *iswcntrl(lpString[0])* /CID.myiswcntrl(lpString[0])) { return ORIG_ExtTextOutW(hdc, nXStart, nYStart, fuOptions, lprc, lpString, cbString, lpDx); } #endif */ if (pTLInfo->InExtTextOut()) { //是异常之后的自动还原执行 return ORIG_ExtTextOutW(hdc, nXStart, nYStart, fuOptions, lprc, lpString, cbString, lpDx); } XFORM xfm; static XFORM stdXfm = {1.0,0,0,1.0,0,0}; bool bZoomedDC = false; CDCTransformer* DCTrans = NULL; if (GetTransform) { GetTransform(hdc, GT_WORLD_TO_DEVICE, &xfm); if (memcmp(&xfm, &stdXfm, sizeof(XFORM)-sizeof(FLOAT)*2)) //(xfm.eM11!=1.0 || xfm.eM22!=1.0) //如果存在坐标转换 { bool bZoomInOut = (xfm.eM12==0 && xfm.eM21==0 && xfm.eM11>0 && xfm.eM22>0); //只是缩放,且是正数缩放 if (!bZoomInOut) return ORIG_ExtTextOutW(hdc, nXStart, nYStart, fuOptions, lprc, lpString, cbString, lpDx); //放弃渲染 else { bZoomedDC = true; DCTrans = new CDCTransformer; DCTrans->init(xfm); } } } /* int mm = GetMapMode(hdc); if (mm!=MM_TEXT) { SIZE size; GetWindowExtEx(hdc, &size); if (size.cx!=1 || size.cy!=1) return ORIG_ExtTextOutW(hdc, nXStart, nYStart, fuOptions, lprc, lpString, cbString, lpDx); } if (GetGraphicsMode(hdc)==GM_ADVANCED) { XFORM xfm; GetWorldTransform(hdc, &xfm); if (xfm.eM11!=1.0 || xfm.eM22!=1.0) return ORIG_ExtTextOutW(hdc, nXStart, nYStart, fuOptions, lprc, lpString, cbString, lpDx); }*/ //if (GetROP2(hdc)!=13) // return ORIG_ExtTextOutW(hdc, nXStart, nYStart, fuOptions, lprc, lpString, cbString, lpDx); //if (GetStretchBltMode(hdc)!=BLACKONWHITE) // return ORIG_ExtTextOutW(hdc, nXStart, nYStart, fuOptions, lprc, lpString, cbString, lpDx); /* SIZE size; if (fuOptions & ETO_GLYPH_INDEX) GetTextExtentPointI(hdc,(LPWORD)lpString, cbString,&size); else GetTextExtentPoint(hdc, lpString, cbString, &size); if (!size.cx) return ORIG_ExtTextOutW(hdc, nXStart, nYStart, fuOptions, lprc, lpString, cbString, lpDx);*/ COwnedCriticalSectionLock __lock2(1, COwnedCriticalSectionLock::OCS_DC); //获取所有权,防止冲突 CBitmapCache& cache = pTLInfo->BitmapCache(); CETOBitmap bmp(cache); HDC hCanvasDC = NULL; HFONT hPrevFont = NULL; HFONT hMyCurFont = NULL; HFONT hZoomedFont = NULL, hOldMDCFont = NULL; BOOL bForceFont = false; int * outlpDx = NULL; FT_Referenced_Glyph* GlyphArray = new FT_Referenced_Glyph[cbString]; FT_DRAW_STATE* ftDrawState = new FT_DRAW_STATE[cbString]; memset(GlyphArray, 0, sizeof(FT_Referenced_Glyph)*cbString); memset(ftDrawState, 0, sizeof(FT_DRAW_STATE)*cbString); OUTLINETEXTMETRIC* otm = NULL; ETO_TRY(); //设置标志, pTLInfo->InExtTextOut(true); POINT curPos = { nXStart, nYStart }; //记录开始的位置 POINT destPos; SIZE drawSize; HFONT hCurFont = NULL; BOOL bShadow = FALSE; UINT align; SIZE textSize; SIZE realSize = { 0 }; //================ Is valid DC? ===================== if (!IsValidDC(hdc)) { ETO_THROW(ETOE_INVALIDHDC); // hdc is invalid } int nSize=GetOutlineTextMetrics(hdc, 0, NULL); if (!nSize) { //nSize = sizeof(OUTLINETEXTMETRIC); ETO_THROW(ETOE_INVALIDHDC); } //耗时50-100ms otm = (OUTLINETEXTMETRIC*)malloc(nSize); memset(otm, 0, nSize); otm->otmSize = nSize; TEXTMETRIC& tm = otm->otmTextMetrics; LOGFONT lf = { 0 }; wstring strFamilyName; GetOutlineTextMetrics(hdc, nSize, otm); strFamilyName = (LPWSTR)((DWORD_PTR)otm+(DWORD_PTR)otm->otmpFamilyName); //Get TTF font info const bool bVertical = pSettings->FontLoader()==SETTING_FONTLOADER_FREETYPE? strFamilyName.c_str()[0]==L'@' :false; int nFontHeight = bZoomedDC ? DCTrans->TransformYAB(tm.tmHeight) : tm.tmHeight; if ((pSettings->MaxHeight() && nFontHeight > pSettings->MaxHeight()) || (pSettings->MinHeight() && nFontHeight < pSettings->MinHeight())) { ETO_THROW(ETOE_INVALIDHDC); //Font size too small or too big. } if (pSettings->IsFontExcluded(strFamilyName.c_str())) { // check if it's excluded ETO_THROW(ETOE_INVALIDHDC); } //20-50ms // check pitch to make sure it's truetype or opentype if ((otm->otmTextMetrics.tmPitchAndFamily & (TMPF_TRUETYPE | TMPF_VECTOR)) == 0) { //opentype (collection) sets the vector bit, truetype sets the truetype bit pSettings->AddFontExclude(strFamilyName.c_str()); ETO_THROW(ETOE_INVALIDHDC); // set the font as an exclusion and exit } //====================end================================ hCanvasDC = bmp.CreateDC(hdc); if(!hCanvasDC) { ETO_THROW(ETOE_CREATEDC); } //0ms align = GetTextAlign(hdc); // Get align //if (pTLInfo->InUniscribe() && !(fuOptions & ETO_IGNORELANGUAGE)) // align &= ~TA_UPDATECP; if(align & TA_UPDATECP) { GetCurrentPositionEx(hdc, &curPos); } /* if (!align && lpDx && !fuOptions) //optimized { // ETO_THROW(ETOE_FREETYPE); }//0ms*/ hCurFont = GetCurrentFont(hdc); // get font name of current DC, warning: the font name is potaintially incorrect. if (!hCurFont) { // failed ETO_THROW(ETOE_SETFONT); } TRACE(L"Draw text \"%s\", font=\"%s\", handle=%x\n", lpString, strFamilyName.c_str(), (int)hCurFont); if (!ORIG_GetObjectW(hCurFont, sizeof(LOGFONT), &lf)) { ETO_THROW(ETOE_SETFONT); }//30ms StringCchCopy(lf.lfFaceName, LF_FACESIZE, (LPWSTR)((DWORD_PTR)otm+(DWORD_PTR)otm->otmpFamilyName)); // copy the correct font name from otm info to lf if (lf.lfEscapement != 0) { ETO_THROW(ETOE_ROTATEFONT);// rotated font } hPrevFont = SelectFont(hCanvasDC, hCurFont); if (!hPrevFont) { hMyCurFont = CreateFontIndirect(&lf); hPrevFont = SelectFont(hCanvasDC, hMyCurFont); } if (lf.lfHeight >= 0) { // use height from tm if not specified in lf lf.lfHeight = -(tm.tmHeight-tm.tmInternalLeading); //optimized } if (bZoomedDC) { //DCTrans->SetSourceOffset(curPos.x, curPos.y); curPos.x = DCTrans->TransformXAB(curPos.x); curPos.y = DCTrans->TransformYAB(curPos.y); lf.lfHeight = DCTrans->TransformYAB(lf.lfHeight); lf.lfWidth = DCTrans->TransformXAB(lf.lfWidth); tm.tmHeight = abs(DCTrans->TransformYAB(tm.tmHeight)); tm.tmInternalLeading = abs(DCTrans->TransformYAB(tm.tmInternalLeading)); tm.tmAscent = DCTrans->TransformYAB(tm.tmAscent); tm.tmDescent = DCTrans->TransformYAB(tm.tmDescent); tm.tmAveCharWidth = DCTrans->TransformXAB(tm.tmAveCharWidth); // if (!DCTrans->TransformMode() && !lf.lfWidth && DCTrans->MirrorX()) // lf.lfWidth = tm.tmAveCharWidth; if (lpDx && cbString) //firefox uses coord Y of ETO_PDY to print vertical text { int szDx=fuOptions&ETO_PDY ? cbString*2:cbString; outlpDx = new int[szDx]; DCTrans->TransformlpDx(lpDx, outlpDx, szDx); //lpDx has a size of cbString -1 } } FREETYPE_PARAMS params(fuOptions & ~ETO_OPAQUE, hdc, &lf, otm); if (bZoomedDC) params.charExtra = DCTrans->TransformXAB(params.charExtra); SetTextCharacterExtra(hCanvasDC, params.charExtra); BITMAP bm; HBITMAP hbmpSrc = (HBITMAP)GetCurrentObject(hdc, OBJ_BITMAP); if(hbmpSrc && ORIG_GetObjectW(hbmpSrc, sizeof(BITMAP), &bm) && bm.bmBitsPixel <= 16) { ETO_THROW(ETOE_MONO); // ignore monochrome font, since freetype has really bad support of it. //params.ftOptions |= FTO_MONO; } if(!params.IsMono() && pSettings->EnableShadow()) { bShadow = true; } int xs = 0, ys=0; if (bShadow) { const int* shadow = pSettings->GetShadowParams(); xs = shadow[0], ys = shadow[1]; params.alpha = shadow[2] | shadow[3]; } else params.alpha = 1; int width=0; FreeTypeDrawInfo FTInfo(params, bZoomedDC ? hCanvasDC : hdc, (LOGFONT*)&lf, &cache, bZoomedDC ? outlpDx : lpDx, cbString, xs, ys); lf.lfQuality = 0; //magic number means this is a non scaled font; if (lf.lfWidth) ++lf.lfQuality; if (bZoomedDC) { hZoomedFont = CreateFontIndirect(&lf); if (!DCTrans->TransformMode() || lf.lfWidth) ++lf.lfQuality; //scaled font hOldMDCFont = SelectFont(hCanvasDC, hZoomedFont); SetGraphicsMode(hCanvasDC, GM_ADVANCED); } if (!FreeTypeGetGlyph(FTInfo, lpString, cbString, width, GlyphArray, ftDrawState)) { ETO_THROW(ETOE_FREETYPE); } if (FTInfo.xBase<0) // Change start position if diacritics are found { width-=FTInfo.xBase; // increase width FTInfo.x -= FTInfo.xBase; // increase width for cursor curPos.x+=FTInfo.xBase; // change cursor position for (int i=0;iMirrorX()) //左右反向,RGB和BGR要相反 for (int i=0; iTransformRectAB(lprc, &rcTrans); IntersectRect(&rcClip, &rcBlt, &rcTrans); } else IntersectRect(&rcClip, &rcBlt, lprc); xorg = rcClip.left-destPos.x; //计算偏移 yorg = rcClip.top-destPos.y; destPos.x = rcClip.left; destPos.y = rcClip.top; drawSize.cx = rcClip.right-rcClip.left; drawSize.cy = rcClip.bottom-rcClip.top; } { const BOOL fillrect = (lprc && (fuOptions & ETO_OPAQUE)); //clear bitmap if(fillrect || GetBkMode(hdc) == OPAQUE) { COLORREF bgcolor = GetBkColor(hdc); //両方とも同じ背景色に //if ((bgcolor>>24)%2 || (bgcolor>>28)%2) // bgcolor = 0; if ((bgcolor>>24)%2 || (bgcolor>>28)%2) bgcolor = GetPaletteColor(hdc, bgcolor); SetBkMode(hCanvasDC, OPAQUE); SetBkColor(hCanvasDC, bgcolor); RECT rc = { xorg, yorg, drawSize.cx+ xorg, drawSize.cy+ yorg }; if (bZoomedDC) { rc.right+=2; rc.bottom+=2; } cache.FillSolidRect(bgcolor, &rc); if(fillrect) { //FillRect(hdc, lprc, (HBRUSH)GetCurrentObject(hdc, OBJ_BRUSH)); ORIG_ExtTextOutW(hdc, 0, 0, ETO_OPAQUE, lprc, NULL, 0, NULL); } } else { if (!bZoomedDC) { if (!(BitBlt(hCanvasDC, xorg, yorg, drawSize.cx, drawSize.cy, hdc, destPos.x, destPos.y, SRCCOPY))) { ETO_THROW(ETOE_FREETYPE); } } else { SetWorldTransform(hCanvasDC, DCTrans->GetTransform()); if (!(BitBlt(hCanvasDC, DCTrans->TransformXCoordinateBA(xorg), DCTrans->TransformYCoordinateBA(yorg), DCTrans->TransformXCoordinateBA(drawSize.cx+4), DCTrans->TransformYCoordinateBA(drawSize.cy+4), hdc, DCTrans->TransformXCoordinateBA(destPos.x), DCTrans->TransformYCoordinateBA(destPos.y), SRCCOPY))) { SetWorldTransform(hCanvasDC, &stdXfm); ETO_THROW(ETOE_FREETYPE); } SetWorldTransform(hCanvasDC, &stdXfm); } } } //setup SetTextAlign(hCanvasDC, TA_LEFT | TA_TOP); //debug //Dbg_TraceExtTextOutW(nXStart, nYStart, fuOptions, lpString, cbString, lpDx); //textout SetTextColor(hCanvasDC, FTInfo.params->color); SetBkMode(hCanvasDC, TRANSPARENT); FTInfo.hdc = hCanvasDC; if (!FreeTypeTextOut(hCanvasDC, cache, lpString, cbString, FTInfo, GlyphArray, ftDrawState)) { ETO_THROW(ETOE_FREETYPE); } //blt + clipping /* if(lprc && (fuOptions & ETO_CLIPPED)) { //TRACE(_T("ClipRect={%d %d %d %d}, pos = (%d,%d)\n"), lprc->left, lprc->top, lprc->right, lprc->bottom, // nXStart, nYStart); //trace(L"ClipRect=%d %d %d %d\n", lprc->left, lprc->top, lprc->right, lprc->bottom); const RECT rcBlt = { destPos.x, destPos.y, destPos.x + drawSize.cx, destPos.y + drawSize.cy }; RECT rcClip = { 0 }; IntersectRect(&rcClip, &rcBlt, lprc); BitBlt(hdc, rcClip.left, rcClip.top, rcClip.right - rcClip.left, rcClip.bottom - rcClip.top, hCanvasDC, rcClip.left - rcBlt.left, rcClip.top - rcBlt.top, SRCCOPY); } else {*/ if (!bZoomedDC) BitBlt(hdc, destPos.x, destPos.y, drawSize.cx, drawSize.cy, hCanvasDC, xorg, yorg, SRCCOPY); else { SetWorldTransform(hCanvasDC, DCTrans->GetTransform()); BitBlt(hdc, DCTrans->TransformXCoordinateBA(destPos.x), DCTrans->TransformYCoordinateBA(destPos.y), DCTrans->TransformXCoordinateBA(drawSize.cx), DCTrans->TransformYCoordinateBA(drawSize.cy), hCanvasDC, DCTrans->TransformXCoordinateBA(xorg), DCTrans->TransformYCoordinateBA(yorg), SRCCOPY); SetWorldTransform(hCanvasDC, &stdXfm); } //} //GdiFlush(); if(align & TA_UPDATECP) { if (!bZoomedDC) MoveToEx(hdc, curPos.x, curPos.y, NULL); else MoveToEx(hdc, DCTrans->TransformXCoordinateBA(curPos.x), DCTrans->TransformYCoordinateBA(curPos.y), NULL); } ETO_CATCH(); if (otm) free(otm); bmp.RestoreBitmap(); if (hOldMDCFont) { SelectFont(hCanvasDC, hOldMDCFont); DeleteFont(hZoomedFont); hZoomedFont = NULL; hOldMDCFont = NULL; } if(hPrevFont) { SelectFont(hCanvasDC, hPrevFont); } if (hMyCurFont) DeleteFont(hMyCurFont); { //CCriticalSectionLock __lock; for (UINT i=0;iInExtTextOut(false); return TRUE; } int ret = ORIG_ExtTextOutW(hdc, nXStart, nYStart, fuOptions, lprc, lpString, cbString, lpDx); pTLInfo->InExtTextOut(false); return ret; } BOOL WINAPI IMPL_MySetProcessMitigationPolicy( _In_ PROCESS_MITIGATION_POLICY MitigationPolicy, _In_ PVOID lpBuffer, _In_ SIZE_T dwLength ) { if (MitigationPolicy == ProcessDynamicCodePolicy) { PPROCESS_MITIGATION_DYNAMIC_CODE_POLICY(lpBuffer)->ProhibitDynamicCode = false; } return ORIG_MySetProcessMitigationPolicy(MitigationPolicy, lpBuffer, dwLength); } //HFONT dummy=NULL; /* int WINAPI IMPL_GdipCreateFontFamilyFromName(const WCHAR *name, void *fontCollection, void **FontFamily) { LOGFONT lf={}; memset(&lf, 0, sizeof lf); StringCchCopy(lf.lfFaceName, LF_FACESIZE, name); const CGdippSettings* pSettings = CGdippSettings::GetInstance(); if (pSettings->CopyForceFont(lf, lf)) { //dummy = CreateFont(1,0,0,0,0,0,0,0,DEFAULT_CHARSET,0,0,0,0,lf.lfFaceName); return ORIG_GdipCreateFontFamilyFromName(lf.lfFaceName, fontCollection, FontFamily); } return ORIG_GdipCreateFontFamilyFromName(name, fontCollection, FontFamily); }*/ DWORD WINAPI IMPL_GetFontData(_In_ HDC hdc, _In_ DWORD dwTable, _In_ DWORD dwOffset, _Out_writes_bytes_to_opt_(cjBuffer, return) PVOID pvBuffer, _In_ DWORD cjBuffer ) { if (dwTable != 0x656d616e) // we only simulate the name table, for other tables, use the substituted font data return ORIG_GetFontData(hdc, dwTable, dwOffset, pvBuffer, cjBuffer); DWORD ret = GDI_ERROR; ENUMLOGFONTEXDVW envlf = { 0 }; HFONT hCurFont = GetCurrentFont(hdc); if (GetCachedFontLocale(hCurFont) && GetObjectW(hCurFont, sizeof(LOGFONT), &envlf.elfEnumLogfontEx.elfLogFont)) {// call hooked version of GetObject to retrieve font info that the app originally want to create HDC memdc = CreateCompatibleDC(hdc); HFONT hRealFont = ORIG_CreateFontIndirectExW(&envlf); // create memorydc and a real font so that we can run GetFontData on it if (hRealFont) { HFONT hOldFont = SelectFont(memdc, hRealFont); ret = ORIG_GetFontData(memdc, dwTable, dwOffset, pvBuffer, cjBuffer); // get font data from the real font SelectFont(memdc, hOldFont); DeleteFont(hRealFont); } DeleteDC(memdc); } if (ret == GDI_ERROR) // any of the above operations failed or the font is not substituted ret = ORIG_GetFontData(hdc, dwTable, dwOffset, pvBuffer, cjBuffer); // fallback to original return ret; } /* HPAINTBUFFER WINAPI IMPL_BeginBufferedPaint( HDC hdcTarget, const RECT* prcTarget, BP_BUFFERFORMAT dwFormat, BP_PAINTPARAMS* pPaintParams, HDC* phdc ) { CCriticalSectionLock __lock(CCriticalSectionLock::CS_DCRELATION); auto ret = ORIG_BeginBufferedPaint(hdcTarget, prcTarget, dwFormat, pPaintParams, phdc); // save relations between memoryDC and realDC if (phdc && *phdc && hdcTarget) { PaintBufferCache[ret] = *phdc; // unchain dc relations auto it = DCRelation.find(hdcTarget); if (it != DCRelation.end()) { TRACE(L"BeginBufferedPaint %d->%d->%d", *phdc, hdcTarget, it->second); hdcTarget = it->second; } else { TRACE(L"BeginBufferedPaint: %d->%d\n", *phdc, hdcTarget); } DCRelation[*phdc] = hdcTarget; } return ret; } HRESULT WINAPI IMPL_EndBufferedPaint(HPAINTBUFFER hBufferedPaint, BOOL fUpdateTarget) { CCriticalSectionLock __lock(CCriticalSectionLock::CS_DCRELATION); auto it = PaintBufferCache.find(hBufferedPaint); // remove obsolete DC relations if (it != PaintBufferCache.end()) { TRACE(L"EndBufferedPaint %d", it->second); DCRelation.erase(it->second); PaintBufferCache.erase(it); } return ORIG_EndBufferedPaint(hBufferedPaint, fUpdateTarget); } */ void inline hdcAddRef(HDC dc) { auto it = DCRef.find(dc); if (it == DCRef.end()) { DCRef[dc] = 1; } else { DCRef[dc] = it->second+1; } } void inline hdcReleaseRef(HDC dc) { auto it = DCRef.find(dc); if (it != DCRef.end()) { if (it->second > 1) { DCRef[dc] = it->second-1; } else { TRACE(L"%d is removed\n", dc); DCRef.erase(it); } } } HWND getMyActiveWindow() { HWND activeHwnd = GetForegroundWindow(); if (activeHwnd) { DWORD processId; GetWindowThreadProcessId(activeHwnd, &processId); if (processId == GetCurrentProcessId()) { // the active window belongs to the current process. return activeHwnd; } } // enum current top-level windows and return the first one. EnumThreadWindows(GetCurrentThreadId(), [](HWND hwnd, LPARAM lParam)->BOOL { *(HWND*)lParam = hwnd; return false; }, LPARAM(&activeHwnd)); return activeHwnd; } HDC WINAPI IMPL_CreateCompatibleDC(_In_opt_ HDC hdc) { auto memdc = CreateCompatibleDC(hdc); if (memdc) { TRACE(L"CreateCompatibleDC: %d->%d\n", memdc, hdc); CCriticalSectionLock __lock(CCriticalSectionLock::CS_DCRELATION); // unchain dc relations auto it = DCRelation.find(hdc); if (it != DCRelation.end()) { TRACE(L"Unchain: %d->%d->%d\n", memdc, hdc, it->second); hdc = it->second; } hdcAddRef(memdc); if (hdc) { DCRelation[memdc] = hdc; hdcAddRef(hdc); } else { // hdc = 0, create a relationship auto hWnd = getMyActiveWindow(); TRACE(L"[CreateCompatibleDC] Relation %d->%d\n", memdc, hWnd); DCHwndCache[memdc] = hWnd; } } return memdc; } BOOL WINAPI IMPL_DeleteDC(_In_ HDC hdc) { auto ret = ORIG_DeleteDC(hdc); if (ret) { CCriticalSectionLock __lock(CCriticalSectionLock::CS_DCRELATION); DCRelation.erase(hdc); hdcReleaseRef(hdc); TRACE(L"DeleteDC %d", hdc); } return ret; } HDC WINAPI IMPL_GetDC(_In_opt_ HWND hWnd) { auto dc = ORIG_GetDC(hWnd); if (dc) { if (!hWnd) { hWnd = getMyActiveWindow(); } if (hWnd) { CCriticalSectionLock __lock(CCriticalSectionLock::CS_DCRELATION); TRACE(L"[GetDC] Custom Relation %d->%d\n", dc, hWnd); hdcAddRef(dc); DCHwndCache[dc] = hWnd; } } return dc; } BOOL WINAPI IMPL_ReleaseDC(_In_opt_ HWND hWnd, _In_ HDC hDC) { CCriticalSectionLock __lock(CCriticalSectionLock::CS_DCRELATION); hdcReleaseRef(hDC); return ORIG_ReleaseDC(hWnd, hDC); } //EOF ================================================ FILE: override.h ================================================ #pragma once #include "common.h" #include "tlsdata.h" #include "undocAPI.h" #include "gdiPlusFlat2.h" #include "cache.h" #include "settings.h" #include #include #include #include using namespace std; /* typedef struct _STRING { USHORT Length; USHORT MaximumLength; PCHAR Buffer; } ANSI_STRING, *PANSI_STRING; typedef int (WINAPI *PFNLdrGetProcedureAddress)( IN HMODULE ModuleHandle, IN PANSI_STRING FunctionName OPTIONAL, IN WORD Oridinal OPTIONAL, OUT PVOID *FunctionAddress ); */ struct CFontSubResult { public: LPWSTR lpRealName; LPWSTR lpGDIName; CFontSubResult(LPCWSTR RealName, LPCWSTR GDIName) { lpRealName = _wcsdup(RealName); lpGDIName = _wcsdup(GDIName); } ~CFontSubResult() { if (lpRealName) free(lpRealName); if (lpGDIName) free(lpGDIName); } }; typedef map CFontCache; typedef set CDCArray; typedef map CDCRelationCache; typedef map CDCHwndCache; typedef map CDCRefCache; typedef map CPaintBufferCache; class CThreadLocalInfo { private: CBitmapCache m_bmpCache; bool m_bInExtTextOut; bool m_bInUniscribe; bool m_bInUniTextOut; bool m_bPadding[2]; bool m_bInPath; public: CThreadLocalInfo() : m_bInExtTextOut(false), m_bInUniscribe(false), m_bInPath(false), m_bInUniTextOut(false) { TLSDCArray.insert(&m_bmpCache); } ~CThreadLocalInfo() { TLSDCArray.erase(&m_bmpCache); } CBitmapCache& BitmapCache() { return m_bmpCache; } void InExtTextOut(bool b) { m_bInExtTextOut = b; } bool InExtTextOut() const { return m_bInExtTextOut; } void InUniscribe(bool b) { m_bInUniscribe = b; } bool InUniscribe() const { return m_bInUniscribe; } void InUniTextOut(bool b) { m_bInUniTextOut = b; } bool InUniTextOut() const { return m_bInUniTextOut; } void InPath(bool b) { m_bInPath = b; } bool Path() const { return m_bInPath; } }; extern CTlsData g_TLInfo; BOOL IsProcessExcluded(); BOOL IsProcessUnload(); BOOL IsExeUnload(LPCTSTR lpApp); #define HOOK_MANUALLY HOOK_DEFINE #define HOOK_DEFINE(rettype, name, argtype, arglist) \ extern rettype (WINAPI * ORIG_##name) argtype; \ extern rettype WINAPI IMPL_##name argtype; #include "hooklist.h" #undef HOOK_DEFINE #undef HOOK_MANUALLY HFONT GetCurrentFont(HDC hdc); void AddFontToFT(HFONT hf, LPCTSTR lpszFace, int weight, bool italic); void AddFontToFT(LPCTSTR lpszFace, int weight, bool italic); int MyGetProcAddress(HMODULE dll, LPSTR funcname); #define HOOK_MANUALLY(rettype, name, argtype, arglist) \ LONG hook_demand_##name(bool bForce); #define HOOK_DEFINE(rettype, name, argtype, arglist) ; #include "hooklist.h" #undef HOOK_DEFINE #undef HOOK_MANUALLY //EOF ================================================ FILE: ownedcs.cpp ================================================ #include "ownedcs.h" #include "windows.h" #define InterlockedIncrementInt(x) InterlockedIncrement((volatile LONG *)&(x)) #define InterlockedDecrementInt(x) InterlockedDecrement((volatile LONG *)&(x)) #define InterlockedExchangeInt(x, y) InterlockedExchange((volatile LONG *)&(x), LONG(y)) void WINAPI InitializeOwnedCritialSection(POWNED_CRITIAL_SECTION cs) { cs->nOwner = -1; cs->nRecursiveCount = 0; cs->nRequests = -1; cs->hEvent = CreateEvent(NULL, false, false, NULL); InitializeCriticalSection(&cs->threadLock); } void WINAPI DeleteOwnedCritialSection(POWNED_CRITIAL_SECTION cs) { CloseHandle(cs->hEvent); DeleteCriticalSection(&cs->threadLock); } void WINAPI EnterOwnedCritialSection(POWNED_CRITIAL_SECTION cs, WORD Owner) { EnterCriticalSection(&cs->threadLock); if (cs->nOwner == Owner) { InterlockedIncrementInt(cs->nRecursiveCount); LeaveCriticalSection(&cs->threadLock); } else { if (InterlockedIncrementInt(cs->nRequests)>0) //等待获取所有权 { LeaveCriticalSection(&cs->threadLock); WaitForSingleObject(cs->hEvent, INFINITE); } else LeaveCriticalSection(&cs->threadLock); InterlockedExchangeInt(cs->nOwner, Owner);//更改所有者 InterlockedExchangeInt(cs->nRecursiveCount, 1);//增加占用计数 } } void WINAPI LeaveOwnedCritialSection(POWNED_CRITIAL_SECTION cs, WORD Owner) { EnterCriticalSection(&cs->threadLock); if (cs->nOwner == Owner) { if (InterlockedDecrementInt(cs->nRecursiveCount)<=0) { InterlockedExchangeInt(cs->nOwner, -1);//归还所有权 if (InterlockedDecrementInt(cs->nRequests)>=0) SetEvent(cs->hEvent); } } else InterlockedDecrementInt(cs->nRecursiveCount); LeaveCriticalSection(&cs->threadLock); } ================================================ FILE: ownedcs.h ================================================ #include typedef struct _OWNED_CRITIAL_SECTION { int nOwner, nRequests, nRecursiveCount; HANDLE hEvent; CRITICAL_SECTION threadLock; }OWNED_CRITIAL_SECTION, *POWNED_CRITIAL_SECTION; //用于自定义临界区 void WINAPI InitializeOwnedCritialSection(POWNED_CRITIAL_SECTION cs); void WINAPI DeleteOwnedCritialSection(POWNED_CRITIAL_SECTION cs); void WINAPI EnterOwnedCritialSection(POWNED_CRITIAL_SECTION cs, WORD Owner); void WINAPI LeaveOwnedCritialSection(POWNED_CRITIAL_SECTION cs, WORD Owner); ================================================ FILE: resource ================================================ //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by gdidll.rc // #define SW_HIDE 0 #define HIDE_WINDOW 0 #define WM_NULL 0x0000 #define WA_INACTIVE 0 #define HTNOWHERE 0 #define SMTO_NORMAL 0x0000 #define ICON_SMALL 0 #define SIZE_RESTORED 0 #define BN_CLICKED 0 #define BST_UNCHECKED 0x0000 #define HDS_HORZ 0x0000 #define TBSTYLE_BUTTON 0x0000 #define TBS_HORZ 0x0000 #define TBS_BOTTOM 0x0000 #define TBS_RIGHT 0x0000 #define LVS_ICON 0x0000 #define LVS_ALIGNTOP 0x0000 #define TCS_TABS 0x0000 #define TCS_SINGLELINE 0x0000 #define TCS_RIGHTJUSTIFY 0x0000 #define DTS_SHORTDATEFORMAT 0x0000 #define PGS_VERT 0x00000000 #define LANG_NEUTRAL 0x00 #define SUBLANG_NEUTRAL 0x00 #define SORT_DEFAULT 0x0 #define SORT_JAPANESE_XJIS 0x0 #define SORT_CHINESE_BIG5 0x0 #define SORT_CHINESE_PRCP 0x0 #define SORT_KOREAN_KSC 0x0 #define SORT_HUNGARIAN_DEFAULT 0x0 #define SORT_GEORGIAN_TRADITIONAL 0x0 #define _USE_DECLSPECS_FOR_SAL 0 #define _USE_ATTRIBUTES_FOR_SAL 0 #define CREATEPROCESS_MANIFEST_RESOURCE_ID 1 #define MINIMUM_RESERVED_MANIFEST_RESOURCE_ID 1 #define SW_SHOWNORMAL 1 #define SW_NORMAL 1 #define SHOW_OPENWINDOW 1 #define SW_PARENTCLOSING 1 #define VK_LBUTTON 0x01 #define WM_CREATE 0x0001 #define WA_ACTIVE 1 #define PWR_OK 1 #define PWR_SUSPENDREQUEST 1 #define NFR_ANSI 1 #define UIS_SET 1 #define UISF_HIDEFOCUS 0x1 #define XBUTTON1 0x0001 #define WMSZ_LEFT 1 #define HTCLIENT 1 #define SMTO_BLOCK 0x0001 #define MA_ACTIVATE 1 #define ICON_BIG 1 #define SIZE_MINIMIZED 1 #define MK_LBUTTON 0x0001 #define TME_HOVER 0x00000001 #define CS_VREDRAW 0x0001 #define CF_TEXT 1 #define IDOK 1 #define BN_PAINT 1 #define BST_CHECKED 0x0001 #define TBSTYLE_SEP 0x0001 #define TTS_ALWAYSTIP 0x01 #define TBS_AUTOTICKS 0x0001 #define UDS_WRAP 0x0001 #define PBS_SMOOTH 0x01 #define LWS_TRANSPARENT 0x0001 #define LVS_REPORT 0x0001 #define TVS_HASBUTTONS 0x0001 #define TCS_SCROLLOPPOSITE 0x0001 #define ACS_CENTER 0x0001 #define MCS_DAYSTATE 0x0001 #define DTS_UPDOWN 0x0001 #define PGS_HORZ 0x00000001 #define NFS_EDIT 0x0001 #define BCSIF_GLYPH 0x0001 #define BCSS_NOSPLIT 0x0001 #define LANG_ARABIC 0x01 #define SUBLANG_DEFAULT 0x01 #define SUBLANG_AFRIKAANS_SOUTH_AFRICA 0x01 #define SUBLANG_ALBANIAN_ALBANIA 0x01 #define SUBLANG_ALSATIAN_FRANCE 0x01 #define SUBLANG_AMHARIC_ETHIOPIA 0x01 #define SUBLANG_ARABIC_SAUDI_ARABIA 0x01 #define SUBLANG_ARMENIAN_ARMENIA 0x01 #define SUBLANG_ASSAMESE_INDIA 0x01 #define SUBLANG_AZERI_LATIN 0x01 #define SUBLANG_BASHKIR_RUSSIA 0x01 #define SUBLANG_BASQUE_BASQUE 0x01 #define SUBLANG_BELARUSIAN_BELARUS 0x01 #define SUBLANG_BENGALI_INDIA 0x01 #define SUBLANG_BRETON_FRANCE 0x01 #define SUBLANG_BULGARIAN_BULGARIA 0x01 #define SUBLANG_CATALAN_CATALAN 0x01 #define SUBLANG_CHINESE_TRADITIONAL 0x01 #define SUBLANG_CORSICAN_FRANCE 0x01 #define SUBLANG_CZECH_CZECH_REPUBLIC 0x01 #define SUBLANG_CROATIAN_CROATIA 0x01 #define SUBLANG_DANISH_DENMARK 0x01 #define SUBLANG_DARI_AFGHANISTAN 0x01 #define SUBLANG_DIVEHI_MALDIVES 0x01 #define SUBLANG_DUTCH 0x01 #define SUBLANG_ENGLISH_US 0x01 #define SUBLANG_ESTONIAN_ESTONIA 0x01 #define SUBLANG_FAEROESE_FAROE_ISLANDS 0x01 #define SUBLANG_FILIPINO_PHILIPPINES 0x01 #define SUBLANG_FINNISH_FINLAND 0x01 #define SUBLANG_FRENCH 0x01 #define SUBLANG_FRISIAN_NETHERLANDS 0x01 #define SUBLANG_GALICIAN_GALICIAN 0x01 #define SUBLANG_GEORGIAN_GEORGIA 0x01 #define SUBLANG_GERMAN 0x01 #define SUBLANG_GREEK_GREECE 0x01 #define SUBLANG_GREENLANDIC_GREENLAND 0x01 #define SUBLANG_GUJARATI_INDIA 0x01 #define SUBLANG_HAUSA_NIGERIA_LATIN 0x01 #define SUBLANG_HEBREW_ISRAEL 0x01 #define SUBLANG_HINDI_INDIA 0x01 #define SUBLANG_HUNGARIAN_HUNGARY 0x01 #define SUBLANG_ICELANDIC_ICELAND 0x01 #define SUBLANG_IGBO_NIGERIA 0x01 #define SUBLANG_INDONESIAN_INDONESIA 0x01 #define SUBLANG_INUKTITUT_CANADA 0x01 #define SUBLANG_ITALIAN 0x01 #define SUBLANG_JAPANESE_JAPAN 0x01 #define SUBLANG_KANNADA_INDIA 0x01 #define SUBLANG_KAZAK_KAZAKHSTAN 0x01 #define SUBLANG_KHMER_CAMBODIA 0x01 #define SUBLANG_KICHE_GUATEMALA 0x01 #define SUBLANG_KINYARWANDA_RWANDA 0x01 #define SUBLANG_KONKANI_INDIA 0x01 #define SUBLANG_KOREAN 0x01 #define SUBLANG_KYRGYZ_KYRGYZSTAN 0x01 #define SUBLANG_LAO_LAO 0x01 #define SUBLANG_LATVIAN_LATVIA 0x01 #define SUBLANG_LITHUANIAN 0x01 #define SUBLANG_LUXEMBOURGISH_LUXEMBOURG 0x01 #define SUBLANG_MACEDONIAN_MACEDONIA 0x01 #define SUBLANG_MALAY_MALAYSIA 0x01 #define SUBLANG_MALAYALAM_INDIA 0x01 #define SUBLANG_MALTESE_MALTA 0x01 #define SUBLANG_MAORI_NEW_ZEALAND 0x01 #define SUBLANG_MAPUDUNGUN_CHILE 0x01 #define SUBLANG_MARATHI_INDIA 0x01 #define SUBLANG_MOHAWK_MOHAWK 0x01 #define SUBLANG_MONGOLIAN_CYRILLIC_MONGOLIA 0x01 #define SUBLANG_NEPALI_NEPAL 0x01 #define SUBLANG_NORWEGIAN_BOKMAL 0x01 #define SUBLANG_OCCITAN_FRANCE 0x01 #define SUBLANG_ORIYA_INDIA 0x01 #define SUBLANG_PASHTO_AFGHANISTAN 0x01 #define SUBLANG_PERSIAN_IRAN 0x01 #define SUBLANG_POLISH_POLAND 0x01 #define SUBLANG_PORTUGUESE_BRAZILIAN 0x01 #define SUBLANG_PUNJABI_INDIA 0x01 #define SUBLANG_QUECHUA_BOLIVIA 0x01 #define SUBLANG_ROMANIAN_ROMANIA 0x01 #define SUBLANG_ROMANSH_SWITZERLAND 0x01 #define SUBLANG_RUSSIAN_RUSSIA 0x01 #define SUBLANG_SAMI_NORTHERN_NORWAY 0x01 #define SUBLANG_SANSKRIT_INDIA 0x01 #define SUBLANG_SERBIAN_CROATIA 0x01 #define SUBLANG_SINDHI_INDIA 0x01 #define SUBLANG_SINHALESE_SRI_LANKA 0x01 #define SUBLANG_SOTHO_NORTHERN_SOUTH_AFRICA 0x01 #define SUBLANG_SLOVAK_SLOVAKIA 0x01 #define SUBLANG_SLOVENIAN_SLOVENIA 0x01 #define SUBLANG_SPANISH 0x01 #define SUBLANG_SWAHILI_KENYA 0x01 #define SUBLANG_SWEDISH 0x01 #define SUBLANG_SYRIAC_SYRIA 0x01 #define SUBLANG_TAJIK_TAJIKISTAN 0x01 #define SUBLANG_TAMIL_INDIA 0x01 #define SUBLANG_TATAR_RUSSIA 0x01 #define SUBLANG_TELUGU_INDIA 0x01 #define SUBLANG_THAI_THAILAND 0x01 #define SUBLANG_TIBETAN_PRC 0x01 #define SUBLANG_TSWANA_SOUTH_AFRICA 0x01 #define SUBLANG_TURKISH_TURKEY 0x01 #define SUBLANG_TURKMEN_TURKMENISTAN 0x01 #define SUBLANG_UIGHUR_PRC 0x01 #define SUBLANG_UKRAINIAN_UKRAINE 0x01 #define SUBLANG_UPPER_SORBIAN_GERMANY 0x01 #define SUBLANG_URDU_PAKISTAN 0x01 #define SUBLANG_UZBEK_LATIN 0x01 #define SUBLANG_VIETNAMESE_VIETNAM 0x01 #define SUBLANG_WELSH_UNITED_KINGDOM 0x01 #define SUBLANG_WOLOF_SENEGAL 0x01 #define SUBLANG_XHOSA_SOUTH_AFRICA 0x01 #define SUBLANG_YAKUT_RUSSIA 0x01 #define SUBLANG_YI_PRC 0x01 #define SUBLANG_YORUBA_NIGERIA 0x01 #define SUBLANG_ZULU_SOUTH_AFRICA 0x01 #define SORT_INVARIANT_MATH 0x1 #define SORT_JAPANESE_UNICODE 0x1 #define SORT_CHINESE_UNICODE 0x1 #define SORT_KOREAN_UNICODE 0x1 #define SORT_GERMAN_PHONE_BOOK 0x1 #define SORT_HUNGARIAN_TECHNICAL 0x1 #define SORT_GEORGIAN_MODERN 0x1 #define VS_VERSION_INFO 1 #define VFFF_ISSHAREDFILE 0x0001 #define VFF_CURNEDEST 0x0001 #define VIFF_FORCEINSTALL 0x0001 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID 2 #define SW_SHOWMINIMIZED 2 #define SHOW_ICONWINDOW 2 #define SW_OTHERZOOM 2 #define VK_RBUTTON 0x02 #define WM_DESTROY 0x0002 #define WA_CLICKACTIVE 2 #define PWR_SUSPENDRESUME 2 #define NFR_UNICODE 2 #define UIS_CLEAR 2 #define UISF_HIDEACCEL 0x2 #define XBUTTON2 0x0002 #define WMSZ_RIGHT 2 #define HTCAPTION 2 #define SMTO_ABORTIFHUNG 0x0002 #define MA_ACTIVATEANDEAT 2 #define SIZE_MAXIMIZED 2 #define MK_RBUTTON 0x0002 #define TME_LEAVE 0x00000002 #define CS_HREDRAW 0x0002 #define CF_BITMAP 2 #define IDCANCEL 2 #define BN_HILITE 2 #define BST_INDETERMINATE 0x0002 #define HDS_BUTTONS 0x0002 #define TBSTYLE_CHECK 0x0002 #define TTS_NOPREFIX 0x02 #define TBS_VERT 0x0002 #define UDS_SETBUDDYINT 0x0002 #define LWS_IGNORERETURN 0x0002 #define LVS_SMALLICON 0x0002 #define TVS_HASLINES 0x0002 #define TCS_BOTTOM 0x0002 #define TCS_RIGHT 0x0002 #define ACS_TRANSPARENT 0x0002 #define MCS_MULTISELECT 0x0002 #define DTS_SHOWNONE 0x0002 #define PGS_AUTOSCROLL 0x00000002 #define NFS_STATIC 0x0002 #define BCSIF_IMAGE 0x0002 #define BCSS_STRETCH 0x0002 #define LANG_BULGARIAN 0x02 #define SUBLANG_SYS_DEFAULT 0x02 #define SUBLANG_ARABIC_IRAQ 0x02 #define SUBLANG_AZERI_CYRILLIC 0x02 #define SUBLANG_BENGALI_BANGLADESH 0x02 #define SUBLANG_CHINESE_SIMPLIFIED 0x02 #define SUBLANG_DUTCH_BELGIAN 0x02 #define SUBLANG_ENGLISH_UK 0x02 #define SUBLANG_FRENCH_BELGIAN 0x02 #define SUBLANG_GERMAN_SWISS 0x02 #define SUBLANG_INUKTITUT_CANADA_LATIN 0x02 #define SUBLANG_IRISH_IRELAND 0x02 #define SUBLANG_ITALIAN_SWISS 0x02 #define SUBLANG_KASHMIRI_SASIA 0x02 #define SUBLANG_KASHMIRI_INDIA 0x02 #define SUBLANG_LOWER_SORBIAN_GERMANY 0x02 #define SUBLANG_MALAY_BRUNEI_DARUSSALAM 0x02 #define SUBLANG_MONGOLIAN_PRC 0x02 #define SUBLANG_NEPALI_INDIA 0x02 #define SUBLANG_NORWEGIAN_NYNORSK 0x02 #define SUBLANG_PORTUGUESE 0x02 #define SUBLANG_QUECHUA_ECUADOR 0x02 #define SUBLANG_SAMI_NORTHERN_SWEDEN 0x02 #define SUBLANG_SERBIAN_LATIN 0x02 #define SUBLANG_SINDHI_PAKISTAN 0x02 #define SUBLANG_SINDHI_AFGHANISTAN 0x02 #define SUBLANG_SPANISH_MEXICAN 0x02 #define SUBLANG_SWEDISH_FINLAND 0x02 #define SUBLANG_TAMAZIGHT_ALGERIA_LATIN 0x02 #define SUBLANG_TIGRIGNA_ERITREA 0x02 #define SUBLANG_URDU_INDIA 0x02 #define SUBLANG_UZBEK_CYRILLIC 0x02 #define SORT_CHINESE_PRC 0x2 #define VFF_FILEINUSE 0x0002 #define VIFF_DONTDELETEOLD 0x0002 #define ISOLATIONAWARE_NOSTATICIMPORT_MANIFEST_RESOURCE_ID 3 #define SW_SHOWMAXIMIZED 3 #define SW_MAXIMIZE 3 #define SHOW_FULLSCREEN 3 #define SW_PARENTOPENING 3 #define VK_CANCEL 0x03 #define WM_MOVE 0x0003 #define PWR_CRITICALRESUME 3 #define NF_QUERY 3 #define UIS_INITIALIZE 3 #define WMSZ_TOP 3 #define HTSYSMENU 3 #define MA_NOACTIVATE 3 #define SIZE_MAXSHOW 3 #define CF_METAFILEPICT 3 #define IDABORT 3 #define BN_UNHILITE 3 #define LVS_LIST 0x0003 #define LVS_TYPEMASK 0x0003 #define LANG_CATALAN 0x03 #define SUBLANG_CUSTOM_DEFAULT 0x03 #define SUBLANG_ARABIC_EGYPT 0x03 #define SUBLANG_CHINESE_HONGKONG 0x03 #define SUBLANG_ENGLISH_AUS 0x03 #define SUBLANG_FRENCH_CANADIAN 0x03 #define SUBLANG_GERMAN_AUSTRIAN 0x03 #define SUBLANG_QUECHUA_PERU 0x03 #define SUBLANG_SAMI_NORTHERN_FINLAND 0x03 #define SUBLANG_SERBIAN_CYRILLIC 0x03 #define SUBLANG_SPANISH_MODERN 0x03 #define SORT_CHINESE_BOPOMOFO 0x3 #define SW_SHOWNOACTIVATE 4 #define SHOW_OPENNOACTIVATE 4 #define SW_OTHERUNZOOM 4 #define VK_MBUTTON 0x04 #define NF_REQUERY 4 #define WMSZ_TOPLEFT 4 #define HTGROWBOX 4 #define MA_NOACTIVATEANDEAT 4 #define SIZE_MAXHIDE 4 #define MK_SHIFT 0x0004 #define CF_SYLK 4 #define IDRETRY 4 #define BN_DISABLE 4 #define BST_PUSHED 0x0004 #define HDS_HOTTRACK 0x0004 #define TBSTYLE_GROUP 0x0004 #define TBS_TOP 0x0004 #define TBS_LEFT 0x0004 #define UDS_ALIGNRIGHT 0x0004 #define PBS_VERTICAL 0x04 #define LVS_SINGLESEL 0x0004 #define TVS_LINESATROOT 0x0004 #define TCS_MULTISELECT 0x0004 #define ACS_AUTOPLAY 0x0004 #define MCS_WEEKNUMBERS 0x0004 #define DTS_LONGDATEFORMAT 0x0004 #define PGS_DRAGNDROP 0x00000004 #define NFS_LISTCOMBO 0x0004 #define BCSIF_STYLE 0x0004 #define BCSS_ALIGNLEFT 0x0004 #define LANG_CHINESE 0x04 #define LANG_CHINESE_SIMPLIFIED 0x04 #define SUBLANG_CUSTOM_UNSPECIFIED 0x04 #define SUBLANG_ARABIC_LIBYA 0x04 #define SUBLANG_CHINESE_SINGAPORE 0x04 #define SUBLANG_CROATIAN_BOSNIA_HERZEGOVINA_LATIN 0x04 #define SUBLANG_ENGLISH_CAN 0x04 #define SUBLANG_FRENCH_SWISS 0x04 #define SUBLANG_GERMAN_LUXEMBOURG 0x04 #define SUBLANG_SAMI_LULE_NORWAY 0x04 #define SUBLANG_SPANISH_GUATEMALA 0x04 #define SORT_JAPANESE_RADICALSTROKE 0x4 #define VFF_BUFFTOOSMALL 0x0004 #define SW_SHOW 5 #define VK_XBUTTON1 0x05 #define WM_SIZE 0x0005 #define WMSZ_TOPRIGHT 5 #define HTMENU 5 #define CF_DIF 5 #define IDIGNORE 5 #define BN_DOUBLECLICKED 5 #define LANG_CZECH 0x05 #define SUBLANG_UI_CUSTOM_DEFAULT 0x05 #define SUBLANG_ARABIC_ALGERIA 0x05 #define SUBLANG_BOSNIAN_BOSNIA_HERZEGOVINA_LATIN 0x05 #define SUBLANG_CHINESE_MACAU 0x05 #define SUBLANG_ENGLISH_NZ 0x05 #define SUBLANG_FRENCH_LUXEMBOURG 0x05 #define SUBLANG_GERMAN_LIECHTENSTEIN 0x05 #define SUBLANG_SAMI_LULE_SWEDEN 0x05 #define SUBLANG_SPANISH_COSTA_RICA 0x05 #define SW_MINIMIZE 6 #define VK_XBUTTON2 0x06 #define WM_ACTIVATE 0x0006 #define WMSZ_BOTTOM 6 #define HTHSCROLL 6 #define CF_TIFF 6 #define IDYES 6 #define BN_SETFOCUS 6 #define LANG_DANISH 0x06 #define SUBLANG_ARABIC_MOROCCO 0x06 #define SUBLANG_ENGLISH_EIRE 0x06 #define SUBLANG_FRENCH_MONACO 0x06 #define SUBLANG_SAMI_SOUTHERN_NORWAY 0x06 #define SUBLANG_SERBIAN_BOSNIA_HERZEGOVINA_LATIN 0x06 #define SUBLANG_SPANISH_PANAMA 0x06 #define SW_SHOWMINNOACTIVE 7 #define WM_SETFOCUS 0x0007 #define WMSZ_BOTTOMLEFT 7 #define HTVSCROLL 7 #define CF_OEMTEXT 7 #define IDNO 7 #define BN_KILLFOCUS 7 #define LANG_GERMAN 0x07 #define SUBLANG_ARABIC_TUNISIA 0x07 #define SUBLANG_ENGLISH_SOUTH_AFRICA 0x07 #define SUBLANG_SAMI_SOUTHERN_SWEDEN 0x07 #define SUBLANG_SERBIAN_BOSNIA_HERZEGOVINA_CYRILLIC 0x07 #define SUBLANG_SPANISH_DOMINICAN_REPUBLIC 0x07 #define SW_SHOWNA 8 #define VK_BACK 0x08 #define WM_KILLFOCUS 0x0008 #define WMSZ_BOTTOMRIGHT 8 #define HTMINBUTTON 8 #define SMTO_NOTIMEOUTIFNOTHUNG 0x0008 #define MK_CONTROL 0x0008 #define CS_DBLCLKS 0x0008 #define CF_DIB 8 #define IDCLOSE 8 #define BST_FOCUS 0x0008 #define HDS_HIDDEN 0x0008 #define TBSTYLE_DROPDOWN 0x0008 #define TBS_BOTH 0x0008 #define UDS_ALIGNLEFT 0x0008 #define LVS_SHOWSELALWAYS 0x0008 #define TVS_EDITLABELS 0x0008 #define TCS_FLATBUTTONS 0x0008 #define ACS_TIMER 0x0008 #define MCS_NOTODAYCIRCLE 0x0008 #define NFS_BUTTON 0x0008 #define BCSIF_SIZE 0x0008 #define BCSS_IMAGE 0x0008 #define LANG_GREEK 0x08 #define SUBLANG_ARABIC_OMAN 0x08 #define SUBLANG_BOSNIAN_BOSNIA_HERZEGOVINA_CYRILLIC 0x08 #define SUBLANG_ENGLISH_JAMAICA 0x08 #define SUBLANG_SAMI_SKOLT_FINLAND 0x08 #define SUBLANG_SPANISH_VENEZUELA 0x08 #define SW_RESTORE 9 #define VK_TAB 0x09 #define HTMAXBUTTON 9 #define CF_PALETTE 9 #define IDHELP 9 #define DTS_TIMEFORMAT 0x0009 #define LANG_ENGLISH 0x09 #define SUBLANG_ARABIC_YEMEN 0x09 #define SUBLANG_ENGLISH_CARIBBEAN 0x09 #define SUBLANG_SAMI_INARI_FINLAND 0x09 #define SUBLANG_SPANISH_COLOMBIA 0x09 #define SW_SHOWDEFAULT 10 #define WM_ENABLE 0x000A #define HTLEFT 10 #define CF_PENDATA 10 #define IDTRYAGAIN 10 #define HELP_CONTEXTMENU 0x000a #define LANG_SPANISH 0x0a #define SUBLANG_ARABIC_SYRIA 0x0a #define SUBLANG_ENGLISH_BELIZE 0x0a #define SUBLANG_SPANISH_PERU 0x0a #define SW_FORCEMINIMIZE 11 #define SW_MAX 11 #define WM_SETREDRAW 0x000B #define HTRIGHT 11 #define CF_RIFF 11 #define IDCONTINUE 11 #define HELP_FINDER 0x000b #define LANG_FINNISH 0x0b #define SUBLANG_ARABIC_JORDAN 0x0b #define SUBLANG_ENGLISH_TRINIDAD 0x0b #define SUBLANG_SPANISH_ARGENTINA 0x0b #define VK_CLEAR 0x0C #define WM_SETTEXT 0x000C #define HTTOP 12 #define CF_WAVE 12 #define HELP_WM_HELP 0x000c #define DTS_SHORTDATECENTURYFORMAT 0x000C #define LANG_FRENCH 0x0c #define SUBLANG_ARABIC_LEBANON 0x0c #define SUBLANG_ENGLISH_ZIMBABWE 0x0c #define SUBLANG_SPANISH_ECUADOR 0x0c #define VK_RETURN 0x0D #define WM_GETTEXT 0x000D #define HTTOPLEFT 13 #define CF_UNICODETEXT 13 #define HELP_SETPOPUP_POS 0x000d #define LANG_HEBREW 0x0d #define SUBLANG_ARABIC_KUWAIT 0x0d #define SUBLANG_ENGLISH_PHILIPPINES 0x0d #define SUBLANG_SPANISH_CHILE 0x0d #define WM_GETTEXTLENGTH 0x000E #define HTTOPRIGHT 14 #define CF_ENHMETAFILE 14 #define LANG_HUNGARIAN 0x0e #define SUBLANG_ARABIC_UAE 0x0e #define SUBLANG_SPANISH_URUGUAY 0x0e #define WM_PAINT 0x000F #define HTBOTTOM 15 #define CF_HDROP 15 #define LANG_ICELANDIC 0x0f #define SUBLANG_ARABIC_BAHRAIN 0x0f #define SUBLANG_SPANISH_PARAGUAY 0x0f #define MAXIMUM_RESERVED_MANIFEST_RESOURCE_ID 16 #define VK_SHIFT 0x10 #define WM_CLOSE 0x0010 #define HTBOTTOMLEFT 16 #define WVR_ALIGNTOP 0x0010 #define MK_MBUTTON 0x0010 #define TME_NONCLIENT 0x00000010 #define CF_LOCALE 16 #define HELP_TCARD_DATA 0x0010 #define TBSTYLE_AUTOSIZE 0x0010 #define TTS_NOANIMATE 0x10 #define TBS_NOTICKS 0x0010 #define UDS_AUTOBUDDY 0x0010 #define LVS_SORTASCENDING 0x0010 #define TVS_DISABLEDRAGDROP 0x0010 #define TCS_FORCEICONLEFT 0x0010 #define MCS_NOTODAY 0x0010 #define DTS_APPCANPARSE 0x0010 #define NFS_ALL 0x0010 #define LANG_ITALIAN 0x10 #define SUBLANG_ARABIC_QATAR 0x10 #define SUBLANG_ENGLISH_INDIA 0x10 #define SUBLANG_SPANISH_BOLIVIA 0x10 #define VK_CONTROL 0x11 #define WM_QUERYENDSESSION 0x0011 #define HTBOTTOMRIGHT 17 #define CF_DIBV5 17 #define HELP_TCARD_OTHER_CALLER 0x0011 #define LANG_JAPANESE 0x11 #define SUBLANG_ENGLISH_MALAYSIA 0x11 #define SUBLANG_SPANISH_EL_SALVADOR 0x11 #define VK_MENU 0x12 #define WM_QUIT 0x0012 #define HTBORDER 18 #define CF_MAX 18 #define LANG_KOREAN 0x12 #define SUBLANG_ENGLISH_SINGAPORE 0x12 #define SUBLANG_SPANISH_HONDURAS 0x12 #define VK_PAUSE 0x13 #define WM_QUERYOPEN 0x0013 #define HTOBJECT 19 #define LANG_DUTCH 0x13 #define SUBLANG_SPANISH_NICARAGUA 0x13 #define VK_CAPITAL 0x14 #define WM_ERASEBKGND 0x0014 #define HTCLOSE 20 #define LANG_NORWEGIAN 0x14 #define SUBLANG_SPANISH_PUERTO_RICO 0x14 #define VK_KANA 0x15 #define VK_HANGEUL 0x15 #define VK_HANGUL 0x15 #define WM_SYSCOLORCHANGE 0x0015 #define HTHELP 21 #define LANG_POLISH 0x15 #define SUBLANG_SPANISH_US 0x15 #define WM_ENDSESSION 0x0016 #define LANG_PORTUGUESE 0x16 #define VK_JUNJA 0x17 #define LANG_ROMANSH 0x17 #define RT_MANIFEST 24 #define VK_FINAL 0x18 #define WM_SHOWWINDOW 0x0018 #define LANG_ROMANIAN 0x18 #define VK_HANJA 0x19 #define VK_KANJI 0x19 #define LANG_RUSSIAN 0x19 #define WM_WININICHANGE 0x001A #define LANG_BOSNIAN 0x1a #define LANG_CROATIAN 0x1a #define LANG_SERBIAN 0x1a #define VK_ESCAPE 0x1B #define WM_DEVMODECHANGE 0x001B #define LANG_SLOVAK 0x1b #define VK_CONVERT 0x1C #define WM_ACTIVATEAPP 0x001C #define LANG_ALBANIAN 0x1c #define VK_NONCONVERT 0x1D #define WM_FONTCHANGE 0x001D #define LANG_SWEDISH 0x1d #define VK_ACCEPT 0x1E #define WM_TIMECHANGE 0x001E #define LANG_THAI 0x1e #define VK_MODECHANGE 0x1F #define WM_CANCELMODE 0x001F #define LANG_TURKISH 0x1f #define VK_SPACE 0x20 #define WM_SETCURSOR 0x0020 #define WVR_ALIGNLEFT 0x0020 #define MK_XBUTTON1 0x0020 #define CS_OWNDC 0x0020 #define TBSTYLE_NOPREFIX 0x0020 #define TTS_NOFADE 0x20 #define TBS_ENABLESELRANGE 0x0020 #define UDS_ARROWKEYS 0x0020 #define LVS_SORTDESCENDING 0x0020 #define TVS_SHOWSELALWAYS 0x0020 #define TCS_FORCELABELLEFT 0x0020 #define DTS_RIGHTALIGN 0x0020 #define NFS_USEFONTASSOC 0x0020 #define LANG_URDU 0x20 #define VK_PRIOR 0x21 #define WM_MOUSEACTIVATE 0x0021 #define LANG_INDONESIAN 0x21 #define VK_NEXT 0x22 #define WM_CHILDACTIVATE 0x0022 #define LANG_UKRAINIAN 0x22 #define VK_END 0x23 #define WM_QUEUESYNC 0x0023 #define LANG_BELARUSIAN 0x23 #define VK_HOME 0x24 #define WM_GETMINMAXINFO 0x0024 #define LANG_SLOVENIAN 0x24 #define VK_LEFT 0x25 #define LANG_ESTONIAN 0x25 #define VK_UP 0x26 #define WM_PAINTICON 0x0026 #define LANG_LATVIAN 0x26 #define VK_RIGHT 0x27 #define WM_ICONERASEBKGND 0x0027 #define LANG_LITHUANIAN 0x27 #define VK_DOWN 0x28 #define WM_NEXTDLGCTL 0x0028 #define LANG_TAJIK 0x28 #define VK_SELECT 0x29 #define LANG_FARSI 0x29 #define LANG_PERSIAN 0x29 #define VK_PRINT 0x2A #define WM_SPOOLERSTATUS 0x002A #define LANG_VIETNAMESE 0x2a #define VK_EXECUTE 0x2B #define WM_DRAWITEM 0x002B #define LANG_ARMENIAN 0x2b #define VK_SNAPSHOT 0x2C #define WM_MEASUREITEM 0x002C #define LANG_AZERI 0x2c #define VK_INSERT 0x2D #define WM_DELETEITEM 0x002D #define LANG_BASQUE 0x2d #define VK_DELETE 0x2E #define WM_VKEYTOITEM 0x002E #define LANG_LOWER_SORBIAN 0x2e #define LANG_UPPER_SORBIAN 0x2e #define VK_HELP 0x2F #define WM_CHARTOITEM 0x002F #define LANG_MACEDONIAN 0x2f #define WM_SETFONT 0x0030 #define WM_GETFONT 0x0031 #define WM_SETHOTKEY 0x0032 #define LANG_TSWANA 0x32 #define WM_GETHOTKEY 0x0033 #define LANG_XHOSA 0x34 #define LANG_ZULU 0x35 #define LANG_AFRIKAANS 0x36 #define WM_QUERYDRAGICON 0x0037 #define LANG_GEORGIAN 0x37 #define LANG_FAEROESE 0x38 #define WM_COMPAREITEM 0x0039 #define LANG_HINDI 0x39 #define LANG_MALTESE 0x3a #define LANG_SAMI 0x3b #define LANG_IRISH 0x3c #define WM_GETOBJECT 0x003D #define LANG_MALAY 0x3e #define LANG_KAZAK 0x3f #define WVR_ALIGNBOTTOM 0x0040 #define MK_XBUTTON2 0x0040 #define CS_CLASSDC 0x0040 #define HDS_DRAGDROP 0x0040 #define BTNS_SHOWTEXT 0x0040 #define TTS_BALLOON 0x40 #define TBS_FIXEDLENGTH 0x0040 #define UDS_HORZ 0x0040 #define LVS_SHAREIMAGELISTS 0x0040 #define TVS_RTLREADING 0x0040 #define TCS_HOTTRACK 0x0040 #define MCS_NOTRAILINGDATES 0x0040 #define LANG_KYRGYZ 0x40 #define WM_COMPACTING 0x0041 #define LANG_SWAHILI 0x41 #define LANG_TURKMEN 0x42 #define LANG_UZBEK 0x43 #define WM_COMMNOTIFY 0x0044 #define LANG_TATAR 0x44 #define LANG_BENGALI 0x45 #define WM_WINDOWPOSCHANGING 0x0046 #define LANG_PUNJABI 0x46 #define WM_WINDOWPOSCHANGED 0x0047 #define LANG_GUJARATI 0x47 #define WM_POWER 0x0048 #define LANG_ORIYA 0x48 #define LANG_TAMIL 0x49 #define WM_COPYDATA 0x004A #define LANG_TELUGU 0x4a #define WM_CANCELJOURNAL 0x004B #define LANG_KANNADA 0x4b #define LANG_MALAYALAM 0x4c #define LANG_ASSAMESE 0x4d #define WM_NOTIFY 0x004E #define LANG_MARATHI 0x4e #define LANG_SANSKRIT 0x4f #define WM_INPUTLANGCHANGEREQUEST 0x0050 #define LANG_MONGOLIAN 0x50 #define WM_INPUTLANGCHANGE 0x0051 #define LANG_TIBETAN 0x51 #define WM_TCARD 0x0052 #define LANG_WELSH 0x52 #define WM_HELP 0x0053 #define LANG_KHMER 0x53 #define WM_USERCHANGED 0x0054 #define LANG_LAO 0x54 #define WM_NOTIFYFORMAT 0x0055 #define LANG_GALICIAN 0x56 #define LANG_KONKANI 0x57 #define LANG_MANIPURI 0x58 #define LANG_SINDHI 0x59 #define LANG_SYRIAC 0x5a #define VK_LWIN 0x5B #define LANG_SINHALESE 0x5b #define VK_RWIN 0x5C #define VK_APPS 0x5D #define LANG_INUKTITUT 0x5d #define LANG_AMHARIC 0x5e #define VK_SLEEP 0x5F #define LANG_TAMAZIGHT 0x5f #define VK_NUMPAD0 0x60 #define LANG_KASHMIRI 0x60 #define VK_NUMPAD1 0x61 #define LANG_NEPALI 0x61 #define VK_NUMPAD2 0x62 #define LANG_FRISIAN 0x62 #define VK_NUMPAD3 0x63 #define LANG_PASHTO 0x63 #define VK_NUMPAD4 0x64 #define LANG_FILIPINO 0x64 #define VS_USER_DEFINED 100 #define VK_NUMPAD5 0x65 #define LANG_DIVEHI 0x65 #define VK_NUMPAD6 0x66 #define VK_NUMPAD7 0x67 #define VK_NUMPAD8 0x68 #define LANG_HAUSA 0x68 #define VK_NUMPAD9 0x69 #define VK_MULTIPLY 0x6A #define LANG_YORUBA 0x6a #define VK_ADD 0x6B #define LANG_QUECHUA 0x6b #define VK_SEPARATOR 0x6C #define LANG_SOTHO 0x6c #define VK_SUBTRACT 0x6D #define LANG_BASHKIR 0x6d #define VK_DECIMAL 0x6E #define LANG_LUXEMBOURGISH 0x6e #define VK_DIVIDE 0x6F #define LANG_GREENLANDIC 0x6f #define VK_F1 0x70 #define LANG_IGBO 0x70 #define VK_F2 0x71 #define VK_F3 0x72 #define VK_F4 0x73 #define LANG_TIGRIGNA 0x73 #define VK_F5 0x74 #define VK_F6 0x75 #define VK_F7 0x76 #define VK_F8 0x77 #define VK_F9 0x78 #define WHEEL_DELTA 120 #define LANG_YI 0x78 #define VK_F10 0x79 #define VK_F11 0x7A #define LANG_MAPUDUNGUN 0x7a #define VK_F12 0x7B #define WM_CONTEXTMENU 0x007B #define VK_F13 0x7C #define WM_STYLECHANGING 0x007C #define LANG_MOHAWK 0x7c #define VK_F14 0x7D #define WM_STYLECHANGED 0x007D #define VK_F15 0x7E #define WM_DISPLAYCHANGE 0x007E #define LANG_BRETON 0x7e #define VK_F16 0x7F #define WM_GETICON 0x007F #define LANG_INVARIANT 0x7f #define VK_F17 0x80 #define WM_SETICON 0x0080 #define WVR_ALIGNRIGHT 0x0080 #define CS_PARENTDC 0x0080 #define CF_OWNERDISPLAY 0x0080 #define HDS_FULLDRAG 0x0080 #define BTNS_WHOLEDROPDOWN 0x0080 #define TTS_CLOSE 0x80 #define TBS_NOTHUMB 0x0080 #define UDS_NOTHOUSANDS 0x0080 #define LVS_NOLABELWRAP 0x0080 #define TVS_NOTOOLTIPS 0x0080 #define TCS_VERTICAL 0x0080 #define MCS_SHORTDAYSOFWEEK 0x0080 #define LANG_UIGHUR 0x80 #define VK_F18 0x81 #define WM_NCCREATE 0x0081 #define CF_DSPTEXT 0x0081 #define LANG_MAORI 0x81 #define VK_F19 0x82 #define WM_NCDESTROY 0x0082 #define CF_DSPBITMAP 0x0082 #define LANG_OCCITAN 0x82 #define VK_F20 0x83 #define WM_NCCALCSIZE 0x0083 #define CF_DSPMETAFILEPICT 0x0083 #define LANG_CORSICAN 0x83 #define VK_F21 0x84 #define WM_NCHITTEST 0x0084 #define LANG_ALSATIAN 0x84 #define VK_F22 0x85 #define WM_NCPAINT 0x0085 #define LANG_YAKUT 0x85 #define VK_F23 0x86 #define WM_NCACTIVATE 0x0086 #define LANG_KICHE 0x86 #define VK_F24 0x87 #define WM_GETDLGCODE 0x0087 #define LANG_KINYARWANDA 0x87 #define WM_SYNCPAINT 0x0088 #define LANG_WOLOF 0x88 #define LANG_DARI 0x8c #define CF_DSPENHMETAFILE 0x008E #define VK_NUMLOCK 0x90 #define VK_SCROLL 0x91 #define VK_OEM_NEC_EQUAL 0x92 #define VK_OEM_FJ_JISHO 0x92 #define VK_OEM_FJ_MASSHOU 0x93 #define VK_OEM_FJ_TOUROKU 0x94 #define VK_OEM_FJ_LOYA 0x95 #define VK_OEM_FJ_ROYA 0x96 #define VK_LSHIFT 0xA0 #define WM_NCMOUSEMOVE 0x00A0 #define VK_RSHIFT 0xA1 #define WM_NCLBUTTONDOWN 0x00A1 #define VK_LCONTROL 0xA2 #define WM_NCLBUTTONUP 0x00A2 #define VK_RCONTROL 0xA3 #define WM_NCLBUTTONDBLCLK 0x00A3 #define VK_LMENU 0xA4 #define WM_NCRBUTTONDOWN 0x00A4 #define VK_RMENU 0xA5 #define WM_NCRBUTTONUP 0x00A5 #define VK_BROWSER_BACK 0xA6 #define WM_NCRBUTTONDBLCLK 0x00A6 #define VK_BROWSER_FORWARD 0xA7 #define WM_NCMBUTTONDOWN 0x00A7 #define VK_BROWSER_REFRESH 0xA8 #define WM_NCMBUTTONUP 0x00A8 #define VK_BROWSER_STOP 0xA9 #define WM_NCMBUTTONDBLCLK 0x00A9 #define VK_BROWSER_SEARCH 0xAA #define VK_BROWSER_FAVORITES 0xAB #define WM_NCXBUTTONDOWN 0x00AB #define VK_BROWSER_HOME 0xAC #define WM_NCXBUTTONUP 0x00AC #define VK_VOLUME_MUTE 0xAD #define WM_NCXBUTTONDBLCLK 0x00AD #define VK_VOLUME_DOWN 0xAE #define VK_VOLUME_UP 0xAF #define VK_MEDIA_NEXT_TRACK 0xB0 #define EM_GETSEL 0x00B0 #define VK_MEDIA_PREV_TRACK 0xB1 #define EM_SETSEL 0x00B1 #define VK_MEDIA_STOP 0xB2 #define EM_GETRECT 0x00B2 #define VK_MEDIA_PLAY_PAUSE 0xB3 #define EM_SETRECT 0x00B3 #define VK_LAUNCH_MAIL 0xB4 #define EM_SETRECTNP 0x00B4 #define VK_LAUNCH_MEDIA_SELECT 0xB5 #define EM_SCROLL 0x00B5 #define VK_LAUNCH_APP1 0xB6 #define EM_LINESCROLL 0x00B6 #define VK_LAUNCH_APP2 0xB7 #define EM_SCROLLCARET 0x00B7 #define EM_GETMODIFY 0x00B8 #define EM_SETMODIFY 0x00B9 #define VK_OEM_1 0xBA #define EM_GETLINECOUNT 0x00BA #define VK_OEM_PLUS 0xBB #define EM_LINEINDEX 0x00BB #define VK_OEM_COMMA 0xBC #define EM_SETHANDLE 0x00BC #define VK_OEM_MINUS 0xBD #define EM_GETHANDLE 0x00BD #define VK_OEM_PERIOD 0xBE #define EM_GETTHUMB 0x00BE #define VK_OEM_2 0xBF #define VK_OEM_3 0xC0 #define EM_LINELENGTH 0x00C1 #define EM_REPLACESEL 0x00C2 #define EM_GETLINE 0x00C4 #define EM_LIMITTEXT 0x00C5 #define EM_CANUNDO 0x00C6 #define EM_UNDO 0x00C7 #define EM_FMTLINES 0x00C8 #define EM_LINEFROMCHAR 0x00C9 #define EM_SETTABSTOPS 0x00CB #define EM_SETPASSWORDCHAR 0x00CC #define EM_EMPTYUNDOBUFFER 0x00CD #define EM_GETFIRSTVISIBLELINE 0x00CE #define EM_SETREADONLY 0x00CF #define EM_SETWORDBREAKPROC 0x00D0 #define EM_GETWORDBREAKPROC 0x00D1 #define EM_GETPASSWORDCHAR 0x00D2 #define EM_SETMARGINS 0x00D3 #define EM_GETMARGINS 0x00D4 #define EM_GETLIMITTEXT 0x00D5 #define EM_POSFROMCHAR 0x00D6 #define EM_CHARFROMPOS 0x00D7 #define EM_SETIMESTATUS 0x00D8 #define EM_GETIMESTATUS 0x00D9 #define VK_OEM_4 0xDB #define VK_OEM_5 0xDC #define VK_OEM_6 0xDD #define VK_OEM_7 0xDE #define VK_OEM_8 0xDF #define VK_OEM_AX 0xE1 #define VK_OEM_102 0xE2 #define VK_ICO_HELP 0xE3 #define VK_ICO_00 0xE4 #define VK_PROCESSKEY 0xE5 #define VK_ICO_CLEAR 0xE6 #define VK_PACKET 0xE7 #define VK_OEM_RESET 0xE9 #define VK_OEM_JUMP 0xEA #define VK_OEM_PA1 0xEB #define VK_OEM_PA2 0xEC #define VK_OEM_PA3 0xED #define VK_OEM_WSCTRL 0xEE #define VK_OEM_CUSEL 0xEF #define VK_OEM_ATTN 0xF0 #define BM_GETCHECK 0x00F0 #define VK_OEM_FINISH 0xF1 #define BM_SETCHECK 0x00F1 #define VK_OEM_COPY 0xF2 #define BM_GETSTATE 0x00F2 #define VK_OEM_AUTO 0xF3 #define BM_SETSTATE 0x00F3 #define VK_OEM_ENLW 0xF4 #define BM_SETSTYLE 0x00F4 #define VK_OEM_BACKTAB 0xF5 #define BM_CLICK 0x00F5 #define VK_ATTN 0xF6 #define BM_GETIMAGE 0x00F6 #define VK_CRSEL 0xF7 #define BM_SETIMAGE 0x00F7 #define VK_EXSEL 0xF8 #define VK_EREOF 0xF9 #define VK_PLAY 0xFA #define VK_ZOOM 0xFB #define VK_NONAME 0xFC #define VK_PA1 0xFD #define VK_OEM_CLEAR 0xFE #define WM_KEYFIRST 0x0100 #define WM_KEYDOWN 0x0100 #define WVR_HREDRAW 0x0100 #define HDS_FILTERBAR 0x0100 #define TBSTYLE_TOOLTIPS 0x0100 #define RBS_TOOLTIPS 0x00000100 #define SBARS_SIZEGRIP 0x0100 #define TBS_TOOLTIPS 0x0100 #define UDS_HOTTRACK 0x0100 #define LVS_AUTOARRANGE 0x0100 #define TVS_CHECKBOXES 0x0100 #define TCS_BUTTONS 0x0100 #define MCS_NOSELCHANGEONNAV 0x0100 #define WM_KEYUP 0x0101 #define WM_CHAR 0x0102 #define WM_DEADCHAR 0x0103 #define WM_SYSKEYDOWN 0x0104 #define WM_SYSKEYUP 0x0105 #define WM_SYSCHAR 0x0106 #define WM_SYSDEADCHAR 0x0107 #define WM_KEYLAST 0x0108 #define WM_IME_STARTCOMPOSITION 0x010D #define WM_IME_ENDCOMPOSITION 0x010E #define WM_IME_COMPOSITION 0x010F #define WM_IME_KEYLAST 0x010F #define WM_INITDIALOG 0x0110 #define WM_COMMAND 0x0111 #define WM_SYSCOMMAND 0x0112 #define WM_TIMER 0x0113 #define WM_HSCROLL 0x0114 #define WM_VSCROLL 0x0115 #define WM_INITMENU 0x0116 #define WM_INITMENUPOPUP 0x0117 #define WM_MENUSELECT 0x011F #define WM_MENUCHAR 0x0120 #define WM_ENTERIDLE 0x0121 #define WM_MENURBUTTONUP 0x0122 #define WM_MENUDRAG 0x0123 #define WM_MENUGETOBJECT 0x0124 #define WM_UNINITMENUPOPUP 0x0125 #define WM_MENUCOMMAND 0x0126 #define WM_CHANGEUISTATE 0x0127 #define WM_UPDATEUISTATE 0x0128 #define WM_QUERYUISTATE 0x0129 #define WM_CTLCOLORMSGBOX 0x0132 #define WM_CTLCOLOREDIT 0x0133 #define WM_CTLCOLORLISTBOX 0x0134 #define WM_CTLCOLORBTN 0x0135 #define WM_CTLCOLORDLG 0x0136 #define WM_CTLCOLORSCROLLBAR 0x0137 #define WM_CTLCOLORSTATIC 0x0138 #define MN_GETHMENU 0x01E1 #define WM_MOUSEFIRST 0x0200 #define WM_MOUSEMOVE 0x0200 #define WVR_VREDRAW 0x0200 #define CS_NOCLOSE 0x0200 #define CF_PRIVATEFIRST 0x0200 #define TBSTYLE_WRAPABLE 0x0200 #define RBS_VARHEIGHT 0x00000200 #define TBS_REVERSED 0x0200 #define LVS_EDITLABELS 0x0200 #define TVS_TRACKSELECT 0x0200 #define TCS_MULTILINE 0x0200 #define WM_LBUTTONDOWN 0x0201 #define WM_LBUTTONUP 0x0202 #define WM_LBUTTONDBLCLK 0x0203 #define WM_RBUTTONDOWN 0x0204 #define WM_RBUTTONUP 0x0205 #define WM_RBUTTONDBLCLK 0x0206 #define WM_MBUTTONDOWN 0x0207 #define WM_MBUTTONUP 0x0208 #define WM_MBUTTONDBLCLK 0x0209 #define WM_MOUSEWHEEL 0x020A #define WM_XBUTTONDOWN 0x020B #define WM_XBUTTONUP 0x020C #define WM_XBUTTONDBLCLK 0x020D #define WM_MOUSELAST 0x020D #define WM_PARENTNOTIFY 0x0210 #define WM_ENTERMENULOOP 0x0211 #define WM_EXITMENULOOP 0x0212 #define WM_NEXTMENU 0x0213 #define WM_SIZING 0x0214 #define WM_CAPTURECHANGED 0x0215 #define WM_MOVING 0x0216 #define WM_POWERBROADCAST 0x0218 #define WM_DEVICECHANGE 0x0219 #define WM_MDICREATE 0x0220 #define WM_MDIDESTROY 0x0221 #define WM_MDIACTIVATE 0x0222 #define WM_MDIRESTORE 0x0223 #define WM_MDINEXT 0x0224 #define WM_MDIMAXIMIZE 0x0225 #define WM_MDITILE 0x0226 #define WM_MDICASCADE 0x0227 #define WM_MDIICONARRANGE 0x0228 #define WM_MDIGETACTIVE 0x0229 #define WM_MDISETMENU 0x0230 #define WM_ENTERSIZEMOVE 0x0231 #define WM_EXITSIZEMOVE 0x0232 #define WM_DROPFILES 0x0233 #define WM_MDIREFRESHMENU 0x0234 #define WM_IME_SETCONTEXT 0x0281 #define WM_IME_NOTIFY 0x0282 #define WM_IME_CONTROL 0x0283 #define WM_IME_COMPOSITIONFULL 0x0284 #define WM_IME_SELECT 0x0285 #define WM_IME_CHAR 0x0286 #define WM_IME_REQUEST 0x0288 #define WM_IME_KEYDOWN 0x0290 #define WM_IME_KEYUP 0x0291 #define WM_NCMOUSEHOVER 0x02A0 #define WM_MOUSEHOVER 0x02A1 #define WM_NCMOUSELEAVE 0x02A2 #define WM_MOUSELEAVE 0x02A3 #define CF_PRIVATELAST 0x02FF #define WM_CUT 0x0300 #define CF_GDIOBJFIRST 0x0300 #define WM_COPY 0x0301 #define WM_PASTE 0x0302 #define WM_CLEAR 0x0303 #define WM_UNDO 0x0304 #define WM_RENDERFORMAT 0x0305 #define WM_RENDERALLFORMATS 0x0306 #define WM_DESTROYCLIPBOARD 0x0307 #define WM_DRAWCLIPBOARD 0x0308 #define WM_PAINTCLIPBOARD 0x0309 #define WM_VSCROLLCLIPBOARD 0x030A #define WM_SIZECLIPBOARD 0x030B #define WM_ASKCBFORMATNAME 0x030C #define WM_CHANGECBCHAIN 0x030D #define WM_HSCROLLCLIPBOARD 0x030E #define WM_QUERYNEWPALETTE 0x030F #define WM_PALETTEISCHANGING 0x0310 #define WM_PALETTECHANGED 0x0311 #define WM_HOTKEY 0x0312 #define WM_PRINT 0x0317 #define WM_PRINTCLIENT 0x0318 #define WM_APPCOMMAND 0x0319 #define WM_HANDHELDFIRST 0x0358 #define WM_HANDHELDLAST 0x035F #define WM_AFXFIRST 0x0360 #define WM_AFXLAST 0x037F #define WM_PENWINFIRST 0x0380 #define WM_PENWINLAST 0x038F #define WM_DDE_FIRST 0x03E0 #define CF_GDIOBJLAST 0x03FF #define WM_USER 0x0400 #define WVR_VALIDRECTS 0x0400 #define TBSTYLE_ALTDRAG 0x0400 #define RBS_BANDBORDERS 0x00000400 #define TBS_DOWNISLEFT 0x0400 #define LVS_OWNERDRAWFIXED 0x0400 #define TVS_SINGLEEXPAND 0x0400 #define TCS_FIXEDWIDTH 0x0400 #define ctlFirst 0x0400 #define psh1 0x0400 #define psh2 0x0401 #define psh3 0x0402 #define psh4 0x0403 #define psh5 0x0404 #define psh6 0x0405 #define psh7 0x0406 #define psh8 0x0407 #define psh9 0x0408 #define psh10 0x0409 #define psh11 0x040a #define psh12 0x040b #define psh13 0x040c #define psh14 0x040d #define psh15 0x040e #define psh16 0x040f #define _WIN32_WINDOWS 0x0410 #define chx1 0x0410 #define chx2 0x0411 #define chx3 0x0412 #define chx4 0x0413 #define chx5 0x0414 #define chx6 0x0415 #define chx7 0x0416 #define chx8 0x0417 #define chx9 0x0418 #define chx10 0x0419 #define chx11 0x041a #define chx12 0x041b #define chx13 0x041c #define chx14 0x041d #define chx15 0x041e #define chx16 0x041f #define rad1 0x0420 #define rad2 0x0421 #define rad3 0x0422 #define rad4 0x0423 #define rad5 0x0424 #define rad6 0x0425 #define rad7 0x0426 #define rad8 0x0427 #define rad9 0x0428 #define rad10 0x0429 #define rad11 0x042a #define rad12 0x042b #define rad13 0x042c #define rad14 0x042d #define rad15 0x042e #define rad16 0x042f #define grp1 0x0430 #define grp2 0x0431 #define grp3 0x0432 #define grp4 0x0433 #define frm1 0x0434 #define frm2 0x0435 #define frm3 0x0436 #define frm4 0x0437 #define rct1 0x0438 #define rct2 0x0439 #define rct3 0x043a #define rct4 0x043b #define ico1 0x043c #define ico2 0x043d #define ico3 0x043e #define ico4 0x043f #define stc1 0x0440 #define stc2 0x0441 #define stc3 0x0442 #define stc4 0x0443 #define stc5 0x0444 #define stc6 0x0445 #define stc7 0x0446 #define stc8 0x0447 #define stc9 0x0448 #define stc10 0x0449 #define stc11 0x044a #define stc12 0x044b #define stc13 0x044c #define stc14 0x044d #define stc15 0x044e #define stc16 0x044f #define stc17 0x0450 #define stc18 0x0451 #define stc19 0x0452 #define stc20 0x0453 #define stc21 0x0454 #define stc22 0x0455 #define stc23 0x0456 #define stc24 0x0457 #define stc25 0x0458 #define stc26 0x0459 #define stc27 0x045a #define stc28 0x045b #define stc29 0x045c #define stc30 0x045d #define stc31 0x045e #define stc32 0x045f #define lst1 0x0460 #define lst2 0x0461 #define lst3 0x0462 #define lst4 0x0463 #define lst5 0x0464 #define lst6 0x0465 #define lst7 0x0466 #define lst8 0x0467 #define lst9 0x0468 #define lst10 0x0469 #define lst11 0x046a #define lst12 0x046b #define lst13 0x046c #define lst14 0x046d #define lst15 0x046e #define lst16 0x046f #define cmb1 0x0470 #define cmb2 0x0471 #define cmb3 0x0472 #define cmb4 0x0473 #define cmb5 0x0474 #define cmb6 0x0475 #define cmb7 0x0476 #define cmb8 0x0477 #define cmb9 0x0478 #define cmb10 0x0479 #define cmb11 0x047a #define cmb12 0x047b #define cmb13 0x047c #define cmb14 0x047d #define cmb15 0x047e #define cmb16 0x047f #define edt1 0x0480 #define edt2 0x0481 #define edt3 0x0482 #define edt4 0x0483 #define edt5 0x0484 #define edt6 0x0485 #define edt7 0x0486 #define edt8 0x0487 #define edt9 0x0488 #define edt10 0x0489 #define edt11 0x048a #define edt12 0x048b #define edt13 0x048c #define edt14 0x048d #define edt15 0x048e #define edt16 0x048f #define scr1 0x0490 #define scr2 0x0491 #define scr3 0x0492 #define scr4 0x0493 #define scr5 0x0494 #define scr6 0x0495 #define scr7 0x0496 #define scr8 0x0497 #define ctl1 0x04A0 #define ctlLast 0x04ff #define WINVER 0x0500 #define _WIN32_WINNT 0x0500 #define _WIN32_IE 0x0501 #define FILEOPENORD 1536 #define MULTIFILEOPENORD 1537 #define PRINTDLGORD 1538 #define PRNSETUPDLGORD 1539 #define FINDDLGORD 1540 #define REPLACEDLGORD 1541 #define FONTDLGORD 1542 #define FORMATDLGORD31 1543 #define FORMATDLGORD30 1544 #define RUNDLGORD 1545 #define PAGESETUPDLGORD 1546 #define NEWFILEOPENORD 1547 #define PRINTDLGEXORD 1549 #define PAGESETUPDLGORDMOTIF 1550 #define COLORMGMTDLGORD 1551 #define NEWFILEOPENV2ORD 1552 #define NEWFILEOPENV3ORD 1553 #define CS_SAVEBITS 0x0800 #define TBSTYLE_FLAT 0x0800 #define RBS_FIXEDORDER 0x00000800 #define SBARS_TOOLTIPS 0x0800 #define SBT_TOOLTIPS 0x0800 #define LVS_ALIGNLEFT 0x0800 #define TVS_INFOTIP 0x0800 #define TCS_RAGGEDRIGHT 0x0800 #define LVS_ALIGNMASK 0x0c00 #define CS_BYTEALIGNCLIENT 0x1000 #define TBSTYLE_LIST 0x1000 #define RBS_REGISTERDROP 0x00001000 #define TBS_TRANSPARENTBKGND 0x1000 #define LVS_OWNERDATA 0x1000 #define TVS_FULLROWSELECT 0x1000 #define TCS_FOCUSONBUTTONDOWN 0x1000 #define CS_BYTEALIGNWINDOW 0x2000 #define TBSTYLE_CUSTOMERASE 0x2000 #define RBS_AUTOSIZE 0x00002000 #define LVS_NOSCROLL 0x2000 #define TVS_NOSCROLL 0x2000 #define TCS_OWNERDRAWFIXED 0x2000 #define CS_GLOBALCLASS 0x4000 #define TBSTYLE_REGISTERDROP 0x4000 #define RBS_VERTICALGRIPPER 0x00004000 #define LVS_NOCOLUMNHEADER 0x4000 #define TVS_NONEVENHEIGHT 0x4000 #define TCS_TOOLTIPS 0x4000 #define IDH_NO_HELP 28440 #define IDH_MISSING_CONTEXT 28441 #define IDH_GENERIC_HELP_BUTTON 28442 #define IDH_OK 28443 #define IDH_CANCEL 28444 #define IDH_HELP 28445 #define LANG_BOSNIAN_NEUTRAL 0x781a #define LANG_CHINESE_TRADITIONAL 0x7c04 #define LANG_SERBIAN_NEUTRAL 0x7c1a #define OCR_NORMAL 32512 #define OIC_SAMPLE 32512 #define IDI_APPLICATION 32512 #define OCR_IBEAM 32513 #define OIC_HAND 32513 #define IDI_HAND 32513 #define OCR_WAIT 32514 #define OIC_QUES 32514 #define IDI_QUESTION 32514 #define OCR_CROSS 32515 #define OIC_BANG 32515 #define IDI_EXCLAMATION 32515 #define OCR_UP 32516 #define OIC_NOTE 32516 #define IDI_ASTERISK 32516 #define OIC_WINLOGO 32517 #define IDI_WINLOGO 32517 #define OCR_SIZE 32640 #define OCR_ICON 32641 #define OCR_SIZENWSE 32642 #define OCR_SIZENESW 32643 #define OCR_SIZEWE 32644 #define OCR_SIZENS 32645 #define OCR_SIZEALL 32646 #define OCR_ICOCUR 32647 #define OCR_NO 32648 #define OCR_HAND 32649 #define OCR_APPSTARTING 32650 #define OBM_LFARROWI 32734 #define OBM_RGARROWI 32735 #define OBM_DNARROWI 32736 #define OBM_UPARROWI 32737 #define OBM_COMBO 32738 #define OBM_MNARROW 32739 #define OBM_LFARROWD 32740 #define OBM_RGARROWD 32741 #define OBM_DNARROWD 32742 #define OBM_UPARROWD 32743 #define OBM_RESTORED 32744 #define OBM_ZOOMD 32745 #define OBM_REDUCED 32746 #define OBM_RESTORE 32747 #define OBM_ZOOM 32748 #define OBM_REDUCE 32749 #define OBM_LFARROW 32750 #define OBM_RGARROW 32751 #define OBM_DNARROW 32752 #define OBM_UPARROW 32753 #define OBM_CLOSE 32754 #define OBM_OLD_RESTORE 32755 #define OBM_OLD_ZOOM 32756 #define OBM_OLD_REDUCE 32757 #define OBM_BTNCORNERS 32758 #define OBM_CHECKBOXES 32759 #define OBM_CHECK 32760 #define OBM_BTSIZE 32761 #define OBM_OLD_LFARROW 32762 #define OBM_OLD_RGARROW 32763 #define OBM_OLD_DNARROW 32764 #define OBM_OLD_UPARROW 32765 #define OBM_SIZE 32766 #define OBM_OLD_CLOSE 32767 #define WM_APP 0x8000 #define HELP_TCARD 0x8000 #define TBSTYLE_TRANSPARENT 0x8000 #define RBS_DBLCLKTOGGLE 0x00008000 #define LVS_NOSORTHEADER 0x8000 #define TVS_NOHSCROLL 0x8000 #define TCS_FOCUSNEVER 0x8000 #define SC_SIZE 0xF000 #define SC_SEPARATOR 0xF00F #define SC_MOVE 0xF010 #define SC_MINIMIZE 0xF020 #define SC_MAXIMIZE 0xF030 #define SC_NEXTWINDOW 0xF040 #define SC_PREVWINDOW 0xF050 #define SC_CLOSE 0xF060 #define SC_VSCROLL 0xF070 #define SC_HSCROLL 0xF080 #define SC_MOUSEMENU 0xF090 #define SC_KEYMENU 0xF100 #define SC_ARRANGE 0xF110 #define SC_RESTORE 0xF120 #define SC_TASKLIST 0xF130 #define SC_SCREENSAVE 0xF140 #define SC_HOTKEY 0xF150 #define SC_DEFAULT 0xF160 #define SC_MONITORPOWER 0xF170 #define SC_CONTEXTHELP 0xF180 #define LVS_TYPESTYLEMASK 0xfc00 //#define HTERROR -2 //#define PWR_FAIL -1 //#define HTTRANSPARENT -1 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NO_MFC 1 #define _APS_NEXT_RESOURCE_VALUE 101 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1000 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif ================================================ FILE: resource.h ================================================ //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by gdidll.rc // #define SW_HIDE 0 #define HIDE_WINDOW 0 #define WM_NULL 0x0000 #define WA_INACTIVE 0 #define HTNOWHERE 0 #define SMTO_NORMAL 0x0000 #define ICON_SMALL 0 #define SIZE_RESTORED 0 #define BN_CLICKED 0 #define BST_UNCHECKED 0x0000 #define HDS_HORZ 0x0000 #define TBSTYLE_BUTTON 0x0000 #define TBS_HORZ 0x0000 #define TBS_BOTTOM 0x0000 #define TBS_RIGHT 0x0000 #define LVS_ICON 0x0000 #define LVS_ALIGNTOP 0x0000 #define TCS_TABS 0x0000 #define TCS_SINGLELINE 0x0000 #define TCS_RIGHTJUSTIFY 0x0000 #define DTS_SHORTDATEFORMAT 0x0000 #define PGS_VERT 0x00000000 #define LANG_NEUTRAL 0x00 #define SUBLANG_NEUTRAL 0x00 #define SORT_DEFAULT 0x0 #define SORT_JAPANESE_XJIS 0x0 #define SORT_CHINESE_BIG5 0x0 #define SORT_CHINESE_PRCP 0x0 #define SORT_KOREAN_KSC 0x0 #define SORT_HUNGARIAN_DEFAULT 0x0 #define SORT_GEORGIAN_TRADITIONAL 0x0 #define _USE_DECLSPECS_FOR_SAL 0 #define _USE_ATTRIBUTES_FOR_SAL 0 #define CREATEPROCESS_MANIFEST_RESOURCE_ID 1 #define MINIMUM_RESERVED_MANIFEST_RESOURCE_ID 1 #define SW_SHOWNORMAL 1 #define SW_NORMAL 1 #define SHOW_OPENWINDOW 1 #define SW_PARENTCLOSING 1 #define VK_LBUTTON 0x01 #define WM_CREATE 0x0001 #define WA_ACTIVE 1 #define PWR_OK 1 #define PWR_SUSPENDREQUEST 1 #define NFR_ANSI 1 #define UIS_SET 1 #define UISF_HIDEFOCUS 0x1 #define XBUTTON1 0x0001 #define WMSZ_LEFT 1 #define HTCLIENT 1 #define SMTO_BLOCK 0x0001 #define MA_ACTIVATE 1 #define ICON_BIG 1 #define SIZE_MINIMIZED 1 #define MK_LBUTTON 0x0001 #define TME_HOVER 0x00000001 #define CS_VREDRAW 0x0001 #define CF_TEXT 1 #define IDOK 1 #define BN_PAINT 1 #define BST_CHECKED 0x0001 #define TBSTYLE_SEP 0x0001 #define TTS_ALWAYSTIP 0x01 #define TBS_AUTOTICKS 0x0001 #define UDS_WRAP 0x0001 #define PBS_SMOOTH 0x01 #define LWS_TRANSPARENT 0x0001 #define LVS_REPORT 0x0001 #define TVS_HASBUTTONS 0x0001 #define TCS_SCROLLOPPOSITE 0x0001 #define ACS_CENTER 0x0001 #define MCS_DAYSTATE 0x0001 #define DTS_UPDOWN 0x0001 #define PGS_HORZ 0x00000001 #define NFS_EDIT 0x0001 #define BCSIF_GLYPH 0x0001 #define BCSS_NOSPLIT 0x0001 #define LANG_ARABIC 0x01 #define SUBLANG_DEFAULT 0x01 #define SUBLANG_AFRIKAANS_SOUTH_AFRICA 0x01 #define SUBLANG_ALBANIAN_ALBANIA 0x01 #define SUBLANG_ALSATIAN_FRANCE 0x01 #define SUBLANG_AMHARIC_ETHIOPIA 0x01 #define SUBLANG_ARABIC_SAUDI_ARABIA 0x01 #define SUBLANG_ARMENIAN_ARMENIA 0x01 #define SUBLANG_ASSAMESE_INDIA 0x01 #define SUBLANG_AZERI_LATIN 0x01 #define SUBLANG_BASHKIR_RUSSIA 0x01 #define SUBLANG_BASQUE_BASQUE 0x01 #define SUBLANG_BELARUSIAN_BELARUS 0x01 #define SUBLANG_BENGALI_INDIA 0x01 #define SUBLANG_BRETON_FRANCE 0x01 #define SUBLANG_BULGARIAN_BULGARIA 0x01 #define SUBLANG_CATALAN_CATALAN 0x01 #define SUBLANG_CHINESE_TRADITIONAL 0x01 #define SUBLANG_CORSICAN_FRANCE 0x01 #define SUBLANG_CZECH_CZECH_REPUBLIC 0x01 #define SUBLANG_CROATIAN_CROATIA 0x01 #define SUBLANG_DANISH_DENMARK 0x01 #define SUBLANG_DARI_AFGHANISTAN 0x01 #define SUBLANG_DIVEHI_MALDIVES 0x01 #define SUBLANG_DUTCH 0x01 #define SUBLANG_ENGLISH_US 0x01 #define SUBLANG_ESTONIAN_ESTONIA 0x01 #define SUBLANG_FAEROESE_FAROE_ISLANDS 0x01 #define SUBLANG_FILIPINO_PHILIPPINES 0x01 #define SUBLANG_FINNISH_FINLAND 0x01 #define SUBLANG_FRENCH 0x01 #define SUBLANG_FRISIAN_NETHERLANDS 0x01 #define SUBLANG_GALICIAN_GALICIAN 0x01 #define SUBLANG_GEORGIAN_GEORGIA 0x01 #define SUBLANG_GERMAN 0x01 #define SUBLANG_GREEK_GREECE 0x01 #define SUBLANG_GREENLANDIC_GREENLAND 0x01 #define SUBLANG_GUJARATI_INDIA 0x01 #define SUBLANG_HAUSA_NIGERIA_LATIN 0x01 #define SUBLANG_HEBREW_ISRAEL 0x01 #define SUBLANG_HINDI_INDIA 0x01 #define SUBLANG_HUNGARIAN_HUNGARY 0x01 #define SUBLANG_ICELANDIC_ICELAND 0x01 #define SUBLANG_IGBO_NIGERIA 0x01 #define SUBLANG_INDONESIAN_INDONESIA 0x01 #define SUBLANG_INUKTITUT_CANADA 0x01 #define SUBLANG_ITALIAN 0x01 #define SUBLANG_JAPANESE_JAPAN 0x01 #define SUBLANG_KANNADA_INDIA 0x01 #define SUBLANG_KAZAK_KAZAKHSTAN 0x01 #define SUBLANG_KHMER_CAMBODIA 0x01 #define SUBLANG_KICHE_GUATEMALA 0x01 #define SUBLANG_KINYARWANDA_RWANDA 0x01 #define SUBLANG_KONKANI_INDIA 0x01 #define SUBLANG_KOREAN 0x01 #define SUBLANG_KYRGYZ_KYRGYZSTAN 0x01 #define SUBLANG_LAO_LAO 0x01 #define SUBLANG_LATVIAN_LATVIA 0x01 #define SUBLANG_LITHUANIAN 0x01 #define SUBLANG_LUXEMBOURGISH_LUXEMBOURG 0x01 #define SUBLANG_MACEDONIAN_MACEDONIA 0x01 #define SUBLANG_MALAY_MALAYSIA 0x01 #define SUBLANG_MALAYALAM_INDIA 0x01 #define SUBLANG_MALTESE_MALTA 0x01 #define SUBLANG_MAORI_NEW_ZEALAND 0x01 #define SUBLANG_MAPUDUNGUN_CHILE 0x01 #define SUBLANG_MARATHI_INDIA 0x01 #define SUBLANG_MOHAWK_MOHAWK 0x01 #define SUBLANG_MONGOLIAN_CYRILLIC_MONGOLIA 0x01 #define SUBLANG_NEPALI_NEPAL 0x01 #define SUBLANG_NORWEGIAN_BOKMAL 0x01 #define SUBLANG_OCCITAN_FRANCE 0x01 #define SUBLANG_ORIYA_INDIA 0x01 #define SUBLANG_PASHTO_AFGHANISTAN 0x01 #define SUBLANG_PERSIAN_IRAN 0x01 #define SUBLANG_POLISH_POLAND 0x01 #define SUBLANG_PORTUGUESE_BRAZILIAN 0x01 #define SUBLANG_PUNJABI_INDIA 0x01 #define SUBLANG_QUECHUA_BOLIVIA 0x01 #define SUBLANG_ROMANIAN_ROMANIA 0x01 #define SUBLANG_ROMANSH_SWITZERLAND 0x01 #define SUBLANG_RUSSIAN_RUSSIA 0x01 #define SUBLANG_SAMI_NORTHERN_NORWAY 0x01 #define SUBLANG_SANSKRIT_INDIA 0x01 #define SUBLANG_SERBIAN_CROATIA 0x01 #define SUBLANG_SINDHI_INDIA 0x01 #define SUBLANG_SINHALESE_SRI_LANKA 0x01 #define SUBLANG_SOTHO_NORTHERN_SOUTH_AFRICA 0x01 #define SUBLANG_SLOVAK_SLOVAKIA 0x01 #define SUBLANG_SLOVENIAN_SLOVENIA 0x01 #define SUBLANG_SPANISH 0x01 #define SUBLANG_SWAHILI_KENYA 0x01 #define SUBLANG_SWEDISH 0x01 #define SUBLANG_SYRIAC_SYRIA 0x01 #define SUBLANG_TAJIK_TAJIKISTAN 0x01 #define SUBLANG_TAMIL_INDIA 0x01 #define SUBLANG_TATAR_RUSSIA 0x01 #define SUBLANG_TELUGU_INDIA 0x01 #define SUBLANG_THAI_THAILAND 0x01 #define SUBLANG_TIBETAN_PRC 0x01 #define SUBLANG_TSWANA_SOUTH_AFRICA 0x01 #define SUBLANG_TURKISH_TURKEY 0x01 #define SUBLANG_TURKMEN_TURKMENISTAN 0x01 #define SUBLANG_UIGHUR_PRC 0x01 #define SUBLANG_UKRAINIAN_UKRAINE 0x01 #define SUBLANG_UPPER_SORBIAN_GERMANY 0x01 #define SUBLANG_URDU_PAKISTAN 0x01 #define SUBLANG_UZBEK_LATIN 0x01 #define SUBLANG_VIETNAMESE_VIETNAM 0x01 #define SUBLANG_WELSH_UNITED_KINGDOM 0x01 #define SUBLANG_WOLOF_SENEGAL 0x01 #define SUBLANG_XHOSA_SOUTH_AFRICA 0x01 #define SUBLANG_YAKUT_RUSSIA 0x01 #define SUBLANG_YI_PRC 0x01 #define SUBLANG_YORUBA_NIGERIA 0x01 #define SUBLANG_ZULU_SOUTH_AFRICA 0x01 #define SORT_INVARIANT_MATH 0x1 #define SORT_JAPANESE_UNICODE 0x1 #define SORT_CHINESE_UNICODE 0x1 #define SORT_KOREAN_UNICODE 0x1 #define SORT_GERMAN_PHONE_BOOK 0x1 #define SORT_HUNGARIAN_TECHNICAL 0x1 #define SORT_GEORGIAN_MODERN 0x1 #define VS_VERSION_INFO 1 #define VFFF_ISSHAREDFILE 0x0001 #define VFF_CURNEDEST 0x0001 #define VIFF_FORCEINSTALL 0x0001 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID 2 #define SW_SHOWMINIMIZED 2 #define SHOW_ICONWINDOW 2 #define SW_OTHERZOOM 2 #define VK_RBUTTON 0x02 #define WM_DESTROY 0x0002 #define WA_CLICKACTIVE 2 #define PWR_SUSPENDRESUME 2 #define NFR_UNICODE 2 #define UIS_CLEAR 2 #define UISF_HIDEACCEL 0x2 #define XBUTTON2 0x0002 #define WMSZ_RIGHT 2 #define HTCAPTION 2 #define SMTO_ABORTIFHUNG 0x0002 #define MA_ACTIVATEANDEAT 2 #define SIZE_MAXIMIZED 2 #define MK_RBUTTON 0x0002 #define TME_LEAVE 0x00000002 #define CS_HREDRAW 0x0002 #define CF_BITMAP 2 #define IDCANCEL 2 #define BN_HILITE 2 #define BST_INDETERMINATE 0x0002 #define HDS_BUTTONS 0x0002 #define TBSTYLE_CHECK 0x0002 #define TTS_NOPREFIX 0x02 #define TBS_VERT 0x0002 #define UDS_SETBUDDYINT 0x0002 #define LWS_IGNORERETURN 0x0002 #define LVS_SMALLICON 0x0002 #define TVS_HASLINES 0x0002 #define TCS_BOTTOM 0x0002 #define TCS_RIGHT 0x0002 #define ACS_TRANSPARENT 0x0002 #define MCS_MULTISELECT 0x0002 #define DTS_SHOWNONE 0x0002 #define PGS_AUTOSCROLL 0x00000002 #define NFS_STATIC 0x0002 #define BCSIF_IMAGE 0x0002 #define BCSS_STRETCH 0x0002 #define LANG_BULGARIAN 0x02 #define SUBLANG_SYS_DEFAULT 0x02 #define SUBLANG_ARABIC_IRAQ 0x02 #define SUBLANG_AZERI_CYRILLIC 0x02 #define SUBLANG_BENGALI_BANGLADESH 0x02 #define SUBLANG_CHINESE_SIMPLIFIED 0x02 #define SUBLANG_DUTCH_BELGIAN 0x02 #define SUBLANG_ENGLISH_UK 0x02 #define SUBLANG_FRENCH_BELGIAN 0x02 #define SUBLANG_GERMAN_SWISS 0x02 #define SUBLANG_INUKTITUT_CANADA_LATIN 0x02 #define SUBLANG_IRISH_IRELAND 0x02 #define SUBLANG_ITALIAN_SWISS 0x02 #define SUBLANG_KASHMIRI_SASIA 0x02 #define SUBLANG_KASHMIRI_INDIA 0x02 #define SUBLANG_LOWER_SORBIAN_GERMANY 0x02 #define SUBLANG_MALAY_BRUNEI_DARUSSALAM 0x02 #define SUBLANG_MONGOLIAN_PRC 0x02 #define SUBLANG_NEPALI_INDIA 0x02 #define SUBLANG_NORWEGIAN_NYNORSK 0x02 #define SUBLANG_PORTUGUESE 0x02 #define SUBLANG_QUECHUA_ECUADOR 0x02 #define SUBLANG_SAMI_NORTHERN_SWEDEN 0x02 #define SUBLANG_SERBIAN_LATIN 0x02 #define SUBLANG_SINDHI_PAKISTAN 0x02 #define SUBLANG_SINDHI_AFGHANISTAN 0x02 #define SUBLANG_SPANISH_MEXICAN 0x02 #define SUBLANG_SWEDISH_FINLAND 0x02 #define SUBLANG_TAMAZIGHT_ALGERIA_LATIN 0x02 #define SUBLANG_TIGRIGNA_ERITREA 0x02 #define SUBLANG_URDU_INDIA 0x02 #define SUBLANG_UZBEK_CYRILLIC 0x02 #define SORT_CHINESE_PRC 0x2 #define VFF_FILEINUSE 0x0002 #define VIFF_DONTDELETEOLD 0x0002 #define ISOLATIONAWARE_NOSTATICIMPORT_MANIFEST_RESOURCE_ID 3 #define SW_SHOWMAXIMIZED 3 #define SW_MAXIMIZE 3 #define SHOW_FULLSCREEN 3 #define SW_PARENTOPENING 3 #define VK_CANCEL 0x03 #define WM_MOVE 0x0003 #define PWR_CRITICALRESUME 3 #define NF_QUERY 3 #define UIS_INITIALIZE 3 #define WMSZ_TOP 3 #define HTSYSMENU 3 #define MA_NOACTIVATE 3 #define SIZE_MAXSHOW 3 #define CF_METAFILEPICT 3 #define IDABORT 3 #define BN_UNHILITE 3 #define LVS_LIST 0x0003 #define LVS_TYPEMASK 0x0003 #define LANG_CATALAN 0x03 #define SUBLANG_CUSTOM_DEFAULT 0x03 #define SUBLANG_ARABIC_EGYPT 0x03 #define SUBLANG_CHINESE_HONGKONG 0x03 #define SUBLANG_ENGLISH_AUS 0x03 #define SUBLANG_FRENCH_CANADIAN 0x03 #define SUBLANG_GERMAN_AUSTRIAN 0x03 #define SUBLANG_QUECHUA_PERU 0x03 #define SUBLANG_SAMI_NORTHERN_FINLAND 0x03 #define SUBLANG_SERBIAN_CYRILLIC 0x03 #define SUBLANG_SPANISH_MODERN 0x03 #define SORT_CHINESE_BOPOMOFO 0x3 #define SW_SHOWNOACTIVATE 4 #define SHOW_OPENNOACTIVATE 4 #define SW_OTHERUNZOOM 4 #define VK_MBUTTON 0x04 #define NF_REQUERY 4 #define WMSZ_TOPLEFT 4 #define HTGROWBOX 4 #define MA_NOACTIVATEANDEAT 4 #define SIZE_MAXHIDE 4 #define MK_SHIFT 0x0004 #define CF_SYLK 4 #define IDRETRY 4 #define BN_DISABLE 4 #define BST_PUSHED 0x0004 #define HDS_HOTTRACK 0x0004 #define TBSTYLE_GROUP 0x0004 #define TBS_TOP 0x0004 #define TBS_LEFT 0x0004 #define UDS_ALIGNRIGHT 0x0004 #define PBS_VERTICAL 0x04 #define LVS_SINGLESEL 0x0004 #define TVS_LINESATROOT 0x0004 #define TCS_MULTISELECT 0x0004 #define ACS_AUTOPLAY 0x0004 #define MCS_WEEKNUMBERS 0x0004 #define DTS_LONGDATEFORMAT 0x0004 #define PGS_DRAGNDROP 0x00000004 #define NFS_LISTCOMBO 0x0004 #define BCSIF_STYLE 0x0004 #define BCSS_ALIGNLEFT 0x0004 #define LANG_CHINESE 0x04 #define LANG_CHINESE_SIMPLIFIED 0x04 #define SUBLANG_CUSTOM_UNSPECIFIED 0x04 #define SUBLANG_ARABIC_LIBYA 0x04 #define SUBLANG_CHINESE_SINGAPORE 0x04 #define SUBLANG_CROATIAN_BOSNIA_HERZEGOVINA_LATIN 0x04 #define SUBLANG_ENGLISH_CAN 0x04 #define SUBLANG_FRENCH_SWISS 0x04 #define SUBLANG_GERMAN_LUXEMBOURG 0x04 #define SUBLANG_SAMI_LULE_NORWAY 0x04 #define SUBLANG_SPANISH_GUATEMALA 0x04 #define SORT_JAPANESE_RADICALSTROKE 0x4 #define VFF_BUFFTOOSMALL 0x0004 #define SW_SHOW 5 #define VK_XBUTTON1 0x05 #define WM_SIZE 0x0005 #define WMSZ_TOPRIGHT 5 #define HTMENU 5 #define CF_DIF 5 #define IDIGNORE 5 #define BN_DOUBLECLICKED 5 #define LANG_CZECH 0x05 #define SUBLANG_UI_CUSTOM_DEFAULT 0x05 #define SUBLANG_ARABIC_ALGERIA 0x05 #define SUBLANG_BOSNIAN_BOSNIA_HERZEGOVINA_LATIN 0x05 #define SUBLANG_CHINESE_MACAU 0x05 #define SUBLANG_ENGLISH_NZ 0x05 #define SUBLANG_FRENCH_LUXEMBOURG 0x05 #define SUBLANG_GERMAN_LIECHTENSTEIN 0x05 #define SUBLANG_SAMI_LULE_SWEDEN 0x05 #define SUBLANG_SPANISH_COSTA_RICA 0x05 #define SW_MINIMIZE 6 #define VK_XBUTTON2 0x06 #define WM_ACTIVATE 0x0006 #define WMSZ_BOTTOM 6 #define HTHSCROLL 6 #define CF_TIFF 6 #define IDYES 6 #define BN_SETFOCUS 6 #define LANG_DANISH 0x06 #define SUBLANG_ARABIC_MOROCCO 0x06 #define SUBLANG_ENGLISH_EIRE 0x06 #define SUBLANG_FRENCH_MONACO 0x06 #define SUBLANG_SAMI_SOUTHERN_NORWAY 0x06 #define SUBLANG_SERBIAN_BOSNIA_HERZEGOVINA_LATIN 0x06 #define SUBLANG_SPANISH_PANAMA 0x06 #define SW_SHOWMINNOACTIVE 7 #define WM_SETFOCUS 0x0007 #define WMSZ_BOTTOMLEFT 7 #define HTVSCROLL 7 #define CF_OEMTEXT 7 #define IDNO 7 #define BN_KILLFOCUS 7 #define LANG_GERMAN 0x07 #define SUBLANG_ARABIC_TUNISIA 0x07 #define SUBLANG_ENGLISH_SOUTH_AFRICA 0x07 #define SUBLANG_SAMI_SOUTHERN_SWEDEN 0x07 #define SUBLANG_SERBIAN_BOSNIA_HERZEGOVINA_CYRILLIC 0x07 #define SUBLANG_SPANISH_DOMINICAN_REPUBLIC 0x07 #define SW_SHOWNA 8 #define VK_BACK 0x08 #define WM_KILLFOCUS 0x0008 #define WMSZ_BOTTOMRIGHT 8 #define HTMINBUTTON 8 #define SMTO_NOTIMEOUTIFNOTHUNG 0x0008 #define MK_CONTROL 0x0008 #define CS_DBLCLKS 0x0008 #define CF_DIB 8 #define IDCLOSE 8 #define BST_FOCUS 0x0008 #define HDS_HIDDEN 0x0008 #define TBSTYLE_DROPDOWN 0x0008 #define TBS_BOTH 0x0008 #define UDS_ALIGNLEFT 0x0008 #define LVS_SHOWSELALWAYS 0x0008 #define TVS_EDITLABELS 0x0008 #define TCS_FLATBUTTONS 0x0008 #define ACS_TIMER 0x0008 #define MCS_NOTODAYCIRCLE 0x0008 #define NFS_BUTTON 0x0008 #define BCSIF_SIZE 0x0008 #define BCSS_IMAGE 0x0008 #define LANG_GREEK 0x08 #define SUBLANG_ARABIC_OMAN 0x08 #define SUBLANG_BOSNIAN_BOSNIA_HERZEGOVINA_CYRILLIC 0x08 #define SUBLANG_ENGLISH_JAMAICA 0x08 #define SUBLANG_SAMI_SKOLT_FINLAND 0x08 #define SUBLANG_SPANISH_VENEZUELA 0x08 #define SW_RESTORE 9 #define VK_TAB 0x09 #define HTMAXBUTTON 9 #define CF_PALETTE 9 #define IDHELP 9 #define DTS_TIMEFORMAT 0x0009 #define LANG_ENGLISH 0x09 #define SUBLANG_ARABIC_YEMEN 0x09 #define SUBLANG_ENGLISH_CARIBBEAN 0x09 #define SUBLANG_SAMI_INARI_FINLAND 0x09 #define SUBLANG_SPANISH_COLOMBIA 0x09 #define SW_SHOWDEFAULT 10 #define WM_ENABLE 0x000A #define HTLEFT 10 #define CF_PENDATA 10 #define IDTRYAGAIN 10 #define HELP_CONTEXTMENU 0x000a #define LANG_SPANISH 0x0a #define SUBLANG_ARABIC_SYRIA 0x0a #define SUBLANG_ENGLISH_BELIZE 0x0a #define SUBLANG_SPANISH_PERU 0x0a #define SW_FORCEMINIMIZE 11 #define SW_MAX 11 #define WM_SETREDRAW 0x000B #define HTRIGHT 11 #define CF_RIFF 11 #define IDCONTINUE 11 #define HELP_FINDER 0x000b #define LANG_FINNISH 0x0b #define SUBLANG_ARABIC_JORDAN 0x0b #define SUBLANG_ENGLISH_TRINIDAD 0x0b #define SUBLANG_SPANISH_ARGENTINA 0x0b #define VK_CLEAR 0x0C #define WM_SETTEXT 0x000C #define HTTOP 12 #define CF_WAVE 12 #define HELP_WM_HELP 0x000c #define DTS_SHORTDATECENTURYFORMAT 0x000C #define LANG_FRENCH 0x0c #define SUBLANG_ARABIC_LEBANON 0x0c #define SUBLANG_ENGLISH_ZIMBABWE 0x0c #define SUBLANG_SPANISH_ECUADOR 0x0c #define VK_RETURN 0x0D #define WM_GETTEXT 0x000D #define HTTOPLEFT 13 #define CF_UNICODETEXT 13 #define HELP_SETPOPUP_POS 0x000d #define LANG_HEBREW 0x0d #define SUBLANG_ARABIC_KUWAIT 0x0d #define SUBLANG_ENGLISH_PHILIPPINES 0x0d #define SUBLANG_SPANISH_CHILE 0x0d #define WM_GETTEXTLENGTH 0x000E #define HTTOPRIGHT 14 #define CF_ENHMETAFILE 14 #define LANG_HUNGARIAN 0x0e #define SUBLANG_ARABIC_UAE 0x0e #define SUBLANG_SPANISH_URUGUAY 0x0e #define WM_PAINT 0x000F #define HTBOTTOM 15 #define CF_HDROP 15 #define LANG_ICELANDIC 0x0f #define SUBLANG_ARABIC_BAHRAIN 0x0f #define SUBLANG_SPANISH_PARAGUAY 0x0f #define MAXIMUM_RESERVED_MANIFEST_RESOURCE_ID 16 #define VK_SHIFT 0x10 #define WM_CLOSE 0x0010 #define HTBOTTOMLEFT 16 #define WVR_ALIGNTOP 0x0010 #define MK_MBUTTON 0x0010 #define TME_NONCLIENT 0x00000010 #define CF_LOCALE 16 #define HELP_TCARD_DATA 0x0010 #define TBSTYLE_AUTOSIZE 0x0010 #define TTS_NOANIMATE 0x10 #define TBS_NOTICKS 0x0010 #define UDS_AUTOBUDDY 0x0010 #define LVS_SORTASCENDING 0x0010 #define TVS_DISABLEDRAGDROP 0x0010 #define TCS_FORCEICONLEFT 0x0010 #define MCS_NOTODAY 0x0010 #define DTS_APPCANPARSE 0x0010 #define NFS_ALL 0x0010 #define LANG_ITALIAN 0x10 #define SUBLANG_ARABIC_QATAR 0x10 #define SUBLANG_ENGLISH_INDIA 0x10 #define SUBLANG_SPANISH_BOLIVIA 0x10 #define VK_CONTROL 0x11 #define WM_QUERYENDSESSION 0x0011 #define HTBOTTOMRIGHT 17 #define CF_DIBV5 17 #define HELP_TCARD_OTHER_CALLER 0x0011 #define LANG_JAPANESE 0x11 #define SUBLANG_ENGLISH_MALAYSIA 0x11 #define SUBLANG_SPANISH_EL_SALVADOR 0x11 #define VK_MENU 0x12 #define WM_QUIT 0x0012 #define HTBORDER 18 #define CF_MAX 18 #define LANG_KOREAN 0x12 #define SUBLANG_ENGLISH_SINGAPORE 0x12 #define SUBLANG_SPANISH_HONDURAS 0x12 #define VK_PAUSE 0x13 #define WM_QUERYOPEN 0x0013 #define HTOBJECT 19 #define LANG_DUTCH 0x13 #define SUBLANG_SPANISH_NICARAGUA 0x13 #define VK_CAPITAL 0x14 #define WM_ERASEBKGND 0x0014 #define HTCLOSE 20 #define LANG_NORWEGIAN 0x14 #define SUBLANG_SPANISH_PUERTO_RICO 0x14 #define VK_KANA 0x15 #define VK_HANGEUL 0x15 #define VK_HANGUL 0x15 #define WM_SYSCOLORCHANGE 0x0015 #define HTHELP 21 #define LANG_POLISH 0x15 #define SUBLANG_SPANISH_US 0x15 #define WM_ENDSESSION 0x0016 #define LANG_PORTUGUESE 0x16 #define VK_JUNJA 0x17 #define LANG_ROMANSH 0x17 #define RT_MANIFEST 24 #define VK_FINAL 0x18 #define WM_SHOWWINDOW 0x0018 #define LANG_ROMANIAN 0x18 #define VK_HANJA 0x19 #define VK_KANJI 0x19 #define LANG_RUSSIAN 0x19 #define WM_WININICHANGE 0x001A #define LANG_BOSNIAN 0x1a #define LANG_CROATIAN 0x1a #define LANG_SERBIAN 0x1a #define VK_ESCAPE 0x1B #define WM_DEVMODECHANGE 0x001B #define LANG_SLOVAK 0x1b #define VK_CONVERT 0x1C #define WM_ACTIVATEAPP 0x001C #define LANG_ALBANIAN 0x1c #define VK_NONCONVERT 0x1D #define WM_FONTCHANGE 0x001D #define LANG_SWEDISH 0x1d #define VK_ACCEPT 0x1E #define WM_TIMECHANGE 0x001E #define LANG_THAI 0x1e #define VK_MODECHANGE 0x1F #define WM_CANCELMODE 0x001F #define LANG_TURKISH 0x1f #define VK_SPACE 0x20 #define WM_SETCURSOR 0x0020 #define WVR_ALIGNLEFT 0x0020 #define MK_XBUTTON1 0x0020 #define CS_OWNDC 0x0020 #define TBSTYLE_NOPREFIX 0x0020 #define TTS_NOFADE 0x20 #define TBS_ENABLESELRANGE 0x0020 #define UDS_ARROWKEYS 0x0020 #define LVS_SORTDESCENDING 0x0020 #define TVS_SHOWSELALWAYS 0x0020 #define TCS_FORCELABELLEFT 0x0020 #define DTS_RIGHTALIGN 0x0020 #define NFS_USEFONTASSOC 0x0020 #define LANG_URDU 0x20 #define VK_PRIOR 0x21 #define WM_MOUSEACTIVATE 0x0021 #define LANG_INDONESIAN 0x21 #define VK_NEXT 0x22 #define WM_CHILDACTIVATE 0x0022 #define LANG_UKRAINIAN 0x22 #define VK_END 0x23 #define WM_QUEUESYNC 0x0023 #define LANG_BELARUSIAN 0x23 #define VK_HOME 0x24 #define WM_GETMINMAXINFO 0x0024 #define LANG_SLOVENIAN 0x24 #define VK_LEFT 0x25 #define LANG_ESTONIAN 0x25 #define VK_UP 0x26 #define WM_PAINTICON 0x0026 #define LANG_LATVIAN 0x26 #define VK_RIGHT 0x27 #define WM_ICONERASEBKGND 0x0027 #define LANG_LITHUANIAN 0x27 #define VK_DOWN 0x28 #define WM_NEXTDLGCTL 0x0028 #define LANG_TAJIK 0x28 #define VK_SELECT 0x29 #define LANG_FARSI 0x29 #define LANG_PERSIAN 0x29 #define VK_PRINT 0x2A #define WM_SPOOLERSTATUS 0x002A #define LANG_VIETNAMESE 0x2a #define VK_EXECUTE 0x2B #define WM_DRAWITEM 0x002B #define LANG_ARMENIAN 0x2b #define VK_SNAPSHOT 0x2C #define WM_MEASUREITEM 0x002C #define LANG_AZERI 0x2c #define VK_INSERT 0x2D #define WM_DELETEITEM 0x002D #define LANG_BASQUE 0x2d #define VK_DELETE 0x2E #define WM_VKEYTOITEM 0x002E #define LANG_LOWER_SORBIAN 0x2e #define LANG_UPPER_SORBIAN 0x2e #define VK_HELP 0x2F #define WM_CHARTOITEM 0x002F #define LANG_MACEDONIAN 0x2f #define WM_SETFONT 0x0030 #define WM_GETFONT 0x0031 #define WM_SETHOTKEY 0x0032 #define LANG_TSWANA 0x32 #define WM_GETHOTKEY 0x0033 #define LANG_XHOSA 0x34 #define LANG_ZULU 0x35 #define LANG_AFRIKAANS 0x36 #define WM_QUERYDRAGICON 0x0037 #define LANG_GEORGIAN 0x37 #define LANG_FAEROESE 0x38 #define WM_COMPAREITEM 0x0039 #define LANG_HINDI 0x39 #define LANG_MALTESE 0x3a #define LANG_SAMI 0x3b #define LANG_IRISH 0x3c #define WM_GETOBJECT 0x003D #define LANG_MALAY 0x3e #define LANG_KAZAK 0x3f #define WVR_ALIGNBOTTOM 0x0040 #define MK_XBUTTON2 0x0040 #define CS_CLASSDC 0x0040 #define HDS_DRAGDROP 0x0040 #define BTNS_SHOWTEXT 0x0040 #define TTS_BALLOON 0x40 #define TBS_FIXEDLENGTH 0x0040 #define UDS_HORZ 0x0040 #define LVS_SHAREIMAGELISTS 0x0040 #define TVS_RTLREADING 0x0040 #define TCS_HOTTRACK 0x0040 #define MCS_NOTRAILINGDATES 0x0040 #define LANG_KYRGYZ 0x40 #define WM_COMPACTING 0x0041 #define LANG_SWAHILI 0x41 #define LANG_TURKMEN 0x42 #define LANG_UZBEK 0x43 #define WM_COMMNOTIFY 0x0044 #define LANG_TATAR 0x44 #define LANG_BENGALI 0x45 #define WM_WINDOWPOSCHANGING 0x0046 #define LANG_PUNJABI 0x46 #define WM_WINDOWPOSCHANGED 0x0047 #define LANG_GUJARATI 0x47 #define WM_POWER 0x0048 #define LANG_ORIYA 0x48 #define LANG_TAMIL 0x49 #define WM_COPYDATA 0x004A #define LANG_TELUGU 0x4a #define WM_CANCELJOURNAL 0x004B #define LANG_KANNADA 0x4b #define LANG_MALAYALAM 0x4c #define LANG_ASSAMESE 0x4d #define WM_NOTIFY 0x004E #define LANG_MARATHI 0x4e #define LANG_SANSKRIT 0x4f #define WM_INPUTLANGCHANGEREQUEST 0x0050 #define LANG_MONGOLIAN 0x50 #define WM_INPUTLANGCHANGE 0x0051 #define LANG_TIBETAN 0x51 #define WM_TCARD 0x0052 #define LANG_WELSH 0x52 #define WM_HELP 0x0053 #define LANG_KHMER 0x53 #define WM_USERCHANGED 0x0054 #define LANG_LAO 0x54 #define WM_NOTIFYFORMAT 0x0055 #define LANG_GALICIAN 0x56 #define LANG_KONKANI 0x57 #define LANG_MANIPURI 0x58 #define LANG_SINDHI 0x59 #define LANG_SYRIAC 0x5a #define VK_LWIN 0x5B #define LANG_SINHALESE 0x5b #define VK_RWIN 0x5C #define VK_APPS 0x5D #define LANG_INUKTITUT 0x5d #define LANG_AMHARIC 0x5e #define VK_SLEEP 0x5F #define LANG_TAMAZIGHT 0x5f #define VK_NUMPAD0 0x60 #define LANG_KASHMIRI 0x60 #define VK_NUMPAD1 0x61 #define LANG_NEPALI 0x61 #define VK_NUMPAD2 0x62 #define LANG_FRISIAN 0x62 #define VK_NUMPAD3 0x63 #define LANG_PASHTO 0x63 #define VK_NUMPAD4 0x64 #define LANG_FILIPINO 0x64 #define VS_USER_DEFINED 100 #define VK_NUMPAD5 0x65 #define LANG_DIVEHI 0x65 #define VK_NUMPAD6 0x66 #define VK_NUMPAD7 0x67 #define VK_NUMPAD8 0x68 #define LANG_HAUSA 0x68 #define VK_NUMPAD9 0x69 #define VK_MULTIPLY 0x6A #define LANG_YORUBA 0x6a #define VK_ADD 0x6B #define LANG_QUECHUA 0x6b #define VK_SEPARATOR 0x6C #define LANG_SOTHO 0x6c #define VK_SUBTRACT 0x6D #define LANG_BASHKIR 0x6d #define VK_DECIMAL 0x6E #define LANG_LUXEMBOURGISH 0x6e #define VK_DIVIDE 0x6F #define LANG_GREENLANDIC 0x6f #define VK_F1 0x70 #define LANG_IGBO 0x70 #define VK_F2 0x71 #define VK_F3 0x72 #define VK_F4 0x73 #define LANG_TIGRIGNA 0x73 #define VK_F5 0x74 #define VK_F6 0x75 #define VK_F7 0x76 #define VK_F8 0x77 #define VK_F9 0x78 #define WHEEL_DELTA 120 #define LANG_YI 0x78 #define VK_F10 0x79 #define VK_F11 0x7A #define LANG_MAPUDUNGUN 0x7a #define VK_F12 0x7B #define WM_CONTEXTMENU 0x007B #define VK_F13 0x7C #define WM_STYLECHANGING 0x007C #define LANG_MOHAWK 0x7c #define VK_F14 0x7D #define WM_STYLECHANGED 0x007D #define VK_F15 0x7E #define WM_DISPLAYCHANGE 0x007E #define LANG_BRETON 0x7e #define VK_F16 0x7F #define WM_GETICON 0x007F #define LANG_INVARIANT 0x7f #define VK_F17 0x80 #define WM_SETICON 0x0080 #define WVR_ALIGNRIGHT 0x0080 #define CS_PARENTDC 0x0080 #define CF_OWNERDISPLAY 0x0080 #define HDS_FULLDRAG 0x0080 #define BTNS_WHOLEDROPDOWN 0x0080 #define TTS_CLOSE 0x80 #define TBS_NOTHUMB 0x0080 #define UDS_NOTHOUSANDS 0x0080 #define LVS_NOLABELWRAP 0x0080 #define TVS_NOTOOLTIPS 0x0080 #define TCS_VERTICAL 0x0080 #define MCS_SHORTDAYSOFWEEK 0x0080 #define LANG_UIGHUR 0x80 #define VK_F18 0x81 #define WM_NCCREATE 0x0081 #define CF_DSPTEXT 0x0081 #define LANG_MAORI 0x81 #define VK_F19 0x82 #define WM_NCDESTROY 0x0082 #define CF_DSPBITMAP 0x0082 #define LANG_OCCITAN 0x82 #define VK_F20 0x83 #define WM_NCCALCSIZE 0x0083 #define CF_DSPMETAFILEPICT 0x0083 #define LANG_CORSICAN 0x83 #define VK_F21 0x84 #define WM_NCHITTEST 0x0084 #define LANG_ALSATIAN 0x84 #define VK_F22 0x85 #define WM_NCPAINT 0x0085 #define LANG_YAKUT 0x85 #define VK_F23 0x86 #define WM_NCACTIVATE 0x0086 #define LANG_KICHE 0x86 #define VK_F24 0x87 #define WM_GETDLGCODE 0x0087 #define LANG_KINYARWANDA 0x87 #define WM_SYNCPAINT 0x0088 #define LANG_WOLOF 0x88 #define LANG_DARI 0x8c #define CF_DSPENHMETAFILE 0x008E #define VK_NUMLOCK 0x90 #define VK_SCROLL 0x91 #define VK_OEM_NEC_EQUAL 0x92 #define VK_OEM_FJ_JISHO 0x92 #define VK_OEM_FJ_MASSHOU 0x93 #define VK_OEM_FJ_TOUROKU 0x94 #define VK_OEM_FJ_LOYA 0x95 #define VK_OEM_FJ_ROYA 0x96 #define VK_LSHIFT 0xA0 #define WM_NCMOUSEMOVE 0x00A0 #define VK_RSHIFT 0xA1 #define WM_NCLBUTTONDOWN 0x00A1 #define VK_LCONTROL 0xA2 #define WM_NCLBUTTONUP 0x00A2 #define VK_RCONTROL 0xA3 #define WM_NCLBUTTONDBLCLK 0x00A3 #define VK_LMENU 0xA4 #define WM_NCRBUTTONDOWN 0x00A4 #define VK_RMENU 0xA5 #define WM_NCRBUTTONUP 0x00A5 #define VK_BROWSER_BACK 0xA6 #define WM_NCRBUTTONDBLCLK 0x00A6 #define VK_BROWSER_FORWARD 0xA7 #define WM_NCMBUTTONDOWN 0x00A7 #define VK_BROWSER_REFRESH 0xA8 #define WM_NCMBUTTONUP 0x00A8 #define VK_BROWSER_STOP 0xA9 #define WM_NCMBUTTONDBLCLK 0x00A9 #define VK_BROWSER_SEARCH 0xAA #define VK_BROWSER_FAVORITES 0xAB #define WM_NCXBUTTONDOWN 0x00AB #define VK_BROWSER_HOME 0xAC #define WM_NCXBUTTONUP 0x00AC #define VK_VOLUME_MUTE 0xAD #define WM_NCXBUTTONDBLCLK 0x00AD #define VK_VOLUME_DOWN 0xAE #define VK_VOLUME_UP 0xAF #define VK_MEDIA_NEXT_TRACK 0xB0 #define EM_GETSEL 0x00B0 #define VK_MEDIA_PREV_TRACK 0xB1 #define EM_SETSEL 0x00B1 #define VK_MEDIA_STOP 0xB2 #define EM_GETRECT 0x00B2 #define VK_MEDIA_PLAY_PAUSE 0xB3 #define EM_SETRECT 0x00B3 #define VK_LAUNCH_MAIL 0xB4 #define EM_SETRECTNP 0x00B4 #define VK_LAUNCH_MEDIA_SELECT 0xB5 #define EM_SCROLL 0x00B5 #define VK_LAUNCH_APP1 0xB6 #define EM_LINESCROLL 0x00B6 #define VK_LAUNCH_APP2 0xB7 #define EM_SCROLLCARET 0x00B7 #define EM_GETMODIFY 0x00B8 #define EM_SETMODIFY 0x00B9 #define VK_OEM_1 0xBA #define EM_GETLINECOUNT 0x00BA #define VK_OEM_PLUS 0xBB #define EM_LINEINDEX 0x00BB #define VK_OEM_COMMA 0xBC #define EM_SETHANDLE 0x00BC #define VK_OEM_MINUS 0xBD #define EM_GETHANDLE 0x00BD #define VK_OEM_PERIOD 0xBE #define EM_GETTHUMB 0x00BE #define VK_OEM_2 0xBF #define VK_OEM_3 0xC0 #define EM_LINELENGTH 0x00C1 #define EM_REPLACESEL 0x00C2 #define EM_GETLINE 0x00C4 #define EM_LIMITTEXT 0x00C5 #define EM_CANUNDO 0x00C6 #define EM_UNDO 0x00C7 #define EM_FMTLINES 0x00C8 #define EM_LINEFROMCHAR 0x00C9 #define EM_SETTABSTOPS 0x00CB #define EM_SETPASSWORDCHAR 0x00CC #define EM_EMPTYUNDOBUFFER 0x00CD #define EM_GETFIRSTVISIBLELINE 0x00CE #define EM_SETREADONLY 0x00CF #define EM_SETWORDBREAKPROC 0x00D0 #define EM_GETWORDBREAKPROC 0x00D1 #define EM_GETPASSWORDCHAR 0x00D2 #define EM_SETMARGINS 0x00D3 #define EM_GETMARGINS 0x00D4 #define EM_GETLIMITTEXT 0x00D5 #define EM_POSFROMCHAR 0x00D6 #define EM_CHARFROMPOS 0x00D7 #define EM_SETIMESTATUS 0x00D8 #define EM_GETIMESTATUS 0x00D9 #define VK_OEM_4 0xDB #define VK_OEM_5 0xDC #define VK_OEM_6 0xDD #define VK_OEM_7 0xDE #define VK_OEM_8 0xDF #define VK_OEM_AX 0xE1 #define VK_OEM_102 0xE2 #define VK_ICO_HELP 0xE3 #define VK_ICO_00 0xE4 #define VK_PROCESSKEY 0xE5 #define VK_ICO_CLEAR 0xE6 #define VK_PACKET 0xE7 #define VK_OEM_RESET 0xE9 #define VK_OEM_JUMP 0xEA #define VK_OEM_PA1 0xEB #define VK_OEM_PA2 0xEC #define VK_OEM_PA3 0xED #define VK_OEM_WSCTRL 0xEE #define VK_OEM_CUSEL 0xEF #define VK_OEM_ATTN 0xF0 #define BM_GETCHECK 0x00F0 #define VK_OEM_FINISH 0xF1 #define BM_SETCHECK 0x00F1 #define VK_OEM_COPY 0xF2 #define BM_GETSTATE 0x00F2 #define VK_OEM_AUTO 0xF3 #define BM_SETSTATE 0x00F3 #define VK_OEM_ENLW 0xF4 #define BM_SETSTYLE 0x00F4 #define VK_OEM_BACKTAB 0xF5 #define BM_CLICK 0x00F5 #define VK_ATTN 0xF6 #define BM_GETIMAGE 0x00F6 #define VK_CRSEL 0xF7 #define BM_SETIMAGE 0x00F7 #define VK_EXSEL 0xF8 #define VK_EREOF 0xF9 #define VK_PLAY 0xFA #define VK_ZOOM 0xFB #define VK_NONAME 0xFC #define VK_PA1 0xFD #define VK_OEM_CLEAR 0xFE #define WM_KEYFIRST 0x0100 #define WM_KEYDOWN 0x0100 #define WVR_HREDRAW 0x0100 #define HDS_FILTERBAR 0x0100 #define TBSTYLE_TOOLTIPS 0x0100 #define RBS_TOOLTIPS 0x00000100 #define SBARS_SIZEGRIP 0x0100 #define TBS_TOOLTIPS 0x0100 #define UDS_HOTTRACK 0x0100 #define LVS_AUTOARRANGE 0x0100 #define TVS_CHECKBOXES 0x0100 #define TCS_BUTTONS 0x0100 #define MCS_NOSELCHANGEONNAV 0x0100 #define WM_KEYUP 0x0101 #define WM_CHAR 0x0102 #define WM_DEADCHAR 0x0103 #define WM_SYSKEYDOWN 0x0104 #define WM_SYSKEYUP 0x0105 #define WM_SYSCHAR 0x0106 #define WM_SYSDEADCHAR 0x0107 #define WM_KEYLAST 0x0108 #define WM_IME_STARTCOMPOSITION 0x010D #define WM_IME_ENDCOMPOSITION 0x010E #define WM_IME_COMPOSITION 0x010F #define WM_IME_KEYLAST 0x010F #define WM_INITDIALOG 0x0110 #define WM_COMMAND 0x0111 #define WM_SYSCOMMAND 0x0112 #define WM_TIMER 0x0113 #define WM_HSCROLL 0x0114 #define WM_VSCROLL 0x0115 #define WM_INITMENU 0x0116 #define WM_INITMENUPOPUP 0x0117 #define WM_MENUSELECT 0x011F #define WM_MENUCHAR 0x0120 #define WM_ENTERIDLE 0x0121 #define WM_MENURBUTTONUP 0x0122 #define WM_MENUDRAG 0x0123 #define WM_MENUGETOBJECT 0x0124 #define WM_UNINITMENUPOPUP 0x0125 #define WM_MENUCOMMAND 0x0126 #define WM_CHANGEUISTATE 0x0127 #define WM_UPDATEUISTATE 0x0128 #define WM_QUERYUISTATE 0x0129 #define WM_CTLCOLORMSGBOX 0x0132 #define WM_CTLCOLOREDIT 0x0133 #define WM_CTLCOLORLISTBOX 0x0134 #define WM_CTLCOLORBTN 0x0135 #define WM_CTLCOLORDLG 0x0136 #define WM_CTLCOLORSCROLLBAR 0x0137 #define WM_CTLCOLORSTATIC 0x0138 #define MN_GETHMENU 0x01E1 #define WM_MOUSEFIRST 0x0200 #define WM_MOUSEMOVE 0x0200 #define WVR_VREDRAW 0x0200 #define CS_NOCLOSE 0x0200 #define CF_PRIVATEFIRST 0x0200 #define TBSTYLE_WRAPABLE 0x0200 #define RBS_VARHEIGHT 0x00000200 #define TBS_REVERSED 0x0200 #define LVS_EDITLABELS 0x0200 #define TVS_TRACKSELECT 0x0200 #define TCS_MULTILINE 0x0200 #define WM_LBUTTONDOWN 0x0201 #define WM_LBUTTONUP 0x0202 #define WM_LBUTTONDBLCLK 0x0203 #define WM_RBUTTONDOWN 0x0204 #define WM_RBUTTONUP 0x0205 #define WM_RBUTTONDBLCLK 0x0206 #define WM_MBUTTONDOWN 0x0207 #define WM_MBUTTONUP 0x0208 #define WM_MBUTTONDBLCLK 0x0209 #define WM_MOUSEWHEEL 0x020A #define WM_XBUTTONDOWN 0x020B #define WM_XBUTTONUP 0x020C #define WM_XBUTTONDBLCLK 0x020D #define WM_MOUSELAST 0x020D #define WM_PARENTNOTIFY 0x0210 #define WM_ENTERMENULOOP 0x0211 #define WM_EXITMENULOOP 0x0212 #define WM_NEXTMENU 0x0213 #define WM_SIZING 0x0214 #define WM_CAPTURECHANGED 0x0215 #define WM_MOVING 0x0216 #define WM_POWERBROADCAST 0x0218 #define WM_DEVICECHANGE 0x0219 #define WM_MDICREATE 0x0220 #define WM_MDIDESTROY 0x0221 #define WM_MDIACTIVATE 0x0222 #define WM_MDIRESTORE 0x0223 #define WM_MDINEXT 0x0224 #define WM_MDIMAXIMIZE 0x0225 #define WM_MDITILE 0x0226 #define WM_MDICASCADE 0x0227 #define WM_MDIICONARRANGE 0x0228 #define WM_MDIGETACTIVE 0x0229 #define WM_MDISETMENU 0x0230 #define WM_ENTERSIZEMOVE 0x0231 #define WM_EXITSIZEMOVE 0x0232 #define WM_DROPFILES 0x0233 #define WM_MDIREFRESHMENU 0x0234 #define WM_IME_SETCONTEXT 0x0281 #define WM_IME_NOTIFY 0x0282 #define WM_IME_CONTROL 0x0283 #define WM_IME_COMPOSITIONFULL 0x0284 #define WM_IME_SELECT 0x0285 #define WM_IME_CHAR 0x0286 #define WM_IME_REQUEST 0x0288 #define WM_IME_KEYDOWN 0x0290 #define WM_IME_KEYUP 0x0291 #define WM_NCMOUSEHOVER 0x02A0 #define WM_MOUSEHOVER 0x02A1 #define WM_NCMOUSELEAVE 0x02A2 #define WM_MOUSELEAVE 0x02A3 #define CF_PRIVATELAST 0x02FF #define WM_CUT 0x0300 #define CF_GDIOBJFIRST 0x0300 #define WM_COPY 0x0301 #define WM_PASTE 0x0302 #define WM_CLEAR 0x0303 #define WM_UNDO 0x0304 #define WM_RENDERFORMAT 0x0305 #define WM_RENDERALLFORMATS 0x0306 #define WM_DESTROYCLIPBOARD 0x0307 #define WM_DRAWCLIPBOARD 0x0308 #define WM_PAINTCLIPBOARD 0x0309 #define WM_VSCROLLCLIPBOARD 0x030A #define WM_SIZECLIPBOARD 0x030B #define WM_ASKCBFORMATNAME 0x030C #define WM_CHANGECBCHAIN 0x030D #define WM_HSCROLLCLIPBOARD 0x030E #define WM_QUERYNEWPALETTE 0x030F #define WM_PALETTEISCHANGING 0x0310 #define WM_PALETTECHANGED 0x0311 #define WM_HOTKEY 0x0312 #define WM_PRINT 0x0317 #define WM_PRINTCLIENT 0x0318 #define WM_APPCOMMAND 0x0319 #define WM_HANDHELDFIRST 0x0358 #define WM_HANDHELDLAST 0x035F #define WM_AFXFIRST 0x0360 #define WM_AFXLAST 0x037F #define WM_PENWINFIRST 0x0380 #define WM_PENWINLAST 0x038F #define WM_DDE_FIRST 0x03E0 #define CF_GDIOBJLAST 0x03FF #define WM_USER 0x0400 #define WVR_VALIDRECTS 0x0400 #define TBSTYLE_ALTDRAG 0x0400 #define RBS_BANDBORDERS 0x00000400 #define TBS_DOWNISLEFT 0x0400 #define LVS_OWNERDRAWFIXED 0x0400 #define TVS_SINGLEEXPAND 0x0400 #define TCS_FIXEDWIDTH 0x0400 #define ctlFirst 0x0400 #define psh1 0x0400 #define psh2 0x0401 #define psh3 0x0402 #define psh4 0x0403 #define psh5 0x0404 #define psh6 0x0405 #define psh7 0x0406 #define psh8 0x0407 #define psh9 0x0408 #define psh10 0x0409 #define psh11 0x040a #define psh12 0x040b #define psh13 0x040c #define psh14 0x040d #define psh15 0x040e #define psh16 0x040f #define _WIN32_WINDOWS 0x0410 #define chx1 0x0410 #define chx2 0x0411 #define chx3 0x0412 #define chx4 0x0413 #define chx5 0x0414 #define chx6 0x0415 #define chx7 0x0416 #define chx8 0x0417 #define chx9 0x0418 #define chx10 0x0419 #define chx11 0x041a #define chx12 0x041b #define chx13 0x041c #define chx14 0x041d #define chx15 0x041e #define chx16 0x041f #define rad1 0x0420 #define rad2 0x0421 #define rad3 0x0422 #define rad4 0x0423 #define rad5 0x0424 #define rad6 0x0425 #define rad7 0x0426 #define rad8 0x0427 #define rad9 0x0428 #define rad10 0x0429 #define rad11 0x042a #define rad12 0x042b #define rad13 0x042c #define rad14 0x042d #define rad15 0x042e #define rad16 0x042f #define grp1 0x0430 #define grp2 0x0431 #define grp3 0x0432 #define grp4 0x0433 #define frm1 0x0434 #define frm2 0x0435 #define frm3 0x0436 #define frm4 0x0437 #define rct1 0x0438 #define rct2 0x0439 #define rct3 0x043a #define rct4 0x043b #define ico1 0x043c #define ico2 0x043d #define ico3 0x043e #define ico4 0x043f #define stc1 0x0440 #define stc2 0x0441 #define stc3 0x0442 #define stc4 0x0443 #define stc5 0x0444 #define stc6 0x0445 #define stc7 0x0446 #define stc8 0x0447 #define stc9 0x0448 #define stc10 0x0449 #define stc11 0x044a #define stc12 0x044b #define stc13 0x044c #define stc14 0x044d #define stc15 0x044e #define stc16 0x044f #define stc17 0x0450 #define stc18 0x0451 #define stc19 0x0452 #define stc20 0x0453 #define stc21 0x0454 #define stc22 0x0455 #define stc23 0x0456 #define stc24 0x0457 #define stc25 0x0458 #define stc26 0x0459 #define stc27 0x045a #define stc28 0x045b #define stc29 0x045c #define stc30 0x045d #define stc31 0x045e #define stc32 0x045f #define lst1 0x0460 #define lst2 0x0461 #define lst3 0x0462 #define lst4 0x0463 #define lst5 0x0464 #define lst6 0x0465 #define lst7 0x0466 #define lst8 0x0467 #define lst9 0x0468 #define lst10 0x0469 #define lst11 0x046a #define lst12 0x046b #define lst13 0x046c #define lst14 0x046d #define lst15 0x046e #define lst16 0x046f #define cmb1 0x0470 #define cmb2 0x0471 #define cmb3 0x0472 #define cmb4 0x0473 #define cmb5 0x0474 #define cmb6 0x0475 #define cmb7 0x0476 #define cmb8 0x0477 #define cmb9 0x0478 #define cmb10 0x0479 #define cmb11 0x047a #define cmb12 0x047b #define cmb13 0x047c #define cmb14 0x047d #define cmb15 0x047e #define cmb16 0x047f #define edt1 0x0480 #define edt2 0x0481 #define edt3 0x0482 #define edt4 0x0483 #define edt5 0x0484 #define edt6 0x0485 #define edt7 0x0486 #define edt8 0x0487 #define edt9 0x0488 #define edt10 0x0489 #define edt11 0x048a #define edt12 0x048b #define edt13 0x048c #define edt14 0x048d #define edt15 0x048e #define edt16 0x048f #define scr1 0x0490 #define scr2 0x0491 #define scr3 0x0492 #define scr4 0x0493 #define scr5 0x0494 #define scr6 0x0495 #define scr7 0x0496 #define scr8 0x0497 #define ctl1 0x04A0 #define ctlLast 0x04ff #define WINVER 0x0500 #define _WIN32_WINNT 0x0500 #define _WIN32_IE 0x0501 #define FILEOPENORD 1536 #define MULTIFILEOPENORD 1537 #define PRINTDLGORD 1538 #define PRNSETUPDLGORD 1539 #define FINDDLGORD 1540 #define REPLACEDLGORD 1541 #define FONTDLGORD 1542 #define FORMATDLGORD31 1543 #define FORMATDLGORD30 1544 #define RUNDLGORD 1545 #define PAGESETUPDLGORD 1546 #define NEWFILEOPENORD 1547 #define PRINTDLGEXORD 1549 #define PAGESETUPDLGORDMOTIF 1550 #define COLORMGMTDLGORD 1551 #define NEWFILEOPENV2ORD 1552 #define NEWFILEOPENV3ORD 1553 #define CS_SAVEBITS 0x0800 #define TBSTYLE_FLAT 0x0800 #define RBS_FIXEDORDER 0x00000800 #define SBARS_TOOLTIPS 0x0800 #define SBT_TOOLTIPS 0x0800 #define LVS_ALIGNLEFT 0x0800 #define TVS_INFOTIP 0x0800 #define TCS_RAGGEDRIGHT 0x0800 #define LVS_ALIGNMASK 0x0c00 #define CS_BYTEALIGNCLIENT 0x1000 #define TBSTYLE_LIST 0x1000 #define RBS_REGISTERDROP 0x00001000 #define TBS_TRANSPARENTBKGND 0x1000 #define LVS_OWNERDATA 0x1000 #define TVS_FULLROWSELECT 0x1000 #define TCS_FOCUSONBUTTONDOWN 0x1000 #define CS_BYTEALIGNWINDOW 0x2000 #define TBSTYLE_CUSTOMERASE 0x2000 #define RBS_AUTOSIZE 0x00002000 #define LVS_NOSCROLL 0x2000 #define TVS_NOSCROLL 0x2000 #define TCS_OWNERDRAWFIXED 0x2000 #define CS_GLOBALCLASS 0x4000 #define TBSTYLE_REGISTERDROP 0x4000 #define RBS_VERTICALGRIPPER 0x00004000 #define LVS_NOCOLUMNHEADER 0x4000 #define TVS_NONEVENHEIGHT 0x4000 #define TCS_TOOLTIPS 0x4000 #define IDH_NO_HELP 28440 #define IDH_MISSING_CONTEXT 28441 #define IDH_GENERIC_HELP_BUTTON 28442 #define IDH_OK 28443 #define IDH_CANCEL 28444 #define IDH_HELP 28445 #define LANG_BOSNIAN_NEUTRAL 0x781a #define LANG_CHINESE_TRADITIONAL 0x7c04 #define LANG_SERBIAN_NEUTRAL 0x7c1a #define OCR_NORMAL 32512 #define OIC_SAMPLE 32512 #define IDI_APPLICATION 32512 #define OCR_IBEAM 32513 #define OIC_HAND 32513 #define IDI_HAND 32513 #define OCR_WAIT 32514 #define OIC_QUES 32514 #define IDI_QUESTION 32514 #define OCR_CROSS 32515 #define OIC_BANG 32515 #define IDI_EXCLAMATION 32515 #define OCR_UP 32516 #define OIC_NOTE 32516 #define IDI_ASTERISK 32516 #define OIC_WINLOGO 32517 #define IDI_WINLOGO 32517 #define OCR_SIZE 32640 #define OCR_ICON 32641 #define OCR_SIZENWSE 32642 #define OCR_SIZENESW 32643 #define OCR_SIZEWE 32644 #define OCR_SIZENS 32645 #define OCR_SIZEALL 32646 #define OCR_ICOCUR 32647 #define OCR_NO 32648 #define OCR_HAND 32649 #define OCR_APPSTARTING 32650 #define OBM_LFARROWI 32734 #define OBM_RGARROWI 32735 #define OBM_DNARROWI 32736 #define OBM_UPARROWI 32737 #define OBM_COMBO 32738 #define OBM_MNARROW 32739 #define OBM_LFARROWD 32740 #define OBM_RGARROWD 32741 #define OBM_DNARROWD 32742 #define OBM_UPARROWD 32743 #define OBM_RESTORED 32744 #define OBM_ZOOMD 32745 #define OBM_REDUCED 32746 #define OBM_RESTORE 32747 #define OBM_ZOOM 32748 #define OBM_REDUCE 32749 #define OBM_LFARROW 32750 #define OBM_RGARROW 32751 #define OBM_DNARROW 32752 #define OBM_UPARROW 32753 #define OBM_CLOSE 32754 #define OBM_OLD_RESTORE 32755 #define OBM_OLD_ZOOM 32756 #define OBM_OLD_REDUCE 32757 #define OBM_BTNCORNERS 32758 #define OBM_CHECKBOXES 32759 #define OBM_CHECK 32760 #define OBM_BTSIZE 32761 #define OBM_OLD_LFARROW 32762 #define OBM_OLD_RGARROW 32763 #define OBM_OLD_DNARROW 32764 #define OBM_OLD_UPARROW 32765 #define OBM_SIZE 32766 #define OBM_OLD_CLOSE 32767 #define WM_APP 0x8000 #define HELP_TCARD 0x8000 #define TBSTYLE_TRANSPARENT 0x8000 #define RBS_DBLCLKTOGGLE 0x00008000 #define LVS_NOSORTHEADER 0x8000 #define TVS_NOHSCROLL 0x8000 #define TCS_FOCUSNEVER 0x8000 #define SC_SIZE 0xF000 #define SC_SEPARATOR 0xF00F #define SC_MOVE 0xF010 #define SC_MINIMIZE 0xF020 #define SC_MAXIMIZE 0xF030 #define SC_NEXTWINDOW 0xF040 #define SC_PREVWINDOW 0xF050 #define SC_CLOSE 0xF060 #define SC_VSCROLL 0xF070 #define SC_HSCROLL 0xF080 #define SC_MOUSEMENU 0xF090 #define SC_KEYMENU 0xF100 #define SC_ARRANGE 0xF110 #define SC_RESTORE 0xF120 #define SC_TASKLIST 0xF130 #define SC_SCREENSAVE 0xF140 #define SC_HOTKEY 0xF150 #define SC_DEFAULT 0xF160 #define SC_MONITORPOWER 0xF170 #define SC_CONTEXTHELP 0xF180 #define LVS_TYPESTYLEMASK 0xfc00 // #define HTERROR -2 // #define PWR_FAIL -1 // #define HTTRANSPARENT -1 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NO_MFC 1 #define _APS_NEXT_RESOURCE_VALUE 101 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1000 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by Resource.rc // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 101 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1001 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif ================================================ FILE: run.cpp ================================================ // dll injection #define _CRT_SECURE_NO_DEPRECATE 1 #define WINVER 0x500 #define _WIN32_WINNT 0x500 #define _WIN32_IE 0x601 #define WIN32_LEAN_AND_MEAN 1 #define UNICODE 1 #define _UNICODE 1 #include #include #include #include #include #include #include "array.h" #include // _vsnwprintf用 #include #include #define _CRTDBG_MAP_ALLOC #include #include #include #define for if(0);else for #ifndef _countof #define _countof(array) (sizeof(array) / sizeof((array)[0])) #endif #pragma comment(linker, "/subsystem:windows,5.0") #pragma comment(lib, "Kernel32.lib") #pragma comment(lib, "User32.lib") #pragma comment(lib, "Shell32.lib") #pragma comment(lib, "ShLwApi.lib") #pragma comment(lib, "Ole32.lib") #define IDS_USAGE 101 #define IDS_DLL 102 #define IDC_EXEC 103 static void showmsg(LPCSTR msg) { MessageBoxA(NULL, msg, "MacType ERROR", MB_OK | MB_ICONSTOP); } static void errmsg(UINT id, DWORD code) { char buffer[512]; char format[128]; LoadStringA(GetModuleHandleA(NULL), id, format, 128); wnsprintfA(buffer, 512, format, code); showmsg(buffer); } inline HRESULT HresultFromLastError() { DWORD dwErr = GetLastError(); return HRESULT_FROM_WIN32(dwErr); } #include "detours.h" #ifdef _M_IX86 #pragma comment (lib, "detours.lib") const auto MacTypeDll = L"MacType.dll"; const auto MacTypeDllA = "MacType.dll"; #else #pragma comment (lib, "detours64.lib") const auto MacTypeDll = L"MacType64.dll"; const auto MacTypeDllA = "MacType64.dll"; #endif HINSTANCE hinstDLL; #include #define GetDLLInstance() (hinstDLL) #define _GDIPP_EXE #define _GDIPP_RUN_CPP //#include "supinfo.h" //#define OLD_PSDK #ifdef OLD_PSDK extern "C" { HRESULT WINAPI _SHILCreateFromPath(LPCWSTR pszPath, LPITEMIDLIST* ppidl, DWORD* rgflnOut) { if (!pszPath || !ppidl) { return E_INVALIDARG; } LPSHELLFOLDER psf; HRESULT hr = ::SHGetDesktopFolder(&psf); if (hr != NOERROR) { return hr; } ULONG chEaten; LPOLESTR lpszDisplayName = ::StrDupW(pszPath); hr = psf->ParseDisplayName(NULL, NULL, lpszDisplayName, &chEaten, ppidl, rgflnOut); ::LocalFree(lpszDisplayName); psf->Release(); return hr; } void WINAPI _SHFree(void* pv) { if (!pv) { return; } LPMALLOC pMalloc = NULL; if (::SHGetMalloc(&pMalloc) == NOERROR) { pMalloc->Free(pv); pMalloc->Release(); } } } #else #define _SHILCreateFromPath SHILCreateFromPath #define _SHFree SHFree #endif bool isX64PE(const TCHAR* file_path) { HANDLE hFile = CreateFile(file_path, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { showmsg("Error opening file"); return false; } IMAGE_DOS_HEADER dosHeader; DWORD bytesRead; if (!ReadFile(hFile, &dosHeader, sizeof(IMAGE_DOS_HEADER), &bytesRead, NULL)) { showmsg("Error reading file"); CloseHandle(hFile); return false; } // Check if it's a PE file if (dosHeader.e_magic != IMAGE_DOS_SIGNATURE) { showmsg("Not a PE file"); CloseHandle(hFile); return false; } IMAGE_NT_HEADERS ntHeaders; // Seek to the PE header offset SetFilePointer(hFile, dosHeader.e_lfanew, NULL, FILE_BEGIN); if (!ReadFile(hFile, &ntHeaders, sizeof(IMAGE_NT_HEADERS), &bytesRead, NULL)) { showmsg("Error reading PE header"); CloseHandle(hFile); return false; } if (ntHeaders.FileHeader.Machine == IMAGE_FILE_MACHINE_I386) { CloseHandle(hFile); return false; } else if (ntHeaders.FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64) { CloseHandle(hFile); return true; } else { CloseHandle(hFile); return false; } } // 1つ目の引数だけファイルとして扱い、実行する。 // // コマンドは こんな感じで連結されます。 // exe linkpath linkarg cmdarg2 cmdarg3 cmdarg4 ... // static HRESULT HookAndExecute(int show) { int argc = 0; LPWSTR* argv = CommandLineToArgvW(GetCommandLineW(), &argc); if (!argv) { return HresultFromLastError(); } if (argc <= 1) { char buffer[256]; LoadStringA(GetModuleHandleA(NULL), IDS_USAGE, buffer, 256); MessageBoxA(NULL, buffer , "MacType", MB_OK | MB_ICONINFORMATION); LocalFree(argv); return S_OK; } int i; size_t length = 1; for (i = 1; i < argc; i++) { length += wcslen(argv[i]) + 3; } LPWSTR cmdline = (WCHAR*)calloc(sizeof(WCHAR), length); if (!cmdline) { LocalFree(argv); return E_OUTOFMEMORY; } LPWSTR p = cmdline; *p = L'\0'; for (i = 1; i < argc; i++) { const bool dq = !!wcschr(argv[i], L' '); if (dq) { *p++ = '"'; length--; } StringCchCopyExW(p, length, argv[i], &p, &length, STRSAFE_NO_TRUNCATION); if (dq) { *p++ = '"'; length--; } *p++ = L' '; length--; } *CharPrevW(cmdline, p) = L'\0'; // now we got the full cmdline for external exetuble. let's check if we can hook into it #ifdef _M_IX86 if (isX64PE(argv[1])) { ShellExecute(NULL, NULL, L"macloader64.exe", cmdline, NULL, SW_SHOW); return S_OK; } #else if (!isX64PE(argv[1])) { ShellExecute(NULL, NULL, L"macloader.exe", cmdline, NULL, SW_SHOW); return S_OK; } #endif WCHAR file[MAX_PATH], dir[MAX_PATH]; GetCurrentDirectoryW(_countof(dir), dir); StringCchCopyW(file, _countof(file), argv[1]); if (PathIsRelativeW(file)) { PathCombineW(file, dir, file); } else { WCHAR gdippDir[MAX_PATH]; GetModuleFileNameW(NULL, gdippDir, _countof(gdippDir)); PathRemoveFileSpec(gdippDir); // カレントディレクトリがgdi++.exeの置かれているディレクトリと同じだったら、 // 起動しようとしているEXEのフルパスから抜き出したディレクトリ名をカレント // ディレクトリとして起動する。(カレントディレクトリがEXEと同じ場所である // 前提で作られているアプリ対策) if (wcscmp(dir, gdippDir) == 0) { StringCchCopyW(dir, _countof(dir), argv[1]); PathRemoveFileSpec(dir); } } #ifdef _DEBUG if ((GetAsyncKeyState(VK_CONTROL) & 0x8000) && MessageBoxW(NULL, cmdline, NULL, MB_YESNO) != IDYES) { free(cmdline); return NOERROR; } #endif PROCESS_INFORMATION processInfo; STARTUPINFO startupInfo = { 0 }; startupInfo.cb = sizeof(startupInfo); // get current directory and append mactype dll char path[MAX_PATH] = { 0 }; if (GetModuleFileNameA(NULL, path, _countof(path))) { PathRemoveFileSpecA(path); strcat(path, "\\"); } strcat(path, MacTypeDllA); auto ret = DetourCreateProcessWithDllEx(NULL, cmdline, NULL, NULL, false, 0, NULL, dir, &startupInfo, &processInfo, path, NULL); free(cmdline); LocalFree(argv); argv = NULL; return ret ? S_OK : E_ACCESSDENIED; } int WINAPI wWinMain(HINSTANCE ins, HINSTANCE prev, LPWSTR cmd, int show) { _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF); OleInitialize(NULL); WCHAR path[MAX_PATH]; if (GetModuleFileNameW(NULL, path, _countof(path))) { PathRemoveFileSpec(path); wcscat(path, L"\\"); wcscat(path, MacTypeDll); //DONT_RESOLVE_DLL_REFERENCESを指定すると依存関係の解決や //DllMainの呼び出しが行われない hinstDLL = LoadLibraryExW(path, NULL, DONT_RESOLVE_DLL_REFERENCES); } if (!hinstDLL) { errmsg(IDS_DLL, HresultFromLastError()); } else { PathRemoveFileSpecW(path); SetCurrentDirectoryW(path); HRESULT hr = HookAndExecute(show); if (hr != S_OK) { errmsg(IDC_EXEC, hr); } } OleUninitialize(); return 0; } //EOF ================================================ FILE: settings.cpp ================================================ #include "settings.h" #include "strtoken.h" #include //pow #include "supinfo.h" #include "fteng.h" #include #include #ifdef INFINALITY #include #endif CControlCenter* g_ControlCenter = NULL; inline BOOL IsFolder(LPCTSTR pszPath) { return pszPath && *pszPath && *(pszPath + wcslen(pszPath) - 1) == '\\'; } int _StrToInt(LPCTSTR pStr, int nDefault) { #define isspace(ch) (ch == _T('\t') || ch == _T(' ')) #define isdigit(ch) ((_TUCHAR)(ch - _T('0')) <= 9) int ret; bool neg = false; LPCTSTR pStart; for (; isspace(*pStr); pStr++); switch (*pStr) { case _T('-'): neg = true; case _T('+'): pStr++; break; } pStart = pStr; ret = 0; for (; isdigit(*pStr); pStr++) { ret = 10 * ret + (*pStr - _T('0')); } if (pStr == pStart) { return nDefault; } return neg ? -ret : ret; #undef isspace #undef isdigit } wstring LowerCase(wstring str) { transform(str.begin(), str.end(), str.begin(), ::tolower); return str; } // split a comma separated string into an int vector vector SplitString(LPCTSTR str) { CStringTokenizer token; vector intList; int argc = 0; argc = token.Parse(str); for (int i = 0; i < 6; i++) { LPCTSTR arg = token.GetArgument(i); if (!arg) break; intList.push_back(_StrToInt(arg, 0)); } return intList; } const wstring GetAppDir() { static wstring AppDir; if (AppDir.length()) { return AppDir; } WCHAR name[MAX_PATH] = { 0 }; int nSize = GetModuleFileName(NULL, name, MAX_PATH + 1); PathRemoveFileSpec(name); AppDir = wstring(name) + L"\\"; // path should always end with a "\" AppDir = LowerCase(AppDir); return AppDir; } CGdippSettings* CGdippSettings::s_pInstance; CParseIni CGdippSettings::m_Config; CHashedStringList FontNameCache; static const TCHAR c_szGeneral[] = _T("General"); static const TCHAR c_szFreeType[] = _T("FreeType"); static const TCHAR c_szDirectWrite[] = _T("DirectWrite"); #define HINTING_MIN 0 #define HINTING_MAX 2 #define AAMODE_MIN -1 #define AAMODE_MAX 6 #define GAMMAVALUE_MIN 0.0625f #define GAMMAVALUE_MAX 20.0f #define CONTRAST_MIN 0.0625f #define CONTRAST_MAX 10.0f #define RENDERWEIGHT_MIN 0.0625f #define RENDERWEIGHT_MAX 10.0f #define NWEIGHT_MIN -64 #define NWEIGHT_MAX +64 #define BWEIGHT_MIN -32 #define BWEIGHT_MAX +32 #define SLANT_MIN -32 #define SLANT_MAX +32 CGdippSettings* CGdippSettings::CreateInstance() { CCriticalSectionLock __lock(CCriticalSectionLock::CS_SETTING); CGdippSettings* pSettings = new CGdippSettings; CGdippSettings* pOldSettings = reinterpret_cast(InterlockedExchangePointer(reinterpret_cast(&s_pInstance), pSettings)); _ASSERTE(pOldSettings == NULL); int nSize = GetModuleFileName(NULL, pSettings->m_szexeName, MAX_PATH); for (int i = nSize; i > 0; --i) { if (pSettings->m_szexeName[i] == _T('\\')) { StringCchCopy(pSettings->m_szexeName, nSize - i, pSettings->m_szexeName + i + 1); break; } } return pSettings; } void CGdippSettings::DestroyInstance() { CCriticalSectionLock __lock(CCriticalSectionLock::CS_SETTING); CGdippSettings* pSettings = reinterpret_cast(InterlockedExchangePointer(reinterpret_cast(&s_pInstance), NULL)); if (pSettings) { delete pSettings; } } CGdippSettings* CGdippSettings::GetInstance() { CCriticalSectionLock __lock(CCriticalSectionLock::CS_SETTING); CGdippSettings* pSettings = s_pInstance; _ASSERTE(pSettings != NULL); if (!pSettings->m_bDelayedInit) { pSettings->DelayedInit(); } return pSettings; } const CGdippSettings* CGdippSettings::GetInstanceNoInit() { CCriticalSectionLock __lock(CCriticalSectionLock::CS_SETTING); CGdippSettings* pSettings = s_pInstance; _ASSERTE(pSettings != NULL); return pSettings; } void CGdippSettings::DelayedInit() { if (!g_pFTEngine) { return; } if (IsBadCodePtr((FARPROC)RegOpenKeyExW) || *(DWORD_PTR*)RegOpenKeyExW==0) return; /* In Windows 8, this call will fail in restricted environment if GetDC failed, we are in a restricted environment where features like font subsitutations doesn't work properly. Because these features requires DC to get the real font name and we don't have access to any DC, even CreateCompatibleDC(null) fails (it will succeed, but DeleteDC will fail) So it is better exit than doing initialization. */ m_bDelayedInit = true; HDC hdcScreen = GetDC(NULL); if (!hdcScreen) { return; } //ForceChangeFont //if (m_szForceChangeFont[0]) { // EnumFontFamilies(hdcScreen, m_szForceChangeFont, EnumFontFamProc, reinterpret_cast(this)); //} //fetch screen dpi m_nScreenDpi = GetDeviceCaps(hdcScreen, LOGPIXELSX); ReleaseDC(NULL, hdcScreen); // //FontLink // if (FontLink()) { // m_fontlinkinfo.init(); // } const int nTextTuning = _GetFreeTypeProfileInt(_T("TextTuning"), 0, NULL), nTextTuningR = _GetFreeTypeProfileInt(_T("TextTuningR"), 0, NULL), nTextTuningG = _GetFreeTypeProfileInt(_T("TextTuningG"), 0, NULL), nTextTuningB = _GetFreeTypeProfileInt(_T("TextTuningB"), 0, NULL); InitInitTuneTable(); InitTuneTable(nTextTuning, m_nTuneTable); InitTuneTable(nTextTuningR, m_nTuneTableR); InitTuneTable(nTextTuningG, m_nTuneTableG); InitTuneTable(nTextTuningB, m_nTuneTableB); RefreshAlphaTable(); //FontSubstitutes CFontSubstitutesIniArray arrFontSubstitutes; wstring names = _T("FontSubstitutes@") + wstring(m_szexeName); if (_IsFreeTypeProfileSectionExists(names.c_str(), m_szFileName)) AddListFromSection(names.c_str(), m_szFileName, arrFontSubstitutes); else AddListFromSection(_T("FontSubstitutes"), m_szFileName, arrFontSubstitutes); m_FontSubstitutesInfo.init(m_nFontSubstitutes, arrFontSubstitutes); names = _T("Individual@") + wstring(m_szexeName); if (_IsFreeTypeProfileSectionExists(names.c_str(), NULL)) AddIndividualFromSection(names.c_str(), NULL, m_arrIndividual); else AddIndividualFromSection(_T("Individual"), NULL, m_arrIndividual); AddExcludeListFromSection(_T("Exclude"), NULL, m_arrExcludeFont); AddExcludeListFromSection(_T("Include"), NULL, m_arrIncludeFont); //I know it's include not exclude, but they share the same logic. //WritePrivateProfileString(NULL, NULL, NULL, m_szFileName); //m_bDelayedInit = true; //FontLink if (FontLink()) { m_fontlinkinfo.init(); } // check wheteher harmony LCD should be used over ClearType FT_LCDMode_Set(freetype_library, this->HarmonyLCD() ? 1 : 0); // Init LCD settings // this->m_bHarmonyLCDRendering = FT_Library_SetLcdFilter(NULL, FT_LCD_FILTER_NONE) == FT_Err_Unimplemented_Feature; // official method of detecting freetype mode. if (this->HarmonyLCD()) { FT_Library_SetLcdFilter(NULL, FT_LCD_FILTER_NONE); // Harmony LCD rendering if (m_bUseCustomPixelLayout) { FT_Vector sub[3] = { { m_arrPixelLayout[0], m_arrPixelLayout[1]}, {m_arrPixelLayout[2], m_arrPixelLayout[3]}, {m_arrPixelLayout[4], m_arrPixelLayout[5]}}; // custom layout FT_Library_SetLcdGeometry(freetype_library, sub); } else { switch (this->m_FontSettings.GetAntiAliasMode()) { case 0: case 1: { FT_Vector sub[3] = { { 0, 0 }, { 0, 0 }, { 0, 0 } }; // gray scale FT_Library_SetLcdGeometry(freetype_library, sub); break; } case 2: //RGB case 4: { FT_Vector sub[3] = { { -21, 0 }, { 0, 0 }, { 21, 0 } }; FT_Library_SetLcdGeometry(freetype_library, sub); break; } case 3: //BGR case 5: { FT_Vector sub[3] = { { 21, 0 }, { 0, 0 }, { -21, 0 } }; FT_Library_SetLcdGeometry(freetype_library, sub); break; } case 6: { //Pentile FT_Vector sub[3] = { {-11, 16}, {-11, -16}, {22, 0} }; FT_Library_SetLcdGeometry(freetype_library, sub); break; } } if (m_FontSettings.GetAntiAliasMode() > 2) m_FontSettings.SetAntiAliasMode(2); // all non-grayscale panel should use DrawLCD routine as its output. } } else { int nLcdFilter = LcdFilter(); if ((int)FT_LCD_FILTER_NONE <= nLcdFilter && nLcdFilter < (int)FT_LCD_FILTER_MAX) { switch (GetFontSettings().GetAntiAliasMode()) { case 1: case 4: case 5: nLcdFilter = FT_LCD_FILTER_LIGHT; // now we apply a light filter to lcd based on AA mode automatically, unless a custom lcd filter is defined. } FT_Library_SetLcdFilter(freetype_library, (FT_LcdFilter)nLcdFilter); if (UseCustomLcdFilter()) { unsigned char buff[5]; memcpy(buff, LcdFilterWeights(), sizeof(buff)); FT_Library_SetLcdFilterWeights(freetype_library, buff); } } } //強制フォント /* LPCTSTR lpszFace = GetForceFontName(); if (lpszFace) g_pFTEngine->AddFont(lpszFace, FW_NORMAL, false);*/ /* DWORD dwVersion = GetVersion(); if (m_bDirectWrite && (DWORD)(LOBYTE(LOWORD(dwVersion)))>5) //vista or later { if (GetModuleHandle(_T("d2d1.dll"))) //directwrite support HookD2D1(); }*/ } bool CGdippSettings::LoadSettings(HINSTANCE hModule) { CCriticalSectionLock __lock(CCriticalSectionLock::CS_SETTING); int nSize = ::GetModuleFileName(hModule, m_szFileName, MAX_PATH - sizeof(".ini") + 1); if (!nSize) { return false; } ChangeFileName(m_szFileName, nSize, L"MacType.ini"); return LoadAppSettings(m_szFileName); } int CGdippSettings::_GetFreeTypeProfileIntFromSection(LPCTSTR lpszSection, LPCTSTR lpszKey, int nDefault, LPCTSTR lpszFile) { wstring names = wstring((LPTSTR)lpszSection) + _T("@") + wstring((LPTSTR)m_szexeName); if (m_Config.IsPartExists(names.c_str()) && m_Config[names.c_str()].IsValueExists(lpszKey)) return m_Config[names.c_str()][lpszKey].ToInt(); else if (m_Config[lpszSection].IsValueExists(lpszKey)) return m_Config[lpszSection][lpszKey].ToInt(); else return nDefault; } bool CGdippSettings::_GetFreeTypeProfileBoolFromSection(LPCTSTR lpszSection, LPCTSTR lpszKey, bool nDefault, LPCTSTR lpszFile) { wstring names = wstring((LPTSTR)lpszSection) + _T("@") + wstring((LPTSTR)m_szexeName); if (m_Config.IsPartExists(names.c_str()) && m_Config[names.c_str()].IsValueExists(lpszKey)) return m_Config[names.c_str()][lpszKey].ToBool(); else if (m_Config[lpszSection].IsValueExists(lpszKey)) return m_Config[lpszSection][lpszKey].ToBool(); else return nDefault; } wstring CGdippSettings::_GetFreeTypeProfileStrFromSection(LPCTSTR lpszSection, LPCTSTR lpszKey, const TCHAR* nDefault, LPCTSTR lpszFile) { wstring names = wstring((LPTSTR)lpszSection) + _T("@") + wstring((LPTSTR)m_szexeName); if (m_Config.IsPartExists(names.c_str()) && m_Config[names.c_str()].IsValueExists(lpszKey)) return m_Config[names.c_str()][lpszKey].ToString(); else if (m_Config[lpszSection].IsValueExists(lpszKey)) return m_Config[lpszSection][lpszKey].ToString(); else return nDefault; } int CGdippSettings::_GetFreeTypeProfileInt(LPCTSTR lpszKey, int nDefault, LPCTSTR lpszFile) { int ret = _GetFreeTypeProfileIntFromSection(c_szFreeType, lpszKey, nDefault, lpszFile); if (ret == nDefault) return _GetFreeTypeProfileIntFromSection(c_szGeneral, lpszKey, nDefault, lpszFile); else return ret; } int CGdippSettings::_GetFreeTypeProfileBoundInt(LPCTSTR lpszKey, int nDefault, int nMin, int nMax, LPCTSTR lpszFile) { const int ret = _GetFreeTypeProfileInt(lpszKey, nDefault, lpszFile); return Bound(ret, nMin, nMax); } bool CGdippSettings::_IsFreeTypeProfileSectionExists(LPCTSTR lpszKey, LPCTSTR lpszFile) { return m_Config.IsPartExists(lpszKey); } float CGdippSettings::FastGetProfileFloat(LPCTSTR lpszSection, LPCTSTR lpszKey, float fDefault) { wstring names = wstring((LPTSTR)lpszSection) + _T("@") + wstring((LPTSTR)m_szexeName); if (m_Config.IsPartExists(names.c_str()) && m_Config[names.c_str()].IsValueExists(lpszKey)) return m_Config[names.c_str()][lpszKey].ToDouble(); else if (m_Config[lpszSection].IsValueExists(lpszKey)) return m_Config[lpszSection][lpszKey].ToDouble(); else return fDefault; } int CGdippSettings::FastGetProfileInt(LPCTSTR lpszSection, LPCTSTR lpszKey, int nDefault) { wstring names = wstring((LPTSTR)lpszSection) + _T("@") + wstring((LPTSTR)m_szexeName); if (m_Config.IsPartExists(names.c_str()) && m_Config[names.c_str()].IsValueExists(lpszKey)) return m_Config[names.c_str()][lpszKey].ToInt(); else if (m_Config[lpszSection].IsValueExists(lpszKey)) return m_Config[lpszSection][lpszKey].ToInt(); else return nDefault; } float CGdippSettings::_GetFreeTypeProfileFloat(LPCTSTR lpszKey, float fDefault, LPCTSTR lpszFile) { wstring names = wstring((LPTSTR)c_szFreeType) + _T("@") + wstring((LPTSTR)m_szexeName); if (m_Config.IsPartExists(names.c_str()) && m_Config[names.c_str()].IsValueExists(lpszKey)) return m_Config[names.c_str()][lpszKey].ToInt(); else { names = wstring((LPTSTR)c_szGeneral) + _T("@") + wstring((LPTSTR)m_szexeName); if (m_Config.IsPartExists(names.c_str()) && m_Config[names.c_str()].IsValueExists(lpszKey)) return m_Config[names.c_str()][lpszKey].ToDouble(); else if (m_Config[c_szFreeType].IsValueExists(lpszKey)) return m_Config[c_szFreeType][lpszKey].ToDouble(); if (m_Config[c_szGeneral].IsValueExists(lpszKey)) return m_Config[c_szGeneral][lpszKey].ToDouble(); else return fDefault; } } float CGdippSettings::_GetFreeTypeProfileBoundFloat(LPCTSTR lpszKey, float fDefault, float fMin, float fMax, LPCTSTR lpszFile) { const float ret = _GetFreeTypeProfileFloat(lpszKey, fDefault, lpszFile); return Bound(ret, fMin, fMax); } DWORD CGdippSettings::FastGetProfileString(LPCTSTR lpszSection, LPCTSTR lpszKey, LPCTSTR lpszDefault, LPTSTR lpszRet, DWORD cch) { wstring names = wstring((LPTSTR)lpszSection) + _T("@") + wstring((LPTSTR)m_szexeName); if (m_Config.IsPartExists(names.c_str()) && m_Config[names.c_str()].IsValueExists(lpszKey)) { LPCTSTR p = m_Config[names.c_str()][lpszKey]; StringCchCopy(lpszRet, cch, p); return wcslen(p); } else if (m_Config[lpszSection].IsValueExists(lpszKey)) { LPCTSTR p = m_Config[lpszSection][lpszKey]; StringCchCopy(lpszRet, cch, p); return wcslen(p); } else { if (lpszDefault) { StringCchCopy(lpszRet, cch, lpszDefault); return wcslen(lpszDefault); } else { lpszRet = NULL; return 0; } } } DWORD CGdippSettings::_GetFreeTypeProfileString(LPCTSTR lpszKey, LPCTSTR lpszDefault, LPTSTR lpszRet, DWORD cch, LPCTSTR lpszFile) { wstring names = wstring((LPTSTR)c_szFreeType) + _T("@") + wstring((LPTSTR)m_szexeName); if (m_Config.IsPartExists(names.c_str()) && m_Config[names.c_str()].IsValueExists(lpszKey)) { LPCTSTR p = m_Config[names.c_str()][lpszKey]; StringCchCopy(lpszRet, cch, p); return wcslen(p); } else { names = wstring((LPTSTR)c_szGeneral) + _T("@") + wstring((LPTSTR)m_szexeName); if (m_Config.IsPartExists(names.c_str()) && m_Config[names.c_str()].IsValueExists(lpszKey)) { LPCTSTR p = m_Config[names.c_str()][lpszKey]; StringCchCopy(lpszRet, cch, p); return wcslen(p); } else if (m_Config[c_szFreeType].IsValueExists(lpszKey)) { LPCTSTR p = m_Config[c_szFreeType][lpszKey]; StringCchCopy(lpszRet, cch, p); return wcslen(p); } else if (m_Config[c_szGeneral].IsValueExists(lpszKey)) { LPCTSTR p = m_Config[c_szGeneral][lpszKey]; StringCchCopy(lpszRet, cch, p); return wcslen(p); } else { StringCchCopy(lpszRet, cch, lpszDefault); return wcslen(lpszDefault); } } } void CGdippSettings::GetOSVersion() { OSVERSIONINFO info; memset(&info, 0, sizeof(OSVERSIONINFO)); info.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&info); m_dwOSMajorVer = info.dwMajorVersion; m_dwOSMinorVer = info.dwMinorVersion; } bool CGdippSettings::LoadAppSettings(LPCTSTR lpszFile) { // 各種設定読み込み // INIファイルの例: // [General] // HookChildProcesses=0 // HintingMode=0 // AntiAliasMode=0 // NormalWeight=0 // BoldWeight=0 // ItalicSlant=0 // EnableKerning=0 // MaxHeight=0 // ForceChangeFont=MS Pゴシック // TextTuning=0 // TextTuningR=0 // TextTuningG=0 // TextTuningB=0 // CacheMaxFaces=0 // CacheMaxSizes=0 // CacheMaxBytes=0 // AlternativeFile= // LoadOnDemand=0 // UseMapping=0 // LcdFilter=0 // Shadow=1,1,4 // [Individual] // MS Pゴシック=0,1,2,3,4,5 GetOSVersion(); WritePrivateProfileString(NULL, NULL, NULL, lpszFile); m_Config.Clear(); m_Config.LoadFromFile(lpszFile); TCHAR szAlternative[MAX_PATH], szMainFile[MAX_PATH]; if (FastGetProfileString(c_szGeneral, _T("AlternativeFile"), _T(""), szAlternative, MAX_PATH)) { if (PathIsRelative(szAlternative)) { TCHAR szDir[MAX_PATH]; StringCchCopy(szDir, MAX_PATH, lpszFile); PathRemoveFileSpec(szDir); PathCombine(szAlternative, szDir, szAlternative); } StringCchCopy(szMainFile, MAX_PATH, lpszFile); //把原始文件名保存下来 StringCchCopy(m_szFileName, MAX_PATH, szAlternative); lpszFile = m_szFileName; m_Config.Clear(); m_Config.LoadFromFile(lpszFile); } _GetAlternativeProfileName(m_szexeName, lpszFile); CFontSettings& fs = m_FontSettings; fs.Clear(); fs.SetHintingMode(_GetFreeTypeProfileBoundInt(_T("HintingMode"), 0, HINTING_MIN, HINTING_MAX, lpszFile)); fs.SetAntiAliasMode(_GetFreeTypeProfileBoundInt(_T("AntiAliasMode"), 0, AAMODE_MIN, AAMODE_MAX, lpszFile)); fs.SetNormalWeight(_GetFreeTypeProfileBoundInt(_T("NormalWeight"), 0, NWEIGHT_MIN, NWEIGHT_MAX, lpszFile)); fs.SetBoldWeight(_GetFreeTypeProfileBoundInt(_T("BoldWeight"), 0, BWEIGHT_MIN, BWEIGHT_MAX, lpszFile)); fs.SetItalicSlant(_GetFreeTypeProfileBoundInt(_T("ItalicSlant"), 0, SLANT_MIN, SLANT_MAX, lpszFile)); fs.SetKerning(!!_GetFreeTypeProfileInt(_T("EnableKerning"), 0, lpszFile)); m_nAntiAliasModeForDW = fs.GetAntiAliasMode(); // DirectWrite always use the user defined AA mode. { TCHAR szShadow[256]; CStringTokenizer token; m_bEnableShadow = false; if (!_GetFreeTypeProfileString(_T("Shadow"), _T(""), szShadow, countof(szShadow), lpszFile) || token.Parse(szShadow) < 3) { goto SKIP; } for (int i=0; i<3; i++) { m_nShadow[i] = _StrToInt(token.GetArgument(i), 0); /*if (m_nShadow[i] <= 0) { goto SKIP; }*/ } m_bEnableShadow = true; if (token.GetCount()>=4) //如果指定了浅色阴影 m_nShadowDarkColor = _httoi(token.GetArgument(3)); //读取阴影 else m_nShadowDarkColor = 0; //否则为黑色 if (token.GetCount()>=6) //如果指定了甥瀚阴影 { m_nShadowLightColor = _httoi(token.GetArgument(5)); //读取阴影 m_nShadow[3] = _StrToInt(token.GetArgument(4), m_nShadow[2]); //读取甥胰 } else { m_nShadowLightColor = m_nShadowDarkColor; //否则和浅色阴影相同 m_nShadow[3] = m_nShadow[2]; //甥胰也相同 } SKIP: ; } m_bHookChildProcesses = !!_GetFreeTypeProfileInt(_T("HookChildProcesses"), false, lpszFile); m_bUseMapping = !!_GetFreeTypeProfileInt(_T("UseMapping"), false, lpszFile); m_nBolderMode = _GetFreeTypeProfileInt(_T("BolderMode"), 0, lpszFile); m_nGammaMode = _GetFreeTypeProfileInt(_T("GammaMode"), -1, lpszFile); m_fGammaValue = _GetFreeTypeProfileBoundFloat(_T("GammaValue"), 1.0f, GAMMAVALUE_MIN, GAMMAVALUE_MAX, lpszFile); m_fRenderWeight = _GetFreeTypeProfileBoundFloat(_T("RenderWeight"), 1.0f, RENDERWEIGHT_MIN, RENDERWEIGHT_MAX, lpszFile); m_fContrast = _GetFreeTypeProfileBoundFloat(_T("Contrast"), 1.0f, CONTRAST_MIN, CONTRAST_MAX, lpszFile); //DirectWrite/Direct2D exclusive settings float fCalculatedDWGamma = m_fGammaValue*m_fGammaValue > 1.3 ? m_fGammaValue * m_fGammaValue / 2 : 0.7f; // if not set, use calculated gamma as DW gamma m_fGammaValueForDW = Bound(FastGetProfileFloat(c_szDirectWrite, _T("GammaValue"), fCalculatedDWGamma), 0.0f, GAMMAVALUE_MAX); m_fContrastForDW = Bound(FastGetProfileFloat(c_szDirectWrite, _T("Contrast"), 1.0f), CONTRAST_MIN, CONTRAST_MAX); m_nRenderingModeForDW = Bound(FastGetProfileInt(c_szDirectWrite, _T("RenderingMode"), 5), 0, 6); m_fClearTypeLevelForDW = Bound(FastGetProfileFloat(c_szDirectWrite, _T("ClearTypeLevel"), 1.0f), 0.0f, 1.0f); #ifdef _DEBUG // GammaValue検証用 //CHAR GammaValueTest[1025]; //sprintf(GammaValueTest, "GammaValue=%.6f\nContrast=%.6f\n", m_fGammaValue, m_fContrast); //MessageBoxA(NULL, GammaValueTest, "GammaValueテスト", 0); #endif m_bLoadOnDemand = !!_GetFreeTypeProfileInt(_T("LoadOnDemand"), false, lpszFile); m_bFontLink = _GetFreeTypeProfileInt(_T("FontLink"), 0, lpszFile); m_bIsInclude = !!_GetFreeTypeProfileInt(_T("UseInclude"), false, lpszFile); m_nMaxHeight = _GetFreeTypeProfileBoundInt(_T("MaxHeight"), 0, 0, 0xfff, lpszFile); //赃只能到65535,cache的限制,而且大字体无实际价值 m_nMinHeight = _GetFreeTypeProfileBoundInt(_T("MinHeight"), 0, 0, (m_nMaxHeight) ? m_nMaxHeight : 0xfff, // shouldn't be greater than MaxHeight unless it is undefined lpszFile); //Minimum size of rendered font. DPI aware alternative. //patched by krrr https://github.com/krrr/mactype/commit/146a213e2304208cb3c1a3e6fa941a386d908761 m_nBitmapHeight = _GetFreeTypeProfileBoundInt(_T("MaxBitmap"), 0, 0, 255, lpszFile); m_bHintSmallFont = _GetFreeTypeProfileInt(_T("HintSmallFont"), 0, lpszFile); m_bDirectWrite = _GetFreeTypeProfileInt(_T("DirectWrite"), 0, lpszFile); m_nLcdFilter = _GetFreeTypeProfileInt(_T("LcdFilter"), 0, lpszFile); m_nFontSubstitutes = _GetFreeTypeProfileBoundInt(_T("FontSubstitutes"), SETTING_FONTSUBSTITUTE_DISABLE, SETTING_FONTSUBSTITUTE_DISABLE, SETTING_FONTSUBSTITUTE_ALL, lpszFile); m_nWidthMode = SETTING_WIDTHMODE_GDI32; m_nFontLoader = _GetFreeTypeProfileBoundInt(_T("FontLoader"), SETTING_FONTLOADER_FREETYPE, SETTING_FONTLOADER_FREETYPE, SETTING_FONTLOADER_WIN32, lpszFile); m_nCacheMaxFaces = _GetFreeTypeProfileInt(_T("CacheMaxFaces"), 64, lpszFile); m_nCacheMaxFaces = m_nCacheMaxFaces > 64 ? m_nCacheMaxFaces : 64; m_nCacheMaxSizes = _GetFreeTypeProfileInt(_T("CacheMaxSizes"), 1200, lpszFile); m_nCacheMaxBytes = _GetFreeTypeProfileInt(_T("CacheMaxBytes"), 10485760, lpszFile); //parse display affinity string into an integer set { TCHAR sAffinity[260] = { 0 }; _GetFreeTypeProfileString(_T("DisplayAffinity"), _T(""), sAffinity, 256, lpszFile); auto displays = SplitString(sAffinity); for (auto id : displays) { m_nDisplayAffinity.insert(id); } } //experimental settings: m_bEnableClipBoxFix = !!_GetFreeTypeProfileIntFromSection(_T("Experimental"), _T("ClipBoxFix"), 1, lpszFile); m_bColorFont = !!_GetFreeTypeProfileIntFromSection(_T("Experimental"), _T("ColorFont"), 0, lpszFile); m_bInvertColor = !!_GetFreeTypeProfileIntFromSection(_T("Experimental"), _T("InvertColor"), 0, lpszFile); #ifdef INFINALITY // define some macros #define INF_INT_ENV(y, def) \ nTemp = _GetFreeTypeProfileIntFromSection(_T("Infinality"), _T(y), def, lpszFile); \ FT_PutEnv(y, _ltoa(nTemp, buff, 10)); #define INF_BOOL_ENV(y, def) \ bTemp = _GetFreeTypeProfileBoolFromSection(_T("Infinality"), _T(y), def, lpszFile); \ FT_PutEnv(y, bTemp?"true":"false"); #define INF_STR_ENV(y, def) \ sTemp = _GetFreeTypeProfileStrFromSection(_T("Infinality"), _T(y), def, lpszFile); \ FT_PutEnv(y, WstringToString(sTemp).c_str()); char* buff = (char*)malloc(256); int nTemp; bool bTemp; wstring sTemp; // INFINALITY settings: INF_INT_ENV( "INFINALITY_FT_CHROMEOS_STYLE_SHARPENING_STRENGTH", 0); INF_INT_ENV( "INFINALITY_FT_CONTRAST", 0); INF_INT_ENV( "INFINALITY_FT_STEM_FITTING_STRENGTH", 25); INF_INT_ENV( "INFINALITY_FT_AUTOHINT_SNAP_STEM_HEIGHT", 100); INF_INT_ENV( "INFINALITY_FT_GRAYSCALE_FILTER_STRENGTH", 0); INF_INT_ENV( "INFINALITY_FT_WINDOWS_STYLE_SHARPENING_STRENGTH", 20); INF_INT_ENV( "INFINALITY_FT_BRIGHTNESS", 0); INF_INT_ENV( "INFINALITY_FT_AUTOHINT_HORIZONTAL_STEM_DARKEN_STRENGTH", 10); INF_INT_ENV( "INFINALITY_FT_STEM_ALIGNMENT_STRENGTH", 25); INF_INT_ENV( "INFINALITY_FT_AUTOHINT_VERTICAL_STEM_DARKEN_STRENGTH", 25); INF_INT_ENV( "INFINALITY_FT_FRINGE_FILTER_STRENGTH", 0); INF_INT_ENV("INFINALITY_FT_GLOBAL_EMBOLDEN_X_VALUE", 0); INF_INT_ENV("INFINALITY_FT_GLOBAL_EMBOLDEN_Y_VALUE", 0); INF_INT_ENV("INFINALITY_FT_BOLD_EMBOLDEN_X_VALUE", 0); INF_INT_ENV("INFINALITY_FT_BOLD_EMBOLDEN_Y_VALUE", 0); INF_INT_ENV("INFINALITY_FT_STEM_SNAPPING_SLIDING_SCALE", 0); INF_BOOL_ENV("INFINALITY_FT_USE_KNOWN_SETTINGS_ON_SELECTED_FONTS", true); INF_BOOL_ENV( "INFINALITY_FT_AUTOFIT_ADJUST_HEIGHTS", true); INF_BOOL_ENV( "INFINALITY_FT_USE_VARIOUS_TWEAKS", true); INF_BOOL_ENV( "INFINALITY_FT_AUTOHINT_INCREASE_GLYPH_HEIGHTS", true); INF_BOOL_ENV( "INFINALITY_FT_STEM_DARKENING_CFF", true); INF_BOOL_ENV( "INFINALITY_FT_STEM_DARKENING_AUTOFIT", true); INF_STR_ENV( "INFINALITY_FT_GAMMA_CORRECTION", _T("0 100")); INF_STR_ENV( "INFINALITY_FT_FILTER_PARAMS", _T("11 22 38 22 11")); free(buff); #endif if (m_nFontLoader == SETTING_FONTLOADER_WIN32) { // APIが処理してくれるはずなので自前処理は無効化 if (m_nFontSubstitutes == SETTING_FONTSUBSTITUTE_ALL) { m_nFontSubstitutes = SETTING_FONTSUBSTITUTE_DISABLE; } m_bFontLink = 0; } // フォント指定 ZeroMemory(&m_lfForceFont, sizeof(LOGFONT)); m_szForceChangeFont[0] = _T('\0'); //_GetFreeTypeProfileString(_T("ForceChangeFont"), _T(""), m_szForceChangeFont, LF_FACESIZE, lpszFile); // OSのバージョンがXP以降かどうか //OSVERSIONINFO osvi = { sizeof(OSVERSIONINFO) }; //GetVersionEx(&osvi); m_bIsWinXPorLater = IsWindowsXPOrGreater(); STARTUPINFO si = { sizeof(STARTUPINFO) }; GetStartupInfo(&si); m_bRunFromGdiExe = IsGdiPPStartupInfo(si); // if (!m_bRunFromGdiExe) { // m_bHookChildProcesses = false; // } /* const int nTextTuning = _GetFreeTypeProfileInt(_T("TextTuning"), 0, lpszFile), nTextTuningR = _GetFreeTypeProfileInt(_T("TextTuningR"), 0, lpszFile), nTextTuningG = _GetFreeTypeProfileInt(_T("TextTuningG"), 0, lpszFile), nTextTuningB = _GetFreeTypeProfileInt(_T("TextTuningB"), 0, lpszFile); InitInitTuneTable(); InitTuneTable(nTextTuning, m_nTuneTable); InitTuneTable(nTextTuningR, m_nTuneTableR); InitTuneTable(nTextTuningG, m_nTuneTableG); InitTuneTable(nTextTuningB, m_nTuneTableB);*/ // m_bIsHDBench = (GetModuleHandle(_T("HDBENCH.EXE")) == GetModuleHandle(NULL)); m_arrExcludeFont.clear(); m_arrIncludeFont.clear(); m_arrExcludeModule.clear(); m_arrIncludeModule.clear(); m_arrUnloadModule.clear(); m_arrUnFontSubModule.clear(); // [Exclude]セクションから除外フォントリストを読み込む // [ExcludeModule]セクションから除外モジュールリストを読み込む AddListFromSection(_T("ExcludeModule"), lpszFile, m_arrExcludeModule); //AddListFromSection(_T("ExcludeModule"), szMainFile, m_arrExcludeModule); // [IncludeModule]セクションから対象モジュールリストを読み込む AddListFromSection(_T("IncludeModule"), lpszFile, m_arrIncludeModule); //AddListFromSection(_T("IncludeModule"), szMainFile, m_arrIncludeModule); // [UnloadDLL]蛠E患釉氐哪?丒 AddListFromSection(_T("UnloadDLL"), lpszFile, m_arrUnloadModule); //AddListFromSection(_T("UnloadDLL"), szMainFile, m_arrUnloadModule); // [ExcludeSub]不进行字体替换的模縼E AddListFromSection(L"ExcludeSub", lpszFile, m_arrUnFontSubModule); //AddListFromSection(L"ExcludeSub", szMainFile, m_arrUnFontSubModule); //如果是排除的模块,则关闭字体替换 if (m_nFontSubstitutes) { ModuleHashMap::const_iterator it=m_arrUnFontSubModule.begin(); while (it!=m_arrUnFontSubModule.end()) { if (GetModuleHandle(it->c_str())) { m_nFontSubstitutes = 0; //关闭替换 break; } ++it; } } // [Individual]セクションからフォント別設定を読み込む wstring names = _T("LcdFilterWeight@") + wstring(m_szexeName); if (_IsFreeTypeProfileSectionExists(names.c_str(), lpszFile)) m_bUseCustomLcdFilter = AddLcdFilterFromSection(names.c_str(), lpszFile, m_arrLcdFilterWeights); else m_bUseCustomLcdFilter = AddLcdFilterFromSection(_T("LcdFilterWeight"), lpszFile, m_arrLcdFilterWeights); m_bUseCustomPixelLayout = AddPixelModeFromSection(_T("PixelLayout"), lpszFile, m_arrPixelLayout); return true; } bool CGdippSettings::AddExcludeListFromSection(LPCTSTR lpszSection, LPCTSTR lpszFile, set & arr) { LPTSTR buffer = _GetPrivateProfileSection(lpszSection, lpszFile); if (buffer == NULL) { SetLastError(ERROR_NOT_ENOUGH_MEMORY); return false; } LPTSTR p = buffer; TCHAR buff[LF_FACESIZE+1]; LOGFONT truefont={0}; while (*p) { bool b = false; GetFontLocalName(p, buff);//转换字体脕E set::const_iterator it = arr.find(buff); if (it==arr.end()) arr.insert(buff); for (; *p; p++); //来到下一行 p++; } return false; } //template bool CGdippSettings::AddListFromSection(LPCTSTR lpszSection, LPCTSTR lpszFile, set & arr) { LPTSTR buffer = _GetPrivateProfileSection(lpszSection, lpszFile); if (buffer == NULL) { SetLastError(ERROR_NOT_ENOUGH_MEMORY); return false; } LPTSTR p = buffer; while (*p) { bool b = false; set::const_iterator it = arr.find(p); if (it==arr.end()) arr.insert(p); for (; *p; p++); //来到下一行 p++; } return false; } bool CGdippSettings::AddLcdFilterFromSection(LPCTSTR lpszKey, LPCTSTR lpszFile, unsigned char* arr) { TCHAR buffer[100]; _GetFreeTypeProfileString(lpszKey, _T("\0"), buffer, sizeof(buffer), lpszFile); if (buffer[0] == '\0') { SetLastError(ERROR_NOT_ENOUGH_MEMORY); return false; } LPTSTR p = buffer; CStringTokenizer token; int argc = 0; argc = token.Parse(buffer); for (int i = 0; i < 5; i++) { LPCTSTR arg = token.GetArgument(i); if (!arg) return false; //参数少于5个则视为不使用此参数 arr[i] = _StrToInt(arg, arr[i]); } return true; } bool CGdippSettings::AddPixelModeFromSection(LPCTSTR lpszKey, LPCTSTR lpszFile, char* arr) { TCHAR buffer[100]; _GetFreeTypeProfileString(lpszKey, _T("\0"), buffer, sizeof(buffer), lpszFile); if (buffer[0] == '\0') { SetLastError(ERROR_NOT_ENOUGH_MEMORY); return false; } LPTSTR p = buffer; CStringTokenizer token; int argc = 0; argc = token.Parse(buffer); for (int i = 0; i < 6; i++) { LPCTSTR arg = token.GetArgument(i); if (!arg) return false; arr[i] = _StrToInt(arg, arr[i]); } return true; } bool CGdippSettings::AddIndividualFromSection(LPCTSTR lpszSection, LPCTSTR lpszFile, IndividualArray& arr) { LPTSTR buffer = _GetPrivateProfileSection(lpszSection, lpszFile); if (buffer == NULL) { SetLastError(ERROR_NOT_ENOUGH_MEMORY); return false; } LPTSTR p = buffer; TCHAR buff[LF_FACESIZE+1]; LOGFONT truefont={0}; while (*p) { bool b = false; LPTSTR pnext = p; for (; *pnext; pnext++); //"MS Pゴシック=0,0" みたいな文字列を分割 LPTSTR value = _tcschr(p, _T('=')); CStringTokenizer token; int argc = 0; if (value) { *value++ = _T('\0'); argc = token.Parse(value); } GetFontLocalName(p, buff);//转换字体脕E CFontIndividual fi(buff); const CFontSettings& fsCommon = m_FontSettings; CFontSettings& fs = fi.GetIndividual(); //Individualが無ければ共通設定を使う fs = fsCommon; for (int i = 0; i < MAX_FONT_SETTINGS; i++) { LPCTSTR arg = token.GetArgument(i); if (!arg) break; const int n = _StrToInt(arg, fsCommon.GetParam(i)); fs.SetParam(i, n); } for (int i = 0 ; i < arr.GetSize(); i++) { if (arr[i] == fi) { b = true; break; } } if (!b) { arr.Add(fi); #ifdef _DEBUG TRACE(_T("Individual: %s, %d, %d, %d, %d, %d, %d\n"), fi.GetName(), fs.GetParam(0), fs.GetParam(1), fs.GetParam(2), fs.GetParam(3), fs.GetParam(4), fs.GetParam(5)); #endif } p = pnext; p++; } return false; } LPTSTR CGdippSettings::_GetPrivateProfileSection(LPCTSTR lpszSection, LPCTSTR lpszFile) { return const_cast((LPCTSTR)m_Config[lpszSection]); } int CGdippSettings::_httoi(const TCHAR *value) { struct CHexMap { TCHAR chr; int value; }; const int HexMapL = 16; CHexMap HexMap[HexMapL] = { {'0', 0}, {'1', 1}, {'2', 2}, {'3', 3}, {'4', 4}, {'5', 5}, {'6', 6}, {'7', 7}, {'8', 8}, {'9', 9}, {'A', 10}, {'B', 11}, {'C', 12}, {'D', 13}, {'E', 14}, {'F', 15} }; TCHAR *mstr = _tcsupr(_tcsdup(value)); TCHAR *s = mstr; int result = 0; if (*s == '0' && *(s + 1) == 'X') s += 2; bool firsttime = true; while (*s != '\0') { bool found = false; for (int i = 0; i < HexMapL; i++) { if (*s == HexMap[i].chr) { if (!firsttime) result <<= 4; result |= HexMap[i].value; found = true; break; } } if (!found) break; s++; firsttime = false; } free(mstr); return result; } //atofにデフォルト値を返せるようにしたような物 float CGdippSettings::_StrToFloat(LPCTSTR pStr, float fDefault) { #define isspace(ch) (ch == _T('\t') || ch == _T(' ')) #define isdigit(ch) ((_TUCHAR)(ch - _T('0')) <= 9) int ret_i; int ret_d; float ret; bool neg = false; LPCTSTR pStart; for (; isspace(*pStr); pStr++); switch (*pStr) { case _T('-'): neg = true; case _T('+'): pStr++; break; } pStart = pStr; ret = 0; ret_i = 0; ret_d = 1; for (; isdigit(*pStr); pStr++) { ret_i = 10 * ret_i + (*pStr - _T('0')); } if (*pStr == _T('.')) { pStr++; for (; isdigit(*pStr); pStr++) { ret_i = 10 * ret_i + (*pStr - _T('0')); ret_d *= 10; } } ret = (float)ret_i / (float)ret_d; if (pStr == pStart) { return fDefault; } return neg ? -ret : ret; #undef isspace #undef isdigit } bool CGdippSettings::IsFontExcluded(LPCSTR lpFaceName) const { WCHAR szStack[LF_FACESIZE]; LPWSTR lpUnicode = _StrDupExAtoW(lpFaceName, -1, szStack, LF_FACESIZE, NULL); if (!lpUnicode) { return false; } bool b = IsFontExcluded(lpUnicode); if (lpUnicode != szStack) free(lpUnicode); return b; } bool CGdippSettings::IsFontExcluded(LPCWSTR lpFaceName) const { FontHashMap::const_iterator it = m_arrExcludeFont.find(lpFaceName); bool bExcluded = it != m_arrExcludeFont.end(); // if it's excluded, true if (!bExcluded && m_arrIncludeFont.size() != 0) { // if it's not excluded, and includefont enabled FontHashMap::const_iterator it = m_arrIncludeFont.find(lpFaceName); bExcluded = it == m_arrIncludeFont.end(); // check if it's included } return bExcluded; } void CGdippSettings::AddFontExclude(LPCWSTR lpFaceName) { if (!IsFontExcluded(lpFaceName)) m_arrExcludeFont.insert(lpFaceName); } bool CGdippSettings::IsProcessUnload() const { if (m_bRunFromGdiExe) { return false; } GetEnvironmentVariableW(L"MACTYPE_FORCE_LOAD", NULL, 0); if (GetLastError()!=ERROR_ENVVAR_NOT_FOUND) return false; ModuleHashMap::const_iterator it = m_arrUnloadModule.begin(); for(; it != m_arrUnloadModule.end(); ++it) { if (IsFolder(it->c_str())) { // if the user is trying to include a folder instead of a single executable. if (GetAppDir() == LowerCase(*it)) { return true; } } else if (GetModuleHandleW(it->c_str())) { return true; } } return false; } bool CGdippSettings::IsExeUnload(LPCTSTR lpApp) const //紒E槭欠裨诤诿チ斜? { if (m_bRunFromGdiExe) { return false; } GetEnvironmentVariableW(L"MACTYPE_FORCE_LOAD", NULL, 0); if (GetLastError()!=ERROR_ENVVAR_NOT_FOUND) return false; ModuleHashMap::const_iterator it = m_arrUnloadModule.begin(); for(; it != m_arrUnloadModule.end(); ++it) { if (!lstrcmpi(lpApp, it->c_str())) { //匹配排除蟻E return true; } } return false; } bool CGdippSettings::IsExeInclude(LPCTSTR lpApp) const //紒E槭欠裨诎酌チ斜? { if (m_bRunFromGdiExe) { return false; } GetEnvironmentVariableW(L"MACTYPE_FORCE_LOAD", NULL, 0); if (GetLastError()!=ERROR_ENVVAR_NOT_FOUND) return false; ModuleHashMap::const_iterator it = m_arrIncludeModule.begin(); for(; it != m_arrIncludeModule.end(); ++it) { if (!lstrcmpi(lpApp, it->c_str())) { //匹配排除蟻E return true; } } return false; } bool CGdippSettings::IsProcessExcluded() const { if (m_bRunFromGdiExe) { return false; } GetEnvironmentVariableW(L"MACTYPE_FORCE_EXCLUDE", NULL, 0); if (GetLastError() != ERROR_ENVVAR_NOT_FOUND) return true; GetEnvironmentVariableW(L"MACTYPE_FORCE_LOAD", NULL, 0); if (GetLastError()!=ERROR_ENVVAR_NOT_FOUND) return false; ModuleHashMap::const_iterator it = m_arrExcludeModule.begin(); for(; it != m_arrExcludeModule.end(); ++it) { if (IsFolder(it->c_str())) { // if the user is trying to exclude a folder instead of a single executable. if (GetAppDir().find(LowerCase(*it)) == 0) { return true; } } else if (GetModuleHandleW(it->c_str())) { return true; } } return false; } bool CGdippSettings::IsProcessIncluded() const { if (m_bRunFromGdiExe) { return true; } GetEnvironmentVariableW(L"MACTYPE_FORCE_LOAD", NULL, 0); if (GetLastError()!=ERROR_ENVVAR_NOT_FOUND) return true; ModuleHashMap::const_iterator it = m_arrIncludeModule.begin(); for(; it != m_arrIncludeModule.end(); ++it) { if (IsFolder(it->c_str())) { // if the user is trying to include a folder instead of a single executable. if (GetAppDir() == LowerCase(*it)) { return true; } } else if (GetModuleHandleW(it->c_str())) { return true; } } return false; } void CGdippSettings::InitInitTuneTable() { int i, *table; #define init_table(name) \ for (i=0,table=name; i<256; i++) table[i] = i init_table(m_nTuneTable); init_table(m_nTuneTableR); init_table(m_nTuneTableG); init_table(m_nTuneTableB); #undef init_table } // テーブル初期化関数 0 - 12まで // LCD用テーブル初期化関数 各0 - 12まで void CGdippSettings::InitTuneTable(int v, int* table) { int i; int col; double tmp, p; if (v < 0) { return; } v = Min(v, 12); p = (double)v; p = 1 - (p / (p + 10.0)); for(i = 0;i < 256;i++){ tmp = (double)i / 255.0; tmp = pow(tmp, p); col = 255 - (int)(tmp * 255.0 + 0.5); table[255 - i] = col; } } //見つからない場合は共通設定を返す extern BOOL g_ccbIndividual; const CFontSettings& CGdippSettings::FindIndividual(LPCTSTR lpFaceName) const { CFontIndividual* p = m_arrIndividual.Begin(); CFontIndividual* end = m_arrIndividual.End(); if (lpFaceName && *lpFaceName==L'@') ++lpFaceName; //纵向字体使用横向的设定 StringHashFont hash(lpFaceName); for(; p != end; ++p) { if (p->GetHash() == hash) { CFontSettings& result = p->GetIndividual(); if (result.GetAntiAliasMode() > 2 && HarmonyLCD()) result.SetAntiAliasMode(2); return result; } } return GetFontSettings(); } int CGdippSettings::_GetAlternativeProfileName(LPTSTR lpszName, LPCTSTR lpszFile) { TCHAR szexe[MAX_PATH + 1]; TCHAR* pexe = szexe + GetModuleFileName(NULL, szexe, MAX_PATH); while (pexe >= szexe && *pexe != '\\') pexe--; pexe++; wstring exename = _T("General@") + wstring((LPTSTR)pexe); if (FastGetProfileString(exename.c_str(), _T("Alternative"), NULL, lpszName, MAX_PATH)) { return true; } else { //StringCchCopy(lpszName, MAX_PATH + 1, pexe); return false; } } bool CGdippSettings::CopyForceFont(LOGFONT& lf, const LOGFONT& lfOrg) const { _ASSERTE(m_bDelayedInit); //__asm{ int 3 } GetEnvironmentVariableW(L"MACTYPE_FONTSUBSTITUTES_ENV", NULL, 0); if (GetLastError()!=ERROR_ENVVAR_NOT_FOUND) return false; //&lf == &lfOrgも可 bool bForceFont = false; BOOL bFontExist = true; const LOGFONT *lplf; lplf = GetFontSubstitutesInfo().lookup((LOGFONT&)lfOrg); if (lplf) bForceFont = true; if (bForceFont) { memcpy(&lf, &lfOrg, sizeof(LOGFONT)-sizeof(lf.lfFaceName)); StringCchCopy(lf.lfFaceName, LF_FACESIZE, lplf->lfFaceName); } return bForceFont; } //値的にchar(-128~127)で十分 const char CFontSettings::m_bound[MAX_FONT_SETTINGS][2] = { { HINTING_MIN, HINTING_MAX }, //Hinting { AAMODE_MIN, AAMODE_MAX }, //AAMode { NWEIGHT_MIN, NWEIGHT_MAX }, //NormalWeight { BWEIGHT_MIN, BWEIGHT_MAX }, //BoldWeight { SLANT_MIN, SLANT_MAX }, //ItalicSlant { 0, 1 }, //Kerning }; CFontLinkInfo::CFontLinkInfo() { memset(&info, 0, sizeof info); memset(AllowDefaultLink, 1, sizeof(AllowDefaultLink)); //默认允喧笾体链接 } CFontLinkInfo::~CFontLinkInfo() { clear(); } /* static int CALLBACK EnumFontCallBack(const LOGFONT *lplf, const TEXTMETRIC *lptm, DWORD / *FontType* /, LPARAM lParam) { LOGFONT * lf=(LOGFONT *)lParam; StringCchCopy(lf->lfFaceName, LF_FACESIZE, lplf->lfFaceName); return 0; } static void GetFontLocalName(LOGFONT& lf) //获得字体的本地化名称 { HDC dc=GetDC(NULL); EnumFontFamiliesEx(dc, &lf, &EnumFontCallBack, (LPARAM)&lf, 0); ReleaseDC(NULL, dc); }*/ void CFontLinkInfo::init() { const TCHAR REGKEY1[] = _T("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\FontLink\\SystemLink"); const TCHAR REGKEY2[] = _T("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts"); const TCHAR REGKEY3[] = _T("SYSTEM\\CurrentControlSet\\Control\\FontAssoc\\Associated DefaultFonts"); const TCHAR REGKEY4[] = _T("SYSTEM\\CurrentControlSet\\Control\\FontAssoc\\Associated Charset"); HKEY h1; HKEY h2; if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, REGKEY1, 0, KEY_QUERY_VALUE, &h1)) return; if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, REGKEY2, 0, KEY_QUERY_VALUE, &h2)) { RegCloseKey(h1); return; } //OSVERSIONINFO sOsVinfo={sizeof(OSVERSIONINFO),0,0,0,0,{0}}; //GetVersionEx(&sOsVinfo); //获得操作系统版本号 //const CGdippSettings* pSettings = CGdippSettings::GetInstance(); WCHAR* name = new WCHAR[0x2000]; DWORD namesz; DWORD valuesz; WCHAR* value = new WCHAR[0x2000]; WCHAR* buf = new WCHAR[0x2000]; const DWORD nBufSize = 0x2000 * sizeof(WCHAR); LONG rc; DWORD regtype; for (int k = 0; ; ++k) { //获得字体柄蛐的所有字虂E namesz = nBufSize; valuesz = nBufSize; rc = RegEnumValue(h2, k, name, &namesz, 0, ®type, (LPBYTE)value, &valuesz); //从字体柄蛐寻找 if (rc == ERROR_NO_MORE_ITEMS) break; if (rc != ERROR_SUCCESS) break; if (regtype != REG_SZ) continue; StringCchCopy(buf, nBufSize / sizeof(buf[0]), name); if (buf[wcslen(buf) - 1] == L')') { //去掉括号 LPWSTR p; if ((p = wcsrchr(buf, L'(')) != NULL) { *p = 0; } } while (buf[wcslen(buf)-1] == L' ') buf[wcslen(buf)-1] = 0; //获得的对应的字体脕E FontNameCache.Add(value, buf); } int row = 0; LOGFONT truefont; memset(&truefont, 0, sizeof(truefont)); for (int i = 0; row < INFOMAX; ++i) { int col = 0; namesz = nBufSize; valuesz = nBufSize; rc = RegEnumValue(h1, i, name, &namesz, 0, ®type, (LPBYTE)value, &valuesz); //获得一个字体的字体链接 if (rc == ERROR_NO_MORE_ITEMS) break; if (rc != ERROR_SUCCESS) break; if (regtype != REG_MULTI_SZ) continue; //有效的字体链接 //获得字体的真实名字 TCHAR buff[LF_FACESIZE]; GetFontLocalName(name, buff); info[row][col] = _wcsdup(buff); //第一消戟字体脕E ++col; for (LPCWSTR linep = value; col < FONTMAX && *linep; linep += wcslen(linep) + 1) { LPCWSTR valp = NULL; for (LPCWSTR p = linep; *p; ++p) { if (*p == L',' && ((char)*(p+1)<0x30 || (char)*(p+1)>0x39)) //尝试寻找字体链接中“,”后提供的字体名称 { LPWSTR lp; StringCchCopy(buf, nBufSize / sizeof(buf[0]), p + 1); if (lp=wcschr(buf, L',')) *lp = 0; valp = buf; break; } } if (!valp) { //没找到字体链接中提供的名称 /*for (int k = 0; ; ++k) { namesz = sizeof name; value2sz = sizeof value2; rc = RegEnumValue(h2, k, name, &namesz, 0, ®type, (LPBYTE)value2, &value2sz); //从字体柄蛐寻找 if (rc == ERROR_NO_MORE_ITEMS) break; if (rc != ERROR_SUCCESS) break; if (regtype != REG_SZ) continue; if (lstrcmpi(value2, linep) != 0) continue; //寻找字体链接中字体文件对应的字体脕E StringCchCopyW(buf, sizeof(buf)/sizeof(buf[0]), name); if (buf[wcslen(buf) - 1] == L')') { //去掉括号 LPWSTR p; if ((p = wcsrchr(buf, L'(')) != NULL) { *p = 0; } } while (buf[wcslen(buf)-1] == L' ') buf[wcslen(buf)-1] = 0; valp = buf; break; }*/ LPWSTR lp; StringCchCopy(buf, nBufSize / sizeof(buf[0]), linep); if (lp=wcschr(buf, L',')) *lp = 0; valp = FontNameCache.Find((TCHAR*)buf); } if (valp) { GetFontLocalName((TCHAR*)valp, buff);; //StringCchCopy(truefont.lfFaceName, LF_FACESIZE, buff); //复制到结构中 //pSettings->CopyForceFont(truefont, truefont); //获得替换字虂E info[row][col] = _wcsdup(buff);//truefont.lfFaceName); //复制到链接柄蛐 ++col; } } if (col == 1) { //只有一消楷即没有链接,删掉。 free(info[row][0]); info[row][0] = NULL; } else { /*if (sOsVinfo.dwMajorVersion>=6 && sOsVinfo.dwMinorVersion>=1) //版本号>=6.1,是Win7系列 { //对字体链接柄篥逆向处纴E LPWSTR swapbuff[32]; memcpy(swapbuff, info[row], 32*sizeof(LPWSTR)); //整个柄源制过来 for (int i=1; iFontSubstitutes()>=SETTING_FONTSUBSTITUTE_SAFE && pSettings->CopyForceFont(truefont, syslf)) //使用蛠E婊荒J绞保婊坏粝低匙痔丒 { WCHAR envname[30] = L"MT_SYSFONT"; WCHAR envvalue[30] = { 0 }; HFONT tempfont; if (GetEnvironmentVariable(L"MT_SYSFONT", envvalue, 29) && GetObjectType(tempfont = (HFONT)wcstoull(envvalue, 0 ,10)) == OBJ_FONT)//已经有字体存在 { g_alterGUIFont = tempfont; //直接使用先前的字虂E } else { g_alterGUIFont = CreateFontIndirectW(&truefont); //创建一个新的替换字虂E _ui64tow((ULONG_PTR)g_alterGUIFont, envvalue, 10); //转换为字符串 SetEnvironmentVariable(envname, envvalue); //写葋E肪潮淞? } } //现在获取对应字体类型的默认字体链接 memset(DefaultFontLink, 0, sizeof(TCHAR)*(FF_DECORATIVE+1)*(LF_FACESIZE+1)); //初始化为0 HKEY h3; DWORD len; if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, REGKEY3, 0, KEY_QUERY_VALUE, &h3)) return; len = (LF_FACESIZE+1)*sizeof(TCHAR); RegQueryValueEx(h3, _T("FontPackage"), 0, ®type, (LPBYTE)DefaultFontLink[1], &len); len = (LF_FACESIZE+1)*sizeof(TCHAR); RegQueryValueEx(h3, _T("FontPackageDecorative"), 0, ®type, (LPBYTE)DefaultFontLink[FF_DECORATIVE], &len); len = (LF_FACESIZE+1)*sizeof(TCHAR); RegQueryValueEx(h3, _T("FontPackageDontCare"), 0, ®type, (LPBYTE)DefaultFontLink[FF_DONTCARE], &len); len = (LF_FACESIZE+1)*sizeof(TCHAR); RegQueryValueEx(h3, _T("FontPackageModern"), 0, ®type, (LPBYTE)DefaultFontLink[FF_MODERN], &len); len = (LF_FACESIZE+1)*sizeof(TCHAR); RegQueryValueEx(h3, _T("FontPackageRoman"), 0, ®type, (LPBYTE)DefaultFontLink[FF_ROMAN], &len); len = (LF_FACESIZE+1)*sizeof(TCHAR); RegQueryValueEx(h3, _T("FontPackageScript"), 0, ®type, (LPBYTE)DefaultFontLink[FF_SCRIPT], &len); len = (LF_FACESIZE+1)*sizeof(TCHAR); RegQueryValueEx(h3, _T("FontPackageSwiss"), 0, ®type, (LPBYTE)DefaultFontLink[FF_SWISS], &len); RegCloseKey(h3); for (int i=0; i= (unsigned int)INFOMAX || (unsigned int)col >= (unsigned int)FONTMAX) { return NULL; } return info[row][col]; } CFontSubstituteData::CFontSubstituteData() { memset(this, 0, sizeof *this); } int CALLBACK CFontSubstituteData::EnumFontFamProc(const LOGFONT *lplf, const TEXTMETRIC *lptm, DWORD /*FontType*/, LPARAM lParam) { CFontSubstituteData& self = *(CFontSubstituteData *)lParam; self.m_lf = *lplf; return 0; } bool CFontSubstituteData::initnocheck(LPCTSTR config) { memset(this, 0, sizeof *this); TCHAR buf[LF_FACESIZE + 20]; StringCchCopy(buf, countof(buf), config); memset(&m_lf, 0, sizeof m_lf); LPTSTR p; for (p = buf + lstrlen(buf) - 1; p >= buf; --p) { if (*p == _T(',')) { *p++ = 0; break; } } if (p >= buf) { StringCchCopy(m_lf.lfFaceName, countof(m_lf.lfFaceName), buf); m_lf.lfCharSet = (BYTE)_StrToInt(p + 1, 0); m_bCharSet = true; } else { StringCchCopy(m_lf.lfFaceName, LF_FACESIZE, buf); m_lf.lfCharSet = DEFAULT_CHARSET; m_bCharSet = false; } return m_lf.lfFaceName[0] != 0; } bool CFontSubstituteData::init(LPCTSTR config) { memset(this, 0, sizeof *this); TCHAR buf[LF_FACESIZE + 20]; StringCchCopy(buf, countof(buf), config); LOGFONT lf; memset(&lf, 0, sizeof lf); LPTSTR p; for (p = buf + lstrlen(buf) - 1; p >= buf; --p ) { if (*p == _T(',')) { *p++ = 0; break; } } if (p >= buf) { StringCchCopy(lf.lfFaceName, countof(lf.lfFaceName), buf); lf.lfCharSet = (BYTE)_StrToInt(p + 1, 0); m_bCharSet = true; } else { StringCchCopy(lf.lfFaceName, LF_FACESIZE, buf); lf.lfCharSet = DEFAULT_CHARSET; m_bCharSet = false; } HDC hdc = GetDC(NULL); EnumFontFamiliesEx(hdc, &lf, &CFontSubstituteData::EnumFontFamProc, (LPARAM)this, 0); ReleaseDC(NULL, hdc); return m_lf.lfFaceName[0] != 0; } bool CFontSubstituteData::operator == (const CFontSubstituteData& o) const { if (m_bCharSet != o.m_bCharSet) return false; if (m_bCharSet) { if (m_lf.lfCharSet != o.m_lf.lfCharSet) return false; } if (_wcsicmp(m_lf.lfFaceName, o.m_lf.lfFaceName) == 0) return true; return false; } // We scan the registry and see if there is any font mapping whose mapping target is also one of our substitution source, // and we add them as our rules. void CFontSubstitutesInfo::initreg() { const LPCTSTR REGKEY = _T("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\FontSubstitutes"); HKEY h; if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE, REGKEY, 0, KEY_QUERY_VALUE, &h)) return; CFontSubstituteData k; CFontSubstituteData v; std::vector name(0x2000); std::vector value(0x2000); DWORD namesz, valuesz; DWORD regtype; for (int i = 0; ; ++i) { namesz = name.size(); valuesz = value.size(); LONG rc = RegEnumValue(h, i, name.data(), &namesz, 0, ®type, (LPBYTE)value.data(), &valuesz); if (rc == ERROR_NO_MORE_ITEMS) break; if (rc != ERROR_SUCCESS) break; if (regtype != REG_SZ) continue; if (k.initnocheck(name.data()) && v.init(value.data())) { // init k and v (k is a virtual font) int pos = FindKey(v); if ( pos >= 0) { // check if v is substituted to another font x Add(k, GetValueAt(pos)); // add k=>x as well } } } RegCloseKey(h); } void CFontSubstitutesInfo::initini(const CFontSubstitutesIniArray& iniarray) { CFontSubstitutesIniArray::const_iterator it=iniarray.begin(); // LOGFONT truefont={0}, truefont2={0}; // TCHAR* buff, *buff2; for (; it!=iniarray.end(); ++it) { LPCTSTR inistr = it->c_str(); LPTSTR buf = _tcsdup(inistr); for (LPTSTR vp = buf; *vp; ++vp) { if (*vp == _T('=')) { *vp++ = 0; CFontSubstituteData k; CFontSubstituteData v; if (k.init(buf) && v.init(vp)) { if (FindKey(k) < 0 && k.m_bCharSet == v.m_bCharSet) Add(k, v); } /* StringCchCopy(truefont.lfFaceName, LF_FACESIZE, buf); truefont.lfCharSet=DEFAULT_CHARSET; if (!GetFontLocalName(truefont)) continue; //没有此字虂E buff = truefont.lfFaceName; StringCchCopy(truefont2.lfFaceName, LF_FACESIZE, vp); truefont2.lfCharSet=DEFAULT_CHARSET; if (!GetFontLocalName(truefont2)) continue; //没有此字虂E buff2 = truefont2.lfFaceName; if (m_mfontsub.find(buff)==m_mfontsub.end()) m_mfontsub[buff]=wstring(buff2); */ } } free(buf); } } void CFontSubstitutesInfo::init(int nFontSubstitutes, const CFontSubstitutesIniArray& iniarray) { if (nFontSubstitutes >= SETTING_FONTSUBSTITUTE_SAFE) { initini(iniarray); // init substitution from ini array initreg(); // add more substitutions from registry } } void GetMacTypeInternalFontName(LOGFONT* lf, LPTSTR fn) { StringCchCopy(fn, 9, _T("MACTYPE_")); fn+=8; TCHAR* lfbyte=(TCHAR*)lf; for (int i=0;i<(sizeof(LOGFONT)-sizeof(TCHAR)*LF_FACESIZE+1)/sizeof(TCHAR);i++) *fn++=_T('0') + *lfbyte++; *fn=0; } const LOGFONT * CFontSubstitutesInfo::lookup(LOGFONT& lf) const { if (GetSize() <= 0) return NULL; //bFontExist = true; CFontSubstituteData v; CFontSubstituteData k; k.m_bCharSet = true; k.m_lf = lf; TCHAR * buff; //縼E倩竦米痔宓恼媸得? LOGFONT mylf(lf); if (!(buff = FontNameCache.Find((TCHAR*)lf.lfFaceName))) { TCHAR localname[LF_FACESIZE+1]; if (GetFontLocalName(mylf.lfFaceName, localname)) { FontNameCache.Add((TCHAR*)lf.lfFaceName, localname); StringCchCopy(mylf.lfFaceName, LF_FACESIZE, localname); } else { TCHAR inName[LF_FACESIZE]; GetMacTypeInternalFontName(&mylf, inName); if (!(buff = FontNameCache.Find(inName))) { mylf.lfClipPrecision = FONT_MAGIC_NUMBER; HFONT tempfont = CreateFontIndirect(&mylf); HDC dc = CreateCompatibleDC(NULL); HFONT oldfont = SelectFont(dc, tempfont); ORIG_GetTextFaceW(dc, LF_FACESIZE, mylf.lfFaceName); SelectFont(dc, oldfont); DeleteFont(tempfont); DeleteDC(dc); FontNameCache.Add(inName, mylf.lfFaceName); } } buff = mylf.lfFaceName; } StringCchCopy(k.m_lf.lfFaceName, LF_FACESIZE, buff); StringCchCopy(lf.lfFaceName, LF_FACESIZE, buff); int pos = FindKey(k); if (pos < 0) { k.m_bCharSet = false; pos = FindKey(k); } if (pos >= 0) { return (const LOGFONT *)&GetValueAt(pos); } return NULL; } CFontFaceNamesEnumerator::CFontFaceNamesEnumerator(LPCWSTR facename, int nFontFamily) : m_pos(0) { //CCriticalSectionLock __lock; const CGdippSettings* pSettings = CGdippSettings::GetInstance(); TCHAR buff[LF_FACESIZE+1]; GetFontLocalName((TCHAR*)facename, buff); LPCWSTR srcfacenames[] = { buff, NULL, NULL }; int destpos = 0; for (const LPCWSTR *p = srcfacenames; *p && destpos < MAXFACENAMES; ++p) { m_facenames[destpos++] = *p; if (pSettings->FontLink()) { const LPCWSTR *facenamep = pSettings->GetFontLinkInfo().lookup(*p); if (facenamep) { for ( ; *facenamep && **facenamep && destpos < MAXFACENAMES; ++facenamep) { m_facenames[destpos++] = *facenamep; } } } } m_facenames[0] = facename; if (pSettings->IsWinXPorLater() && pSettings->FontLink() && pSettings->FontLoader() == SETTING_FONTLOADER_FREETYPE) { m_facenames[destpos++] = pSettings->GetFontLinkInfo().sysfn(nFontFamily); } m_endpos = destpos; } ================================================ FILE: settings.h ================================================ #pragma once #include "common.h" #include "gdiPlusFlat2.h" #include "cache.h" #include "hash_list.h" #include #include #include #include "json.hpp" #include using json = nlohmann::json; #ifdef _WIN64 #ifdef DEBUG #pragma comment (lib, "iniparser64_dbg.lib") #else #pragma comment (lib, "iniparser64.lib") #endif #else #ifdef DEBUG #pragma comment (lib, "iniparser_dbg.lib") #else #pragma comment (lib, "iniparser.lib") #endif #endif #define MACTYPE_VERSION 20220712 #define MAX_FONT_SETTINGS 16 #define DEFINE_FS_MEMBER(name, param) \ int Get##name() const { return GetParam(param); } \ void Set##name(int n) { SetParam(param, n); } #define HOOK_MANUALLY HOOK_DEFINE #define HOOK_DEFINE(rettype, name, argtype, arglist) \ extern rettype (WINAPI * ORIG_##name) argtype; \ extern rettype WINAPI IMPL_##name argtype; #include "hooklist.h" #undef HOOK_DEFINE //为了确保此文件也能直接使用正确的函数,需要申明。 #undef HOOK_MANUALLY /* struct CFontName { LPWSTR content; public: bool operator < (const CFontName fn) const { return wcscmp(content, fn.content)>0; } CFontName(LPCWSTR fontname) { content = _wcsdup(fontname); wcsupr(content); } ~CFontName() { free(content); } }; struct CFontSubResult { public: LPWSTR lpRealName; LPWSTR lpGDIName; CFontSubResult(LPCWSTR RealName, LPCWSTR GDIName) { lpRealName = _wcsdup(RealName); lpGDIName = _wcsdup(GDIName); } ~CFontSubResult() { free(lpRealName); free(lpGDIName); } }; typedef map CFontNameCache;*/ int _StrToInt(LPCTSTR pStr, int nDefault); class CFontSettings { private: int m_settings[MAX_FONT_SETTINGS]; static const char m_bound[MAX_FONT_SETTINGS][2]; enum _FontSettingsParams { FSP_HINTING = 0, FSP_AAMODE = 1, FSP_NORMAL_WEIGHT = 2, FSP_BOLD_WEIGHT = 3, FSP_ITALIC_SLANT = 4, FSP_KERNING = 5, }; public: CFontSettings() { Clear(); } DEFINE_FS_MEMBER(HintingMode, FSP_HINTING); DEFINE_FS_MEMBER(AntiAliasMode, FSP_AAMODE); DEFINE_FS_MEMBER(NormalWeight, FSP_NORMAL_WEIGHT); DEFINE_FS_MEMBER(BoldWeight, FSP_BOLD_WEIGHT); DEFINE_FS_MEMBER(ItalicSlant, FSP_ITALIC_SLANT); DEFINE_FS_MEMBER(Kerning, FSP_KERNING); int GetParam(int x) const { Assert(0 <= x && x < MAX_FONT_SETTINGS); return m_settings[x]; } void SetParam(int x, int n) { Assert(0 <= x && x < MAX_FONT_SETTINGS); m_settings[x] = Bound(n, m_bound[x][0], m_bound[x][1]); } void Clear() { ZeroMemory(m_settings, sizeof(m_settings)); } void SetSettings(const int* p, int count) { count = Min(count, MAX_FONT_SETTINGS); memcpy(m_settings, p, count * sizeof(int)); } }; #undef DEFINE_FS_MEMBER class CFontIndividual { CFontSettings m_set; StringHashFont m_hash; public: CFontIndividual() { } CFontIndividual(LPCTSTR name) : m_hash(name) { } CFontSettings& GetIndividual() { return m_set; } LPCTSTR GetName() const { return m_hash.c_str(); } const StringHashFont& GetHash() const { return m_hash; } bool operator ==(const CFontIndividual& x) const { return (m_hash == x.m_hash); } }; class CFontLinkInfo { public: enum { INFOMAX = 180, //源文件=15 FONTMAX = 31, }; private: LPWSTR info[INFOMAX + 1][FONTMAX + 1]; bool AllowDefaultLink[256]; WCHAR DefaultFontLink[FF_DECORATIVE + 1][LF_FACESIZE + 1]; //存放对应字体类型的默认链接 public: CFontLinkInfo(); ~CFontLinkInfo(); void init(); void clear(); const bool IsAllowFontLink(BYTE aCharset) const { return AllowDefaultLink[aCharset]; } const LPCWSTR sysfn(int nFontFamily) const { return *DefaultFontLink[nFontFamily] ? DefaultFontLink[nFontFamily] : DefaultFontLink[1]; } const LPCWSTR * lookup(LPCWSTR fontname) const; LPCWSTR get(int row, int col) const; }; class CFontSubstitutesInfo; class CFontSubstituteData { friend CFontSubstitutesInfo; private: LOGFONT m_lf; bool m_bCharSet; //TCHAR CustomName[LF_FACESIZE]; public: bool operator == (const CFontSubstituteData& o) const; private: CFontSubstituteData(); bool initnocheck(LPCTSTR config); //init data w/o checking the font existence. bool init(LPCTSTR config); static int CALLBACK EnumFontFamProc(const LOGFONT *lplf, const TEXTMETRIC *lptm, DWORD FontType, LPARAM lParam); }; typedef StringHashT CFontSubstitutesHash; typedef set CFontSubstitutesIniArray; class CFontSubstitutesInfo : public CSimpleMap { private: //typedef map FontSubMap; //FontSubMap m_mfontsub; void initini(const CFontSubstitutesIniArray& iniarray); void initreg(); public: void init(int nFontSubstitutes, const CFontSubstitutesIniArray& iniarray); const LOGFONT * lookup(LOGFONT &lf) const; //void RemoveAll() {m_mfontsub.clear();}; //bool TrySub(LPCTSTR lpFacename) {return m_mfontsub.find(lpFacename)!=m_mfontsub.end(); }; }; #define SETTING_FONTSUBSTITUTE_DISABLE (0) #define SETTING_FONTSUBSTITUTE_SAFE (1) #define SETTING_FONTSUBSTITUTE_ALL (2) #define SETTING_WIDTHMODE_GDI32 (0) #define SETTING_WIDTHMODE_FREETYPE (1) #define SETTING_FONTLOADER_FREETYPE (0) #define SETTING_FONTLOADER_WIN32 (1) class CGdippSettings; interface IControlCenter { virtual HRESULT STDMETHODCALLTYPE QueryInterface( /* [in] */ REFIID riid, /* [iid_is][out] */ __RPC__deref_out void __RPC_FAR *__RPC_FAR *ppvObject) = 0; virtual ULONG STDMETHODCALLTYPE AddRef( void) = 0; virtual ULONG STDMETHODCALLTYPE Release( void) = 0; virtual ULONG WINAPI GetVersion(void) = 0; virtual BOOL WINAPI SetIntAttribute(int eSet, int nValue) = 0; virtual BOOL WINAPI SetFloatAttribute(int eSet, float nValue) = 0; virtual int WINAPI GetIntAttribute(int eSet) = 0; virtual float WINAPI GetFloatAttribute(int eSet) = 0; virtual BOOL WINAPI RefreshSetting(void) = 0; virtual BOOL WINAPI EnableRender(BOOL bEnable) = 0; virtual BOOL WINAPI EnableCache(BOOL bEnable) = 0; virtual BOOL WINAPI ClearIndividual() = 0; virtual BOOL WINAPI AddIndividual(WCHAR* fontSetting) = 0; virtual BOOL WINAPI DelIndividual(WCHAR* lpFaceName) = 0; virtual void WINAPI LoadSetting(const WCHAR* lpFileName) = 0; virtual HWND WINAPI CreateMessageWnd() = 0; virtual void WINAPI DestroyMessageWnd() = 0; }; class CControlCenter; class CGdippSettings { friend CControlCenter; friend CFontSubstituteData; friend BOOL WINAPI DllMain(HINSTANCE, DWORD, LPVOID); private: static CGdippSettings* s_pInstance; //INI用 CFontSettings m_FontSettings; static CParseIni m_Config; bool m_bHookChildProcesses : 1; bool m_bUseMapping : 1; bool m_bLoadOnDemand : 1; bool m_bEnableShadow : 1; //それ以外 bool m_bIsWinXPorLater : 1; bool m_bRunFromGdiExe : 1; bool m_bIsInclude : 1; bool m_bDelayedInit : 1; // bool m_bIsHDBench : 1; // bool m_bHaveNewerFreeType : 1; bool : 0; bool m_bUseCustomLcdFilter; // use custom lcdfilter bool m_bUseCustomPixelLayout; BOOL m_bHintSmallFont; BOOL m_bDirectWrite; int m_nBolderMode; int m_nGammaMode; float m_fGammaValue; float m_fRenderWeight; float m_fContrast; int m_nMaxHeight; int m_nMinHeight; int m_nBitmapHeight; int m_nLcdFilter; int m_nShadow[4]; int m_nFontSubstitutes; int m_bFontLink; //改为可以使用多种参数 int m_nWidthMode; int m_nFontLoader; int m_nScreenDpi; // screen dpi DWORD m_nShadowLightColor; DWORD m_nShadowDarkColor; unsigned char m_arrLcdFilterWeights[5]; char m_arrPixelLayout[6]; set m_nDisplayAffinity; // screen affinity set for per-display rendering //settings for experimental bool m_bEnableClipBoxFix; bool m_bColorFont; bool m_bInvertColor; //settings for directwrite float m_fGammaValueForDW; float m_fContrastForDW; float m_fClearTypeLevelForDW; int m_nRenderingModeForDW; int m_nAntiAliasModeForDW; CFontSubstitutesInfo m_FontSubstitutesInfoForDW; //FTC_Manager_Newに渡すパラメータ int m_nCacheMaxFaces; int m_nCacheMaxSizes; int m_nCacheMaxBytes; int m_dwOSMajorVer; int m_dwOSMinorVer; // アンチエイリアス調整用テーブル int m_nTuneTable[256]; // LCD用 int m_nTuneTableR[256]; int m_nTuneTableG[256]; int m_nTuneTableB[256]; static TCHAR m_szexeName[MAX_PATH+1]; typedef set FontHashMap; typedef set ModuleHashMap; typedef set FontSubSet; typedef CArray IndividualArray; FontHashMap m_arrExcludeFont; FontHashMap m_arrIncludeFont; ModuleHashMap m_arrExcludeModule; ModuleHashMap m_arrIncludeModule; ModuleHashMap m_arrUnloadModule; ModuleHashMap m_arrUnFontSubModule; IndividualArray m_arrIndividual; // 指定フォント LOGFONT m_lfForceFont; TCHAR m_szForceChangeFont[LF_FACESIZE]; //INIファイル名 TCHAR m_szFileName[MAX_PATH]; //INIからの読み込み処理 bool LoadAppSettings(LPCTSTR lpszFile); void GetOSVersion(); float FastGetProfileFloat(LPCTSTR lpszSection, LPCTSTR lpszKey, float fDefault); int FastGetProfileInt(LPCTSTR lpszSection, LPCTSTR lpszKey, int nDefault); DWORD FastGetProfileString(LPCTSTR lpszSection, LPCTSTR lpszKey, LPCTSTR lpszDefault, LPTSTR lpszRet, DWORD cch); static bool _IsFreeTypeProfileSectionExists(LPCTSTR lpszKey, LPCTSTR lpszFile); static LPTSTR _GetPrivateProfileSection (LPCTSTR lpszSection, LPCTSTR lpszFile); static int _GetFreeTypeProfileInt (LPCTSTR lpszKey, int nDefault, LPCTSTR lpszFile); static int _GetFreeTypeProfileIntFromSection(LPCTSTR lpszSection, LPCTSTR lpszKey, int nDefault, LPCTSTR lpszFile); static bool _GetFreeTypeProfileBoolFromSection(LPCTSTR lpszSection, LPCTSTR lpszKey, bool nDefault, LPCTSTR lpszFile); static wstring _GetFreeTypeProfileStrFromSection(LPCTSTR lpszSection, LPCTSTR lpszKey, const TCHAR* nDefault, LPCTSTR lpszFile); static int _GetFreeTypeProfileBoundInt (LPCTSTR lpszKey, int nDefault, int nMin, int nMax, LPCTSTR lpszFile); static float _GetFreeTypeProfileFloat (LPCTSTR lpszKey, float fDefault, LPCTSTR lpszFile); static float _GetFreeTypeProfileBoundFloat(LPCTSTR lpszKey, float fDefault, float fMin, float fMax, LPCTSTR lpszFile); static DWORD _GetFreeTypeProfileString (LPCTSTR lpszKey, LPCTSTR lpszDefault, LPTSTR lpszRet, DWORD cch, LPCTSTR lpszFile); //template static bool AddListFromSection(LPCTSTR lpszSection, LPCTSTR lpszFile, set & arr); static bool AddExcludeListFromSection(LPCTSTR lpszSection, LPCTSTR lpszFile, set & arr); bool AddIndividualFromSection(LPCTSTR lpszSection, LPCTSTR lpszFile, IndividualArray& arr); bool AddLcdFilterFromSection(LPCTSTR lpszKey, LPCTSTR lpszFile, unsigned char* arr); bool AddPixelModeFromSection(LPCTSTR lpszKey, LPCTSTR lpszFile, char* arr); static float _StrToFloat(LPCTSTR pStr, float fDefault); static int _httoi(const TCHAR *value); void InitInitTuneTable(); static void InitTuneTable(int v, int* table); void DelayedInit(); int _GetAlternativeProfileName(LPTSTR lpszName, LPCTSTR lpszFile); CFontLinkInfo m_fontlinkinfo; CFontSubstitutesInfo m_FontSubstitutesInfo; CGdippSettings() : m_bHookChildProcesses(false) , m_bUseMapping(false) , m_bLoadOnDemand(false) , m_bEnableShadow(false) , m_bFontLink(0) // , m_bEnableKerning(false) , m_bIsWinXPorLater(false) , m_bRunFromGdiExe(false) , m_bIsInclude(false) , m_bDelayedInit(false) // , m_bIsHDBench(false) // , m_bHaveNewerFreeType(false) , m_nBolderMode(0) , m_nGammaMode(0) , m_fGammaValue(1.0f) , m_fGammaValueForDW(0.0f) , m_nAntiAliasModeForDW(0) , m_fRenderWeight(1.0f) , m_fContrast(1.0f) , m_nMaxHeight(0) , m_nMinHeight(0) , m_nBitmapHeight(0) , m_nLcdFilter(0) , m_nCacheMaxFaces(0) , m_nCacheMaxSizes(0) , m_nCacheMaxBytes(0) , m_bHintSmallFont(true) , m_bDirectWrite(true) , m_nScreenDpi(96) , m_bUseCustomPixelLayout(false) { ZeroMemory(m_nTuneTable, sizeof(m_nTuneTable)); ZeroMemory(m_nTuneTableR, sizeof(m_nTuneTableR)); ZeroMemory(m_nTuneTableG, sizeof(m_nTuneTableG)); ZeroMemory(m_nTuneTableB, sizeof(m_nTuneTableB)); ZeroMemory(&m_lfForceFont, sizeof(LOGFONT)); ZeroMemory(m_nShadow, sizeof(m_nShadow)); ZeroMemory(m_szFileName, sizeof(m_szFileName)); ZeroMemory(m_szForceChangeFont, sizeof(m_szForceChangeFont)); } ~CGdippSettings() { } static CGdippSettings* CreateInstance(); static void DestroyInstance(); public: static CGdippSettings* GetInstance(); static const CGdippSettings* GetInstanceNoInit(); //FreeTypeFontEngine //INI用 const CFontSettings& GetFontSettings() const { return m_FontSettings; } bool HookChildProcesses() const { return m_bHookChildProcesses; } bool UseMapping() const { return m_bUseMapping; } bool LoadOnDemand() const { return m_bLoadOnDemand; } char FontLink() const { return m_bFontLink; } BOOL DirectWrite() const { return m_bDirectWrite; } BOOL HintSmallFont() const { return m_bHintSmallFont; } // bool EnableKerning() const { return m_bEnableKerning; } int BolderMode() const { return m_nBolderMode; } int GammaMode() const { return m_nGammaMode; } float GammaValue() const { return m_fGammaValue; } // Only fallback to tranditional ClearType mode when Custom LCD Filter is defined, and pixelLayout is not defined and AAMode is not in pentile. bool HarmonyLCD() const { return m_bUseCustomPixelLayout || m_FontSettings.GetAntiAliasMode() == 6 || !m_bUseCustomLcdFilter; } //DW options float GammaValueForDW() const { return m_fGammaValueForDW; } float ContrastForDW() const { return m_fContrastForDW; } float ClearTypeLevelForDW() const { return m_fClearTypeLevelForDW; } int RenderingModeForDW() const { return m_nRenderingModeForDW; } int AntiAliasModeForDW() const { return m_nAntiAliasModeForDW; } /*const CFontSubstitutesInfo& GetFontSubstitutesInfoForDW() const { _ASSERTE(m_bDelayedInit); return m_FontSubstitutesInfoForDW; }*/ float RenderWeight() const { return m_fRenderWeight; } float Contrast() const { return m_fContrast; } int MaxHeight() const { return m_nMaxHeight; } int MinHeight() const { return m_nMinHeight; } int BitmapHeight() const { return m_nBitmapHeight; } int ScreenDpi() const { return m_nScreenDpi; } int LcdFilter() const { return m_nLcdFilter; } const unsigned char* LcdFilterWeights() const { return m_arrLcdFilterWeights; } bool UseCustomLcdFilter() const { return m_bUseCustomLcdFilter; } int WidthMode() const { return m_nWidthMode; } int FontLoader() const { return m_nFontLoader; } bool EnableClipBoxFix() const { return m_bEnableClipBoxFix; } bool LoadColorFont() const { return m_bColorFont; } bool InvertColor() const { return m_bInvertColor; } DWORD ShadowLightColor() const { return m_nShadowLightColor; } DWORD ShadowDarkColor() const { return m_nShadowDarkColor; } int FontSubstitutes() const { return m_nFontSubstitutes; } //判断替换模式 int CacheMaxFaces() const { return m_nCacheMaxFaces; } int CacheMaxSizes() const { return m_nCacheMaxSizes; } int CacheMaxBytes() const { return m_nCacheMaxBytes; } bool EnableShadow() const { return m_bEnableShadow; } const int* GetShadowParams() const { return m_nShadow; } bool DelayedInited() const { return m_bDelayedInit; } // return the delayedinit status // OS version comparsion for magic code bool IsWindows8() const { return m_dwOSMajorVer == 6 && m_dwOSMinorVer == 2; } bool IsWindows81() const { return m_dwOSMajorVer == 6 && m_dwOSMinorVer == 3; } bool CopyForceFont(LOGFONT& lf, const LOGFONT& lfOrg) const; //それ以外 bool IsWinXPorLater() const { return m_bIsWinXPorLater; } bool IsInclude() const { return m_bIsInclude; } // bool IsHDBench() const { return m_bIsHDBench; } bool RunFromGdiExe() const { return m_bRunFromGdiExe; } // bool HaveNewerFreeType() const { return m_bHaveNewerFreeType; } const int* GetTuneTable() const { return m_nTuneTable; } const int* GetTuneTableR() const { return m_nTuneTableR; } const int* GetTuneTableG() const { return m_nTuneTableG; } const int* GetTuneTableB() const { return m_nTuneTableB; } set& DisplayAffinity() { return m_nDisplayAffinity; } bool LoadSettings(HINSTANCE hModule); bool IsFontExcluded(LPCSTR lpFaceName) const; bool IsFontExcluded(LPCWSTR lpFaceName) const; //Snowie!! bool IsProcessUnload() const; bool IsExeUnload(LPCTSTR lpApp) const; bool IsExeInclude(LPCTSTR lpApp) const; void AddFontExclude(LPCWSTR lpFaceName); //点阵字体直接自动添加到此列表 bool IsProcessExcluded() const; bool IsProcessIncluded() const; const CFontSettings& FindIndividual(LPCTSTR lpFaceName) const; const CFontLinkInfo& GetFontLinkInfo() const { _ASSERTE(m_bDelayedInit); return m_fontlinkinfo; } const CFontSubstitutesInfo& GetFontSubstitutesInfo() const { _ASSERTE(m_bDelayedInit); return m_FontSubstitutesInfo; } }; class CFontFaceNamesEnumerator { private: enum { MAXFACENAMES = CFontLinkInfo::FONTMAX * 2 + 1, }; LPCWSTR m_facenames[MAXFACENAMES]; int m_pos; int m_endpos; CFontFaceNamesEnumerator(); public: CFontFaceNamesEnumerator(LPCWSTR facename, int nFontFamily); operator LPCWSTR () { return m_facenames[m_pos]; } LPCWSTR getname() { return m_facenames[m_pos]; } void next() { ++m_pos; } void prev() { m_pos>0?--m_pos:0; } bool atend() { return !!(m_pos >= m_endpos); } }; #include "fteng.h" #include "ft.h" #include #include "strtoken.h" extern FreeTypeFontEngine* g_pFTEngine; extern BOOL g_ccbCache; extern BOOL g_ccbRender; extern CControlCenter* g_ControlCenter; class CControlCenter: public IControlCenter { private: int m_nRefCount; bool m_bDirty; HWND m_msgwnd; enum eMTSettings{ ATTR_HINTINGMODE, ATTR_ANTIALIASMODE, ATTR_NormalWeight, ATTR_BoldWeight, ATTR_ItalicSlant, ATTR_EnableKerning, ATTR_GammaMode, ATTR_LcdFilter, ATTR_BolderMode, ATTR_TextTuning, ATTR_TextTuningR, ATTR_TextTuningG, ATTR_TextTuningB, ATTR_GammaValue, ATTR_Contrast, ATTR_RenderWeight, ATTR_ShadowAlpha, ATTR_ShadowOffset, ATTR_Fontlink, ATTR_HookChildProcess, ATTR_LoadOnDemand, ATTR_FontLoader, ATTR_FontSubstitute, ATTR_LcdFilterWeight, ATTR_ShadowBuffer, ATTR_MaxBitmap, ATTR_DirectWrite, ATTR_HintSmallFont }; typedef CArray IndividualArray; public: HRESULT STDMETHODCALLTYPE QueryInterface( /* [in] */ REFIID riid, /* [iid_is][out] */ __RPC__deref_out void __RPC_FAR *__RPC_FAR *ppvObject) { ppvObject = (void**)this; return 0; } ULONG STDMETHODCALLTYPE AddRef( void) {return InterlockedIncrement((LONG*)&m_nRefCount);}; ULONG STDMETHODCALLTYPE Release( void) { int result = InterlockedDecrement((LONG*)&m_nRefCount); if (!result) delete this; return result; } ULONG WINAPI GetVersion(void){ return MACTYPE_VERSION; }; static void UpdateLcdFilter() { const CGdippSettings* pSettings = CGdippSettings::GetInstance(); if (pSettings->HarmonyLCD()) { FT_LCDMode_Set(freetype_library, 1); return; } FT_LCDMode_Set(freetype_library, 0); const int nLcdFilter = pSettings->LcdFilter(); if ((int)FT_LCD_FILTER_NONE <= nLcdFilter && nLcdFilter < (int)FT_LCD_FILTER_MAX) { FT_Library_SetLcdFilter(freetype_library, (FT_LcdFilter)nLcdFilter); if (pSettings->UseCustomLcdFilter()) { unsigned char buff[5]; memcpy(buff, pSettings->LcdFilterWeights(), sizeof(buff)); FT_Library_SetLcdFilterWeights(freetype_library, buff); } /* else switch (nLcdFilter) { case FT_LCD_FILTER_NONE: case FT_LCD_FILTER_DEFAULT: case FT_LCD_FILTER_LEGACY: { FT_Library_SetLcdFilterWeights(freetype_library, (unsigned char*)"\x10\x40\x70\x40\x10" ); break; } case FT_LCD_FILTER_LIGHT: default: FT_Library_SetLcdFilterWeights(freetype_library, (unsigned char*)"\x00\x55\x56\x55\x00" ); }*/ } } BOOL WINAPI SetIntAttribute(int eSet, int nValue) { CGdippSettings* pSettings = CGdippSettings::GetInstance(); switch ((eMTSettings)eSet) { case ATTR_HINTINGMODE: pSettings->m_FontSettings.SetHintingMode(nValue); break; case ATTR_ANTIALIASMODE: pSettings->m_FontSettings.SetAntiAliasMode(nValue); break; case ATTR_NormalWeight: pSettings->m_FontSettings.SetNormalWeight(nValue); break; case ATTR_BoldWeight: pSettings->m_FontSettings.SetBoldWeight(nValue); break; case ATTR_ItalicSlant: pSettings->m_FontSettings.SetItalicSlant(nValue); break; case ATTR_EnableKerning: pSettings->m_FontSettings.SetKerning(nValue); break; case ATTR_GammaMode: pSettings->m_nGammaMode = nValue; RefreshAlphaTable(); break; case ATTR_LcdFilter: pSettings->m_nLcdFilter = nValue; UpdateLcdFilter(); break; case ATTR_BolderMode: pSettings->m_nBolderMode = nValue; break; case ATTR_TextTuning: pSettings->InitTuneTable(nValue, pSettings->m_nTuneTable); RefreshAlphaTable(); break; case ATTR_TextTuningR: pSettings->InitTuneTable(nValue, pSettings->m_nTuneTableR); RefreshAlphaTable(); break; case ATTR_TextTuningG: pSettings->InitTuneTable(nValue, pSettings->m_nTuneTableG); RefreshAlphaTable(); break; case ATTR_TextTuningB: pSettings->InitTuneTable(nValue, pSettings->m_nTuneTableB); RefreshAlphaTable(); break; case ATTR_LoadOnDemand: pSettings->m_bLoadOnDemand = !!nValue; break; case ATTR_ShadowAlpha: pSettings->m_nShadow[2] = nValue; pSettings->m_bEnableShadow = (nValue!=1); RefreshAlphaTable(); break; case ATTR_ShadowOffset: pSettings->m_nShadow[1] = nValue; pSettings->m_nShadow[0] = nValue; case ATTR_Fontlink: if (!!pSettings->m_bFontLink != !!nValue) { pSettings->m_fontlinkinfo.clear(); if (nValue) pSettings->m_fontlinkinfo.init(); } pSettings->m_bFontLink = nValue; break; case ATTR_FontLoader: pSettings->m_nFontLoader = nValue; break; case ATTR_LcdFilterWeight: if (!nValue) pSettings->m_bUseCustomLcdFilter = false; //传NULL过来就是关闭自定义过滤器 else { pSettings->m_bUseCustomLcdFilter = true; //否则打开过滤器 if (!IsBadReadPtr((void*)nValue, sizeof(pSettings->m_arrLcdFilterWeights))) //如果指针有效 memcpy(pSettings->m_arrLcdFilterWeights, (void*)nValue, sizeof(pSettings->m_arrLcdFilterWeights)); //复制数据 } UpdateLcdFilter(); //刷新过滤器 break; case ATTR_HintSmallFont: pSettings->m_bHintSmallFont = !!nValue; break; case ATTR_MaxBitmap: pSettings->m_nBitmapHeight = nValue; break; case ATTR_ShadowBuffer: if (nValue && !IsBadReadPtr((void*)nValue, sizeof(pSettings->m_nShadow))) //指针有效 { LPCTSTR szShadow = (LPCTSTR)nValue; CStringTokenizer token; if (token.Parse(szShadow) < 3) { break; } for (int i=0; i<3; i++) { pSettings->m_nShadow[i] = _StrToInt(token.GetArgument(i), 0); /*if (m_nShadow[i] <= 0) { goto SKIP; }*/ } pSettings->m_bEnableShadow = true; if (token.GetCount()>=4) //如果指定了浅色阴影 pSettings->m_nShadowDarkColor = pSettings->_httoi(token.GetArgument(3)); //读取阴影 else pSettings->m_nShadowDarkColor = 0; //否则为黑色 if (token.GetCount()>=6) //如果指定了深色阴影 { pSettings->m_nShadowLightColor = pSettings->_httoi(token.GetArgument(5)); //读取阴影 pSettings->m_nShadow[3] = _StrToInt(token.GetArgument(4), pSettings->m_nShadow[2]); //读取深度 } else { //pSettings->m_nShadowLightColor = pSettings->m_nShadowLightColor; //否则和浅色阴影相同 pSettings->m_nShadow[3] = pSettings->m_nShadow[2]; //深度也相同 } RefreshAlphaTable(); } break; default: return FALSE; } m_bDirty = true; return true; } BOOL WINAPI SetFloatAttribute(int eSet, float nValue) { CGdippSettings* pSettings = CGdippSettings::GetInstance(); switch ((eMTSettings)eSet) { case ATTR_GammaValue: pSettings->m_fGammaValue = nValue; RefreshAlphaTable(); break; case ATTR_Contrast: pSettings->m_fContrast = nValue; RefreshAlphaTable(); break; case ATTR_RenderWeight: pSettings->m_fRenderWeight = nValue; RefreshAlphaTable(); break; default: return FALSE; } m_bDirty = true; return true; }; int WINAPI GetIntAttribute(int eSet) { CGdippSettings* pSettings = CGdippSettings::GetInstance(); switch ((eMTSettings)eSet) { case ATTR_HINTINGMODE: return pSettings->m_FontSettings.GetHintingMode(); case ATTR_ANTIALIASMODE: return pSettings->m_FontSettings.GetAntiAliasMode(); case ATTR_NormalWeight: return pSettings->m_FontSettings.GetNormalWeight(); case ATTR_BoldWeight: return pSettings->m_FontSettings.GetBoldWeight(); case ATTR_ItalicSlant: return pSettings->m_FontSettings.GetItalicSlant(); case ATTR_EnableKerning: return pSettings->m_FontSettings.GetKerning(); case ATTR_GammaMode: return pSettings->m_nGammaMode; case ATTR_HintSmallFont: return pSettings->m_bHintSmallFont; case ATTR_MaxBitmap: return pSettings->m_nBitmapHeight; case ATTR_LcdFilter: return pSettings->m_nLcdFilter; case ATTR_BolderMode: return pSettings->m_nBolderMode; case ATTR_TextTuning: return 0; case ATTR_TextTuningR: return 0; case ATTR_TextTuningG: return 0; case ATTR_TextTuningB: return 0; case ATTR_LoadOnDemand: return pSettings->m_bLoadOnDemand; case ATTR_ShadowAlpha: return pSettings->EnableShadow()? pSettings->m_nShadow[2] : 1; case ATTR_ShadowOffset: return pSettings->EnableShadow()? pSettings->m_nShadow[0] : 1; case ATTR_Fontlink: return pSettings->m_bFontLink; case ATTR_LcdFilterWeight: return pSettings->m_bUseCustomLcdFilter? (int)pSettings->m_arrLcdFilterWeights:NULL; default: return 0; } return 0; }; float WINAPI GetFloatAttribute(int eSet) { CGdippSettings* pSettings = CGdippSettings::GetInstance(); switch ((eMTSettings)eSet) { case ATTR_GammaValue: return pSettings->m_fGammaValue; case ATTR_Contrast: return pSettings->m_fContrast; case ATTR_RenderWeight: return pSettings->m_fRenderWeight; default: return 0; } return 0; }; BOOL WINAPI RefreshSetting(void) { if (m_bDirty) g_pFTEngine->ReloadAll(); m_bDirty = false; return true; }; BOOL WINAPI EnableRender(BOOL bEnable){g_ccbRender = bEnable; return true;}; BOOL WINAPI EnableCache(BOOL bEnable){g_ccbCache = bEnable; return true;}; BOOL WINAPI ClearIndividual(){ CGdippSettings* pSettings = CGdippSettings::GetInstance(); pSettings->m_arrIndividual.RemoveAll(); m_bDirty = true; return true; }; BOOL WINAPI AddIndividual(WCHAR* fontSetting) { CGdippSettings* pSettings = CGdippSettings::GetInstance(); IndividualArray& arr = pSettings->m_arrIndividual; LPTSTR p = fontSetting; LOGFONT truefont={0}; if (*p) { bool b = false; LPTSTR pnext = p; for (; *pnext; pnext++); //"MS Pゴシック=0,0" みたいな文字列を分割 LPTSTR value = _tcschr(p, _T('=')); CStringTokenizer token; int argc = 0; if (value) { *value++ = _T('\0'); argc = token.Parse(value); } TCHAR buff[LF_FACESIZE+1]; GetFontLocalName(p, buff); //转换字体名 CFontIndividual fi(buff); const CFontSettings& fsCommon = pSettings->m_FontSettings; CFontSettings& fs = fi.GetIndividual(); //Individualが無ければ共通設定を使う fs = fsCommon; for (int i = 0; i < MAX_FONT_SETTINGS; i++) { LPCTSTR arg = token.GetArgument(i); if (!arg) break; const int n = _StrToInt(arg, fsCommon.GetParam(i)); fs.SetParam(i, n); } for (int i = 0 ; i < arr.GetSize(); i++) { if (arr[i] == fi) { b = true; break; } } if (!b) { arr.Add(fi); } } m_bDirty = true; return true; }; BOOL WINAPI DelIndividual(WCHAR* lpFaceName) { CGdippSettings* pSettings = CGdippSettings::GetInstance(); CFontIndividual* p = pSettings->m_arrIndividual.Begin(); CFontIndividual* end = pSettings->m_arrIndividual.End(); StringHashFont hash(lpFaceName); for(; p != end; ++p) { if (p->GetHash() == hash) { pSettings->m_arrIndividual.Remove(*p); } } m_bDirty = true; return true;}; void WINAPI LoadSetting(const WCHAR* lpFileName) { CGdippSettings* pSettings = CGdippSettings::GetInstance(); ClearIndividual(); pSettings->m_FontSubstitutesInfoForDW.RemoveAll(); pSettings->m_FontSubstitutesInfo.RemoveAll(); pSettings->m_fontlinkinfo.clear(); pSettings->LoadAppSettings(lpFileName); pSettings->m_bDelayedInit = false; m_bDirty = true; RefreshAlphaTable(); RefreshSetting(); } CControlCenter():m_nRefCount(1), m_bDirty(false), m_msgwnd(NULL) { g_ControlCenter = this; }; ~CControlCenter(){ g_ControlCenter = NULL; }; static void WINAPI ReloadConfig() { //CCriticalSectionLock __lock(CCriticalSectionLock::CS_LIBRARY); CGdippSettings* pSettings = CGdippSettings::GetInstance(); extern HINSTANCE g_dllInstance; pSettings->m_arrIndividual.RemoveAll(); pSettings->m_FontSubstitutesInfoForDW.RemoveAll(); pSettings->m_FontSubstitutesInfo.RemoveAll(); pSettings->m_fontlinkinfo.clear(); pSettings->LoadSettings(g_dllInstance); pSettings->m_bDelayedInit = false; RefreshAlphaTable(); UpdateLcdFilter(); if (g_pFTEngine) g_pFTEngine->ReloadAll(); } HWND WINAPI CreateMessageWnd() { HANDLE event = CreateEvent(NULL, true, false, NULL); auto run = [&]() -> void { if (this->m_msgwnd) { SendMessage(this->m_msgwnd, WM_CLOSE, 0, 0); } WNDCLASS wndclass; wndclass.style = 0; wndclass.lpfnWndProc = [](HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) -> LRESULT { return g_ControlCenter ? g_ControlCenter->MsgProc(hwnd, message, wParam, lParam) : DefWindowProc(hwnd, message, wParam, lParam); }; wndclass.cbClsExtra = 0; wndclass.cbWndExtra = 0; wndclass.hInstance = 0; wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); wndclass.hCursor = LoadCursor(NULL, IDC_ARROW); wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wndclass.lpszMenuName = NULL; wndclass.lpszClassName = L"MT_CMSGWND"; RegisterClass(&wndclass); this->m_msgwnd = CreateWindow(L"MT_CMSGWND", NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, 0, 0, NULL); SetEvent(event); MSG msg; while (GetMessage(&msg, NULL, 0, 0)) //消息循环 { TranslateMessage(&msg); DispatchMessage(&msg); } DestroyWindow(this->m_msgwnd); }; auto wndThread = thread(run); wndThread.detach(); WaitForSingleObject(event, 10000); CloseHandle(event); return this->m_msgwnd; } void RedrawCurrentApp() { auto EnumCurrentProcWindow = [](HWND hwnd, LPARAM lparam)->BOOL { DWORD pid = 0; GetWindowThreadProcessId(hwnd, &pid); if (pid == lparam) { RedrawWindow(hwnd, NULL, 0, RDW_ALLCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW | RDW_NOERASE); } return true; }; EnumWindows(EnumCurrentProcWindow, GetCurrentProcessId()); } LRESULT WINAPI MsgProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) { switch (msg) { case WM_COPYDATA: { COPYDATASTRUCT* data = (COPYDATASTRUCT*)lparam; if (data->cbData && data->lpData) { // ignore invalid request. string json; json.resize(data->cbData); memcpy((void*)json.c_str(), data->lpData, data->cbData); // now parse the json string auto jsonobj = json::parse(json.begin(), json.end()); string command = jsonobj["command"].get(); // various command dispatch if (command == "loadprofile") { // load target profile from disk string filename = jsonobj["file"].get(); if (filename.length()) { this->LoadSetting(to_wide_string(filename).c_str()); RedrawCurrentApp(); } return ERROR_SUCCESS; } if (command == "ping") { //__asm db 0xcc; // cause debugger to break //DebugBreak(); return ERROR_SUCCESS; } } break; } default: { return DefWindowProc(hwnd, msg, wparam, lparam); } } return 0; } void WINAPI DestroyMessageWnd() { if (m_msgwnd) { DestroyWindow(m_msgwnd); m_msgwnd = NULL; } } }; ================================================ FILE: stdint.h ================================================ /* stdint.h Integer types - c99 7.18 */ /* * C/C++ Run Time Library - Version 13.0 * * Copyright (c) 2002, 2007 by CodeGear * All Rights Reserved. * */ #ifndef __STDINT_H #define __STDINT_H /* 7.18.1.1 Exact-width integer types */ typedef __int8 int8_t; typedef __int16 int16_t; typedef __int32 int32_t; typedef __int64 int64_t; typedef unsigned __int8 uint8_t; typedef unsigned __int16 uint16_t; typedef unsigned __int32 uint32_t; typedef unsigned __int64 uint64_t; /* 7.18.1.2 Minimum-width integer types */ typedef __int8 int_least8_t; typedef __int16 int_least16_t; typedef __int32 int_least32_t; typedef __int64 int_least64_t; typedef unsigned __int8 uint_least8_t; typedef unsigned __int16 uint_least16_t; typedef unsigned __int32 uint_least32_t; typedef unsigned __int64 uint_least64_t; /* 7.18.1.3 Fastest minimum-width integer types */ typedef __int8 int_fast8_t; typedef __int16 int_fast16_t; typedef __int32 int_fast32_t; typedef __int64 int_fast64_t; typedef unsigned __int8 uint_fast8_t; typedef unsigned __int16 uint_fast16_t; typedef unsigned __int32 uint_fast32_t; typedef unsigned __int64 uint_fast64_t; /* 7.18.1.4 Integer types capable of holding object pointers */ typedef int32_t intptr_t; typedef uint32_t uintptr_t; /* 7.18.1.5 Greatest-width integer types */ typedef int64_t intmax_t; typedef uint64_t uintmax_t; /* 7.18.2.1 Limits of exact-width integer types */ #define INT8_MIN ((int8_t) -128) #define INT16_MIN ((int16_t) -32768) #define INT32_MIN ((int32_t) -2147483647L - 1) #define INT64_MIN ((int64_t) -9223372036854775807LL - 1) #define INT8_MAX ((int8_t) 127) #define INT16_MAX ((int16_t) 32767) #define INT32_MAX ((int32_t) 2147483647L) #define INT64_MAX ((int64_t) 9223372036854775807LL) #define UINT8_MAX ((uint8_t) 255) #define UINT16_MAX ((uint16_t) 65535) #define UINT32_MAX ((uint32_t) 4294967295UL) #define UINT64_MAX ((uint64_t) 18446744073709551615ULL) /* 7.18.2.2 Limits of minimum-width integer types */ #define INT_LEAST8_MIN ((int_least8_t) -128) #define INT_LEAST16_MIN ((int_least16_t) -32768) #define INT_LEAST32_MIN ((int_least32_t) -2147483647L - 1) #define INT_LEAST64_MIN ((int_least64_t) -9223372036854775807LL - 1) #define INT_LEAST8_MAX ((int_least8_t) 127) #define INT_LEAST16_MAX ((int_least16_t) 32767) #define INT_LEAST32_MAX ((int_least32_t) 2147483647L) #define INT_LEAST64_MAX ((int_least64_t) 9223372036854775807LL) #define UINT_LEAST8_MAX ((uint_least8_t) 255) #define UINT_LEAST16_MAX ((uint_least16_t) 65535) #define UINT_LEAST32_MAX ((uint_least32_t) 4294967295UL) #define UINT_LEAST64_MAX ((uint_least64_t) 18446744073709551615ULL) /* 7.18.2.3 Limits of fastest minimum-width integer types */ #define INT_FAST8_MIN ((int_fast8_t) -128) #define INT_FAST16_MIN ((int_fast16_t) -32768) #define INT_FAST32_MIN ((int_fast32_t) -2147483647L - 1) #define INT_FAST64_MIN ((int_fast64_t) -9223372036854775807LL - 1) #define INT_FAST8_MAX ((int_fast8_t) 127) #define INT_FAST16_MAX ((int_fast16_t) 32767) #define INT_FAST32_MAX ((int_fast32_t) 2147483647L) #define INT_FAST64_MAX ((int_fast64_t) 9223372036854775807LL) #define UINT_FAST8_MAX ((uint_fast8_t) 255) #define UINT_FAST16_MAX ((uint_fast16_t) 65535) #define UINT_FAST32_MAX ((uint_fast32_t) 4294967295UL) #define UINT_FAST64_MAX ((uint_fast64_t) 18446744073709551615ULL) /* 7.18.2.4 Limits of integer types capable of holding object pointers */ #define INTPTR_MIN ((intptr_t) -2147483647L - 1) #define INTPTR_MAX ((intptr_t) 2147483647L) #define UINTPTR_MAX ((intptr_t) 4294967295UL) /* 7.18.2.5 Limits of greatest-width integer types */ #define INTMAX_MIN ((intmax_t) -9223372036854775807LL - 1) #define INTMAX_MAX ((intmax_t) 9223372036854775807LL) #define UINTMAX_MAX ((uintmax_t) 18446744073709551615ULL) /* 7.18.3 Limits of other integer types */ #define PTRDIFF_MIN ((int32_t) -2147483647L - 1) #define PTRDIFF_MAX ((int32_t) 2147483647L) #ifdef __STDC_LIMIT_MACROS #define SIG_ATOMIC_MIN INT32_MIN #define SIG_ATOMIC_MAX INT32_MAX #endif #define SIZE_MAX UINT32_MAX #ifdef __STDC_CONSTANT_MACROS #define WCHAR_MIN 0 #define WCHAR_MAX UINT16_MAX #define WINT_MIN 0 #define WINT_MAX UINT16_MAX #endif /* 7.18.4.1 Macros for minimum-width integer constants */ #define INT8_C(x) ((int8_t) x) #define INT16_C(x) ((int16_t) x) #define INT32_C(x) ((int32_t) x) #define INT64_C(x) ((int64_t) x) #define UINT8_C(x) ((uint8_t) x) #define UINT16_C(x) ((uint16_t) x) #define UINT32_C(x) ((uint32_t) x) #define UINT64_C(x) ((uint64_t) x) /* 7.18.4.2 Macros for greatest-width integer constants */ #define INTMAX_C(x) ((intmax_t) x) #define UINTMAX_C(x) ((uintmax_t) x) #endif /* __STDINT_H */ ================================================ FILE: strtoken.h ================================================ #pragma once //例 // 'a,b,c,d' { "a", "b", "c", "d" } // 'a,,b,c,' { "a", "", "b", "c", "" } // '"a,b",c' { ""a,b"", "c" } class CStringTokenizer { private: enum _Const { MAX_ARGUMENTS = 16, }; int m_nNumArgs; LPTSTR m_ppszArgv[MAX_ARGUMENTS + 1]; LPTSTR m_pszBuffer; void Clear() { m_nNumArgs = 0; ZeroMemory(m_ppszArgv, sizeof(m_ppszArgv)); free(m_pszBuffer); m_pszBuffer = NULL; } public: CStringTokenizer() : m_pszBuffer(NULL) { Clear(); } ~CStringTokenizer() { free(m_pszBuffer); } int GetCount() const { return m_nNumArgs; } LPCTSTR GetArgument(int x) const { Assert(0 <= x && x <= GetCount()); return m_ppszArgv[x]; } int Parse(LPCTSTR pszStr) { Clear(); if (!pszStr || !*pszStr) { return 0; } m_pszBuffer = _tcsdup(pszStr); if (!m_pszBuffer) { return 0; } LPTSTR p = m_pszBuffer, ps; int nNumArgs = 0; LPTSTR* ppszArgv = m_ppszArgv; #define _isspace(ch) (ch == _T('\t') || ch == _T(' ')) for (;;) { CONT: if (nNumArgs >= MAX_ARGUMENTS) { TRACE(_T("Too many arguments (> %d)\n"), MAX_ARGUMENTS); break; } if (*p == _T('\0')) { ppszArgv[nNumArgs++] = p; goto EXIT; } for (; _isspace(*p); *p++); if (*p == _T('\0')) { break; } switch (*p) { case _T(','): *p = _T('\0'); ppszArgv[nNumArgs++] = p++; goto CONT; case _T('"'): p++; ppszArgv[nNumArgs++] = p++; for (; *p && *p != _T('"'); p++); if (*p == _T('\0')) { TRACE(_T("Unterminated string\n")); goto EXIT; } *p++ = _T('\0'); break; default: ppszArgv[nNumArgs++] = p++; ps = p; for (; *p && *p != _T(','); p++); if (*p == _T('\0')) { goto EXIT; } for (p--; _isspace(*p) && p >= ps; p--); p++; break; } if (_isspace(*p)) { for (*p++ = _T('\0'); *p && _isspace(*p); p++); if (*p == _T('\0')) { break; } } for (; *p && *p != _T(','); p++); if (*p == _T('\0')) { break; } *p++ = _T('\0'); } #undef _isspace EXIT: m_nNumArgs = nNumArgs; return nNumArgs; } }; ================================================ FILE: supinfo.h ================================================ #pragma once #include //mmioFOURCC #define FOURCC_GDIPP mmioFOURCC('G', 'D', 'I', 'P') typedef struct { int dummy; FOURCC magic; // BYTE reserved[256]; } GDIPP_CREATE_MAGIC; //参照 //http://www.catch22.net/tuts/undoc01.asp #ifdef _GDIPP_EXE template void FillGdiPPStartupInfo(_STARTUPINFO& si, GDIPP_CREATE_MAGIC& gppcm) { ZeroMemory(&gppcm, sizeof(GDIPP_CREATE_MAGIC)); gppcm.magic = FOURCC_GDIPP; si.cbReserved2 = sizeof(GDIPP_CREATE_MAGIC); si.lpReserved2 = (LPBYTE)&gppcm; } #endif #ifdef _GDIPP_DLL template bool IsGdiPPStartupInfo(const _STARTUPINFO& si) { if(si.cbReserved2 >= sizeof(int) + sizeof(FOURCC)) { GDIPP_CREATE_MAGIC* pMagic = (GDIPP_CREATE_MAGIC*)si.lpReserved2; if (pMagic->dummy == 0 && pMagic->magic == FOURCC_GDIPP) { return true; } } return false; } #endif EXTERN_C BOOL WINAPI GdippInjectDLL(const PROCESS_INFORMATION* ppi); EXTERN_C LPWSTR WINAPI GdippEnvironment(DWORD& dwCreationFlags, LPVOID lpEnvironment); //子プロセスにも自動でgdi++適用 template BOOL _CreateProcessAorW(const _TCHAR* lpApp, _TCHAR* lpCmd, LPSECURITY_ATTRIBUTES pa, LPSECURITY_ATTRIBUTES ta, BOOL bInherit, DWORD dwFlags, LPVOID lpEnv, const _TCHAR* lpDir, _STARTUPINFO* psi, LPPROCESS_INFORMATION ppi, _Function fn) { #ifdef _GDIPP_RUN_CPP const bool hookCP = true; const bool runGdi = true; #else const CGdippSettings* pSettings = CGdippSettings::GetInstance(); const bool hookCP = pSettings->HookChildProcesses(); const bool runGdi = pSettings->RunFromGdiExe(); #endif if (!hookCP || (!lpApp && !lpCmd) || (dwFlags & (DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS | DETACHED_PROCESS))/* || !psi || psi->cb < sizeof(_STARTUPINFO)*/) { return fn(lpApp, lpCmd, pa, ta, bInherit, dwFlags, lpEnv, lpDir, psi, ppi); } PROCESS_INFORMATION _pi = { 0 }; if (!ppi) { ppi = &_pi; } int szpsi = psi ? (psi->cb ? psi->cb: sizeof(_STARTUPINFO)) : sizeof(_STARTUPINFO); _STARTUPINFO& si = *(_STARTUPINFO*)_alloca(szpsi); memset(&si, 0, sizeof(si)); si.cb=szpsi; if (psi && psi->cb) memcpy(&si, psi, psi->cb); psi = &si; GDIPP_CREATE_MAGIC gppcm; if (runGdi && !si.cbReserved2) { FillGdiPPStartupInfo(si, gppcm); } LPWSTR pEnvW = GdippEnvironment(dwFlags, lpEnv); if (pEnvW) { lpEnv = pEnvW; } if (!fn(lpApp, lpCmd, pa, ta, bInherit, dwFlags | CREATE_SUSPENDED, lpEnv, lpDir, &si, ppi)) { ZeroMemory(ppi, sizeof(*ppi)); free(pEnvW); return FALSE; } GdippInjectDLL(ppi); if (!(dwFlags & CREATE_SUSPENDED)) { ResumeThread(ppi->hThread); } free(pEnvW); return TRUE; } template BOOL _CreateProcessAsUserAorW(HANDLE hToken, const _TCHAR* lpApp, _TCHAR* lpCmd, LPSECURITY_ATTRIBUTES pa, LPSECURITY_ATTRIBUTES ta, BOOL bInherit, DWORD dwFlags, LPVOID lpEnv, const _TCHAR* lpDir, _STARTUPINFO* psi, LPPROCESS_INFORMATION ppi, _Function fn) { #ifdef _GDIPP_RUN_CPP const bool hookCP = true; const bool runGdi = true; #else const CGdippSettings* pSettings = CGdippSettings::GetInstance(); const bool hookCP = pSettings->HookChildProcesses(); const bool runGdi = pSettings->RunFromGdiExe(); #endif if (!hookCP || (!lpApp && !lpCmd) || (dwFlags & (DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS))/* || !psi || psi->cb < sizeof(_STARTUPINFO)*/) { return fn(hToken, lpApp, lpCmd, pa, ta, bInherit, dwFlags, lpEnv, lpDir, psi, ppi); } PROCESS_INFORMATION _pi = { 0 }; if (!ppi) { ppi = &_pi; } int szpsi = psi ? (psi->cb ? psi->cb: sizeof(_STARTUPINFO)) : sizeof(_STARTUPINFO); _STARTUPINFO& si = *(_STARTUPINFO*)_alloca(szpsi); memset(&si, 0, sizeof(si)); si.cb=szpsi; if (psi && psi->cb) memcpy(&si, psi, psi->cb); psi = &si; GDIPP_CREATE_MAGIC gppcm; if (runGdi && !si.cbReserved2) { FillGdiPPStartupInfo(si, gppcm); } LPWSTR pEnvW = GdippEnvironment(dwFlags, lpEnv); if (pEnvW) { lpEnv = pEnvW; } if (!fn(hToken, lpApp, lpCmd, pa, ta, bInherit, dwFlags | CREATE_SUSPENDED, lpEnv, lpDir, &si, ppi)) { ZeroMemory(ppi, sizeof(*ppi)); free(pEnvW); return FALSE; } GdippInjectDLL(ppi); if (!(dwFlags & CREATE_SUSPENDED)) { ResumeThread(ppi->hThread); } free(pEnvW); return TRUE; } static wstring GetExeName(LPCTSTR lpApp, LPTSTR lpCmd) { // HANDLE logfile = CreateFile(_T("C:\\mt.log"), FILE_ALL_ACCESS, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, NULL, NULL); // SetFilePointer(logfile,0,NULL, FILE_END); wstring ret; // DWORD aa=0; // if (GetFileSize(logfile, NULL)==0) // WriteFile(logfile, "\xff\xfe", 2, &aa, NULL); LPTSTR vlpApp = (LPTSTR)lpApp; //变成可以操作的参数 if (lpApp) { do { // WriteFile(logfile, L"lpApp=", 12, &aa, NULL); // WriteFile(logfile, lpApp, _tcslen(lpApp)*2, &aa, NULL); // WriteFile(logfile, _T("\n"), 2, &aa, NULL); vlpApp = _tcsstr(vlpApp+1, _T(" ")); //获得第一个空格所在的位置 ret.assign(lpApp); if (vlpApp) ret.resize(vlpApp-lpApp); // WriteFile(logfile, ret.c_str(), ret.length()*2, &aa, NULL); // WriteFile(logfile, _T("\n"), 2, &aa, NULL); DWORD fa = GetFileAttributes(ret.c_str()); if (fa!=INVALID_FILE_ATTRIBUTES && fa!=FILE_ATTRIBUTE_DIRECTORY) //文件是否存在 { int p = ret.find_last_of(_T("\\")); if (p!=-1) ret.erase(0, p+1); //如果有路径就删掉路径 // WriteFile(logfile, ret.c_str(), ret.length()*2, &aa, NULL); // WriteFile(logfile, _T("\n"), 2, &aa, NULL); // WriteFile(logfile, _T("==========\n"), 24, &aa, NULL); // CloseHandle(logfile); return ret; } else { ret+=_T(".exe"); //加上.exe扩展名再试 DWORD fa = GetFileAttributes(ret.c_str()); if (fa!=INVALID_FILE_ATTRIBUTES && fa!=FILE_ATTRIBUTE_DIRECTORY) { int p = ret.find_last_of(_T("\\")); if (p!=-1) ret.erase(0, p+1); //如果有路径就删掉路径 // WriteFile(logfile, ret.c_str(), ret.length()*2, &aa, NULL); // WriteFile(logfile, _T("\n"), 2, &aa, NULL); // WriteFile(logfile, _T("==========\n"), 24, &aa, NULL); // CloseHandle(logfile); return ret; } } } while (vlpApp); } if (lpCmd) { // WriteFile(logfile, L"lpCmd=", 10, &aa, NULL); // WriteFile(logfile, lpCmd, _tcslen(lpCmd)*2, &aa, NULL); ret.assign(lpCmd); int p=0; if ((*lpCmd)==_T('\"')) { ret.erase(0,1); //删除第一个引号 p=ret.find_first_of(_T("\"")); //查找下一个引号 } else p=ret.find_first_of(_T(" ")); if (p>0) ret.resize(p); //获得Cmd里面的文件名 // WriteFile(logfile, ret.c_str(), ret.length()*2, &aa, NULL); // WriteFile(logfile, _T("\n"), 2, &aa, NULL); p = ret.find_last_of(_T("\\")); if (p>0) ret.erase(0, p+1); //如果有路径就删掉路径 // WriteFile(logfile, ret.c_str(), ret.length()*2, &aa, NULL); // WriteFile(logfile, _T("\n"), 2, &aa, NULL); // WriteFile(logfile, _T("==========\n"), 24, &aa, NULL); // CloseHandle(logfile); return ret; } // WriteFile(logfile, ret.c_str(), ret.length()*2, &aa, NULL); // WriteFile(logfile, _T("\n"), 2, &aa, NULL); // WriteFile(logfile, _T("==========\n"), 24, &aa, NULL); // CloseHandle(logfile); return ret; } template BOOL _CreateProcessInternalW(HANDLE hToken, LPCTSTR lpApp, LPTSTR lpCmd, LPSECURITY_ATTRIBUTES pa, LPSECURITY_ATTRIBUTES ta, BOOL bInherit, \ DWORD dwFlags, LPVOID lpEnv, LPCTSTR lpDir, LPSTARTUPINFO psi, LPPROCESS_INFORMATION ppi , PHANDLE hNewToken, _Function fn) { #ifdef _GDIPP_RUN_CPP const bool hookCP = true; const bool runGdi = true; #else const CGdippSettings* pSettings = CGdippSettings::GetInstanceNoInit(); const bool hookCP = pSettings->HookChildProcesses(); const bool runGdi = pSettings->RunFromGdiExe(); #endif #ifdef _GDIPP_EXE if (!hookCP || (!lpApp && !lpCmd) || (dwFlags & (DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS)) || !psi || psi->cb < sizeof(STARTUPINFO)) { return fn(hToken, lpApp, lpCmd, pa, ta, bInherit, dwFlags, lpEnv, lpDir, psi, ppi, hNewToken); } STARTUPINFO& si = *(STARTUPINFO*)_alloca(psi->cb); memcpy(&si, psi, psi->cb); psi = &si; GDIPP_CREATE_MAGIC gppcm; if (runGdi && !si.cbReserved2) { FillGdiPPStartupInfo(si, gppcm); } PROCESS_INFORMATION _pi = { 0 }; if (!ppi) { ppi = &_pi; } LPWSTR pEnvW = GdippEnvironment(dwFlags, lpEnv); if (pEnvW) { lpEnv = pEnvW; } if (!fn(hToken, lpApp, lpCmd, pa, ta, bInherit, dwFlags | CREATE_SUSPENDED, lpEnv, lpDir, psi, ppi, hNewToken)) { ZeroMemory(ppi, sizeof(*ppi)); free(pEnvW); return FALSE; } GdippInjectDLL(ppi); if (!(dwFlags & CREATE_SUSPENDED)) { ResumeThread(ppi->hThread); } free(pEnvW); #else wstring exe_name = GetExeName(lpApp, lpCmd); if (!hookCP || (!lpApp && !lpCmd) || (dwFlags & (DEBUG_PROCESS | DEBUG_ONLY_THIS_PROCESS)) || IsExeUnload(exe_name.c_str())) { return fn(hToken, lpApp, lpCmd, pa, ta, bInherit, dwFlags, lpEnv, lpDir, psi, ppi, hNewToken); } LPWSTR pEnvW = GdippEnvironment(dwFlags, lpEnv); if (pEnvW) { lpEnv = pEnvW; } if (!fn(hToken, lpApp, lpCmd, pa, ta, bInherit, dwFlags | CREATE_SUSPENDED, lpEnv, lpDir, psi, ppi, hNewToken)) { free(pEnvW); return FALSE; } GdippInjectDLL(ppi); if (!(dwFlags & CREATE_SUSPENDED)) { ResumeThread(ppi->hThread); } free(pEnvW); #endif return TRUE; } ================================================ FILE: tlsdata.h ================================================ #pragma once template class CTlsData { private: DWORD tlsindex; CPtrArray* pArray; enum { INVALID_TLS_VALUE = 0xffffffff }; public: T* GetPtr() const { if(tlsindex == INVALID_TLS_VALUE) return NULL; T* pT = reinterpret_cast(::TlsGetValue(tlsindex)); if(pT) return pT; pT = new T; if(!pT) return NULL; if(!::TlsSetValue(tlsindex, pT)) { delete pT; return NULL; } if(pArray) { pArray->Add(pT); } return pT; } bool ProcessInit() { tlsindex = ::TlsAlloc(); if (tlsindex == INVALID_TLS_VALUE) { return false; } pArray = new CPtrArray; if (!pArray) { ::TlsFree(tlsindex); tlsindex = INVALID_TLS_VALUE; return false; } return true; } void ProcessTerm() { if(tlsindex == INVALID_TLS_VALUE) { return; } ThreadTerm(); //これ入れないとリークする ::TlsFree(tlsindex); tlsindex = INVALID_TLS_VALUE; if (pArray) { for(int i = 0; i < pArray->GetSize(); i++) { delete pArray->operator[](i); } delete pArray; pArray = NULL; } } // bool ThreadInit() // { // } void ThreadTerm() { T* pT = reinterpret_cast(::TlsGetValue(tlsindex)); if(pT) { if (pArray) { pArray->Remove(pT); } delete pT; } ::TlsSetValue(tlsindex, NULL); } }; ================================================ FILE: undocAPI.h ================================================ #pragma once typedef struct _UNICODE_STRING2 { USHORT Length; USHORT MaximumLength; PWSTR Buffer; } UNICODE_STRING2; typedef UNICODE_STRING2 *PUNICODE_STRING2; typedef const UNICODE_STRING2 *PCUNICODE_STRING2; const DWORD GT_DEVICE_TO_WORLD = 0x0402; const DWORD GT_WORLD_TO_DEVICE = 0x0204; const DWORD GT_WORLD_TO_PAGE = 0x0203; const DWORD GT_PAGE_TO_DEVICE = 0x0304; typedef int(__stdcall * TGetTextFA)(HDC, int, LPWSTR); typedef BOOL (__stdcall *PFNCreateProcessInternalW) ( HANDLE hToken, LPCTSTR lpApplicationName, LPTSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCTSTR lpCurrentDirectory, LPSTARTUPINFO lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation , PHANDLE hNewToken ); typedef BOOL (WINAPI *PFNCreateProcessW)( __in_opt LPCWSTR lpApplicationName, __inout_opt LPWSTR lpCommandLine, __in_opt LPSECURITY_ATTRIBUTES lpProcessAttributes, __in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes, __in BOOL bInheritHandles, __in DWORD dwCreationFlags, __in_opt LPVOID lpEnvironment, __in_opt LPCWSTR lpCurrentDirectory, __in LPSTARTUPINFOW lpStartupInfo, __out LPPROCESS_INFORMATION lpProcessInformation ); typedef BOOL (WINAPI *PFNCreateProcessA)( __in_opt LPCSTR lpApplicationName, __inout_opt LPSTR lpCommandLine, __in_opt LPSECURITY_ATTRIBUTES lpProcessAttributes, __in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes, __in BOOL bInheritHandles, __in DWORD dwCreationFlags, __in_opt LPVOID lpEnvironment, __in_opt LPCSTR lpCurrentDirectory, __in LPSTARTUPINFOA lpStartupInfo, __out LPPROCESS_INFORMATION lpProcessInformation ); typedef BOOL (WINAPI *PFNIsWow64Process)(HANDLE hProcess, PBOOL Wow64Process ); typedef int (WINAPI * TGdiGetCodePage)(HDC); typedef BOOL (WINAPI * TGetTransform)(HDC, DWORD, XFORM*); typedef BOOL (WINAPI * PFNGetFontResourceInfo)(LPCWSTR, DWORD*, VOID*, DWORD); typedef LONG (WINAPI * PFNLdrLoadDll)( IN PWCHAR PathToFile OPTIONAL, IN ULONG Flags OPTIONAL, IN UNICODE_STRING2* ModuleFileName, OUT HANDLE* ModuleHandle ); typedef BOOL(WINAPI * PFNSetProcessMitigationPolicy)( _In_ PROCESS_MITIGATION_POLICY MitigationPolicy, _In_ PVOID lpBuffer, _In_ SIZE_T dwLength); static TGetTransform GetTransform = (TGetTransform)GetProcAddress(LoadLibrary(_T("gdi32.dll")), "GetTransform"); /*********************************************************************** * GetTransform (GDI32.@) + * + * Undocumented + * + * Returns one of the co-ordinate space transforms + * + * PARAMS + * hdc [I] Device context. + * which [I] Which xform to return: + * 0x203 World -> Page transform (that set by SetWorldTransform). + * 0x304 Page -> Device transform (the mapping mode transform). + * 0x204 World -> Device transform (the combination of the above two). + * 0x402 Device -> World transform (the inversion of the above). + * xform [O] The xform. + * ************************************************************************/ static TGdiGetCodePage GdiGetCodePage = (TGdiGetCodePage)GetProcAddress(LoadLibrary(_T("gdi32.dll")),"GdiGetCodePage"); static TGetTextFA GetTextFaceAliasW= (TGetTextFA)GetProcAddress(LoadLibrary(_T("gdi32.dll")),"GetTextFaceAliasW"); static PFNCreateProcessInternalW CreateProcessInternalW_KernelBase = (PFNCreateProcessInternalW)GetProcAddress(GetModuleHandle(_T("kernelbase.dll")),"CreateProcessInternalW"); static PFNCreateProcessInternalW CreateProcessInternalW = CreateProcessInternalW_KernelBase ? CreateProcessInternalW_KernelBase:(PFNCreateProcessInternalW)GetProcAddress(GetModuleHandle(_T("kernel32.dll")),"CreateProcessInternalW"); //static PFNIsWow64Process IsWow64Process=(PFNIsWow64Process)GetProcAddress(LoadLibrary(L"Kernel32.dll"), "IsWow64Process"); static PFNGetFontResourceInfo GetFontResourceInfo=(PFNGetFontResourceInfo)GetProcAddress(LoadLibrary(L"gdi32.dll"), "GetFontResourceInfoW"); ================================================ FILE: wow64ext.h ================================================ /** * * WOW64Ext Library * * Copyright (c) 2014 ReWolf * http://blog.rewolf.pl/ * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see . * */ #pragma once #include #ifndef STATUS_SUCCESS # define STATUS_SUCCESS 0 #endif #pragma pack(push) #pragma pack(1) template struct _LIST_ENTRY_T { T Flink; T Blink; }; template struct _UNICODE_STRING_T { union { struct { WORD Length; WORD MaximumLength; }; T dummy; }; T Buffer; }; template struct _NT_TIB_T { T ExceptionList; T StackBase; T StackLimit; T SubSystemTib; T FiberData; T ArbitraryUserPointer; T Self; }; template struct _WOW64_CLIENT_ID { T UniqueProcess; T UniqueThread; }; template struct _TEB_T_ { _NT_TIB_T NtTib; T EnvironmentPointer; _WOW64_CLIENT_ID ClientId; T ActiveRpcHandle; T ThreadLocalStoragePointer; T ProcessEnvironmentBlock; DWORD LastErrorValue; DWORD CountOfOwnedCriticalSections; T CsrClientThread; T Win32ThreadInfo; DWORD User32Reserved[26]; //rest of the structure is not defined for now, as it is not needed }; template struct _LDR_DATA_TABLE_ENTRY_T { _LIST_ENTRY_T InLoadOrderLinks; _LIST_ENTRY_T InMemoryOrderLinks; _LIST_ENTRY_T InInitializationOrderLinks; T DllBase; T EntryPoint; union { DWORD SizeOfImage; T dummy01; }; _UNICODE_STRING_T FullDllName; _UNICODE_STRING_T BaseDllName; DWORD Flags; WORD LoadCount; WORD TlsIndex; union { _LIST_ENTRY_T HashLinks; struct { T SectionPointer; T CheckSum; }; }; union { T LoadedImports; DWORD TimeDateStamp; }; T EntryPointActivationContext; T PatchInformation; _LIST_ENTRY_T ForwarderLinks; _LIST_ENTRY_T ServiceTagLinks; _LIST_ENTRY_T StaticLinks; T ContextInformation; T OriginalBase; _LARGE_INTEGER LoadTime; }; template struct _PEB_LDR_DATA_T { DWORD Length; DWORD Initialized; T SsHandle; _LIST_ENTRY_T InLoadOrderModuleList; _LIST_ENTRY_T InMemoryOrderModuleList; _LIST_ENTRY_T InInitializationOrderModuleList; T EntryInProgress; DWORD ShutdownInProgress; T ShutdownThreadId; }; template struct _PEB_T { union { struct { BYTE InheritedAddressSpace; BYTE ReadImageFileExecOptions; BYTE BeingDebugged; BYTE BitField; }; T dummy01; }; T Mutant; T ImageBaseAddress; T Ldr; T ProcessParameters; T SubSystemData; T ProcessHeap; T FastPebLock; T AtlThunkSListPtr; T IFEOKey; T CrossProcessFlags; T UserSharedInfoPtr; DWORD SystemReserved; DWORD AtlThunkSListPtr32; T ApiSetMap; T TlsExpansionCounter; T TlsBitmap; DWORD TlsBitmapBits[2]; T ReadOnlySharedMemoryBase; T HotpatchInformation; T ReadOnlyStaticServerData; T AnsiCodePageData; T OemCodePageData; T UnicodeCaseTableData; DWORD NumberOfProcessors; union { DWORD NtGlobalFlag; NGF dummy02; }; LARGE_INTEGER CriticalSectionTimeout; T HeapSegmentReserve; T HeapSegmentCommit; T HeapDeCommitTotalFreeThreshold; T HeapDeCommitFreeBlockThreshold; DWORD NumberOfHeaps; DWORD MaximumNumberOfHeaps; T ProcessHeaps; T GdiSharedHandleTable; T ProcessStarterHelper; T GdiDCAttributeList; T LoaderLock; DWORD OSMajorVersion; DWORD OSMinorVersion; WORD OSBuildNumber; WORD OSCSDVersion; DWORD OSPlatformId; DWORD ImageSubsystem; DWORD ImageSubsystemMajorVersion; T ImageSubsystemMinorVersion; T ActiveProcessAffinityMask; T GdiHandleBuffer[A]; T PostProcessInitRoutine; T TlsExpansionBitmap; DWORD TlsExpansionBitmapBits[32]; T SessionId; ULARGE_INTEGER AppCompatFlags; ULARGE_INTEGER AppCompatFlagsUser; T pShimData; T AppCompatInfo; _UNICODE_STRING_T CSDVersion; T ActivationContextData; T ProcessAssemblyStorageMap; T SystemDefaultActivationContextData; T SystemAssemblyStorageMap; T MinimumStackCommit; T FlsCallback; _LIST_ENTRY_T FlsListHead; T FlsBitmap; DWORD FlsBitmapBits[4]; T FlsHighIndex; T WerRegistrationData; T WerShipAssertPtr; T pContextData; T pImageHeaderHash; T TracingFlags; }; typedef _LDR_DATA_TABLE_ENTRY_T LDR_DATA_TABLE_ENTRY32; typedef _LDR_DATA_TABLE_ENTRY_T LDR_DATA_TABLE_ENTRY64; typedef _TEB_T_ TEB32; typedef _TEB_T_ TEB64; typedef _PEB_LDR_DATA_T PEB_LDR_DATA32; typedef _PEB_LDR_DATA_T PEB_LDR_DATA64; typedef _PEB_T PEB32; typedef _PEB_T PEB64; struct _XSAVE_FORMAT64 { WORD ControlWord; WORD StatusWord; BYTE TagWord; BYTE Reserved1; WORD ErrorOpcode; DWORD ErrorOffset; WORD ErrorSelector; WORD Reserved2; DWORD DataOffset; WORD DataSelector; WORD Reserved3; DWORD MxCsr; DWORD MxCsr_Mask; _M128A FloatRegisters[8]; _M128A XmmRegisters[16]; BYTE Reserved4[96]; }; struct _CONTEXT64 { DWORD64 P1Home; DWORD64 P2Home; DWORD64 P3Home; DWORD64 P4Home; DWORD64 P5Home; DWORD64 P6Home; DWORD ContextFlags; DWORD MxCsr; WORD SegCs; WORD SegDs; WORD SegEs; WORD SegFs; WORD SegGs; WORD SegSs; DWORD EFlags; DWORD64 Dr0; DWORD64 Dr1; DWORD64 Dr2; DWORD64 Dr3; DWORD64 Dr6; DWORD64 Dr7; DWORD64 Rax; DWORD64 Rcx; DWORD64 Rdx; DWORD64 Rbx; DWORD64 Rsp; DWORD64 Rbp; DWORD64 Rsi; DWORD64 Rdi; DWORD64 R8; DWORD64 R9; DWORD64 R10; DWORD64 R11; DWORD64 R12; DWORD64 R13; DWORD64 R14; DWORD64 R15; DWORD64 Rip; _XSAVE_FORMAT64 FltSave; _M128A Header[2]; _M128A Legacy[8]; _M128A Xmm0; _M128A Xmm1; _M128A Xmm2; _M128A Xmm3; _M128A Xmm4; _M128A Xmm5; _M128A Xmm6; _M128A Xmm7; _M128A Xmm8; _M128A Xmm9; _M128A Xmm10; _M128A Xmm11; _M128A Xmm12; _M128A Xmm13; _M128A Xmm14; _M128A Xmm15; _M128A VectorRegister[26]; DWORD64 VectorControl; DWORD64 DebugControl; DWORD64 LastBranchToRip; DWORD64 LastBranchFromRip; DWORD64 LastExceptionToRip; DWORD64 LastExceptionFromRip; }; // Below defines for .ContextFlags field are taken from WinNT.h #ifndef CONTEXT_AMD64 #define CONTEXT_AMD64 0x100000 #endif #define CONTEXT64_CONTROL (CONTEXT_AMD64 | 0x1L) #define CONTEXT64_INTEGER (CONTEXT_AMD64 | 0x2L) #define CONTEXT64_SEGMENTS (CONTEXT_AMD64 | 0x4L) #define CONTEXT64_FLOATING_POINT (CONTEXT_AMD64 | 0x8L) #define CONTEXT64_DEBUG_REGISTERS (CONTEXT_AMD64 | 0x10L) #define CONTEXT64_FULL (CONTEXT64_CONTROL | CONTEXT64_INTEGER | CONTEXT64_FLOATING_POINT) #define CONTEXT64_ALL (CONTEXT64_CONTROL | CONTEXT64_INTEGER | CONTEXT64_SEGMENTS | CONTEXT64_FLOATING_POINT | CONTEXT64_DEBUG_REGISTERS) #define CONTEXT64_XSTATE (CONTEXT_AMD64 | 0x20L) #pragma pack(pop) #ifdef WOW64EXT_EXPORTS # define SPEC dllexport #define WOW_EXPORT extern "C" __declspec(SPEC) #else # define SPEC dllimport #define WOW_EXPORT extern "C" #endif WOW_EXPORT DWORD64 __cdecl X64Call(DWORD64 func, int argC, ...); WOW_EXPORT DWORD64 __cdecl GetModuleHandle64(wchar_t* lpModuleName); WOW_EXPORT DWORD64 __cdecl GetProcAddress64(DWORD64 hModule, char* funcName); WOW_EXPORT SIZE_T __cdecl VirtualQueryEx64(HANDLE hProcess, DWORD64 lpAddress, MEMORY_BASIC_INFORMATION64* lpBuffer, SIZE_T dwLength); WOW_EXPORT DWORD64 __cdecl VirtualAllocEx64(HANDLE hProcess, DWORD64 lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect); WOW_EXPORT BOOL __cdecl VirtualFreeEx64(HANDLE hProcess, DWORD64 lpAddress, SIZE_T dwSize, DWORD dwFreeType); WOW_EXPORT BOOL __cdecl VirtualProtectEx64(HANDLE hProcess, DWORD64 lpAddress, SIZE_T dwSize, DWORD flNewProtect, DWORD* lpflOldProtect); WOW_EXPORT BOOL __cdecl ReadProcessMemory64(HANDLE hProcess, DWORD64 lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T *lpNumberOfBytesRead); WOW_EXPORT BOOL __cdecl WriteProcessMemory64(HANDLE hProcess, DWORD64 lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T *lpNumberOfBytesWritten); WOW_EXPORT BOOL __cdecl GetThreadContext64(HANDLE hThread, _CONTEXT64* lpContext); WOW_EXPORT BOOL __cdecl SetThreadContext64(HANDLE hThread, _CONTEXT64* lpContext); WOW_EXPORT VOID __cdecl SetLastErrorFromX64Call(DWORD64 status); WOW_EXPORT DWORD64 __cdecl LoadLibraryW64(LPWSTR lpLibFileName); WOW_EXPORT void __cdecl InitWow64ext(); ================================================ FILE: wow64layer.h ================================================ /* #ifndef CONTEXT_i386 #define CONTEXT_i386 0x00010000 // this assumes that i386 and #define CONTEXT_i486 0x00010000 // i486 have identical context records #endif #define WOW64_CS32 0x23*/ #include BOOL XP_GetThreadWow64Context( __in HANDLE Thread, __in_opt HANDLE Process, __inout PWOW64_CONTEXT Ctx32 ) { THREAD_BASIC_INFORMATION ThreadInfo; PWOW64_CONTEXT RemoteCtx; CONTEXT Ctx64; SIZE_T Transferred; ULONG ContextFlags; BOOLEAN CloseProcess; ULONG LastError; CloseProcess = FALSE; Ctx64.ContextFlags = CONTEXT_ALL; // // Determine whether the thread is running in 64-bit mode or not. If it is // running in 64-bit mode then we'll get the saved 32-bit context out of // the pointer in the 64-bit TEB's TLS slot. // // If, however, the thread is running in 32-bit mode, then we'll need to be // converting the 32-bit halves of the 64-bit registers into the // appropriate fields of the WOW64_CONTEXT structure. // if (!GetThreadContext( Thread, &Ctx64)) return FALSE; if (Ctx64.SegCs != WOW64_CS32) { wprintf(L" -- Target is in 64-bit mode, returning saved 32-bit context\n"); // // The thread is running in 64-bit mode. We'll need to find the base // address of the thread's TEB and from there, read the remote TLS // slots and then the actual WOW64_CONTEXT structure residing within // the target. // // Also, if the caller didn't supply a process handle, then we'll // attempt to open one now using the thread's associated process ID in // the THREAD_BASIC_INFORMATION structure. This is the typical // behavior of the Wow64 implementation of GetThreadContext. // if (!NT_SUCCESS(NtQueryInformationThread( Thread, ThreadBasicInformation, &ThreadInfo, sizeof( THREAD_BASIC_INFORMATION ), 0 ))) { SetLastError( ERROR_INVALID_HANDLE ); return FALSE; } // // If we don't have a process handle then we'll need to be opening one // ourselves for the VM read operation. // if (!Process) { Process = OpenProcess( PROCESS_VM_READ, FALSE, HandleToUlong(ThreadInfo.ClientId.UniqueProcess) ); if (!Process) return FALSE; CloseProcess = TRUE; } // // Fetch the second TLS slot. Wow64 assumes (hardcoded) that the // second TLS slot is the WOW64_CONTEXT. This is a bit sloppy, but it // works out as there's not a 64-bit kernel32.dll loaded in a Wow64 // process, so there won't be anyone calling TlsAlloc anyway. // if (!ReadProcessMemory( Process, &((PTEB)ThreadInfo.TebBaseAddress)->TlsSlots[ 1 ], &RemoteCtx, sizeof( PWOW64_CONTEXT ), &Transferred)) { if (CloseProcess) { LastError = GetLastError(); CloseHandle( Process ); SetLastError( LastError ); } return FALSE; } if (Transferred != sizeof( PWOW64_CONTEXT )) { if (CloseProcess) CloseHandle( Process ); SetLastError( ERROR_PARTIAL_COPY ); return FALSE; } // // Now that we've got the PWOW64_CONTEXT pointer, let's read the memory // where the actual context is stored. // // Note that this is unreliable if the remote thread is still running // when we make the call. // // // TODO: Pay attention to the caller's requested context flags and // filter the returned context appropriately. // if (!ReadProcessMemory( Process, (PUCHAR)(RemoteCtx) + sizeof( ULONG ), Ctx32, sizeof( WOW64_CONTEXT ), &Transferred )) { if (CloseProcess) { LastError = GetLastError(); CloseHandle( Process ); SetLastError( LastError ); } return FALSE; } if (Transferred != sizeof( WOW64_CONTEXT )) { if (CloseProcess) CloseHandle( Process ); SetLastError( ERROR_PARTIAL_COPY ); return FALSE; } // // All done. // } else { wprintf(L" -- Target is in 32-bit mode, truncating 64-bit registers\n"); // // The requested thread is executing 32-bit instructions and is not in // the Wow64 layer (e.g. a system call). This means that the 64-bit // thread context is actually reflective of the Wow64 context, except // that we need to convert from an x64 context strucuture to the // WOW64_CONTEXT structure (the high halves of registers are discarded // here). // ContextFlags = Ctx32->ContextFlags | CONTEXT_i386; ZeroMemory( Ctx32, sizeof( WOW64_CONTEXT ) ); Ctx32->ContextFlags = ContextFlags; if (ContextFlags & CONTEXT_CONTROL) { Ctx32->Eip = (ULONG)Ctx64.Rip; Ctx32->EFlags = (ULONG)Ctx64.EFlags; Ctx32->Esp = (ULONG)Ctx64.Rsp; Ctx32->Ebp = (ULONG)Ctx64.Rbp; } if (ContextFlags & CONTEXT_INTEGER) { Ctx32->Eax = (ULONG)Ctx64.Rax; Ctx32->Ebx = (ULONG)Ctx64.Rbx; Ctx32->Ecx = (ULONG)Ctx64.Rcx; Ctx32->Edx = (ULONG)Ctx64.Rdx; Ctx32->Edi = (ULONG)Ctx64.Rdi; Ctx32->Esi = (ULONG)Ctx64.Rsi; } // // TODO: Convert other registers, pay attention to the caller's // requested context flags. For example, floating point registers // would need to be handled here if support for them is desired. // // // All done. // } if (CloseProcess) CloseHandle( Process ); return TRUE; }