Editors API: Using the Editors API

This section advises on how to utilize the Editors API to implement the use cases that were listed earlier. The examples above will use some common assumptions. CMyContainer is an imaginary container control which has an iEditor member which is declared as required by the editor type being discussed. E.g. in the next section it is declared as CEikEdwin* and when describing numeric editors it is declared as CAknIntegerEdwin*.

Constructing Plain Text editors

Constructing Plain Text editors from resource file

A text editor resource is defined as an EDWIN structure in a resource file. The EDWIN structure is defined in eikon.rh as follows:

STRUCT EDWIN

    {

    LONG flags=0;

    WORD width=0;

    WORD lines=1;

    WORD maxlength=0;

    AKN_EDITOR_EXTENSIONS

    }

Note: Symbian OS versions older than v9.1 (S60 releases 1.x and 2.x) specify the text editor resource in the uikon.rh file.

The meaning of the fields in the EDWIN structure is described in Table 1.

Table 1: Text editor resource structure fields
FieldMeaning
FlagsBit field of flags describing properties of the editor control to be created. These flags are defined in CEikEdwin::TFlags. The properties are listed and described in Miscellaneous Properties.
WidthThe width of the control; can be specified either by the number of characters or by pixels depending on whether the flag EEikEdwinWidthInPixels is specified; if specified by the number of characters, the widest character of the chosen font is used to determine the actual width of the control.
LinesThe number of text lines that the editor will display at once.
maxlengthThe maximum number of characters that can be stored in the editor control.

AKN_EDITOR_EXTENSIONS defines more fields to the resource. These fields are specific to the S60 platform. The extensions contain the following fields:

The roles of the AKN_EDITOR_EXTENSIONS fields are summarized in Table 2.

Table 2: S60 platform-specific text editor resource structure fields
FieldMeaning
default_caseThe default case to apply when receiving user input (input modes and cases are described in Input Mode and Case).
allowed_case_modesThe allowed case modes; the value set for default_case must be included in this field.
numeric_keymapThe numeric key map to be used when the editor is in numeric entry mode.
allowed_input_modes
The allowed input modes (input modes and cases are described in Input Mode and Case); as in case modes, the value set for default_input_mode must be included in this field.
default_input_modeThe default input mode.
special_character_tableThe special character table to be displayed on user request. Special character tables are described in Special Character Tables.
Avkon_flagsBit field of editor flags specific to the S60 platform.
max_view_height_in_linesEditor's maximum height in lines
base_line_deltaUnused
SpareUnused

The code snippets below demonstrate how to construct a plain text editor. The following example resource structure will be used:

RESOURCE EDWIN r_editapp_ptx_edit

	{

	width=30;

	maxlength = 200;

	lines = 2;

	}

Notice that the default resource field values are being utilized.

In case of plain text editor iEditor is declared as a CEikEdwin* member.

void CMyContainer::ConstructL(const TRect& aRect)

    {

    // Create a window for the container

    CreateWindowL();

    // Allocate the editor object in memory

    iEditor = new ( ELeave )CEikEdwin;

    // Share container’s window with editor

    iEditor->SetContainerWindowL( *this );

    TResourceReader reader;

    // Set up the resource reader

    iCoeEnv->CreateResourceReaderLC( reader, R_EDITAPP_PTX_EDIT );

    // Construct the editor

    iEditor->ConstructFromResourceL( reader );

    CleanupStack::PopAndDestroy();

    // Set the focus on editor

    iEditor->SetFocus( ETrue );

    // Layout the container

    SetRect( aRect );

    // Activate container and its children (this time only the editor)

    ActivateL();

    }

Constructing Plain Text editors from code

Another alternative is to call the editor’s second phase constructor and create the CEikEdwin object fully programmatically. Below in CEikEdiwn::ConstructL() the parameters match the fields specified in the r_editapp_ptx_edit resource above this leading to an editor with the same properties.

void CMyContainer::ConstructL(const TRect& aRect)

    {

    // Create a window for the container

    CreateWindowL();

    // Allocate the editor object in memory

    iEditor = new ( ELeave )CEikEdwin;

    // Share container’s window with editor

    iEditor->SetContainerWindowL( *this );

    // Construct the editor with the parameters as from resource

    iEditor->ConstructL( 0, 30, 200, 2);

    // Set the focus on editor

    iEditor->SetFocus( ETrue );

    // Layout the container

    SetRect( aRect );

    // Activate container and its children (this time only the editor)

    ActivateL();

    }

S60 specific settings, which correspond to resource fields described in Table 2, can be set from code directly as described in Setting and Getting the Cursor Position of CEikEdwin based editors.

Common practices

The standard control mechanisms should be applied also in case of editors irrespective of how they were constructed.

void CMyContainer::SizeChanged()

    {

    // Set the size of the editor

    // Use AknLayouUtils for a real-life app

    iEditor->SetExtent( TPoint (10,50), TSize(156,45) );

    }



TInt CMyContainer::CountComponentControls() const

    {

    // Number of child controls (this time the iEditor only)

    return 1;

    }



CCoeControl* CMyContainer::ComponentControl(TInt aIndex) const

    {

    switch (aIndex)

        {

        case 0:

            return iEditor;

        default:

            return NULL;

        }

     }



TKeyResponse CEditappView1Container::OfferKeyEventL(const TKeyEvent& aKeyEvent,TEventCode aType)

    {

    // Forward key events to editor. In real life only do this if editor is focused

    return iEditor->OfferKeyEventL(aKeyEvent, aType);

    }

