replace ::cast_dynamic() with relevant ActionManager::get_*_action() calls
[ardour.git] / libs / gtkmm2ext / gtk_ui.cc
1 /*
2     Copyright (C) 1999-2005 Paul Barton-Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18     $Id$
19 */
20
21 #include <cmath>
22 #include <fcntl.h>
23 #include <signal.h>
24 #include <unistd.h>
25 #include <cerrno>
26 #include <climits>
27 #include <cctype>
28
29 #include <gtkmm.h>
30
31 #include "pbd/error.h"
32 #include "pbd/touchable.h"
33 #include "pbd/failed_constructor.h"
34 #include "pbd/pthread_utils.h"
35 #include "pbd/replace_all.h"
36
37 #include "gtkmm2ext/application.h"
38 #include "gtkmm2ext/bindings.h"
39 #include "gtkmm2ext/gtk_ui.h"
40 #include "gtkmm2ext/textviewer.h"
41 #include "gtkmm2ext/utils.h"
42 #include "gtkmm2ext/window_title.h"
43 #include "gtkmm2ext/actions.h"
44 #include "gtkmm2ext/activatable.h"
45 #include "gtkmm2ext/actions.h"
46 #include "gtkmm2ext/gui_thread.h"
47
48 #include "pbd/i18n.h"
49
50 using namespace Gtkmm2ext;
51 using namespace Gtk;
52 using namespace Glib;
53 using namespace PBD;
54 using std::map;
55
56 UI*   UI::theGtkUI = 0;
57
58 BaseUI::RequestType Gtkmm2ext::NullMessage = BaseUI::new_request_type();
59 BaseUI::RequestType Gtkmm2ext::ErrorMessage = BaseUI::new_request_type();
60 BaseUI::RequestType Gtkmm2ext::TouchDisplay = BaseUI::new_request_type();
61 BaseUI::RequestType Gtkmm2ext::StateChange = BaseUI::new_request_type();
62 BaseUI::RequestType Gtkmm2ext::SetTip = BaseUI::new_request_type();
63 BaseUI::RequestType Gtkmm2ext::AddIdle = BaseUI::new_request_type();
64 BaseUI::RequestType Gtkmm2ext::AddTimeout = BaseUI::new_request_type();
65
66 #include "pbd/abstract_ui.cc"  /* instantiate the template */
67
68 template class AbstractUI<Gtkmm2ext::UIRequest>;
69
70 UI::UI (string application_name, string thread_name, int *argc, char ***argv)
71         : AbstractUI<UIRequest> (thread_name)
72         , _receiver (*this)
73         , global_bindings (0)
74         , errors (0)
75 {
76         theMain = new Main (argc, argv);
77
78         pthread_set_name ("gui");
79
80         _active = false;
81
82         if (!theGtkUI) {
83                 theGtkUI = this;
84         } else {
85                 fatal << "duplicate UI requested" << endmsg;
86                 abort(); /* NOTREACHED */
87         }
88
89         /* the GUI event loop runs in the main thread of the app,
90            which is assumed to have called this.
91         */
92
93         run_loop_thread = Threads::Thread::self();
94
95         /* store "this" as the UI-for-thread of this thread, same argument
96            as for previous line.
97         */
98
99         set_event_loop_for_thread (this);
100
101         /* we will be receiving requests */
102
103         EventLoop::register_request_buffer_factory ("gui", request_buffer_factory);
104
105         /* attach our request source to the default main context */
106
107         attach_request_source ();
108
109         errors = new TextViewer (800,600);
110         errors->text().set_editable (false);
111         errors->text().set_name ("ErrorText");
112         errors->signal_unmap().connect (sigc::bind (sigc::ptr_fun (&ActionManager::uncheck_toggleaction), X_("<Actions>/Editor/toggle-log-window")));
113
114         Glib::set_application_name (application_name);
115
116         WindowTitle title(Glib::get_application_name());
117         title += _("Log");
118         errors->set_title (title.get_string());
119
120         errors->dismiss_button().set_name ("ErrorLogCloseButton");
121         errors->signal_delete_event().connect (sigc::bind (sigc::ptr_fun (just_hide_it), (Window *) errors));
122         errors->set_type_hint (Gdk::WINDOW_TYPE_HINT_UTILITY);
123
124         //load_rcfile (rcfile);
125
126         /* instantiate the Application singleton */
127
128         Application::instance();
129 }
130
131 UI::~UI ()
132 {
133         _receiver.hangup ();
134         delete (errors);
135 }
136
137 bool
138 UI::caller_is_ui_thread ()
139 {
140         return Threads::Thread::self() == run_loop_thread;
141 }
142
143 int
144 UI::load_rcfile (string path, bool themechange)
145 {
146         /* Yes, pointers to Glib::RefPtr.  If these are not kept around,
147          * a segfault somewhere deep in the wonderfully robust glib will result.
148          * This does not occur if wiget.get_style is used instead of rc.get_style below,
149          * except that doesn't actually work...
150          */
151
152         static Glib::RefPtr<Style>* fatal_style   = 0;
153         static Glib::RefPtr<Style>* error_style   = 0;
154         static Glib::RefPtr<Style>* warning_style = 0;
155         static Glib::RefPtr<Style>* info_style    = 0;
156
157         if (path.length() == 0) {
158                 return -1;
159         }
160
161         if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
162                 error << "UI: couldn't find rc file \""
163                       << path
164                       << '"'
165                       << endmsg;
166                 return -1;
167         }
168
169         RC rc (path.c_str());
170         //this is buggy in gtkmm for some reason, so use C
171         //RC::reset_styles (Gtk::Settings::get_default());
172         gtk_rc_reset_styles (gtk_settings_get_default());
173
174         theme_changed.emit();
175
176         if (themechange) {
177                 return 0; //Don't continue on every time there is a theme change
178         }
179
180         /* have to pack widgets into a toplevel window so that styles will stick */
181
182         Window temp_window (WINDOW_TOPLEVEL);
183         temp_window.ensure_style ();
184
185         HBox box;
186         Label fatal_widget;
187         Label error_widget;
188         Label warning_widget;
189         Label info_widget;
190         RefPtr<Gtk::Style> style;
191         RefPtr<TextBuffer> buffer (errors->text().get_buffer());
192
193         box.pack_start (fatal_widget);
194         box.pack_start (error_widget);
195         box.pack_start (warning_widget);
196         box.pack_start (info_widget);
197
198         error_ptag = buffer->create_tag();
199         error_mtag = buffer->create_tag();
200         fatal_ptag = buffer->create_tag();
201         fatal_mtag = buffer->create_tag();
202         warning_ptag = buffer->create_tag();
203         warning_mtag = buffer->create_tag();
204         info_ptag = buffer->create_tag();
205         info_mtag = buffer->create_tag();
206
207         fatal_widget.set_name ("FatalMessage");
208         delete fatal_style;
209
210         /* This next line and the similar ones below are sketchily
211          * guessed to fix #2885.  I think maybe that problems occur
212          * because with gtk_rc_get_style (to quote its docs) "no
213          * refcount is added to the returned style".  So I've switched
214          * this to use Glib::wrap with take_copy == true, which requires
215          * all the nasty casts and calls to plain-old-C GTK.
216          *
217          * At worst I think this causes a memory leak; at least it appears
218          * to fix the bug.
219          *
220          * I could be wrong about any or all of the above.
221          */
222         fatal_style = new Glib::RefPtr<Style> (Glib::wrap (gtk_rc_get_style (reinterpret_cast<GtkWidget*> (fatal_widget.gobj())), true));
223
224         fatal_ptag->property_font_desc().set_value((*fatal_style)->get_font());
225         fatal_ptag->property_foreground_gdk().set_value((*fatal_style)->get_fg(STATE_ACTIVE));
226         fatal_ptag->property_background_gdk().set_value((*fatal_style)->get_bg(STATE_ACTIVE));
227         fatal_mtag->property_font_desc().set_value((*fatal_style)->get_font());
228         fatal_mtag->property_foreground_gdk().set_value((*fatal_style)->get_fg(STATE_NORMAL));
229         fatal_mtag->property_background_gdk().set_value((*fatal_style)->get_bg(STATE_NORMAL));
230
231         error_widget.set_name ("ErrorMessage");
232         delete error_style;
233         error_style = new Glib::RefPtr<Style> (Glib::wrap (gtk_rc_get_style (reinterpret_cast<GtkWidget*> (error_widget.gobj())), true));
234
235         error_ptag->property_font_desc().set_value((*error_style)->get_font());
236         error_ptag->property_foreground_gdk().set_value((*error_style)->get_fg(STATE_ACTIVE));
237         error_ptag->property_background_gdk().set_value((*error_style)->get_bg(STATE_ACTIVE));
238         error_mtag->property_font_desc().set_value((*error_style)->get_font());
239         error_mtag->property_foreground_gdk().set_value((*error_style)->get_fg(STATE_NORMAL));
240         error_mtag->property_background_gdk().set_value((*error_style)->get_bg(STATE_NORMAL));
241
242         warning_widget.set_name ("WarningMessage");
243         delete warning_style;
244         warning_style = new Glib::RefPtr<Style> (Glib::wrap (gtk_rc_get_style (reinterpret_cast<GtkWidget*> (warning_widget.gobj())), true));
245
246         warning_ptag->property_font_desc().set_value((*warning_style)->get_font());
247         warning_ptag->property_foreground_gdk().set_value((*warning_style)->get_fg(STATE_ACTIVE));
248         warning_ptag->property_background_gdk().set_value((*warning_style)->get_bg(STATE_ACTIVE));
249         warning_mtag->property_font_desc().set_value((*warning_style)->get_font());
250         warning_mtag->property_foreground_gdk().set_value((*warning_style)->get_fg(STATE_NORMAL));
251         warning_mtag->property_background_gdk().set_value((*warning_style)->get_bg(STATE_NORMAL));
252
253         info_widget.set_name ("InfoMessage");
254         delete info_style;
255         info_style = new Glib::RefPtr<Style> (Glib::wrap (gtk_rc_get_style (reinterpret_cast<GtkWidget*> (info_widget.gobj())), true));
256
257         info_ptag->property_font_desc().set_value((*info_style)->get_font());
258         info_ptag->property_foreground_gdk().set_value((*info_style)->get_fg(STATE_ACTIVE));
259         info_ptag->property_background_gdk().set_value((*info_style)->get_bg(STATE_ACTIVE));
260         info_mtag->property_font_desc().set_value((*info_style)->get_font());
261         info_mtag->property_foreground_gdk().set_value((*info_style)->get_fg(STATE_NORMAL));
262         info_mtag->property_background_gdk().set_value((*info_style)->get_bg(STATE_NORMAL));
263
264         return 0;
265 }
266
267 void
268 UI::run (Receiver &old_receiver)
269 {
270         _receiver.listen_to (error);
271         _receiver.listen_to (info);
272         _receiver.listen_to (warning);
273         _receiver.listen_to (fatal);
274
275         /* stop the old receiver (text/console) once we hit the first idle */
276
277         Glib::signal_idle().connect (bind_return (mem_fun (old_receiver, &Receiver::hangup), false));
278
279         if (starting ()) {
280                 return;
281         }
282
283         _active = true;
284         theMain->run ();
285         _active = false;
286
287         return;
288 }
289
290 bool
291 UI::running ()
292 {
293         return _active;
294 }
295
296 void
297 UI::quit ()
298 {
299         UIRequest *req = get_request (Quit);
300
301         if (req == 0) {
302                 return;
303         }
304
305         send_request (req);
306 }
307
308 static bool idle_quit ()
309 {
310         Main::quit ();
311         return true;
312 }
313
314 void
315 UI::do_quit ()
316 {
317         if (getenv ("ARDOUR_RUNNING_UNDER_VALGRIND")) {
318                 Main::quit ();
319         } else {
320                 Glib::signal_idle().connect (sigc::ptr_fun (idle_quit));
321         }
322 }
323
324 void
325 UI::touch_display (Touchable *display)
326 {
327         UIRequest *req = get_request (TouchDisplay);
328
329         if (req == 0) {
330                 return;
331         }
332
333         req->display = display;
334
335         send_request (req);
336 }
337
338 void
339 UI::set_tip (Widget &w, const gchar *tip)
340 {
341         set_tip(&w, tip, "");
342 }
343
344 void
345 UI::set_tip (Widget &w, const std::string& tip)
346 {
347         set_tip(&w, tip.c_str(), "");
348 }
349
350 void
351 UI::set_tip (Widget *w, const gchar *tip, const gchar *hlp)
352 {
353         UIRequest *req = get_request (SetTip);
354
355         std::string msg(tip);
356
357         Glib::RefPtr<Gtk::Action> action = w->get_action();
358
359         if (!action) {
360                 Gtkmm2ext::Activatable* activatable;
361                 if ((activatable = dynamic_cast<Gtkmm2ext::Activatable*>(w))) {
362                         action = activatable->get_related_action();
363                 }
364         }
365
366         if (action) {
367                 Bindings* bindings = (Bindings*) w->get_data ("ardour-bindings");
368                 if (!bindings) {
369                         Gtk::Window* win = (Gtk::Window*) w->get_toplevel();
370                         if (win) {
371                                 bindings = (Bindings*) win->get_data ("ardour-bindings");
372                         }
373                 }
374
375                 if (!bindings) {
376                         bindings = global_bindings;
377                 }
378
379                 if (bindings) {
380                         Bindings::Operation op;
381                         KeyboardKey kb = bindings->get_binding_for_action (action, op);
382                         string shortcut = kb.display_label ();
383                         if (!shortcut.empty()) {
384                                 replace_all (shortcut, "<", "");
385                                 replace_all (shortcut, ">", "-");
386                                 msg.append(_("\n\nShortcut: ")).append (shortcut);
387                         }
388                 }
389         }
390
391         if (req == 0) {
392                 return;
393         }
394
395
396         req->widget = w;
397         req->msg = msg.c_str();
398         req->msg2 = hlp;
399
400         send_request (req);
401 }
402
403 void
404 UI::set_state (Widget *w, StateType state)
405 {
406         UIRequest *req = get_request (StateChange);
407
408         if (req == 0) {
409                 return;
410         }
411
412         req->new_state = state;
413         req->widget = w;
414
415         send_request (req);
416 }
417
418 void
419 UI::idle_add (int (*func)(void *), void *arg)
420 {
421         UIRequest *req = get_request (AddIdle);
422
423         if (req == 0) {
424                 return;
425         }
426
427         req->function = func;
428         req->arg = arg;
429
430         send_request (req);
431 }
432
433 /* END abstract_ui interfaces */
434
435 /** Create a PBD::EventLoop::InvalidationRecord and attach a callback
436  *  to a given sigc::trackable so that PBD::EventLoop::invalidate_request
437  *  is called when that trackable is destroyed.
438  */
439 PBD::EventLoop::InvalidationRecord*
440 __invalidator (sigc::trackable& trackable, const char* file, int line)
441 {
442         PBD::EventLoop::InvalidationRecord* ir = new PBD::EventLoop::InvalidationRecord;
443
444         ir->file = file;
445         ir->line = line;
446
447         trackable.add_destroy_notify_callback (ir, PBD::EventLoop::invalidate_request);
448
449         return ir;
450 }
451
452 void
453 UI::do_request (UIRequest* req)
454 {
455         if (req->type == ErrorMessage) {
456
457                 process_error_message (req->chn, req->msg);
458                 free (const_cast<char*>(req->msg)); /* it was strdup'ed */
459                 req->msg = 0; /* don't free it again in the destructor */
460
461         } else if (req->type == Quit) {
462
463                 do_quit ();
464
465         } else if (req->type == CallSlot) {
466 #ifndef NDEBUG
467                 if (getenv ("DEBUG_THREADED_SIGNALS")) {
468                         cerr << "call slot for " << event_loop_name() << endl;
469                 }
470 #endif
471                 req->the_slot ();
472
473         } else if (req->type == TouchDisplay) {
474
475                 req->display->touch ();
476                 if (req->display->delete_after_touch()) {
477                         delete req->display;
478                 }
479
480         } else if (req->type == StateChange) {
481
482                 req->widget->set_state (req->new_state);
483
484         } else if (req->type == SetTip) {
485
486                 gchar* old = gtk_widget_get_tooltip_markup (req->widget->gobj());
487                 if (
488                                 (old && req->msg && strcmp (old, req->msg))
489                                 ||
490                                 ((old == NULL) != (req->msg == NULL || req->msg[0] == '\0'))
491                          ) {
492                         gtk_widget_set_tooltip_markup (req->widget->gobj(), req->msg);
493                 }
494
495         } else {
496
497                 error << "GtkUI: unknown request type "
498                       << (int) req->type
499                       << endmsg;
500         }
501 }
502
503 /*======================================================================
504   Error Display
505   ======================================================================*/
506
507 void
508 UI::dump_errors (std::ostream& ostr)
509 {
510         Glib::Threads::Mutex::Lock lm (error_lock);
511         ostr << endl << X_("Errors/Messages:") << endl;
512         for (list<string>::const_iterator i = error_stack.begin(); i != error_stack.end(); ++i) {
513                 ostr << *i << endl;
514         }
515         ostr << endl;
516 }
517
518 void
519 UI::receive (Transmitter::Channel chn, const char *str)
520 {
521         {
522                 Glib::Threads::Mutex::Lock lm (error_lock);
523                 switch (chn) {
524                 case Transmitter::Fatal:
525                         error_stack.push_back (string (X_("FATAL: ")) + str);
526                         break;
527                 case Transmitter::Error:
528                         error_stack.push_back (string (X_("ERROR: ")) + str);
529                         break;
530                 case Transmitter::Warning:
531                         error_stack.push_back (string (X_("WARNING: ")) + str);
532                         break;
533                 case Transmitter::Info:
534                         error_stack.push_back (string (X_("INFO: ")) + str);
535                         break;
536                 case Transmitter::Throw:
537                         error_stack.push_back (string (X_("THROW: ")) + str);
538                         break;
539                 }
540         }
541
542         if (caller_is_ui_thread()) {
543                 process_error_message (chn, str);
544         } else {
545                 UIRequest* req = get_request (ErrorMessage);
546
547                 if (req == 0) {
548                         return;
549                 }
550
551                 req->chn = chn;
552                 req->msg = strdup (str);
553
554                 send_request (req);
555         }
556 }
557
558 void
559 UI::process_error_message (Transmitter::Channel chn, const char *str)
560 {
561         RefPtr<Style> style;
562         RefPtr<TextBuffer::Tag> ptag;
563         RefPtr<TextBuffer::Tag> mtag;
564         const char *prefix;
565         size_t prefix_len;
566         bool fatal_received = false;
567
568         switch (chn) {
569         case Transmitter::Fatal:
570                 prefix = "[FATAL]: ";
571                 ptag = fatal_ptag;
572                 mtag = fatal_mtag;
573                 prefix_len = 9;
574                 fatal_received = true;
575                 break;
576         case Transmitter::Error:
577                 prefix = "[ERROR]: ";
578                 ptag = error_ptag;
579                 mtag = error_mtag;
580                 prefix_len = 9;
581                 break;
582         case Transmitter::Info:
583                 prefix = "[INFO]: ";
584                 ptag = info_ptag;
585                 mtag = info_mtag;
586                 prefix_len = 8;
587                 break;
588         case Transmitter::Warning:
589                 prefix = "[WARNING]: ";
590                 ptag = warning_ptag;
591                 mtag = warning_mtag;
592                 prefix_len = 11;
593                 break;
594         default:
595                 /* no choice but to use text/console output here */
596                 cerr << "programmer error in UI::check_error_messages (channel = " << chn << ")\n";
597                 ::exit (1);
598         }
599
600         errors->text().get_buffer()->begin_user_action();
601
602         if (fatal_received) {
603                 handle_fatal (str);
604         } else {
605
606                 if (!ptag || !mtag) {
607                         /* oops, message sent before we set up tags - don't crash */
608                         cerr << prefix << str << endl;
609                 } else {
610                         display_message (prefix, prefix_len, ptag, mtag, str);
611                 }
612         }
613
614         errors->text().get_buffer()->end_user_action();
615 }
616
617 void
618 UI::show_errors ()
619 {
620         Glib::RefPtr<ToggleAction> tact = ActionManager::get_toggle_action (X_("Editor"), X_("toggle-log-window"));
621         tact->set_active ();
622 }
623
624 void
625 UI::toggle_errors ()
626 {
627         Glib::RefPtr<ToggleAction> tact = ActionManager::get_toggle_action (X_("Editor"), X_("toggle-log-window"));
628         if (tact->get_active()) {
629                 errors->set_position (WIN_POS_MOUSE);
630                 errors->show ();
631         } else {
632                 errors->hide ();
633         }
634 }
635
636 void
637 UI::display_message (const char *prefix, gint /*prefix_len*/, RefPtr<TextBuffer::Tag> ptag, RefPtr<TextBuffer::Tag> mtag, const char *msg)
638 {
639         RefPtr<TextBuffer> buffer (errors->text().get_buffer());
640
641         buffer->insert_with_tag(buffer->end(), prefix, ptag);
642         buffer->insert_with_tag(buffer->end(), msg, mtag);
643         buffer->insert_with_tag(buffer->end(), "\n", mtag);
644
645         errors->scroll_to_bottom ();
646 }
647
648 void
649 UI::handle_fatal (const char *message)
650 {
651         Dialog win;
652         Label label (message);
653         Button quit (_("Press To Exit"));
654         HBox hpacker;
655
656         win.set_default_size (400, 100);
657
658         WindowTitle title(Glib::get_application_name());
659         title += ": Fatal Error";
660         win.set_title (title.get_string());
661
662         win.set_position (WIN_POS_MOUSE);
663         win.set_border_width (12);
664
665         win.get_vbox()->pack_start (label, true, true);
666         hpacker.pack_start (quit, true, false);
667         win.get_vbox()->pack_start (hpacker, false, false);
668
669         quit.signal_clicked().connect(mem_fun(*this,&UI::quit));
670
671         win.show_all ();
672         win.set_modal (true);
673
674         theMain->run ();
675
676         _exit (1);
677 }
678
679 void
680 UI::popup_error (const string& text)
681 {
682         if (!caller_is_ui_thread()) {
683                 error << "non-UI threads can't use UI::popup_error"
684                       << endmsg;
685                 return;
686         }
687
688         MessageDialog msg (text);
689         msg.set_title (string_compose (_("I'm sorry %1, I can't do that"), g_get_user_name()));
690         msg.set_wmclass (X_("error"), Glib::get_application_name());
691         msg.set_position (WIN_POS_MOUSE);
692         msg.run ();
693 }
694
695 void
696 UI::flush_pending (float timeout)
697 {
698         if (!caller_is_ui_thread()) {
699                 error << "non-UI threads cannot call UI::flush_pending()"
700                       << endmsg;
701                 return;
702         }
703
704         int64_t end = g_get_monotonic_time () + timeout * 1e6;
705
706         gtk_main_iteration();
707
708         while (gtk_events_pending()) {
709                 if (timeout > 0 && end < g_get_monotonic_time ()) {
710                         cerr << "UI::flush_pending timed out after " << timeout << "s.\n";
711                         break;
712                 }
713                 gtk_main_iteration();
714         }
715 }
716
717 bool
718 UI::just_hide_it (GdkEventAny* /*ev*/, Window *win)
719 {
720         win->hide ();
721         return true;
722 }
723
724 void
725 UI::color_selection_done (bool status)
726 {
727         color_picked = status;
728         Main::quit ();
729 }
730
731 bool
732 UI::color_selection_deleted (GdkEventAny* /*ev*/)
733 {
734         Main::quit ();
735         return true;
736 }