Wx collection series: A detailed description of wxwindows

Source: Internet
Author: User
Tags gtk

What is interesting in this document is that it focuses on some details of Wx and some useful but rarely detailed classes or WX features. The layout is completed.

Dish

Wxwindows library, whether or not it is compiled as a dynamic link library (DLL), there may be very small execution bodies. It also provides various features for multi-platform development: OpenGL interfaces and built-in support for HTML, Unicode, and internationalization. It can help you port applications from Windows-only MFC (Microsoft Foundation Classes) to other platforms, such as Linux. Wxwindows is designed to run on as many platforms as possible to support almost every available c ++ compiler. It does not yet use all the features of Standard C ++ (such as namespaces, STD: String classes, and STL containers ). However, the standard C ++ has been listed on the agenda and has some support for the new type conversion syntax and STD: string.

Brief history

Julian smart started wxwindows Research at the University of Edinburgh Institute of Artificial Intelligence Application in 1992. In 1995, Markus holzem released its wxwindows porting to XT (x Toolkit. After stopping for a period of time, in May 1997, windows and GTK + were merged and placed into the CVS resource library, which can be used by anyone who contributes to wxwindows. By the end of 97, Julian smart began distributing wxwindows CD-ROM, including complete source code, compiler material, and more.

Wxwindows is currently released under GPL, but with one exception: binary executable files without source code can be distributed. This is a good choice for commercial projects. It has a variety of UNIX, Microsoft Windows, and Macintosh OS versions. Porting to OS/2 and other operating systems is also under development. Now, let's start to enter the body with rich content...

Platform to be used

Because wxwindows can use local controls at any time, it treats widgets in a different way than most other multi-platform GUI Libraries. We can emulate the unavailable controls, such as tree controls in UNIX. This will provide users with a similar appearance and feeling. The wxwindows library currently supports the following platforms:

  • Windows 3.1, Windows 95/98, Windows NT
  • Most UNIX versions with Motif/lesstif
  • Most UNIX versions with GTK +
  • Mac

Wxbase libraries with only non-Gui classes can also be built under UNIX/Win32 and BEOs (with some restrictions ). Even if you do not compile wxwindows as a DLL, you can obtain very small executable files. For example, the minimum sample application compiled using Microsoft Visual C ++ on Windows is less than 400 kb. Because wxwindows's executable program is very small, it can usually avoid the so-called "DLL disaster ".

Now, let's take a look at the features of multiple platforms...

Architecture-independent type

To avoid the dependency of the architecture, the database provides various types and macros independent of the architecture, which can process bit exchanges based on the tail number of the application. They include:

  • Wxint32 (32-bit signed integer)
  • Wxint16 (16-bit signed integer)
  • Wxint8 (8-bit signed integer)
  • Wxuint32 (32-bit unsigned integer)
  • Wxuint16 = wxword (16-bit unsigned integer)
  • Wxuint8 = wxbyte (8-bit unsigned integer)

Bitwise exchange macros can be used for integers and unsigned integers (XX represents 16 or 32, be represents the big ending number method, and Le represents the small ending number method .)

  • Wxintxx_swap_on_be ()
  • Wxuintxx_swap_on_be ()
  • Wxintxx_swap_on_le ()
  • Wxuintxx_swap_on_le ()
  • Wxintxx_swap_always ()
  • Wxuintxx_swap_always ()

The usage here is very direct, as shown in the following example:

32-bit byte exchange of signed integer variables

wxInt32 old_var = 0xF1F2F3F4;
wxInt32 new_var = wxINT32_SWAP_ALWAYS( old_var );

In addition to these macros, wxwindows also provides#defineTo define the current ending number of the machine (compiled by the database. The following is an example:

Use # define

if ( wxBYTE_ORDER == wxLITTLE_ENDIAN )
{
// Do stuff for little endian machine...
}
else
{
// Do stuff for big endian machine...
}

File Processing

It is always difficult to compile different platforms with different file storage concepts. To overcome this problem, wxwindows has some functions for multi-platform file processing. First, let's look at some functions for basic file operations (such as copying, deleting, and renaming.

Basic File Operations

wxString old_report = "smithers_00.doc";
wxString new_report = "my_smithers.doc";
if ( wxCopyFile( old_report, "smithers_00.bak" ) == true )
{
if ( wxRemoveFile( old_report ) == true )
{
if ( wxRenameFile( new_report, old_report ) == false )
{
// Doh!
}
}
}

Another serious problem caused by writing on different platforms is directory separation,wxPathListClass to completely avoid this problem.wxPathListContains the list of directories used to search for files. To search for a file, you only need to pass the file namewxPathListClass to search for pre-defined directories.

Wxpathlist class

wxPathList path_list;
// Add current working directory
path_list.Add( "." );

// Add one directory above current working directory
path_list.Add( ".." );
// Add directories from environment variable PATH to the list
path_list.AddEnvList( "PATH" );
wxString path = path_list.FindValidPath( "homer.bmp" );

Wxwindows has two useful functions:wxFileNameFromPath(), Used to strip the file name from the complete path, andwxPathOnly()To strip the path from the complete path.

Html

Vaclav Slavik's wxhtml library performs syntax analysis on basic HTML and generates HTML. It does not fully implement HTML standards, but its functions are sufficient for online processing Help. It can also be extended using the tag handler. To display HTML, you must create a class namedwxHtmlWindow. Then, call its method to set the relevant framework and related status bar. The former is used to actually display HTML, and the latter is used to display messages generated by the HTML syntax analyzer.

Wxhtml

wxHtmlWindow html_window = new wxHtmlWindow( this );
html_window->SetRelatedFrame( this, "HTML : %%s" );
html_window->SetRelatedStatusBar( 0 );

Then, you can use the following function to load the HTML page:

Load HTML

html_window->LoadPage( "burns.htm" );

You can also use the following function to display HTML code.

Show html

html_window->SetPage( "

Image

wxImageClass uses an image format processing program to mount different image file formats. You can implement your own image format processing program and expand wximage to mount the new image format. Existing image format processing programs use well-known libraries, such as Sam Leffler's LibTIFF library or an independent JPEG group's JPEG library. There are some processing programs for BMP, PNG, JPEG, GIF, PCX, PNM, And Tiff. You can activate each image format processing program by using the static method addhandler () of wximage class in the code.

Wximages

bool MyApp::OnInit()
{
wxImage::AddHandler( new wxPNGHandler );
// more ...
}

To use all existing image format processing programs, you only need to call the FunctionwxInitAllImageHandlers()Instead ofAddHandler()Method.

Be careful when using toolbar bitmaps in applications on other platforms. On Windows, you will see the Windows bitmap format, but the Linux bitmap is usually pixmaps. In this case, Conditional compilation cannot be completely avoided. Let's look at some sample code.

#if defined(__WXGTK__) || defined(__WXMOTIF__)
#include "maggie.xpm"
#endif
// more ...
void MyApp::UseBitmap()
{
wxBitmap bitmap( wxBITMAP( maggie ));
// more ...
}

Do you understand? All effects are causedwxBITMAP(). For Windows and OS/2, it will use the 'magine' bitmap in the Application resource to createwxBitmapObject. For all other platforms, it will use pixmap called 'Maggie _ XPM 'to createwxBitmapObject.

When you can usewxDC::DrawBitmap()When creating a bitmap in a device context, you must use it for image operations.wxImageObject, as shown below.

Image operations

wxImage* p_image = new wxImage( bitmap );
// Have some fun
if ( p_image->Ok() )
{
if ( p_image->GetHeight() > 50 && p_image->GetWidth() > 50 )
{
unsigned char red = p_image->GetRed( 50, 50 );
unsigned char green = p_image->GetGreen( 50, 50 );
unsigned char blue = p_image->GetBlue( 50, 50 );
// Secure but might be slow
p_image->SetRGB( 50, 50, red, green, blue );
// If you want fast action use a pointer...
unsigned char* data = p_image->GetData();
// Manipulate the data...
}
}

Unicode and internationalization (i18n)

When developing software for the international market, you cannot expect everyone to read application messages in English. However, the widely used ANSI Code cannot process all language symbols. (For example, it cannot process Chinese characters .) Writing ANSI and Unicode at the same time is complicated. You can learn this from the following example:

ANSI and Unicode

#ifdef USE__UNICODE
wchar_t wide_char = L'h';
wchar_t const* wide_string = L"Hello, World!";
int length = wcslen( wide_string );
#else
char ansi_char = 'h';
char const* ansi_string = "Hello, World!";
int length = strlen( ansi_string );
#endif

To use wxwindows Unicode, you only need to write the following code:

Wxt () macro and wxchar and wxstring

wxChar wx_char = wxT( '*' );
wxString wx_string = wxT( "Hello, World!" );
int length = wx_string.Len();

wxT()Macros andwxCharAndwxStringClass will handle all problems. The library uses this method internally for all messages. Currently, there are available translations of Czech, Danish, German, French, Italian and Russian, but you canwxLocaleWith the help of class, compile the local version of the library and then use it.

Debugging

The Library provides various classes, functions, and macros to help you debug applications. If you compile the library by debuggingwxObject(The base class of most classes in wxwindows)newAnddeleteThe operator has been redefined to store additional information about objects allocated on the stack. You can use the classwxDebugContextTo obtain detailed information about object allocation, memory leakage, overwriting, and writing.

// Start logging for Dump() call
wxDebugContext::SetCheckpoint();
wxString *thing = new wxString;
wxDate* date = new wxDate;
// non-object allocation
char *ordinaryNonObject = new char[1000];
// more ...
// Print number of object and non-object allocations
wxDebugContext::Dump();
// Print allocation statistics
wxDebugContext::PrintStatistics();

PairwxDebugContext::Dump()Will pop up a window containing the allocation list. You can see this list below, which is created using the memcheck sample provided by wxwindows.

Call wxdebugcontext: dump ()

13:32:45: ----- Memory dump of memcheck at Tue Dec 26 13:32:45 2000 -----
13:32:45: ../../../samples/memcheck/memcheck.cpp(88): non-object data at $DD3DC0, size 4
13:32:45: ../../../samples/memcheck/memcheck.cpp(89): wxDate at $DD40D0, size 24
13:32:45: ../../../samples/memcheck/memcheck.cpp(92): non-object data at $DD4118, size 1000

PairwxDebugContext::PrintStatistics()Provides some statistical information, as shown below.

Call wxdebugcontext: printstatistics ()

13:32:45: ----- Memory statistics of memcheck at Tue Dec 26 13:32:45 2000 -----
13:32:45: 1 objects of class wxDate, total size 24
13:32:45: 5 objects of class nonobject, total size 4256
13:32:45: 13:32:45: Number of object items: 1
13:32:45: Number of non-object items: 5
13:32:45: Total allocated size: 4280

Port the MFC Application to Linux

The wxwindows library can also port the MFC Application to Linux and other operating systems. You will see in the following code excerpt that the wxwindows string classwxStringAnd MFC string classCStringThere are some similarities.

Wxstring

wxString s1 = "Hello, World!";
wxString s2 = "Hello";
if ( s1.IsEmpty() == false )
{
s2.Empty();
s2 = s1.Left( 5 );
int pos = s1.Find( ',' );
s2 += s1.Mid( pos, 2 );
s2 += s1.Right( 6 );
}

Wxwindows's event system is very similar to MFC. The message ing table maps the event handler Method to the Event System. In wxwindows, these are called event tables. The message ing between the event table macro and MFC is only one difference. The main differences are shown in the source code below.

Header file MFC code

class CButtonCtrl : public COleControl
{
// Implementation
protected:
LRESULT OnOcmCommand( WPARAM wParam, LPARAM lParam );
DECLARE_MESSAGE_MAP()
};

Implementation file MFC code

BEGIN_MESSAGE_MAP( CButtonCtrl, COleControl )
//{{AFX_MSG_MAP( CButtonCtrl )
ON_MESSAGE( OCM_COMMAND, OnOcmCommand )
//}}AFX_MSG_MAP
END_MESSAGE_MAP()

Wxwindows code for header files

class MyButton : public wxButton
{
void OnButton( wxMouseEvent& event )
private:
DECLARE_EVENT_TABLE()
};

Wxwindows code for implementing files

BEGIN_EVENT_TABLE( MyButton, wxButton )
EVT_BUTTON( -1, MyButton::OnButton )
END_EVENT_TABLE()

As you can see, there is no difference. A considerable number of people in the email list have successfully migrated their existing MFC applications to wxwindows (and we are very willing to help you :).

Standard C ++

Wxwindows does not use standard C ++ technology (for examplestd::string, STL, or namespace), because this will greatly reduce the number of platforms on which wxwindows can compile. (Only a few compilers fully support the latest features of the Standard C ++ .) However, as standard C ++ becomes more and more widely supported, the wxwindows Development Group will integrate the support for Standard C ++ into its library. Let's see what they have done.

Secure downward type conversion written in standard C ++

class A 
{
virtual void foo() {};
};
class B : public A {};
A* p_A = new B();
B* p_B = dynamic_cast(p_A);      

If there are any errors,p_BIt will contain 0 pointers. In wxwindows, you will find that a macro-based system is used for runtime type information, but for the above C ++ code, you must use the following methodswxDynamicCast()MACRO:

Wxdynamiccast () macro for Standard C ++

B* p_B = wxDynamicCast( p_A, B );

If type conversion fails,p_BIt will contain 0 pointers. For the implementation of the new type conversion syntax, the macro extension isdynamic_cast<>. Unfortunately, macros only work for pointers, but not references. BesideswxDynamicCast()In addition to macroswxStaticCast()AndwxConstCast()Macro.

Wxwindows string classwxStringProvides a standard string class method of 90%. Here are some examples:

Wxwindows 'wxstring

wxString s1 = "Hello, World!";
wxString s2 = "Hello";
s2.erase();
for ( size_t i = 0; i < s1.length(); ++i )
s2 += s1[i];
if ( s1.compare( s2 ) == 0 )
{
// Strings are equal
}

Note that ifwxString typedefIsstd::stringWxwindows and Standard C ++.

Document

Wxwindows documentation is not excellent at present. Although some old classes (suchwxString) The documentation is complete, but for recently implemented classes (suchwxGrid) Or a more fuzzy class (for examplewxGLCanvas. This document provides a quick introduction to libraries and their concepts, class references in alphabetical order, programming strategies, topic overview, and some comments on wxhtml and wxpython, HTML, winhelp, Ms HTML Help, and PDF are provided (see references ).

If you are new to wxwindows, you should start with the topic overview. They provide many basic information and code examples related to common topics (such as debugging, event processing, printing, and so on. The main document also contains some technical instructions and Tutorials that provide topic information ranging from very common issues related to wxwindows to compiler-specific issues. You will also get a large number of plain text files, including installation and release instructions for supported platforms. The wxwindows release also provides approximately 50 sample applications along with the documentation.

Supported

What if you encounter a problem when using the library and cannot find the answer in the document? Don't worry. Generally, you have two options: free support for the mail list or commercial support. If you need quick answers unfortunately, it may be better to use commercial support. Although core developers always pay attention to the email list, they are often busy and cannot respond immediately. However, you can obtain the answer within one or two days. (If the question is not very common or complex, you should wait for at least two days before submitting the question again .) You can access the latest source code from the CVS source code database on SourceForge (see references.

Summary

Now you know what wxwindows is and what products and services it provides for multi-platform development. But of course, these are not all. Take the current wxstudio project as an example. It uses wxwindows to develop Microsoft Visual Studio similar to IDE. Or wxcvs project, which is used for the multi-platform GUI of the CVS system. Or wxdesigner, which is a rad tool developed by Robert Roebling to build the wxwindows dialog box. You should find that the wxwindows community is growing, so pay attention to it the next time you will develop a multi-platform project.

The names of all products mentioned are trademarks or registered trademarks of their respective owners.

References

  • For more information, see the original article on the developerworks global site.

  • View wxwindows homepage carefully
  • Read about wxwindows on SourceForge
  • Wxstudio is a research plan for creating a free and cross-platform integrated development environment.
  • Wxdesigner is available for Windows and Unix
  • Wxpros is a resource organization for wxwindows and wxpython professionals

About the author

 

Markus neifer initially started programming with the help of the logo turtles, after which he used various basic versions. While studying geographic information, he learned C for a while, but then quickly switched to C ++ and Java because they have an object-oriented nature. He worked in R & D, where he published an article on Object-Oriented scientific software development. Now he is a software engineer in the geographic information system field. You can contact him through the markusneifer@my-deja.com.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.