Performing basic Plain Text manipulation through CEikEdwin based editors

When using CEikEdwin class as Plain Text Editor then setting the text content and retrieving it can be considered the main operations of manipulation. When dealing with plain text it is unnecessary to deal with the content model CEikEdwin uses instead use the convenience methods that hide the complexity of the actual document object.

It is fairly intuitive to get hold of the text stored in the editor:

HBufC* CMyContainer::EditorTextLC() const

    {

    HBufC* text = iEditor->GetTextInHBufL();

    // Push it on cleanup stack as indicated by LC

    CleanupStack::PushL( text );

    }

If there is an already pre-allocated buffer into which you want to load the text then use the GetText() function instead and pass it the descriptor associated with the buffer.

The text can be changed anytime as shown in the following code snippet.

void CMyContainer::AddMytextL()

    {

    _LIT( KMyText, "This is my text" );

    // () operator will return a TDesC reference

    iEditor->SetTextL( &KMyText() );

    }

SetTextL() will perform all the necessary steps needed to update the editor on screen. As a consequence there is no need to call the editor’s HandleTextChangedL() or DrawNow().

Constructing Global Text editors and Rich Text editors

Constructing Global Text editors and Rich Text editors from resource file

Global and Rich text editor resource structures are identical even if they are defined separately. This section will cover them both.

The global text editor resource is defined by the GTXTED resource structure. The GTXTED structure is defined in eikon.rh as follows:

STRUCT GTXTED

    {

    WORD width=0;

    WORD height=0;

    WORD numlines=1;

    WORD textlimit=0;

    LONG flags=0;

    WORD fontcontrolflags=1;

    WORD fontnameflags=EGulNoSymbolFonts;

    AKN_EDITOR_EXTENSIONS

    }

And the very same fields for the Rich Text Editor:

STRUCT RTXTED

    {

    WORD width=0;

    WORD height=0;

    WORD numlines=1;

    WORD textlimit=0;

    LONG flags=0;

    WORD fontcontrolflags=1;

    WORD fontnameflags=EGulNoSymbolFonts;

    AKN_EDITOR_EXTENSIONS

   }

The global and the rich text editor resource definitions contain some extra fields when compared to the EDWIN resource structure. These fields are described in Table 3.

Table 3: Global and rich text editor resource structure field
FieldMeaning
fontcontrolflagsBit field of flags describing font control properties of the global or rich text control. These flags are defined in gulftflg.hrh and follow the naming convention of EGulFontControlXxx. The default value 1 (EGulFontControlAll) provides all font controls to the editor control.
fontnameflagsBit field describing the font types available to the editor control. These flags are defined in gulftflg.hrh beginning with EGulAllFonts.

The initialization of the Global and Rich Text Editors is done in the same way as with Plain Text editors.

void CMyContainer::ConstructL(const TRect& aRect)

    {

    // Create a window for the container

    CreateWindowL();

    // Allocate the editor object in memory

    iEditor = new ( ELeave )CEikRichTextEditor;

    // Share container’s window with editor

    iEditor->SetContainerWindowL( *this );

    TResourceReader reader;

    // Set up the resource reader

    iCoeEnv->CreateResourceReaderLC( reader, R_EDITAPP_RTX_EDIT );

    // Construct the editor

    iEditor->ConstructFromResourceL( reader );

    CleanupStack::PopAndDestroy();

    // Set the focus on editor

    iEditor->SetFocus( ETrue );

    // Layout the container

    SetRect( aRect );

    // Activate container and its children (this time only the editor)

    ActivateL();

    }

Here R_EDITAPP_RTX_EDIT refers to a rich text resource. Here is an example:

RESOURCE RTXTED r_editapp_ptx_edit

	{

	width=30;

	maxlength = 200;

	lines = 2;

	}

Constructing Global Text editors and Rich Text editors from code

When creation happens purely from code use the second phase constructor instead of ConstructFromResourceL().

void CMyContainer::ConstructL(const TRect& aRect)

    {

    // Create a window for the container

    CreateWindowL();

    // Allocate the editor object in memory

    iEditor = new ( ELeave )CEikRichTextEditor;

    //Construct the editor

    iEditor->ConstructL( this, 2, 200, 0 );

    // Set the focus on editor

    iEditor->SetFocus( ETrue );

    // Layout the container

    SetRect( aRect );

    // Activate container and its children (this time only the editor)

    ActivateL();

    }

Note that here there is no need to call SetContainerWindowL() as the ConstructL() will do it. (The first parameter is the parent which will provide the window for it).

Performing Advanced Text manipulation

The text contained in editor controls is stored in a text object instantiated from class CEditableText or from a class derived from it. The following sections describe its usage in manipulating the contents and formatting the text editor controls.

Using selection

Text editor controls allow the user to select some or all of the contents of the editor. The application can then provide functionality concerning only the selection, such as clipboard operations or text formatting.

The API for manipulating the current selection of text editor is straightforward. It consists of five methods provided by the class CEikEdwin: getting the length (SelectionLength()) and position (Selection()) of the current selection, clearing the selection (ClearSelectionL()), and selecting some (SetSelectionL()) or all (SelectAllL()) of the contents.

The following sample code removes the selected text area:

// Get selection position

TCursorSelection pos = iEditor->Selection();

// Get text contents

CPlainText* text = iEditor->Text();

// Remove the selected text

text->DeleteL(pos.LowerPos(), pos.Length());

Specifying global format

