1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/ctrlcmn.cpp
3 // Purpose: wxControl common interface
4 // Author: Vadim Zeitlin
8 // Copyright: (c) wxWidgets team
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
29 #include "wx/control.h"
34 #include "wx/radiobut.h"
35 #include "wx/statbmp.h"
36 #include "wx/bitmap.h"
37 #include "wx/utils.h" // for wxStripMenuCodes()
38 #include "wx/settings.h"
41 #include "wx/private/markupparser.h"
43 const char wxControlNameStr
[] = "control";
45 // ============================================================================
47 // ============================================================================
49 wxControlBase::~wxControlBase()
51 // this destructor is required for Darwin
54 bool wxControlBase::Create(wxWindow
*parent
,
59 const wxValidator
& wxVALIDATOR_PARAM(validator
),
62 bool ret
= wxWindow::Create(parent
, id
, pos
, size
, style
, name
);
66 SetValidator(validator
);
67 #endif // wxUSE_VALIDATORS
72 bool wxControlBase::CreateControl(wxWindowBase
*parent
,
77 const wxValidator
& validator
,
80 // even if it's possible to create controls without parents in some port,
81 // it should surely be discouraged because it doesn't work at all under
83 wxCHECK_MSG( parent
, false, wxT("all controls must have parents") );
85 if ( !CreateBase(parent
, id
, pos
, size
, style
, validator
, name
) )
88 parent
->AddChild(this);
93 void wxControlBase::Command(wxCommandEvent
& event
)
95 (void)GetEventHandler()->ProcessEvent(event
);
98 void wxControlBase::InitCommandEvent(wxCommandEvent
& event
) const
100 event
.SetEventObject(const_cast<wxControlBase
*>(this));
102 // event.SetId(GetId()); -- this is usuall done in the event ctor
104 switch ( m_clientDataType
)
106 case wxClientData_Void
:
107 event
.SetClientData(GetClientData());
110 case wxClientData_Object
:
111 event
.SetClientObject(GetClientObject());
114 case wxClientData_None
:
120 bool wxControlBase::SetFont(const wxFont
& font
)
122 InvalidateBestSize();
123 return wxWindow::SetFont(font
);
126 // wxControl-specific processing after processing the update event
127 void wxControlBase::DoUpdateWindowUI(wxUpdateUIEvent
& event
)
130 wxWindowBase::DoUpdateWindowUI(event
);
133 if ( event
.GetSetText() )
135 if ( event
.GetText() != GetLabel() )
136 SetLabel(event
.GetText());
139 // Unfortunately we don't yet have common base class for
140 // wxRadioButton, so we handle updates of radiobuttons here.
141 // TODO: If once wxRadioButtonBase will exist, move this code there.
143 if ( event
.GetSetChecked() )
145 wxRadioButton
*radiobtn
= wxDynamicCastThis(wxRadioButton
);
147 radiobtn
->SetValue(event
.GetChecked());
149 #endif // wxUSE_RADIOBTN
153 wxString
wxControlBase::GetLabelText(const wxString
& label
)
155 // we don't want strip the TABs here, just the mnemonics
156 return wxStripMenuCodes(label
, wxStrip_Mnemonics
);
160 wxString
wxControlBase::RemoveMnemonics(const wxString
& str
)
162 // we don't want strip the TABs here, just the mnemonics
163 return wxStripMenuCodes(str
, wxStrip_Mnemonics
);
167 wxString
wxControlBase::EscapeMnemonics(const wxString
& text
)
169 wxString
label(text
);
170 label
.Replace("&", "&&");
175 int wxControlBase::FindAccelIndex(const wxString
& label
, wxString
*labelOnly
)
177 // the character following MNEMONIC_PREFIX is the accelerator for this
178 // control unless it is MNEMONIC_PREFIX too - this allows to insert
179 // literal MNEMONIC_PREFIX chars into the label
180 static const wxChar MNEMONIC_PREFIX
= wxT('&');
185 labelOnly
->Alloc(label
.length());
189 for ( wxString::const_iterator pc
= label
.begin(); pc
!= label
.end(); ++pc
)
191 if ( *pc
== MNEMONIC_PREFIX
)
194 if ( pc
== label
.end() )
196 else if ( *pc
!= MNEMONIC_PREFIX
)
198 if ( indexAccel
== -1 )
200 // remember it (-1 is for MNEMONIC_PREFIX itself
201 indexAccel
= pc
- label
.begin() - 1;
205 wxFAIL_MSG(wxT("duplicate accel char in control label"));
219 wxBorder
wxControlBase::GetDefaultBorder() const
221 return wxBORDER_THEME
;
224 /* static */ wxVisualAttributes
225 wxControlBase::GetCompositeControlsDefaultAttributes(wxWindowVariant
WXUNUSED(variant
))
227 wxVisualAttributes attrs
;
228 attrs
.font
= wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT
);
229 attrs
.colFg
= wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT
);
230 attrs
.colBg
= wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW
);
235 // ----------------------------------------------------------------------------
236 // wxControl markup support
237 // ----------------------------------------------------------------------------
242 wxString
wxControlBase::RemoveMarkup(const wxString
& markup
)
244 return wxMarkupParser::Strip(markup
);
247 bool wxControlBase::DoSetLabelMarkup(const wxString
& markup
)
249 const wxString label
= RemoveMarkup(markup
);
250 if ( label
.empty() && !markup
.empty() )
258 #endif // wxUSE_MARKUP
260 // ----------------------------------------------------------------------------
261 // wxControlBase - ellipsization code
262 // ----------------------------------------------------------------------------
264 #define wxELLIPSE_REPLACEMENT wxS("...")
269 struct EllipsizeCalculator
271 EllipsizeCalculator(const wxString
& s
, const wxDC
& dc
,
272 int maxFinalWidthPx
, int replacementWidthPx
)
274 m_initialCharToRemove(0),
276 m_outputNeedsUpdate(true),
279 m_maxFinalWidthPx(maxFinalWidthPx
),
280 m_replacementWidthPx(replacementWidthPx
)
282 m_isOk
= dc
.GetPartialTextExtents(s
, m_charOffsetsPx
);
283 wxASSERT( m_charOffsetsPx
.GetCount() == s
.length() );
286 bool IsOk() const { return m_isOk
; }
288 bool EllipsizationNotNeeded() const
290 // NOTE: charOffsetsPx[n] is the width in pixels of the first n characters (with the last one INCLUDED)
291 // thus charOffsetsPx[len-1] is the total width of the string
292 return m_charOffsetsPx
.Last() <= m_maxFinalWidthPx
;
295 void Init(size_t initialCharToRemove
, size_t nCharsToRemove
)
297 m_initialCharToRemove
= initialCharToRemove
;
298 m_nCharsToRemove
= nCharsToRemove
;
306 void RemoveFromStart()
308 m_initialCharToRemove
--;
312 size_t GetFirstRemoved() const { return m_initialCharToRemove
; }
313 size_t GetLastRemoved() const { return m_initialCharToRemove
+ m_nCharsToRemove
- 1; }
315 const wxString
& GetEllipsizedText()
317 if ( m_outputNeedsUpdate
)
319 wxASSERT(m_initialCharToRemove
<= m_str
.length() - 1); // see valid range for initialCharToRemove above
320 wxASSERT(m_nCharsToRemove
>= 1 && m_nCharsToRemove
<= m_str
.length() - m_initialCharToRemove
); // see valid range for nCharsToRemove above
322 // erase m_nCharsToRemove characters after m_initialCharToRemove (included);
323 // e.g. if we have the string "foobar" (len = 6)
325 // \--- m_initialCharToRemove = 2
326 // and m_nCharsToRemove = 2, then we get "foar"
328 m_output
.replace(m_initialCharToRemove
, m_nCharsToRemove
, wxELLIPSE_REPLACEMENT
);
336 if ( m_nCharsToRemove
== m_str
.length() )
337 return true; // that's the best we could do
339 // Width calculation using partial extents is just an inaccurate
340 // estimate: partial extents have sub-pixel precision and are rounded
341 // by GetPartialTextExtents(); replacing part of the string with "..."
342 // may change them too thanks to changes in ligatures, kerning etc.
344 // The correct algorithm would be to call GetTextExtent() in every step
345 // of ellipsization, but that would be too expensive, especially when
346 // the difference is just a few pixels. So we use partial extents to
347 // estimate string width and only verify it with GetTextExtent() when
350 int estimatedWidth
= m_replacementWidthPx
; // length of "..."
352 // length of text before the removed part:
353 if ( m_initialCharToRemove
> 0 )
354 estimatedWidth
+= m_charOffsetsPx
[m_initialCharToRemove
- 1];
356 // length of text after the removed part:
358 if ( GetLastRemoved() < m_str
.length() )
359 estimatedWidth
+= m_charOffsetsPx
.Last() - m_charOffsetsPx
[GetLastRemoved()];
361 if ( estimatedWidth
> m_maxFinalWidthPx
)
364 return m_dc
.GetTextExtent(GetEllipsizedText()).GetWidth() <= m_maxFinalWidthPx
;
367 // calculation state:
369 // REMEMBER: indexes inside the string have a valid range of [0;len-1] if not otherwise constrained
370 // lengths/counts of characters (e.g. nCharsToRemove) have a
371 // valid range of [0;len] if not otherwise constrained
372 // NOTE: since this point we know we have for sure a non-empty string from which we need
373 // to remove _at least_ one character (thus nCharsToRemove below is constrained to be >= 1)
375 // index of first character to erase, valid range is [0;len-1]:
376 size_t m_initialCharToRemove
;
377 // how many chars do we need to erase? valid range is [0;len-m_initialCharToRemove]
378 size_t m_nCharsToRemove
;
381 bool m_outputNeedsUpdate
;
386 int m_maxFinalWidthPx
;
387 int m_replacementWidthPx
;
388 wxArrayInt m_charOffsetsPx
;
393 } // anonymous namespace
395 /* static and protected */
396 wxString
wxControlBase::DoEllipsizeSingleLine(const wxString
& curLine
, const wxDC
& dc
,
397 wxEllipsizeMode mode
, int maxFinalWidthPx
,
398 int replacementWidthPx
)
400 wxASSERT_MSG(replacementWidthPx
> 0, "Invalid parameters");
401 wxASSERT_LEVEL_2_MSG(!curLine
.Contains('\n'),
402 "Use Ellipsize() instead!");
404 wxASSERT_MSG( mode
!= wxELLIPSIZE_NONE
, "shouldn't be called at all then" );
406 // NOTE: this function assumes that any mnemonic/tab character has already
407 // been handled if it was necessary to handle them (see Ellipsize())
409 if (maxFinalWidthPx
<= 0)
410 return wxEmptyString
;
412 size_t len
= curLine
.length();
416 EllipsizeCalculator
calc(curLine
, dc
, maxFinalWidthPx
, replacementWidthPx
);
421 if ( calc
.EllipsizationNotNeeded() )
424 // let's compute the range of characters to remove depending on the ellipsization mode:
427 case wxELLIPSIZE_START
:
430 while ( !calc
.IsShortEnough() )
431 calc
.RemoveFromEnd();
433 // always show at least one character of the string:
434 if ( calc
.m_nCharsToRemove
== len
)
435 return wxString(wxELLIPSE_REPLACEMENT
) + curLine
[len
-1];
440 case wxELLIPSIZE_MIDDLE
:
442 // NOTE: the following piece of code works also when len == 1
444 // start the removal process from the middle of the string
445 // i.e. separe the string in three parts:
446 // - the first one to preserve, valid range [0;initialCharToRemove-1] or the empty range if initialCharToRemove==0
447 // - the second one to remove, valid range [initialCharToRemove;endCharToRemove]
448 // - the third one to preserve, valid range [endCharToRemove+1;len-1] or the empty range if endCharToRemove==len-1
449 // NOTE: empty range != range [0;0] since the range [0;0] contains 1 character (the zero-th one)!
453 bool removeFromStart
= true;
455 while ( !calc
.IsShortEnough() )
457 const bool canRemoveFromStart
= calc
.GetFirstRemoved() > 0;
458 const bool canRemoveFromEnd
= calc
.GetLastRemoved() < len
- 1;
460 if ( !canRemoveFromStart
&& !canRemoveFromEnd
)
462 // we need to remove all the characters of the string!
466 // Remove from the beginning in even steps and from the end
467 // in odd steps, unless we exhausted one side already:
468 removeFromStart
= !removeFromStart
;
469 if ( removeFromStart
&& !canRemoveFromStart
)
470 removeFromStart
= false;
471 else if ( !removeFromStart
&& !canRemoveFromEnd
)
472 removeFromStart
= true;
474 if ( removeFromStart
)
475 calc
.RemoveFromStart();
477 calc
.RemoveFromEnd();
480 // Always show at least one character of the string.
481 // Additionally, if there's only one character left, prefer
483 if ( calc
.m_nCharsToRemove
== len
||
484 calc
.m_nCharsToRemove
== len
- 1 )
486 return curLine
[0] + wxString(wxELLIPSE_REPLACEMENT
);
491 case wxELLIPSIZE_END
:
493 calc
.Init(len
- 1, 1);
494 while ( !calc
.IsShortEnough() )
495 calc
.RemoveFromStart();
497 // always show at least one character of the string:
498 if ( calc
.m_nCharsToRemove
== len
)
499 return curLine
[0] + wxString(wxELLIPSE_REPLACEMENT
);
504 case wxELLIPSIZE_NONE
:
506 wxFAIL_MSG("invalid ellipsize mode");
510 return calc
.GetEllipsizedText();
514 wxString
wxControlBase::Ellipsize(const wxString
& label
, const wxDC
& dc
,
515 wxEllipsizeMode mode
, int maxFinalWidth
,
520 // these cannot be cached between different Ellipsize() calls as they can
521 // change because of e.g. a font change; however we calculate them only once
522 // when ellipsizing multiline labels:
523 int replacementWidth
= dc
.GetTextExtent(wxELLIPSE_REPLACEMENT
).GetWidth();
525 // NB: we must handle correctly labels with newlines:
527 for ( wxString::const_iterator pc
= label
.begin(); ; ++pc
)
529 if ( pc
== label
.end() || *pc
== wxS('\n') )
531 curLine
= DoEllipsizeSingleLine(curLine
, dc
, mode
, maxFinalWidth
,
534 // add this (ellipsized) row to the rest of the label
536 if ( pc
== label
.end() )
538 // NOTE: this is the return which always exits the function
547 // we need to remove mnemonics from the label for correct calculations
548 else if ( *pc
== wxS('&') && (flags
& wxELLIPSIZE_FLAGS_PROCESS_MNEMONICS
) )
550 // pc+1 is safe: at worst we'll be at end()
551 wxString::const_iterator next
= pc
+ 1;
552 if ( next
!= label
.end() && *next
== wxS('&') )
553 curLine
+= wxS('&'); // && becomes &
554 //else: remove this ampersand
556 // we need also to expand tabs to properly calc their size
557 else if ( *pc
== wxS('\t') && (flags
& wxELLIPSIZE_FLAGS_EXPAND_TABS
) )
559 // Windows natively expands the TABs to 6 spaces. Do the same:
568 // this return would generate a
569 // warning C4702: unreachable code
570 // with MSVC since the function always exits from inside the loop
576 // ----------------------------------------------------------------------------
578 // ----------------------------------------------------------------------------
582 wxStaticBitmapBase::~wxStaticBitmapBase()
584 // this destructor is required for Darwin
587 wxSize
wxStaticBitmapBase::DoGetBestSize() const
590 wxBitmap bmp
= GetBitmap();
592 best
= wxSize(bmp
.GetWidth(), bmp
.GetHeight());
594 // this is completely arbitrary
595 best
= wxSize(16, 16);
600 #endif // wxUSE_STATBMP
602 #endif // wxUSE_CONTROLS