]> git.saurik.com Git - wxWidgets.git/blame - src/common/ctrlcmn.cpp
Add wxFont::Underlined() and MakeUnderlined() methods.
[wxWidgets.git] / src / common / ctrlcmn.cpp
CommitLineData
2d61b48d 1/////////////////////////////////////////////////////////////////////////////
0e2d2986 2// Name: src/common/ctrlcmn.cpp
2d61b48d
VZ
3// Purpose: wxControl common interface
4// Author: Vadim Zeitlin
5// Modified by:
6// Created: 26.07.99
7// RCS-ID: $Id$
77ffb593 8// Copyright: (c) wxWidgets team
65571936 9// Licence: wxWindows licence
2d61b48d
VZ
10/////////////////////////////////////////////////////////////////////////////
11
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
19
2d61b48d
VZ
20// For compilers that support precompilation, includes "wx.h".
21#include "wx/wxprec.h"
22
23#ifdef __BORLANDC__
24 #pragma hdrstop
25#endif
26
1e6feb95
VZ
27#if wxUSE_CONTROLS
28
93fbbe07
WS
29#include "wx/control.h"
30
2d61b48d 31#ifndef WX_PRECOMP
02b4f9fd 32 #include "wx/dc.h"
2d61b48d 33 #include "wx/log.h"
0e2d2986 34 #include "wx/radiobut.h"
e267406e 35 #include "wx/statbmp.h"
1e6feb95 36 #include "wx/bitmap.h"
74639764 37 #include "wx/utils.h" // for wxStripMenuCodes()
0534259a 38 #include "wx/settings.h"
0bca0373 39#endif
1e6feb95 40
f36e602b 41const char wxControlNameStr[] = "control";
e7445ff8 42
2d61b48d
VZ
43// ============================================================================
44// implementation
45// ============================================================================
46
799ea011
GD
47wxControlBase::~wxControlBase()
48{
49 // this destructor is required for Darwin
50}
51
1e6feb95
VZ
52bool wxControlBase::Create(wxWindow *parent,
53 wxWindowID id,
54 const wxPoint &pos,
55 const wxSize &size,
56 long style,
ac8d0c11 57 const wxValidator& wxVALIDATOR_PARAM(validator),
1e6feb95
VZ
58 const wxString &name)
59{
60 bool ret = wxWindow::Create(parent, id, pos, size, style, name);
61
62#if wxUSE_VALIDATORS
63 if ( ret )
64 SetValidator(validator);
65#endif // wxUSE_VALIDATORS
66
67 return ret;
68}
69
2d61b48d
VZ
70bool wxControlBase::CreateControl(wxWindowBase *parent,
71 wxWindowID id,
72 const wxPoint& pos,
73 const wxSize& size,
74 long style,
75 const wxValidator& validator,
76 const wxString& name)
77{
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
80 // Windows
c9d59ee7 81 wxCHECK_MSG( parent, false, wxT("all controls must have parents") );
2d61b48d
VZ
82
83 if ( !CreateBase(parent, id, pos, size, style, validator, name) )
c9d59ee7 84 return false;
2d61b48d
VZ
85
86 parent->AddChild(this);
87
c9d59ee7 88 return true;
2d61b48d
VZ
89}
90
2d61b48d
VZ
91void wxControlBase::Command(wxCommandEvent& event)
92{
bfbd6dc1 93 (void)GetEventHandler()->ProcessEvent(event);
2d61b48d 94}
bfbd6dc1
VZ
95
96void wxControlBase::InitCommandEvent(wxCommandEvent& event) const
97{
f48a1159 98 event.SetEventObject(const_cast<wxControlBase *>(this));
bfbd6dc1
VZ
99
100 // event.SetId(GetId()); -- this is usuall done in the event ctor
101
102 switch ( m_clientDataType )
103 {
1e6feb95 104 case wxClientData_Void:
bfbd6dc1
VZ
105 event.SetClientData(GetClientData());
106 break;
107
1e6feb95 108 case wxClientData_Object:
bfbd6dc1
VZ
109 event.SetClientObject(GetClientObject());
110 break;
111
1e6feb95 112 case wxClientData_None:
bfbd6dc1
VZ
113 // nothing to do
114 ;
115 }
116}
117
9f884528
RD
118bool wxControlBase::SetFont(const wxFont& font)
119{
120 InvalidateBestSize();
121 return wxWindow::SetFont(font);
122}
123
a3a4105d
VZ
124// wxControl-specific processing after processing the update event
125void wxControlBase::DoUpdateWindowUI(wxUpdateUIEvent& event)
126{
127 // call inherited
128 wxWindowBase::DoUpdateWindowUI(event);
129
130 // update label
131 if ( event.GetSetText() )
132 {
133 if ( event.GetText() != GetLabel() )
134 SetLabel(event.GetText());
135 }
136
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.
140#if wxUSE_RADIOBTN
141 if ( event.GetSetChecked() )
142 {
143 wxRadioButton *radiobtn = wxDynamicCastThis(wxRadioButton);
144 if ( radiobtn )
145 radiobtn->SetValue(event.GetChecked());
146 }
147#endif // wxUSE_RADIOBTN
148}
149
32ee98eb
FM
150/* static */
151wxString wxControlBase::GetLabelText(const wxString& label)
152{
153 // we don't want strip the TABs here, just the mnemonics
154 return wxStripMenuCodes(label, wxStrip_Mnemonics);
155}
156
39bc0347
VZ
157/* static */
158wxString wxControlBase::RemoveMnemonics(const wxString& str)
159{
32ee98eb 160 // we don't want strip the TABs here, just the mnemonics
39bc0347
VZ
161 return wxStripMenuCodes(str, wxStrip_Mnemonics);
162}
163
5b8b2c84
VZ
164/* static */
165wxString wxControlBase::EscapeMnemonics(const wxString& text)
166{
167 wxString label(text);
168 label.Replace("&", "&&");
169 return label;
170}
171
916eabe6
VZ
172/* static */
173int wxControlBase::FindAccelIndex(const wxString& label, wxString *labelOnly)
174{
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
9a83f860 178 static const wxChar MNEMONIC_PREFIX = wxT('&');
916eabe6
VZ
179
180 if ( labelOnly )
181 {
182 labelOnly->Empty();
183 labelOnly->Alloc(label.length());
184 }
185
186 int indexAccel = -1;
187 for ( wxString::const_iterator pc = label.begin(); pc != label.end(); ++pc )
188 {
189 if ( *pc == MNEMONIC_PREFIX )
190 {
191 ++pc; // skip it
192 if ( pc == label.end() )
193 break;
194 else if ( *pc != MNEMONIC_PREFIX )
195 {
196 if ( indexAccel == -1 )
197 {
198 // remember it (-1 is for MNEMONIC_PREFIX itself
199 indexAccel = pc - label.begin() - 1;
200 }
201 else
202 {
9a83f860 203 wxFAIL_MSG(wxT("duplicate accel char in control label"));
916eabe6
VZ
204 }
205 }
206 }
207
208 if ( labelOnly )
209 {
210 *labelOnly += *pc;
211 }
212 }
213
214 return indexAccel;
215}
216
a78618b0
FM
217wxBorder wxControlBase::GetDefaultBorder() const
218{
219 return wxBORDER_THEME;
220}
221
0534259a
VZ
222/* static */ wxVisualAttributes
223wxControlBase::GetCompositeControlsDefaultAttributes(wxWindowVariant WXUNUSED(variant))
224{
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);
229
230 return attrs;
231}
232
a78618b0
FM
233// ----------------------------------------------------------------------------
234// wxControlBase - ellipsization code
235// ----------------------------------------------------------------------------
236
8ab11e46 237#define wxELLIPSE_REPLACEMENT wxS("...")
5c87527c 238
38ddd614
VS
239namespace
240{
241
242struct EllipsizeCalculator
243{
244 EllipsizeCalculator(const wxString& s, const wxDC& dc,
245 int maxFinalWidthPx, int replacementWidthPx)
246 :
247 m_initialCharToRemove(0),
248 m_nCharsToRemove(0),
249 m_outputNeedsUpdate(true),
250 m_str(s),
251 m_dc(dc),
252 m_maxFinalWidthPx(maxFinalWidthPx),
253 m_replacementWidthPx(replacementWidthPx)
254 {
255 m_isOk = dc.GetPartialTextExtents(s, m_charOffsetsPx);
256 wxASSERT( m_charOffsetsPx.GetCount() == s.length() );
257 }
258
259 bool IsOk() const { return m_isOk; }
260
261 bool EllipsizationNotNeeded() const
262 {
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;
266 }
267
268 void Init(size_t initialCharToRemove, size_t nCharsToRemove)
269 {
270 m_initialCharToRemove = initialCharToRemove;
271 m_nCharsToRemove = nCharsToRemove;
272 }
273
274 void RemoveFromEnd()
275 {
276 m_nCharsToRemove++;
277 }
278
279 void RemoveFromStart()
280 {
281 m_initialCharToRemove--;
282 m_nCharsToRemove++;
283 }
284
285 size_t GetFirstRemoved() const { return m_initialCharToRemove; }
286 size_t GetLastRemoved() const { return m_initialCharToRemove + m_nCharsToRemove - 1; }
287
288 const wxString& GetEllipsizedText()
289 {
290 if ( m_outputNeedsUpdate )
291 {
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
294
295 // erase m_nCharsToRemove characters after m_initialCharToRemove (included);
296 // e.g. if we have the string "foobar" (len = 6)
297 // ^
298 // \--- m_initialCharToRemove = 2
299 // and m_nCharsToRemove = 2, then we get "foar"
300 m_output = m_str;
301 m_output.replace(m_initialCharToRemove, m_nCharsToRemove, wxELLIPSE_REPLACEMENT);
302 }
303
304 return m_output;
305 }
306
307 bool IsShortEnough()
308 {
309 if ( m_nCharsToRemove == m_str.length() )
310 return true; // that's the best we could do
311
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.
316 //
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
321 // it looks good.
322
323 int estimatedWidth = m_replacementWidthPx; // length of "..."
324
325 // length of text before the removed part:
326 if ( m_initialCharToRemove > 0 )
327 estimatedWidth += m_charOffsetsPx[m_initialCharToRemove - 1];
328
329 // length of text after the removed part:
330
331 if ( GetLastRemoved() < m_str.length() )
332 estimatedWidth += m_charOffsetsPx.Last() - m_charOffsetsPx[GetLastRemoved()];
333
334 if ( estimatedWidth > m_maxFinalWidthPx )
335 return false;
336
337 return m_dc.GetTextExtent(GetEllipsizedText()).GetWidth() <= m_maxFinalWidthPx;
338 }
339
340 // calculation state:
341
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)
347
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;
352
353 wxString m_output;
354 bool m_outputNeedsUpdate;
355
356 // inputs:
357 wxString m_str;
358 const wxDC& m_dc;
359 int m_maxFinalWidthPx;
360 int m_replacementWidthPx;
361 wxArrayInt m_charOffsetsPx;
362
363 bool m_isOk;
364};
365
366} // anonymous namespace
367
a78618b0
FM
368/* static and protected */
369wxString wxControlBase::DoEllipsizeSingleLine(const wxString& curLine, const wxDC& dc,
8ab11e46 370 wxEllipsizeMode mode, int maxFinalWidthPx,
1d065710 371 int replacementWidthPx)
a78618b0 372{
1d065710 373 wxASSERT_MSG(replacementWidthPx > 0, "Invalid parameters");
a37da0fa
FM
374 wxASSERT_LEVEL_2_MSG(!curLine.Contains('\n'),
375 "Use Ellipsize() instead!");
a78618b0 376
c937bcac
VZ
377 wxASSERT_MSG( mode != wxELLIPSIZE_NONE, "shouldn't be called at all then" );
378
a78618b0
FM
379 // NOTE: this function assumes that any mnemonic/tab character has already
380 // been handled if it was necessary to handle them (see Ellipsize())
381
8ab11e46 382 if (maxFinalWidthPx <= 0)
a78618b0
FM
383 return wxEmptyString;
384
a78618b0 385 size_t len = curLine.length();
38ddd614 386 if (len <= 1 )
a78618b0
FM
387 return curLine;
388
38ddd614 389 EllipsizeCalculator calc(curLine, dc, maxFinalWidthPx, replacementWidthPx);
a78618b0 390
38ddd614
VS
391 if ( !calc.IsOk() )
392 return curLine;
a78618b0 393
38ddd614
VS
394 if ( calc.EllipsizationNotNeeded() )
395 return curLine;
a37da0fa
FM
396
397 // let's compute the range of characters to remove depending on the ellipsization mode:
a78618b0
FM
398 switch (mode)
399 {
8d6e8e45 400 case wxELLIPSIZE_START:
38ddd614
VS
401 {
402 calc.Init(0, 1);
403 while ( !calc.IsShortEnough() )
404 calc.RemoveFromEnd();
4b52555d
VS
405
406 // always show at least one character of the string:
407 if ( calc.m_nCharsToRemove == len )
408 return wxString(wxELLIPSE_REPLACEMENT) + curLine[len-1];
409
38ddd614
VS
410 break;
411 }
a78618b0 412
8d6e8e45 413 case wxELLIPSIZE_MIDDLE:
a78618b0 414 {
a37da0fa
FM
415 // NOTE: the following piece of code works also when len == 1
416
417 // start the removal process from the middle of the string
ce00f59b 418 // i.e. separe the string in three parts:
a37da0fa
FM
419 // - the first one to preserve, valid range [0;initialCharToRemove-1] or the empty range if initialCharToRemove==0
420 // - the second one to remove, valid range [initialCharToRemove;endCharToRemove]
421 // - the third one to preserve, valid range [endCharToRemove+1;len-1] or the empty range if endCharToRemove==len-1
422 // NOTE: empty range != range [0;0] since the range [0;0] contains 1 character (the zero-th one)!
a78618b0 423
38ddd614
VS
424 calc.Init(len/2, 0);
425
3433de6e 426 bool removeFromStart = true;
38ddd614
VS
427
428 while ( !calc.IsShortEnough() )
a78618b0 429 {
38ddd614
VS
430 const bool canRemoveFromStart = calc.GetFirstRemoved() > 0;
431 const bool canRemoveFromEnd = calc.GetLastRemoved() < len - 1;
3433de6e
VS
432
433 if ( !canRemoveFromStart && !canRemoveFromEnd )
434 {
435 // we need to remove all the characters of the string!
436 break;
437 }
438
439 // Remove from the beginning in even steps and from the end
440 // in odd steps, unless we exhausted one side already:
441 removeFromStart = !removeFromStart;
442 if ( removeFromStart && !canRemoveFromStart )
443 removeFromStart = false;
444 else if ( !removeFromStart && !canRemoveFromEnd )
445 removeFromStart = true;
446
447 if ( removeFromStart )
38ddd614
VS
448 calc.RemoveFromStart();
449 else
450 calc.RemoveFromEnd();
a78618b0 451 }
4b52555d
VS
452
453 // Always show at least one character of the string.
454 // Additionally, if there's only one character left, prefer
455 // "a..." to "...a":
456 if ( calc.m_nCharsToRemove == len ||
457 calc.m_nCharsToRemove == len - 1 )
458 {
459 return curLine[0] + wxString(wxELLIPSE_REPLACEMENT);
460 }
a78618b0 461 }
8d6e8e45 462 break;
a78618b0 463
8d6e8e45
VZ
464 case wxELLIPSIZE_END:
465 {
38ddd614
VS
466 calc.Init(len - 1, 1);
467 while ( !calc.IsShortEnough() )
468 calc.RemoveFromStart();
4b52555d
VS
469
470 // always show at least one character of the string:
471 if ( calc.m_nCharsToRemove == len )
472 return curLine[0] + wxString(wxELLIPSE_REPLACEMENT);
473
38ddd614 474 break;
a78618b0 475 }
a78618b0 476
c937bcac 477 case wxELLIPSIZE_NONE:
8d6e8e45
VZ
478 default:
479 wxFAIL_MSG("invalid ellipsize mode");
480 return curLine;
a78618b0
FM
481 }
482
38ddd614 483 return calc.GetEllipsizedText();
a78618b0
FM
484}
485
5c87527c
FM
486/* static */
487wxString wxControlBase::Ellipsize(const wxString& label, const wxDC& dc,
a78618b0
FM
488 wxEllipsizeMode mode, int maxFinalWidth,
489 int flags)
5c87527c 490{
5c87527c
FM
491 wxString ret;
492
a78618b0
FM
493 // these cannot be cached between different Ellipsize() calls as they can
494 // change because of e.g. a font change; however we calculate them only once
495 // when ellipsizing multiline labels:
5c87527c 496 int replacementWidth = dc.GetTextExtent(wxELLIPSE_REPLACEMENT).GetWidth();
5c87527c
FM
497
498 // NB: we must handle correctly labels with newlines:
499 wxString curLine;
5c87527c
FM
500 for ( wxString::const_iterator pc = label.begin(); ; ++pc )
501 {
a78618b0 502 if ( pc == label.end() || *pc == wxS('\n') )
5c87527c 503 {
a78618b0 504 curLine = DoEllipsizeSingleLine(curLine, dc, mode, maxFinalWidth,
1d065710 505 replacementWidth);
5c87527c
FM
506
507 // add this (ellipsized) row to the rest of the label
508 ret << curLine;
509 if ( pc == label.end() )
510 {
7d27b626 511 // NOTE: this is the return which always exits the function
5c87527c
FM
512 return ret;
513 }
514 else
515 {
516 ret << *pc;
517 curLine.clear();
518 }
519 }
520 // we need to remove mnemonics from the label for correct calculations
355ce7ad 521 else if ( *pc == wxS('&') && (flags & wxELLIPSIZE_FLAGS_PROCESS_MNEMONICS) )
5c87527c
FM
522 {
523 // pc+1 is safe: at worst we'll be at end()
524 wxString::const_iterator next = pc + 1;
a78618b0
FM
525 if ( next != label.end() && *next == wxS('&') )
526 curLine += wxS('&'); // && becomes &
5c87527c
FM
527 //else: remove this ampersand
528 }
529 // we need also to expand tabs to properly calc their size
355ce7ad 530 else if ( *pc == wxS('\t') && (flags & wxELLIPSIZE_FLAGS_EXPAND_TABS) )
5c87527c
FM
531 {
532 // Windows natively expands the TABs to 6 spaces. Do the same:
a78618b0 533 curLine += wxS(" ");
5c87527c
FM
534 }
535 else
536 {
537 curLine += *pc;
538 }
539 }
540
02b4f9fd 541 // this return would generate a
7d27b626 542 // warning C4702: unreachable code
02b4f9fd 543 // with MSVC since the function always exits from inside the loop
7d27b626 544 //return ret;
5c87527c
FM
545}
546
dc797d8e
JS
547
548
1e6feb95
VZ
549// ----------------------------------------------------------------------------
550// wxStaticBitmap
551// ----------------------------------------------------------------------------
552
553#if wxUSE_STATBMP
554
799ea011
GD
555wxStaticBitmapBase::~wxStaticBitmapBase()
556{
557 // this destructor is required for Darwin
558}
559
b3fcfa4d 560wxSize wxStaticBitmapBase::DoGetBestSize() const
1e6feb95 561{
9f884528 562 wxSize best;
1e6feb95
VZ
563 wxBitmap bmp = GetBitmap();
564 if ( bmp.Ok() )
9f884528
RD
565 best = wxSize(bmp.GetWidth(), bmp.GetHeight());
566 else
567 // this is completely arbitrary
568 best = wxSize(16, 16);
569 CacheBestSize(best);
570 return best;
1e6feb95
VZ
571}
572
573#endif // wxUSE_STATBMP
574
575#endif // wxUSE_CONTROLS