The global text editor control and the rich text editor control provide support for text formatting. This section describes the classes responsible for storing the formats and the methods to apply global format to the editor (i.e. A format that is in effect for all the content of the editor).

Text formatting is performed in two levels: at the paragraph level and at the character level. The paragraph formatting is performed through the class CParaFormat. With the global text editor, all paragraphs assume the same paragraph formatting style. With the rich text editor, the paragraph formatting style can be specified individually to each paragraph of the text. The character formatting is accomplished with class TCharFormat.

The properties available for paragraph formatting are listed in Table 4. These properties are accessible through public members in instances of class CParaFormat.

Table 4: Paragraph formatting properties
FieldMeaning
iBorderMarginInTwipsThe distance between the paragraph border and the paragraph text in twips.
iBulletThe bullet point used in the paragraph. A NULL value indicates no bullet point.
iDefaultTabWidthInTwipsThe default tab stop width in twips.
iFillColorThe background color of the paragraph. The default is the system background color.
iHorizontalAlignmentThe horizontal alignment of the paragraph.
iIndentInTwipsThe indent of the first line of a paragraph in twips relative to the left margin.
iKeepTogetherFlag for preventing page breaks inside the paragraph.
iKeepWithNextFlag for preventing page break between this and the next paragraph.
iLanguageThe language of the paragraph. Used in, for example, spell checking purposes.
iLeftMarginInTwipsThe width of the left margin in twips.
iLineSpacingInTwipsThe inter-line spacing within the paragraph.
iLineSpacingControlWhether iLineSpacingInTwips means 'at least' or 'exactly'
iRightMarginInTwipsThe width of the right margin in twips.
iSpaceAfterInTwipsThe height of space below the paragraph in twips.
iSpaceBeforeInTwipsThe height of space above the paragraph in twips.
iStartNewPageFlag for inserting a page break immediately before this paragraph.
iVerticalAlignmentThe vertical alignment of the paragraph.
iWidowOrphanFlag for preventing the printing of the last line of this paragraph at the top of the page (widow) or the first line of this paragraph at the bottom of the page (orphan).
iWrapFlag for line wrapping at the right margin.

In addition to these formatting properties, the paragraph formatting object also allows specification of tab stops and paragraph borders.

The formatting properties at the character level are listed in Table 5. These properties are accessible through public members of the iFontPresentation structure in instances of class TCharFormat.

Table 5: Character formatting properties
FieldMeaning
iTextColorThe text color.
iHighlightColorThe text color used for selected text.
iHighlightStyleThe highlighting style.
iStrikethroughThe value of the strikethrough attribute.
iUnderlineThe value of the underline attribute.
iHiddenTextSpecifies whether the text is hidden. Note that hidden text is not currently supported by the text layout engine. This attribute is provided to preserve information when copying from and to devices that support hidden text. By default EFalse.
iPictureAlignmentThe vertical alignment of a picture character.

Applying paragraph and character formatting involves the format mask variable. The format mask variable specifies which formatting properties are to be applied in the given formatting object. There are separate format mask types for paragraph (TParaFormatMask) and character (TCharFormatMask) formatting. The mask variable is essentially a bit field, and the properties are set using the SetAttrib() method and reset with the ClearAttrib() method. The values passed to these methods are of type TTextFormatAttribute. When setting many or all formatting properties, it may be useful to call the SetAll() method.

The following code example demonstrates applying paragraph formatting to a global text editor:

void CMyContainer::SetMyFormatL()

    {

    // Create paragraph formatting object

    CParaFormat* pf = new (ELeave) CParaFormat();

    CleanupStack::PushL(pf);

    // Set the alignment

    pf->iHorizontalAlignment = CParaFormat::ECenterAlign;

    // Create paragraph formatting mask

    TParaFormatMask mask;

    // This alignment needs to be changed

    mask.SetAttrib(EAttAlignment);

    // Apply formatting to global text editor control

    iEditor->ApplyParaFormatL(pf, mask);

    CleanupStack::PopAndDestroy(); // pf

    }

Adding the following code demonstrates applying character formatting to a global text editor:

void CMyContainer::SetMyFormatL()

    {

    …

    // Create character format

    TCharFormat cf;

    // Set up the text color and strikethrough properties

    cf.iFontPresentation.iTextColor = KRgbBlue;

    cf.iFontPresentation.iStrikethrough = EStrikethroughOn;

    // Create character format mask	

    TCharFormatMask cmask;

    // The text color and strikethrough need to be changed

    cmask.SetAttrib(EAttColor);

    cmask.SetAttrib(EAttFontStrikethrough);

    // Apply formatting to global text editor control	

    iEditor->ApplyCharFormatL(cf, cmask);

    }

Specifying local formats

In rich text editors it is possible to specify individual paragraph format for each paragraph and character format for any arbitrary section of characters.

All formatting in a rich text object is based on a global character layer and paragraph format layer, and a chain of layers on which they may be based. In case of conflict, upper layers override lower layers. These two format layers are specified on construction, and are not owned by the text object.

Additional formatting may then be added to any portion of the text. This is called specific formatting and in case of conflict, it overrides the formatting in the global layers.

Specific formatting is owned by the text object. So, the effective formatting of a rich text object may be composed of specific formatting and formatting specified in a chain of format layers.

Local formats are based on specific formatting applied at the various positions and with various length of the text content.

The following example demonstrates this with character formats:

