use YieldFor() in wxTopLevelWindowGTK::RequestUserAttention; comment on the use of...
[wxWidgets.git] / src / generic / progdlgg.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/generic/progdlgg.cpp
3 // Purpose: wxProgressDialog class
4 // Author: Karsten Ballueder
5 // Modified by:
6 // Created: 09.05.1999
7 // RCS-ID: $Id$
8 // Copyright: (c) Karsten Ballueder
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #if wxUSE_PROGRESSDLG
28
29 #ifndef WX_PRECOMP
30 #include "wx/utils.h"
31 #include "wx/frame.h"
32 #include "wx/button.h"
33 #include "wx/stattext.h"
34 #include "wx/sizer.h"
35 #include "wx/event.h"
36 #include "wx/gauge.h"
37 #include "wx/intl.h"
38 #include "wx/dcclient.h"
39 #include "wx/timer.h"
40 #include "wx/settings.h"
41 #include "wx/app.h"
42 #endif
43
44 #include "wx/progdlg.h"
45 #include "wx/evtloop.h"
46
47 // ---------------------------------------------------------------------------
48 // macros
49 // ---------------------------------------------------------------------------
50
51 /* Macro for avoiding #ifdefs when value have to be different depending on size of
52 device we display on - take it from something like wxDesktopPolicy in the future
53 */
54
55 #if defined(__SMARTPHONE__)
56 #define wxLARGESMALL(large,small) small
57 #else
58 #define wxLARGESMALL(large,small) large
59 #endif
60
61 // ----------------------------------------------------------------------------
62 // constants
63 // ----------------------------------------------------------------------------
64
65 #define LAYOUT_MARGIN wxLARGESMALL(8,2)
66
67 static const int wxID_SKIP = 32000; // whatever
68
69 // ----------------------------------------------------------------------------
70 // private functions
71 // ----------------------------------------------------------------------------
72
73 // update the label to show the given time (in seconds)
74 static void SetTimeLabel(unsigned long val, wxStaticText *label);
75
76 // ----------------------------------------------------------------------------
77 // event tables
78 // ----------------------------------------------------------------------------
79
80 BEGIN_EVENT_TABLE(wxProgressDialog, wxDialog)
81 EVT_BUTTON(wxID_CANCEL, wxProgressDialog::OnCancel)
82 EVT_BUTTON(wxID_SKIP, wxProgressDialog::OnSkip)
83
84 EVT_CLOSE(wxProgressDialog::OnClose)
85 END_EVENT_TABLE()
86
87 IMPLEMENT_CLASS(wxProgressDialog, wxDialog)
88
89 // ============================================================================
90 // wxProgressDialog implementation
91 // ============================================================================
92
93 // ----------------------------------------------------------------------------
94 // wxProgressDialog creation
95 // ----------------------------------------------------------------------------
96
97 wxProgressDialog::wxProgressDialog(const wxString& title,
98 const wxString& message,
99 int maximum,
100 wxWindow *parent,
101 int style)
102 : wxDialog(GetParentForModalDialog(parent), wxID_ANY, title),
103 m_skip(false),
104 m_delay(3),
105 m_hasAbortButton(false),
106 m_hasSkipButton(false)
107 {
108 // we may disappear at any moment, let the others know about it
109 SetExtraStyle(GetExtraStyle() | wxWS_EX_TRANSIENT);
110 m_windowStyle |= style;
111
112 m_hasAbortButton = (style & wxPD_CAN_ABORT) != 0;
113 m_hasSkipButton = (style & wxPD_CAN_SKIP) != 0;
114
115 #if defined(__WXMSW__) && !defined(__WXUNIVERSAL__)
116 // we have to remove the "Close" button from the title bar then as it is
117 // confusing to have it - it doesn't work anyhow
118 //
119 // FIXME: should probably have a (extended?) window style for this
120 if ( !m_hasAbortButton )
121 {
122 EnableCloseButton(false);
123 }
124 #endif // wxMSW
125
126 #if defined(__SMARTPHONE__)
127 SetLeftMenu();
128 #endif
129
130 m_state = m_hasAbortButton ? Continue : Uncancelable;
131 m_maximum = maximum;
132
133 #if defined(__WXMSW__) || defined(__WXPM__)
134 // we can't have values > 65,536 in the progress control under Windows, so
135 // scale everything down
136 m_factor = m_maximum / 65536 + 1;
137 m_maximum /= m_factor;
138 #endif // __WXMSW__
139
140 m_parentTop = wxGetTopLevelParent(parent);
141
142 wxClientDC dc(this);
143 dc.SetFont(wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT));
144 wxCoord widthText = 0;
145 dc.GetTextExtent(message, &widthText, NULL, NULL, NULL, NULL);
146
147 // top-level sizerTop
148 wxSizer * const sizerTop = new wxBoxSizer(wxVERTICAL);
149
150 m_msg = new wxStaticText(this, wxID_ANY, message);
151 sizerTop->Add(m_msg, 0, wxLEFT | wxTOP, 2*LAYOUT_MARGIN);
152
153 if ( maximum > 0 )
154 {
155 int gauge_style = wxGA_HORIZONTAL;
156 if ( style & wxPD_SMOOTH )
157 gauge_style |= wxGA_SMOOTH;
158 m_gauge = new wxGauge
159 (
160 this,
161 wxID_ANY,
162 m_maximum,
163 wxDefaultPosition,
164 // make the progress bar sufficiently long
165 wxSize(wxMin(wxGetClientDisplayRect().width/3, 300), -1),
166 gauge_style
167 );
168
169 sizerTop->Add(m_gauge, 0, wxLEFT | wxRIGHT | wxTOP | wxEXPAND, 2*LAYOUT_MARGIN);
170 m_gauge->SetValue(0);
171 }
172 else
173 {
174 m_gauge = NULL;
175 }
176
177 // create the estimated/remaining/total time zones if requested
178 m_elapsed =
179 m_estimated =
180 m_remaining = NULL;
181 m_display_estimated =
182 m_last_timeupdate =
183 m_break = 0;
184 m_ctdelay = 0;
185
186 // also count how many labels we really have
187 size_t nTimeLabels = 0;
188
189 wxSizer * const sizerLabels = new wxFlexGridSizer(2);
190
191 if ( style & wxPD_ELAPSED_TIME )
192 {
193 nTimeLabels++;
194
195 m_elapsed = CreateLabel(_("Elapsed time:"), sizerLabels);
196 }
197
198 if ( style & wxPD_ESTIMATED_TIME )
199 {
200 nTimeLabels++;
201
202 m_estimated = CreateLabel(_("Estimated time:"), sizerLabels);
203 }
204
205 if ( style & wxPD_REMAINING_TIME )
206 {
207 nTimeLabels++;
208
209 m_remaining = CreateLabel(_("Remaining time:"), sizerLabels);
210 }
211 sizerTop->Add(sizerLabels, 0, wxALIGN_CENTER_HORIZONTAL | wxTOP, LAYOUT_MARGIN);
212
213 if ( nTimeLabels > 0 )
214 {
215 // set it to the current time
216 m_timeStart = wxGetCurrentTime();
217 }
218
219 #if defined(__SMARTPHONE__)
220 if ( m_hasSkipButton )
221 SetRightMenu(wxID_SKIP, _("Skip"));
222 if ( m_hasAbortButton )
223 SetLeftMenu(wxID_CANCEL);
224 #else
225 m_btnAbort =
226 m_btnSkip = NULL;
227
228 wxBoxSizer *buttonSizer = new wxBoxSizer(wxHORIZONTAL);
229
230 // Windows dialogs usually have buttons in the lower right corner
231 const int sizerFlags =
232 #if defined(__WXMSW__) || defined(__WXPM__)
233 wxALIGN_RIGHT | wxALL
234 #else // !MSW
235 wxALIGN_CENTER_HORIZONTAL | wxBOTTOM | wxTOP
236 #endif // MSW/!MSW
237 ;
238
239 if ( m_hasSkipButton )
240 {
241 m_btnSkip = new wxButton(this, wxID_SKIP, _("&Skip"));
242
243 buttonSizer->Add(m_btnSkip, 0, sizerFlags, LAYOUT_MARGIN);
244 }
245
246 if ( m_hasAbortButton )
247 {
248 m_btnAbort = new wxButton(this, wxID_CANCEL);
249
250 buttonSizer->Add(m_btnAbort, 0, sizerFlags, LAYOUT_MARGIN);
251 }
252
253 sizerTop->Add(buttonSizer, 0, sizerFlags, LAYOUT_MARGIN );
254 #endif // __SMARTPHONE__/!__SMARTPHONE__
255
256 SetSizerAndFit(sizerTop);
257
258 Centre(wxCENTER_FRAME | wxBOTH);
259
260 if ( style & wxPD_APP_MODAL )
261 {
262 m_winDisabler = new wxWindowDisabler(this);
263 }
264 else
265 {
266 if ( m_parentTop )
267 m_parentTop->Disable();
268 m_winDisabler = NULL;
269 }
270
271 Show();
272 Enable();
273
274 // this one can be initialized even if the others are unknown for now
275 //
276 // NB: do it after calling Layout() to keep the labels correctly aligned
277 if ( m_elapsed )
278 {
279 SetTimeLabel(0, m_elapsed);
280 }
281
282 Update();
283 }
284
285 wxStaticText *
286 wxProgressDialog::CreateLabel(const wxString& text, wxSizer *sizer)
287 {
288 wxStaticText *label = new wxStaticText(this, wxID_ANY, text);
289 wxStaticText *value = new wxStaticText(this, wxID_ANY, _("unknown"));
290
291 // select placement most native or nice on target GUI
292 #if defined(__SMARTPHONE__)
293 // value and time to the left in two rows
294 sizer->Add(label, 1, wxALIGN_LEFT);
295 sizer->Add(value, 1, wxALIGN_LEFT);
296 #elif defined(__WXMSW__) || defined(__WXPM__) || defined(__WXMAC__) || defined(__WXGTK20__)
297 // value and time centered in one row
298 sizer->Add(label, 1, wxLARGESMALL(wxALIGN_RIGHT,wxALIGN_LEFT) | wxTOP | wxRIGHT, LAYOUT_MARGIN);
299 sizer->Add(value, 1, wxALIGN_LEFT | wxTOP, LAYOUT_MARGIN);
300 #else
301 // value and time to the right in one row
302 sizer->Add(label);
303 sizer->Add(value, 0, wxLEFT, LAYOUT_MARGIN);
304 #endif
305
306 return value;
307 }
308
309 // ----------------------------------------------------------------------------
310 // wxProgressDialog operations
311 // ----------------------------------------------------------------------------
312
313 bool
314 wxProgressDialog::Update(int value, const wxString& newmsg, bool *skip)
315 {
316 wxASSERT_MSG( value == -1 || m_gauge, wxT("cannot update non existent dialog") );
317
318 #ifdef __WXMSW__
319 value /= m_factor;
320 #endif // __WXMSW__
321
322 wxASSERT_MSG( value <= m_maximum, wxT("invalid progress value") );
323
324 if ( m_gauge )
325 m_gauge->SetValue(value);
326
327 UpdateMessage(newmsg);
328
329 if ( (m_elapsed || m_remaining || m_estimated) && (value != 0) )
330 {
331 unsigned long elapsed = wxGetCurrentTime() - m_timeStart;
332 if ( m_last_timeupdate < elapsed
333 || value == m_maximum
334 )
335 {
336 m_last_timeupdate = elapsed;
337 unsigned long estimated = m_break +
338 (unsigned long)(( (double) (elapsed-m_break) * m_maximum ) / ((double)value)) ;
339 if ( estimated > m_display_estimated
340 && m_ctdelay >= 0
341 )
342 {
343 ++m_ctdelay;
344 }
345 else if ( estimated < m_display_estimated
346 && m_ctdelay <= 0
347 )
348 {
349 --m_ctdelay;
350 }
351 else
352 {
353 m_ctdelay = 0;
354 }
355 if ( m_ctdelay >= m_delay // enough confirmations for a higher value
356 || m_ctdelay <= (m_delay*-1) // enough confirmations for a lower value
357 || value == m_maximum // to stay consistent
358 || elapsed > m_display_estimated // to stay consistent
359 || ( elapsed > 0 && elapsed < 4 ) // additional updates in the beginning
360 )
361 {
362 m_display_estimated = estimated;
363 m_ctdelay = 0;
364 }
365 }
366
367 long display_remaining = m_display_estimated - elapsed;
368 if ( display_remaining < 0 )
369 {
370 display_remaining = 0;
371 }
372
373 SetTimeLabel(elapsed, m_elapsed);
374 SetTimeLabel(m_display_estimated, m_estimated);
375 SetTimeLabel(display_remaining, m_remaining);
376 }
377
378 if ( value == m_maximum )
379 {
380 if ( m_state == Finished )
381 {
382 // ignore multiple calls to Update(m_maximum): it may sometimes be
383 // troublesome to ensure that Update() is not called twice with the
384 // same value (e.g. because of the rounding errors) and if we don't
385 // return now we're going to generate asserts below
386 return true;
387 }
388
389 // so that we return true below and that out [Cancel] handler knew what
390 // to do
391 m_state = Finished;
392 if( !HasFlag(wxPD_AUTO_HIDE) )
393 {
394 EnableClose();
395 DisableSkip();
396 #if defined(__WXMSW__) && !defined(__WXUNIVERSAL__)
397 EnableCloseButton();
398 #endif // __WXMSW__
399
400 if ( newmsg.empty() )
401 {
402 // also provide the finishing message if the application didn't
403 m_msg->SetLabel(_("Done."));
404 }
405
406 // allow the window to repaint:
407 // NOTE: since we yield only for UI events with this call, there
408 // should be no side-effects
409 wxEventLoopBase::GetActive()->YieldFor(wxEVT_CATEGORY_UI);
410
411 (void)ShowModal();
412 }
413 else // auto hide
414 {
415 // reenable other windows before hiding this one because otherwise
416 // Windows wouldn't give the focus back to the window which had
417 // been previously focused because it would still be disabled
418 ReenableOtherWindows();
419
420 Hide();
421 }
422 }
423 else // not at maximum yet
424 {
425 return DoAfterUpdate(skip);
426 }
427
428 // update the display in case yielding above didn't do it
429 Update();
430
431 return m_state != Canceled;
432 }
433
434 bool wxProgressDialog::Pulse(const wxString& newmsg, bool *skip)
435 {
436 wxASSERT_MSG( m_gauge, wxT("cannot update non existent dialog") );
437
438 // show a bit of progress
439 m_gauge->Pulse();
440
441 UpdateMessage(newmsg);
442
443 if (m_elapsed || m_remaining || m_estimated)
444 {
445 unsigned long elapsed = wxGetCurrentTime() - m_timeStart;
446
447 SetTimeLabel(elapsed, m_elapsed);
448 SetTimeLabel((unsigned long)-1, m_estimated);
449 SetTimeLabel((unsigned long)-1, m_remaining);
450 }
451
452 return DoAfterUpdate(skip);
453 }
454
455 bool wxProgressDialog::DoAfterUpdate(bool *skip)
456 {
457 // we have to yield because not only we want to update the display but
458 // also to process the clicks on the cancel and skip buttons
459 // NOTE: using YieldFor() this call shouldn't give re-entrancy problems
460 // for event handlers not interested to UI/user-input events.
461 wxEventLoopBase::GetActive()->YieldFor(wxEVT_CATEGORY_UI|wxEVT_CATEGORY_USER_INPUT);
462
463 Update();
464
465 if ( m_skip && skip && !*skip )
466 {
467 *skip = true;
468 m_skip = false;
469 EnableSkip();
470 }
471
472 return m_state != Canceled;
473 }
474
475 void wxProgressDialog::Resume()
476 {
477 m_state = Continue;
478 m_ctdelay = m_delay; // force an update of the elapsed/estimated/remaining time
479 m_break += wxGetCurrentTime()-m_timeStop;
480
481 EnableAbort();
482 EnableSkip();
483 m_skip = false;
484 }
485
486 bool wxProgressDialog::Show( bool show )
487 {
488 // reenable other windows before hiding this one because otherwise
489 // Windows wouldn't give the focus back to the window which had
490 // been previously focused because it would still be disabled
491 if(!show)
492 ReenableOtherWindows();
493
494 return wxDialog::Show(show);
495 }
496
497 int wxProgressDialog::GetValue() const
498 {
499 if (m_gauge)
500 return m_gauge->GetValue();
501 return wxNOT_FOUND;
502 }
503
504 int wxProgressDialog::GetRange() const
505 {
506 if (m_gauge)
507 return m_gauge->GetRange();
508 return wxNOT_FOUND;
509 }
510
511 wxString wxProgressDialog::GetMessage() const
512 {
513 return m_msg->GetLabel();
514 }
515
516 // ----------------------------------------------------------------------------
517 // event handlers
518 // ----------------------------------------------------------------------------
519
520 void wxProgressDialog::OnCancel(wxCommandEvent& event)
521 {
522 if ( m_state == Finished )
523 {
524 // this means that the count down is already finished and we're being
525 // shown as a modal dialog - so just let the default handler do the job
526 event.Skip();
527 }
528 else
529 {
530 // request to cancel was received, the next time Update() is called we
531 // will handle it
532 m_state = Canceled;
533
534 // update the buttons state immediately so that the user knows that the
535 // request has been noticed
536 DisableAbort();
537 DisableSkip();
538
539 // save the time when the dialog was stopped
540 m_timeStop = wxGetCurrentTime();
541 }
542 }
543
544 void wxProgressDialog::OnSkip(wxCommandEvent& WXUNUSED(event))
545 {
546 DisableSkip();
547 m_skip = true;
548 }
549
550 void wxProgressDialog::OnClose(wxCloseEvent& event)
551 {
552 if ( m_state == Uncancelable )
553 {
554 // can't close this dialog
555 event.Veto();
556 }
557 else if ( m_state == Finished )
558 {
559 // let the default handler close the window as we already terminated
560 event.Skip();
561 }
562 else
563 {
564 // next Update() will notice it
565 m_state = Canceled;
566 DisableAbort();
567 DisableSkip();
568
569 m_timeStop = wxGetCurrentTime();
570 }
571 }
572
573 // ----------------------------------------------------------------------------
574 // destruction
575 // ----------------------------------------------------------------------------
576
577 wxProgressDialog::~wxProgressDialog()
578 {
579 // normally this should have been already done, but just in case
580 ReenableOtherWindows();
581 }
582
583 void wxProgressDialog::ReenableOtherWindows()
584 {
585 if ( HasFlag(wxPD_APP_MODAL) )
586 {
587 delete m_winDisabler;
588 m_winDisabler = NULL;
589 }
590 else
591 {
592 if ( m_parentTop )
593 m_parentTop->Enable();
594 }
595 }
596
597 // ----------------------------------------------------------------------------
598 // private functions
599 // ----------------------------------------------------------------------------
600
601 static void SetTimeLabel(unsigned long val, wxStaticText *label)
602 {
603 if ( label )
604 {
605 wxString s;
606
607 if (val != (unsigned long)-1)
608 {
609 unsigned long hours = val / 3600;
610 unsigned long minutes = (val % 3600) / 60;
611 unsigned long seconds = val % 60;
612 s.Printf(wxT("%lu:%02lu:%02lu"), hours, minutes, seconds);
613 }
614 else
615 {
616 s = _("Unknown");
617 }
618
619 if ( s != label->GetLabel() )
620 label->SetLabel(s);
621 }
622 }
623
624 void wxProgressDialog::EnableSkip(bool enable)
625 {
626 if(m_hasSkipButton)
627 {
628 #ifdef __SMARTPHONE__
629 if(enable)
630 SetRightMenu(wxID_SKIP, _("Skip"));
631 else
632 SetRightMenu();
633 #else
634 if(m_btnSkip)
635 m_btnSkip->Enable(enable);
636 #endif
637 }
638 }
639
640 void wxProgressDialog::EnableAbort(bool enable)
641 {
642 if(m_hasAbortButton)
643 {
644 #ifdef __SMARTPHONE__
645 if(enable)
646 SetLeftMenu(wxID_CANCEL); // stock buttons makes Cancel label
647 else
648 SetLeftMenu();
649 #else
650 if(m_btnAbort)
651 m_btnAbort->Enable(enable);
652 #endif
653 }
654 }
655
656 void wxProgressDialog::EnableClose()
657 {
658 if(m_hasAbortButton)
659 {
660 #ifdef __SMARTPHONE__
661 SetLeftMenu(wxID_CANCEL, _("Close"));
662 #else
663 if(m_btnAbort)
664 {
665 m_btnAbort->Enable();
666 m_btnAbort->SetLabel(_("Close"));
667 }
668 #endif
669 }
670 }
671
672 void wxProgressDialog::UpdateMessage(const wxString &newmsg)
673 {
674 if ( !newmsg.empty() && newmsg != m_msg->GetLabel() )
675 {
676 m_msg->SetLabel(newmsg);
677
678 Fit(); // adapt to the new label size
679
680 // allow the window to repaint:
681 // NOTE: since we yield only for UI events with this call, there
682 // should be no side-effects
683 wxEventLoopBase::GetActive()->YieldFor(wxEVT_CATEGORY_UI);
684 }
685 }
686
687 #endif // wxUSE_PROGRESSDLG