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 const char wxControlNameStr
[] = "control";
43 // ============================================================================
45 // ============================================================================
47 wxControlBase::~wxControlBase()
49 // this destructor is required for Darwin
52 bool wxControlBase::Create(wxWindow
*parent
,
57 const wxValidator
& wxVALIDATOR_PARAM(validator
),
60 bool ret
= wxWindow::Create(parent
, id
, pos
, size
, style
, name
);
64 SetValidator(validator
);
65 #endif // wxUSE_VALIDATORS
70 bool wxControlBase::CreateControl(wxWindowBase
*parent
,
75 const wxValidator
& validator
,
78 // even if it's possible to create controls without parents in some port,
79 // it should surely be discouraged because it doesn't work at all under
81 wxCHECK_MSG( parent
, false, wxT("all controls must have parents") );
83 if ( !CreateBase(parent
, id
, pos
, size
, style
, validator
, name
) )
86 parent
->AddChild(this);
91 void wxControlBase::Command(wxCommandEvent
& event
)
93 (void)GetEventHandler()->ProcessEvent(event
);
96 void wxControlBase::InitCommandEvent(wxCommandEvent
& event
) const
98 event
.SetEventObject(const_cast<wxControlBase
*>(this));
100 // event.SetId(GetId()); -- this is usuall done in the event ctor
102 switch ( m_clientDataType
)
104 case wxClientData_Void
:
105 event
.SetClientData(GetClientData());
108 case wxClientData_Object
:
109 event
.SetClientObject(GetClientObject());
112 case wxClientData_None
:
118 bool wxControlBase::SetFont(const wxFont
& font
)
120 InvalidateBestSize();
121 return wxWindow::SetFont(font
);
124 // wxControl-specific processing after processing the update event
125 void wxControlBase::DoUpdateWindowUI(wxUpdateUIEvent
& event
)
128 wxWindowBase::DoUpdateWindowUI(event
);
131 if ( event
.GetSetText() )
133 if ( event
.GetText() != GetLabel() )
134 SetLabel(event
.GetText());
137 // Unfortunately we don't yet have common base class for
138 // wxRadioButton, so we handle updates of radiobuttons here.
139 // TODO: If once wxRadioButtonBase will exist, move this code there.
141 if ( event
.GetSetChecked() )
143 wxRadioButton
*radiobtn
= wxDynamicCastThis(wxRadioButton
);
145 radiobtn
->SetValue(event
.GetChecked());
147 #endif // wxUSE_RADIOBTN
151 wxString
wxControlBase::GetLabelText(const wxString
& label
)
153 // we don't want strip the TABs here, just the mnemonics
154 return wxStripMenuCodes(label
, wxStrip_Mnemonics
);
158 wxString
wxControlBase::RemoveMnemonics(const wxString
& str
)
160 // we don't want strip the TABs here, just the mnemonics
161 return wxStripMenuCodes(str
, wxStrip_Mnemonics
);
165 wxString
wxControlBase::EscapeMnemonics(const wxString
& text
)
167 wxString
label(text
);
168 label
.Replace("&", "&&");
173 int wxControlBase::FindAccelIndex(const wxString
& label
, wxString
*labelOnly
)
175 // the character following MNEMONIC_PREFIX is the accelerator for this
176 // control unless it is MNEMONIC_PREFIX too - this allows to insert
177 // literal MNEMONIC_PREFIX chars into the label
178 static const wxChar MNEMONIC_PREFIX
= wxT('&');
183 labelOnly
->Alloc(label
.length());
187 for ( wxString::const_iterator pc
= label
.begin(); pc
!= label
.end(); ++pc
)
189 if ( *pc
== MNEMONIC_PREFIX
)
192 if ( pc
== label
.end() )
194 else if ( *pc
!= MNEMONIC_PREFIX
)
196 if ( indexAccel
== -1 )
198 // remember it (-1 is for MNEMONIC_PREFIX itself
199 indexAccel
= pc
- label
.begin() - 1;
203 wxFAIL_MSG(wxT("duplicate accel char in control label"));
217 wxBorder
wxControlBase::GetDefaultBorder() const
219 return wxBORDER_THEME
;
222 /* static */ wxVisualAttributes
223 wxControlBase::GetCompositeControlsDefaultAttributes(wxWindowVariant
WXUNUSED(variant
))
225 wxVisualAttributes attrs
;
226 attrs
.font
= wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT
);
227 attrs
.colFg
= wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT
);
228 attrs
.colBg
= wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW
);
233 // ----------------------------------------------------------------------------
234 // wxControlBase - ellipsization code
235 // ----------------------------------------------------------------------------
237 #define wxELLIPSE_REPLACEMENT wxS("...")
242 struct EllipsizeCalculator
244 EllipsizeCalculator(const wxString
& s
, const wxDC
& dc
,
245 int maxFinalWidthPx
, int replacementWidthPx
)
247 m_initialCharToRemove(0),
249 m_outputNeedsUpdate(true),
252 m_maxFinalWidthPx(maxFinalWidthPx
),
253 m_replacementWidthPx(replacementWidthPx
)
255 m_isOk
= dc
.GetPartialTextExtents(s
, m_charOffsetsPx
);
256 wxASSERT( m_charOffsetsPx
.GetCount() == s
.length() );
259 bool IsOk() const { return m_isOk
; }
261 bool EllipsizationNotNeeded() const
263 // NOTE: charOffsetsPx[n] is the width in pixels of the first n characters (with the last one INCLUDED)
264 // thus charOffsetsPx[len-1] is the total width of the string
265 return m_charOffsetsPx
.Last() <= m_maxFinalWidthPx
;
268 void Init(size_t initialCharToRemove
, size_t nCharsToRemove
)
270 m_initialCharToRemove
= initialCharToRemove
;
271 m_nCharsToRemove
= nCharsToRemove
;
279 void RemoveFromStart()
281 m_initialCharToRemove
--;
285 size_t GetFirstRemoved() const { return m_initialCharToRemove
; }
286 size_t GetLastRemoved() const { return m_initialCharToRemove
+ m_nCharsToRemove
- 1; }
288 const wxString
& GetEllipsizedText()
290 if ( m_outputNeedsUpdate
)
292 wxASSERT(m_initialCharToRemove
<= m_str
.length() - 1); // see valid range for initialCharToRemove above
293 wxASSERT(m_nCharsToRemove
>= 1 && m_nCharsToRemove
<= m_str
.length() - m_initialCharToRemove
); // see valid range for nCharsToRemove above
295 // erase m_nCharsToRemove characters after m_initialCharToRemove (included);
296 // e.g. if we have the string "foobar" (len = 6)
298 // \--- m_initialCharToRemove = 2
299 // and m_nCharsToRemove = 2, then we get "foar"
301 m_output
.replace(m_initialCharToRemove
, m_nCharsToRemove
, wxELLIPSE_REPLACEMENT
);
309 if ( m_nCharsToRemove
== m_str
.length() )
310 return true; // that's the best we could do
312 // Width calculation using partial extents is just an inaccurate
313 // estimate: partial extents have sub-pixel precision and are rounded
314 // by GetPartialTextExtents(); replacing part of the string with "..."
315 // may change them too thanks to changes in ligatures, kerning etc.
317 // The correct algorithm would be to call GetTextExtent() in every step
318 // of ellipsization, but that would be too expensive, especially when
319 // the difference is just a few pixels. So we use partial extents to
320 // estimate string width and only verify it with GetTextExtent() when
323 int estimatedWidth
= m_replacementWidthPx
; // length of "..."
325 // length of text before the removed part:
326 if ( m_initialCharToRemove
> 0 )
327 estimatedWidth
+= m_charOffsetsPx
[m_initialCharToRemove
- 1];
329 // length of text after the removed part:
331 if ( GetLastRemoved() < m_str
.length() )
332 estimatedWidth
+= m_charOffsetsPx
.Last() - m_charOffsetsPx
[GetLastRemoved()];
334 if ( estimatedWidth
> m_maxFinalWidthPx
)
337 return m_dc
.GetTextExtent(GetEllipsizedText()).GetWidth() <= m_maxFinalWidthPx
;
340 // calculation state:
342 // REMEMBER: indexes inside the string have a valid range of [0;len-1] if not otherwise constrained
343 // lengths/counts of characters (e.g. nCharsToRemove) have a
344 // valid range of [0;len] if not otherwise constrained
345 // NOTE: since this point we know we have for sure a non-empty string from which we need
346 // to remove _at least_ one character (thus nCharsToRemove below is constrained to be >= 1)
348 // index of first character to erase, valid range is [0;len-1]:
349 size_t m_initialCharToRemove
;
350 // how many chars do we need to erase? valid range is [0;len-m_initialCharToRemove]
351 size_t m_nCharsToRemove
;
354 bool m_outputNeedsUpdate
;
359 int m_maxFinalWidthPx
;
360 int m_replacementWidthPx
;
361 wxArrayInt m_charOffsetsPx
;
366 } // anonymous namespace
368 /* static and protected */
369 wxString
wxControlBase::DoEllipsizeSingleLine(const wxString
& curLine
, const wxDC
& dc
,
370 wxEllipsizeMode mode
, int maxFinalWidthPx
,
371 int replacementWidthPx
)
373 wxASSERT_MSG(replacementWidthPx
> 0, "Invalid parameters");
374 wxASSERT_LEVEL_2_MSG(!curLine
.Contains('\n'),
375 "Use Ellipsize() instead!");
377 wxASSERT_MSG( mode
!= wxELLIPSIZE_NONE
, "shouldn't be called at all then" );
379 // NOTE: this function assumes that any mnemonic/tab character has already
380 // been handled if it was necessary to handle them (see Ellipsize())
382 if (maxFinalWidthPx
<= 0)
383 return wxEmptyString
;
385 size_t len
= curLine
.length();
389 EllipsizeCalculator
calc(curLine
, dc
, maxFinalWidthPx
, replacementWidthPx
);
394 if ( calc
.EllipsizationNotNeeded() )
397 // let's compute the range of characters to remove depending on the ellipsization mode:
400 case wxELLIPSIZE_START
:
403 while ( !calc
.IsShortEnough() )
404 calc
.RemoveFromEnd();
408 case wxELLIPSIZE_MIDDLE
:
410 // NOTE: the following piece of code works also when len == 1
412 // start the removal process from the middle of the string
413 // i.e. separe the string in three parts:
414 // - the first one to preserve, valid range [0;initialCharToRemove-1] or the empty range if initialCharToRemove==0
415 // - the second one to remove, valid range [initialCharToRemove;endCharToRemove]
416 // - the third one to preserve, valid range [endCharToRemove+1;len-1] or the empty range if endCharToRemove==len-1
417 // NOTE: empty range != range [0;0] since the range [0;0] contains 1 character (the zero-th one)!
421 bool removeFromStart
= true;
423 while ( !calc
.IsShortEnough() )
425 const bool canRemoveFromStart
= calc
.GetFirstRemoved() > 0;
426 const bool canRemoveFromEnd
= calc
.GetLastRemoved() < len
- 1;
428 if ( !canRemoveFromStart
&& !canRemoveFromEnd
)
430 // we need to remove all the characters of the string!
434 // Remove from the beginning in even steps and from the end
435 // in odd steps, unless we exhausted one side already:
436 removeFromStart
= !removeFromStart
;
437 if ( removeFromStart
&& !canRemoveFromStart
)
438 removeFromStart
= false;
439 else if ( !removeFromStart
&& !canRemoveFromEnd
)
440 removeFromStart
= true;
442 if ( removeFromStart
)
443 calc
.RemoveFromStart();
445 calc
.RemoveFromEnd();
450 case wxELLIPSIZE_END
:
452 calc
.Init(len
- 1, 1);
453 while ( !calc
.IsShortEnough() )
454 calc
.RemoveFromStart();
458 case wxELLIPSIZE_NONE
:
460 wxFAIL_MSG("invalid ellipsize mode");
464 return calc
.GetEllipsizedText();
468 wxString
wxControlBase::Ellipsize(const wxString
& label
, const wxDC
& dc
,
469 wxEllipsizeMode mode
, int maxFinalWidth
,
474 // these cannot be cached between different Ellipsize() calls as they can
475 // change because of e.g. a font change; however we calculate them only once
476 // when ellipsizing multiline labels:
477 int replacementWidth
= dc
.GetTextExtent(wxELLIPSE_REPLACEMENT
).GetWidth();
479 // NB: we must handle correctly labels with newlines:
481 for ( wxString::const_iterator pc
= label
.begin(); ; ++pc
)
483 if ( pc
== label
.end() || *pc
== wxS('\n') )
485 curLine
= DoEllipsizeSingleLine(curLine
, dc
, mode
, maxFinalWidth
,
488 // add this (ellipsized) row to the rest of the label
490 if ( pc
== label
.end() )
492 // NOTE: this is the return which always exits the function
501 // we need to remove mnemonics from the label for correct calculations
502 else if ( *pc
== wxS('&') && (flags
& wxELLIPSIZE_FLAGS_PROCESS_MNEMONICS
) )
504 // pc+1 is safe: at worst we'll be at end()
505 wxString::const_iterator next
= pc
+ 1;
506 if ( next
!= label
.end() && *next
== wxS('&') )
507 curLine
+= wxS('&'); // && becomes &
508 //else: remove this ampersand
510 // we need also to expand tabs to properly calc their size
511 else if ( *pc
== wxS('\t') && (flags
& wxELLIPSIZE_FLAGS_EXPAND_TABS
) )
513 // Windows natively expands the TABs to 6 spaces. Do the same:
522 // this return would generate a
523 // warning C4702: unreachable code
524 // with MSVC since the function always exits from inside the loop
530 // ----------------------------------------------------------------------------
532 // ----------------------------------------------------------------------------
536 wxStaticBitmapBase::~wxStaticBitmapBase()
538 // this destructor is required for Darwin
541 wxSize
wxStaticBitmapBase::DoGetBestSize() const
544 wxBitmap bmp
= GetBitmap();
546 best
= wxSize(bmp
.GetWidth(), bmp
.GetHeight());
548 // this is completely arbitrary
549 best
= wxSize(16, 16);
554 #endif // wxUSE_STATBMP
556 #endif // wxUSE_CONTROLS