void CMyContainer::SetMyTextAndCharFormatPatternL()

    {

    _LIT ( KMyText, "OOOOOOOO");

    // Set the initial text of the editor

    iEditor->SetTextL( &KMyText() );

    CRichText* rtx = iEditor->RichText();

    TCharFormat cf;

    // Set up the text color and strikethrough properties

    cf.iFontPresentation.iTextColor = KRgbBlue;

    cf.iFontPresentation.iStrikethrough = EStrikethroughOn;

    // Create character format mask	

    TCharFormatMask cmask;

    // The text color and strikethrough need to be changed

    cmask.SetAttrib( EAttColor );

    cmask.SetAttrib( EAttFontStrikethrough );

    // Apply strikethrough to the whole text

    rtx->ApplyCharFormatL( cf, cmask, 0, rtx->DocumentLength() );

    

    // Apply underline and disable strikethrough for chars for positions 3 to 6

    cmask.SetAttrib( EAttFontUnderline );

    cf.iFontPresentation.iUnderline = EUnderlineOn;

    cf.iFontPresentation.iStrikethrough = EStrikethroughOff;	

    rtx->ApplyCharFormatL( cf, cmask, 2, 4 );

    // Apply strikethrough and disable underline on char positions 4 and 5    

    cf.iFontPresentation.iUnderline = EUnderlineOff;

    cf.iFontPresentation.iStrikethrough = EStrikethroughOn;

    rtx->ApplyCharFormatL( cf, cmask, 3, 2 );

    // Notify the editor about the changed text

    iEditor->HandleTextChangedL();

    }

The code will result in the following formatted text:

CRichText::SetInsertCharFormatL() will prepare the insertion with the specified format and at the specified position. CRichText::CancelInsertCharFormatL() needs to be called after the insertion.

Inserting embedded objects

The rich text editor controls provide support for object embedding. The embedded objects are divided into two types in the rich text API: generic embedded objects and picture objects. The generic embedded objects are objects managed by other applications. Depending on the capabilities of these applications, the objects may be represented as a glass door or as an icon. The use of these external embeddable objects is beyond the scope of this document.

The embedded picture objects are represented within the rich text by objects derived from class CPicture. CPicture is an abstract class that encapsulates the drawing and serialization of picture objects. The following code example demonstrates how to create and use a simple CPicture derived class to draw an embedded picture in rich text:

// CMyPicture is a minimal picture class (derived from CPicture)

class CMyPicture : public CPicture

    {

    public:          

        CMyPicture( TSize aSize);

        void Draw( CGraphicsContext& aGc,

                   const TPoint& aTopLeft,

                   const TRect& aClipRect,

                   MGraphicsDeviceMap* aMap ) const;

        

        void ExternalizeL( RWriteStream& aStream ) const;

        

        void GetOriginalSizeInTwips( TSize& aSize ) const;

    

    protected:	

        TSize iSize;

    };

CMyPicture::CMyPicture(TSize aSize) : iSize(aSize) {}

	

void CMyPicture::ExternalizeL(RWriteStream& ) const {}



void CMyPicture::GetOriginalSizeInTwips(TSize& aSize) const 

    { aSize = iSize; }



// The actual drawing code

void CMyPicture::Draw(CGraphicsContext& aGc, 

                      const TPoint& aTopLeft,

                      const TRect& aClipRect,

                      MGraphicsDeviceMap* aMap) const

    {	

    TSize pixelsize;

    pixelsize.iWidth = aMap->HorizontalTwipsToPixels(iSize.iWidth);

    pixelsize.iHeight = aMap->VerticalTwipsToPixels(iSize.iHeight);

    TRect area = TRect(aTopLeft, pixelsize);

    // Draw a red ellipse

    aGc.SetBrushColor(KRgbRed);

    aGc.SetBrushStyle(CGraphicsContext::ESolidBrush);

    aGc.DrawEllipse(area);

    }

An instance of CMyPicture can then be embedded into a rich text editor by using the following code:

void CMyContainer::AddPictureL()

    {

    // Instantiate CMyPicture object 300x300 twips in size

    CPicture* picture = new( ELeave )CMyPicture( TSize( 300, 300 ) );

    CleanupStack::PushL(picture);

    //Prepare the picture header, which will be inserted into the rich text

    TPictureHeader header;

    header.iPicture = TSwizzle<CPicture>(picture);

    // Insert the picture into the beginning of the rich text editor

    iEditor->RichText()->InsertL(0, header);

    CleanupStack::Pop(); // picture

    }

Setting and getting the cursor position of CEikEdwin -based editors

Another important although not too common use case is when editor client wants to move the cursor in the editor presented to the user to the right text position. This is usually but not exclusively done right after construction.

The following code snippet gained with a slight modification of the AddMyTextL() function implementation in Performing Basic Plain Text Manipulation through CEikEdwin based editors.

 void CMyContainer::AddMyTextL()

    {

    _LIT( KMyText, "This is my text" );

    // () operator will return a TDesC reference

    iEditor->SetTextL( &KMyText() );

    //Place the cursor after ‘This’ w/o selection	

    iEditor->SetCursorPosL( 4, EFalse );

    }

CEikEdwin::SetCursorPosL() will place the cursor to the specified position. The second parameter is used for putting selection between the zero position and the specified position.

The editor will move the text view so that the cursor is visible.

Manipulating the editing properties of CEikEdwin -based editors

Input mode and case

Text editor controls have modifiable properties that aid the user to enter data into the editor with the limited input capabilities of a keypad-based device. These properties include input mode and input case.

