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