There are three distinct input mode options available: text input mode, numeric input mode, and secret text input mode. The text input mode allows the user to input text data using the keypad. Depending on the other properties, text input can be further accelerated with the predictive text input feature. The numeric input mode enables the user to input numeric data directly with the keypad. The secret text input mode is used in conjunction of secret text editors. The defined symbols and their meanings are listed in Table 6.

Table 6: Input modes
SymbolMeaning
EAknEditorTextInputModeText input.
EAknEditorNumericInputModeNumeric input.
EAknEditorSecretAlphaInputModeSecret text input.
EAknEditorAllInputModesAll of the above.

Input case is used in conjunction with text input mode. It gives more fine-grained control of the actual text input process as it specifies the desired case of the text to be entered. There are three options available: all text may be upper case or lower case, or the text is formatted so that the first character is upper case and the rest is lower case. The symbols and their meaning are listed in Table 7.

Table 7: Input cases
SymbolMeaning
EAknEditorUpperCaseAll text input is upper case.
EAknEditorLowerCaseAll text input is lower case.
EAknEditorTextCaseThe first character is upper case, the others are lower case.
EAknEditorAllCaseModesAll of the above.

The input mode and case properties of a text editor can be specified in the editor resource structure or they can be set at run time. The usage of resource structures is described in Constructing Plain Text Editors from Resource File. The following code example shows how to manipulate these options at run time:

// Set allowed input modes

iEditor->SetAknEditorAllowedInputModes(EAknEditorAllInputModes);



// Set the default input mode

iEditor->SetAknEditorInputMode(EAknEditorTextInputMode);

// Set allowed case modes

iEditor->SetAknEditorPermittedCaseModes(EAknEditorUpperCase);

// Set the default case mode

iEditor->SetAknEditorCase(EAknEditorUpperCase);

The example code sets all input modes to be allowed for the user to choose, setting text input mode to be the default. Within the text input mode, only upper case mode is allowed.

Special character tables

Many applications based on the S60 platform also require symbols other than alphanumeric ones to be entered. The most common example is e-mail composition: every valid e-mail address contains the ‘@’ symbol. The S60 platform enables users to enter these special characters into text editor controls through special character tables. A special character table is a pop-up dialog containing a grid of special characters to choose from. Because there are different needs for special characters, the platform provides different special character tables as well.

The special character tables available for text editors in the S60 platform are listed in Table 8.

Table 8: Special character tables
Resource IdentifierMeaning
R_AVKON_SPECIAL_CHARACTER_TABLE_DIALOGDefault.
R_AVKON_URL_SPECIAL_CHARACTER_TABLE_DIALOGURL addresses.
R_AVKON_EMAIL_ADDR_SPECIAL_CHARACTER_TABLE_DIALOGE-mail addresses.
R_AVKON_CURRENCY_NAME_SPECIAL_CHARACTER_TABLE_DIALOGCurrency.

The special character table for an editor control can be specified either in a resource file or with the CEikEdwin::SetAknEditorSpecialCharacterTable() method.

Numeric key maps

Numeric key maps enable users to enter other symbols to the numeric editor: for example, in a calculator application it is useful to have the primary input mode as numeric, but occasionally there is a need to insert other symbols as well (for example, operators and decimal separator). The numeric key map allows the programmer to define this functionality to the two non-numeric keys of the keypad, the asterisk (‘*’) and the hash (‘#’) keys.

Table 9 lists the available options for numeric key maps. The Asterisk key column lists symbols available by pressing the asterisk key (‘*’), and the Hash key column shows the symbol input when pressing the hash key (‘#’).

Table 9: Numeric key maps
SymbolAsterisk keyHash key
EAknEditorStandardNumberModeKeyMap*, +, p, w#
EAknEditorPlainNumberModeKeymap
EAknEditorCalculatorNumberModeKeymap+, -, *, /.
EAknEditorConverterNumberModeKeymap+, -, E.
EAknEditorToFieldNumberModeKeymap+;
EAknEditorFixedDiallingNumberModeKeymap*, +, p, w#
EAknEditorSATNumberModeKeymap*, +#
EAknEditorSATHiddenNumberModeKeymap*#
EAknEditorAlphanumericNumberModeKeymap#

The numeric key map for an editor control can be specified either in a resource file or by using the CEikEdwin::SetAknEditorNumericKeymap() method.

Miscellaneous properties

There are a great number of properties that can be specified for the editor controls. Some of these properties affect the editing properties directly (such as the read-only property) and some of them are purely controlling the implementation of the text editor controls (such as the flag whether to use segmented storage for the contents or not). These properties must be specified when creating the editor control — either by passing them as an argument to the ConstructL() method or by providing them in the flags field in the resource definition. Typically, the properties cannot be altered afterwards.

Some of these properties can, however, be changed at run time: the read-only flag can be set by the SetReadOnly() method and word wrapping can be controlled by, for example, the SetWordWrap() method.

Table 10: Editor flags
FlagMeaning
EkeepDocumentThe EDWIN does not destroy its content on destruction.
ESegmentedStorageThe content buffer uses segmented storage (see CEditableText::ESegmentedStorage). Segmented storage places the data in more than one heap location. Each forms a part of the buffer. When this flag is not used, the content buffer is stored in one memory location (referred to as a flat buffer). Segmented memory tends to be more flexible in memory allocation, but is slower in operation than flat buffering.
EWidthInPixelsThe size specified in the resource used to construct the object is given in pixels, not characters.
ENoAutoSelectionNo automatic selection takes place. Typically, the entire text is selected as one operation whenever the EDWIN is created, resized, or has its text set.
EJustAutoCurEndWhen the control is activated, the cursor is moved to the end of the text.
ENoWrapDo not wrap the text being edited.
ELineCursorUse a line cursor instead of a block cursor.
ENoHorizScrollingHorizontal scrolling is disabled.
EInclusiveSizeFixedIf set, scrollbars for long documents appear inside the EDWIN, reducing the area available to the EDWIN. If not set, scrollbars appear outside the EDWIN. This does not affect the TSize values returned by the method MinimumSize().
EUserSuppliedTextSets the height of the EDWIN in lines, according to text supplied by the user.
EOwnsWindowThe EDWIN is a window-owning control.
EDisplayOnlyThe EDWIN does not respond to user input.
EAlwaysShowSelectionIf the EDWIN loses focus, do not hide the selection.
EReadOnlyThe EDWIN is read-only. Attempting to add text displays a message to say it is read-only.
EAllowPicturesNo special attempt to delete embedded pictures cleanly will be made. This flag does not apply to EDWINs that do not edit rich text.
EAllowUndoEnable undo operations.
ENoLineOrParaBreaksDo not allow line or paragraph breaks in the text being edited.
EOnlyASCIICharsAllow only ASCII characters.
EResizableThe EDWIN control is resizable, for example, when contained in a parent control. Should the parent control be required to resize itself, the image of the EDWIN control that is displayed can be resized to fit within the parent control. This does not affect the maximum width of the EDWIN control.
EIgnoreVirtualCursorThe EDWIN ignores the virtual cursor. Note: Touchscreen devices do not use the virtual cursor.
ENoCustomDrawNo custom draw is done.
EAvkonEditorChanges layout to AVKON style.
EAvkonDisableCursorHides cursor.
EAvkonNotEditableChanges text editor to non-editable mode.
EEdwinAlternativeWrappingSets the S60 style wrapping on.

Below are the flags specific to the S60 platform, settable either from SetAknEditorFlags() or from the avkon_flags field in an AKN_EDITOR_EXTENSIONS resource.

Table 11: Avkon editor flags
FlagMeaning
EAknEditorFlagFixedCaseCase changes are not allowed.
EAknEditorFlagNoT9Predictive text entry is not allowed.
EAknEditorFlagNoEditIndicatorsEditor indicators are not shown.
EAknEditorFlagNoLRNavigationThe cursor cannot be moved horizontally.
EAknEditorFlagSupressShiftMenuEdit menu cannot be opened from edit key.
EAknEditorFlagEnableScrollBarEnables scroll bars.
EAknEditorFlagMTAutoOverwriteThe character next to the cursor (if exists) is replaced by a new entered character. This flag has effect only in latin multitap input.
EAknEditorFlagUseSCTNumericCharmapThe number input mode uses same special character table character set as alpha input mode if the flag is set. The flag overrides number mode keymapping if they are in conflict. This flag can be used also with number input mode only editors.
EAknEditorFlagLatinInputModesOnlyInput language is changed to English locally in the editor.
EAknEditorFlagForceTransparentFepModesChinese find mode input.
EAknEditorFlagAllowEntersWithScrollDownLine feed character is added with scroll down key event if the cursor is at the end of the buffer. The functionality is available only in certain variants.
EAknEditorFlagEnablePictographInputEnables pictograph input.
EAknEditorFlagFindPaneUsed internally by CAknSearchField.

Using the clipboard in CEikEdwin -based editors

The clipboard is used to transfer data between the text editors in same or different applications. The clipboard is implemented as a direct file store in Symbian OS, and it may contain any serializable object.

The text editor base class CEikEdwin provides, however, the utility method ClipboardL() to handle cut, copy, and paste operations. The cut and copy operations target the selected text. The paste operation will replace the currently selected text with the contents of clipboard. If there is no selection, the clipboard contents will be inserted at the current cursor position.

The following code demonstrates the use of these operations:

// Select all in the first editor

iEditor1->SelectAllL();

// Cut the selected text

iEditor1->ClipboardL(CEikEdwin::ECut);

// Paste the contents of clipboard to the second text editor

iEditor2->ClipboardL(CEikEdwin::EPaste);

Observing events from CEikEdwin -based editors

To observe EDWIN based events client needs to register an MEikEdwinObserver derived observer to the editor.

The registration is done by CEikEdwin::SetEdwinObserver(). The observer will get the notification from the editor through the HandleEdwinEventL(CEikEdwin* aEdwin, TEdwinEvent aEventType). The first parameter is a pointer to the EDWIN that generated the event and the second one is the event type, which is defined this way:

enum TEdwinEvent

	{

	EEventFormatChanged,

	EEventNavigation,

	EEventTextUpdate

	};

It is quite obvious that the enum values correspond to format change, cursor movement and text update events respectively.

Constructing Numeric editors

Constructing Numeric editors from resource files

The integer editor control resource is defined by the AVKON_INTEGER_EDWIN resource structure defined in avkon.rh. The AVKON_INTEGER_EDWIN resource structure is defined as follows:

STRUCT AVKON_INTEGER_EDWIN

	{	

	WORD maxlength = 0;

	LONG min = -99999999;

	LONG max = 99999999;

	LONG unset_value= -100000000;

	LLINK extension1 = 0;

	LLINK extension2 = 0;

	}

The semantics of the fields in the numeric editor control resource structure are self-explanatory: the min field contains the smallest allowed value, the max field contains the largest allowed value, maxlength dictates the maximum content length in characters, and unset_value is the default value of the integer editor control.

The fixed-point editor control resource is defined by the FIXPTED resource structure. The FIXPTED resource structure is defined in eikon.rh as follows:

STRUCT FIXPTED

	{

	WORD decimalplaces=2;

	LONG min;

	LONG max;

	LONG default=0;

	}

The decimalplaces field describes the number of decimals allowed in the edited value. Note that the fixed point editor control presents the value as an integer; the actual value is 10n times smaller, n being the specified number of decimals (thus with the default value of decimalplaces the integer value must be divided by 100).

The floating-point editor control resource is defined by the FLPTED resource structure. The FLPTED resource structure is defined in eikon.rh as follows:

STRUCT FLPTED

	{

	WORD maxlength=18;

	DOUBLE min=-9.9e99;

	DOUBLE max=9.9e99;

	DOUBLE default=0;

	}

The code snippets in this section will demonstrate how to construct an integer editor (floating point editors and fixed point editors can be constructed similarly but using the associated resource structure). The following example resource structure will be used:

RESOURCE AVKON_INTEGER_EDWIN r_myapp_int_edit

    {    

    maxlength = 7;

    min=0;

    max= 1000000;

    unset_value = -1;

    }

iEditor now is declared as CAknIntegerEdwin*.

void CMyContainer::ConstructL(const TRect& aRect)

    {

    CreateWindowL();//Create a window for the container

    iEditor = new ( ELeave )CAknIntegerEdwin;

    iEditor->SetContainerWindowL( *this );

    TResourceReader reader;

    iCoeEnv->CreateResourceReaderLC( reader, R_MYAPP_INT_EDIT );

    iEditor->ConstructFromResourceL( reader );

    CleanupStack::PopAndDestroy();

    iEditor->SetFocus( ETrue );

    SetRect( aRect );

    ActivateL();

    }

The code above is not complete it is also required to include the newly created editor in the control hierarchy, forward it the key events and to set its extent when needed. The pattern shown previously in Common Practices can be followed.

Construction from code

A viable alternative to constructing from resource file is to construct the editor purely from code.

void CMyContainer::ConstructL(const TRect& aRect)

    {

    //Create a window for the container

    CreateWindowL();

    // min, max, max length

    iEditor = CAknIntegerEdwin::NewL( 0, 1000000, 7 );

    // Set parent

    iEditor->SetContainerWindowL( *this );

    // Specify unset value

    iEditor->SetUnsetValue( -1 );

    // Set focus

    iEditor->SetFocus( ETrue );

    // Let container take the specified rect

    SetRect( aRect );

    // Activate the container

    ActivateL();

    }

Notice that now that most parameters will be fed into the NewL() factory function instead of reading them from resource file. However the ‘unset value’ has to be set separately through the SetUnsetValue() function.

There is a way to change the initial configuration through the right setter functions. More details on that can be found in the class documentations.

Retrieving the content of a Numeric editor

The following code shows how you can get the content of the Integer Editor. The GetInt() function will return EFalse if the user supplied data was not acceptable (e.g. editor was empty, number was too high or too low). Note that the editor will take care of not letting the user enter longer number than specified as maxlength.

TBool CMyContainer::GetInt( TInt& aNumber )

    {

    TValidationStatus stat = iEditor->GetTextAsInteger( aNumber );

    return (EValueValid == stat);

    }

In case of a Floating Point Editor the GetValueAsReal() provides the same functionality.

Constructing Secret editors

Secret editors can be instantiated using any of the standard methods either from resource file or from code. The alphanumeric secret editor class is CEikSecretEditor and the numeric secret editor class is CAknNumericSecretEditor, which is derived from CEikSecretEditor. Alphanumeric secret editors are defined using a SECRETED resource structure and numeric secret editors are defined using a NUMSECRETED structure as follows:

RESOURCE SECRETED r_my_secret_editor

    {

    num_letters = 10;

    }

RESOURCE NUMSECRETED r_my_num_secret_editor

    {

    num_code_chars = 4;

    }

The SECRETED resource definition can be found in Eikon.rh whereas the NUMSECRETED definition is in Avkon.rh.

void CMyContainer::ConstructL(const TRect& aRect)

    {

    // Create a window for the container

    CreateWindowL();

    // Call first phase constructor

    iEditor = new (ELeave)CEikSecretEditor;

    // Set parent

    iEditor->SetContainerWindowL( *this );

    // Initialize a resource reader

    TResourceReader reader;

    iCoeEnv->CreateResourceReaderLC( reader, R_MY_SECRET_EDITOR );

    // Second phase constructor from resource

    iEditor->ConstructFromResourceL( reader );

    CleanupStack::PopAndDestroy();

    // Set focus

    iEditor->SetFocus( ETrue );

    SetRect( aRect );

    // Activate the container	

    ActivateL();

    }

And in case of a numeric secret editor you would do practically the same except for creating a CAknNumericSecretEditor and using the R_MY_NUMERIC_SECRET_EDITOR.

Retrieving the content of a Secret editor

Use the CEikSecretEditor::GetText() function to retrieve the user provided secret data in a preallocated buffer. Bear in mind that maximum length of the secret text cannot be bigger than CEikSecretEditor::EMaxSecEdBufLength therefore allocating a buffer of this size is sufficient.

Constructing MFNE editors

MFNE editors can be constructed from resource as well as from code. In this document we will not cover all MFNE editors as their usage is very similar.

Constructing MFNE editors from resource

The resource structures for MFNE controls are also defined in eikon.rh. These resource structures generally contain the minimum and maximum value of the fields and — depending on the type of the MFNE control — some additional fields.

The resource structure names used in creating the MFNEs are listed in Table 11. For more information, see the S60 SDK documentation and the eikon.rh file.

Table 12: Multi-field numeric editor resource definition structures
Multi-field numeric editorStructure nameEditor class name
Number editorNUMBER_EDITORCEikNumberEditor
Range editorRANGE_EDITORCEikRangeEditor
Time editorTIME_EDITORCEikTimeEditor
Date editorDATE_EDITORCEikDateEditor
Time and date editorTIME_AND_DATE_EDITORCEikTimeAndDateEditor
Duration editorDURATION_EDITORCEikDurationEditor
Time offset editorTIME_OFFSET_EDITORCEikTimeOffsetEditor
IP address editorIP_FIELD_EDITORCAknIpFieldEditor
Location editorLATITUDE_EDITOR/LONGITUDE_EDITORCAknLocationEditor
Unit editorAVKON_UNIT_EDITORCAknUnitEditor

As an example let’s see how a date editor is constructed from this example resource:

RESOURCE DATE_EDITOR r_my_date_editor

    {

    minDate = DATE

        {

        day = 0;

        month = 6;

        year = 2006;

        };

    maxDate = DATE

        {

        day = 30;

        month = 11;

        year = 2006;

        };	

    }

Note that the days and months start from 0 meaning that 1st of January requires a day = 0; month = 0;.

And here is the code snippet for create the editor (very similar to previous ones).

void CMyContainer::ConstructL(const TRect& aRect)

    {

    // Create a window for the container

    CreateWindowL();

    // Call first phase constructor

    iEditor = new (ELeave)CEikDateEditor;

    // Set parent

    iEditor->SetContainerWindowL( *this );

    // Initialize a resource reader

    TResourceReader reader;

    iCoeEnv->CreateResourceReaderLC( reader, R_MY_DATE_EDITOR );

    // Second phase constructor from resource

    iEditor->ConstructFromResourceL( reader );

    CleanupStack::PopAndDestroy();

    // Set focus

    iEditor->SetFocus( ETrue );

    SetRect( aRect );

    // Activate the container	

    ActivateL();

    }

Construction of other MFNE based editors from resource file could be done according to the above code scheme with the right resource structure.

Constructing MFNE editors from code

Now let’s see how the construction goes from code. We do have a little bit more control over the default value of the editor this way (which can be achieved with adding a SetDate() call to the code snippet in the previous section).

void CMyContainer::ConstructL(const TRect& aRect)

    {

    // Create a window for the container

    CreateWindowL();

    // Call first phase constructor

    iEditor = new (ELeave)CEikDateEditor;

    // Set parent

    iEditor->SetContainerWindowL( *this );

    

    TDateTime dateTime;

    

    // Set the from date

    dateTime.SetYear(2006);

    dateTime.SetMonth( EJuly );//July

    dateTime.SetDay( 0 ); //1st day

    

    TTime fromTime( dateTime );

    

    // Set the to date

    dateTime.SetYear(2006);

    dateTime.SetMonth( EDecember );//July

    dateTime.SetDay( 30 ); //31st day

    

    TTime toTime( dateTime );

    

   //Set default date to current date

    

    TTime now;

    now.HomeTime();

    // Now call second phase constructor with the right params

    // EFalse is for disabling the popup to select the date from

    // there is no S60 support for this

    iEditor->ConstructL( fromTime, toTime, now, EFalse );

    // Set focus

    iEditor->SetFocus( ETrue );

    SetRect( aRect );

    // Activate the container	

    ActivateL();

    }

Note that the last TBool parameter of ConstructL() is ignored in S60.

Retrieving the content of a MFNE editor

The way of getting the user supply data from an MFNE editor can usually be done with a single function call. The return type and the name of the function however vary according to the type of the editor.

To demonstrate this use case we complete the previous date editor example with one more function.

TBool CMyContainer::BirthDay( TTime& aDate ) const

    {

    //Check if the editor is initialized

    TBool valid  = !iEditor->IsUninitialised();

    // if initialized

    if ( valid )

        {

        // Get the Date user provided

        aTime = iEditor->Date();

        }

    return valid;

    }

The code will return false if the editor is not initialised. (It can only happen if SetUninitialised( ETrue ) had been called earlier.)

Retrieving the content of other MFNE Editors can be done in a similar way. E.g. in case of an IP address editor the function Address() need to be used to get the user input in a TInetAddres object.

Error handling

Editors API uses standard Symbian OS error reporting mechanism. It does not define any panic codes of its own. Leaves and system wide error codes as function return values are used if the error is recoverable. A client application can handle these errors similarly as a normal Symbian OS application.

Memory overhead

Memory consumption of various Editors is largely dependent on their content. It is worth considering disabling undo buffer in case of CEikEdwin based editors. CEikEdwin through its underlying components do also store formatting information along with the text. Formatting of large texts result in the editor switching to a band formatting mode, in which the editor will format as little text as needed to be able to display the visible part of the text. User can explicitly change the document length limit from which the editor applies band formatting by calling CEikEdwin::SetUpperFullFormattingLength() function.

Limitations of the API

This API cannot be used without a UI environment (e.g. a Symbian OS sever process cannot use the API).


Copyright © Nokia Corporation 2001-2008
Back to top