1 /*
2  * Copyright (C) 2005-2006 Taybin Rutkin <taybin@taybin.com>
3  * Copyright (C) 2005-2009 Nick Mainsbridge <mainsbridge@gmail.com>
4  * Copyright (C) 2005-2018 Paul Davis <paul@linuxaudiosystems.com>
5  * Copyright (C) 2005 Karsten Wiese <fzuuzf@googlemail.com>
6  * Copyright (C) 2006-2007 Doug McLain <doug@nostar.net>
7  * Copyright (C) 2006-2009 Sampo Savolainen <v2@iki.fi>
8  * Copyright (C) 2007-2015 David Robillard <d@drobilla.net>
9  * Copyright (C) 2007-2015 Tim Mayberry <mojofunk@gmail.com>
10  * Copyright (C) 2009-2012 Carl Hetherington <carl@carlh.net>
11  * Copyright (C) 2013-2019 Robin Gareus <robin@gareus.org>
12  * Copyright (C) 2013 John Emmas <john@creativepost.co.uk>
13  * Copyright (C) 2015 André Nusser <andre.nusser@googlemail.com>
14  *
15  * This program is free software; you can redistribute it and/or modify
16  * it under the terms of the GNU General Public License as published by
17  * the Free Software Foundation; either version 2 of the License, or
18  * (at your option) any later version.
19  *
20  * This program is distributed in the hope that it will be useful,
21  * but WITHOUT ANY WARRANTY; without even the implied warranty of
22  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23  * GNU General Public License for more details.
24  *
25  * You should have received a copy of the GNU General Public License along
26  * with this program; if not, write to the Free Software Foundation, Inc.,
27  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
28  */
29 
30 #ifdef WAF_BUILD
31 #include "gtk2ardour-config.h"
32 #endif
33 
34 #include <cstdlib>
35 #include <clocale>
36 #include <cstring>
37 #include <cctype>
38 #include <cmath>
39 #include <list>
40 #include <sys/stat.h>
41 
42 #include <boost/algorithm/string.hpp>
43 
44 #include <gtk/gtkpaned.h>
45 #include <gtkmm/combo.h>
46 #include <gtkmm/label.h>
47 #include <gtkmm/paned.h>
48 #include <gtkmm/rc.h>
49 #include <gtkmm/stock.h>
50 #include <gtkmm/window.h>
51 
52 #include "pbd/basename.h"
53 #include "pbd/file_utils.h"
54 
55 #include "ardour/audioengine.h"
56 #include "ardour/filesystem_paths.h"
57 #include "ardour/search_paths.h"
58 
59 #include "gtkmm2ext/colors.h"
60 #include "gtkmm2ext/utils.h"
61 
62 #include "canvas/item.h"
63 
64 #include "actions.h"
65 #include "context_menu_helper.h"
66 #include "debug.h"
67 #include "public_editor.h"
68 #include "keyboard.h"
69 #include "utils.h"
70 #include "pbd/i18n.h"
71 #include "rgb_macros.h"
72 #include "gui_thread.h"
73 #include "ui_config.h"
74 #include "ardour_dialog.h"
75 #include "ardour_ui.h"
76 
77 using namespace std;
78 using namespace Gtk;
79 using namespace Glib;
80 using namespace PBD;
81 using Gtkmm2ext::Keyboard;
82 
83 namespace ARDOUR_UI_UTILS {
84 	sigc::signal<void>  DPIReset;
85 }
86 
87 #ifdef PLATFORM_WINDOWS
88 #define random() rand()
89 #endif
90 
91 
92 /** Add an element to a menu, settings its sensitivity.
93  * @param m Menu to add to.
94  * @param e Element to add.
95  * @param s true to make sensitive, false to make insensitive
96  */
97 void
add_item_with_sensitivity(Menu_Helpers::MenuList & m,Menu_Helpers::MenuElem e,bool s)98 ARDOUR_UI_UTILS::add_item_with_sensitivity (Menu_Helpers::MenuList& m, Menu_Helpers::MenuElem e, bool s)
99 {
100 	m.push_back (e);
101 	if (!s) {
102 		m.back().set_sensitive (false);
103 	}
104 }
105 
106 
107 gint
just_hide_it(GdkEventAny *,Gtk::Window * win)108 ARDOUR_UI_UTILS::just_hide_it (GdkEventAny */*ev*/, Gtk::Window *win)
109 {
110 	win->hide ();
111 	return 0;
112 }
113 
114 static bool
idle_notify_engine_stopped()115 idle_notify_engine_stopped ()
116 {
117 	Glib::RefPtr<ToggleAction> tact = ActionManager::get_toggle_action ("Window", "toggle-audio-midi-setup");
118 
119 	MessageDialog msg (
120 			_("The current operation is not possible because of an error communicating with the audio hardware."),
121 			false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE, true);
122 
123 	msg.add_button (_("Cancel"), Gtk::RESPONSE_CANCEL);
124 
125 	if (tact && !tact->get_active()) {
126 		msg.add_button (_("Configure Hardware"), Gtk::RESPONSE_OK);
127 	}
128 
129 	if (msg.run () == Gtk::RESPONSE_OK) {
130 		tact->set_active ();
131 	}
132 	return false; /* do not call again */
133 }
134 
135 bool
engine_is_running()136 ARDOUR_UI_UTILS::engine_is_running ()
137 {
138 	if (ARDOUR::AudioEngine::instance()->running ()) {
139 		return true;
140 	}
141 	Glib::signal_idle().connect (sigc::ptr_fun (&idle_notify_engine_stopped));
142 	return false;
143 }
144 
145 
146 /* xpm2rgb copied from nixieclock, which bore the legend:
147 
148     nixieclock - a nixie desktop timepiece
149     Copyright (C) 2000 Greg Ercolano, erco@3dsite.com
150 
151     and was released under the GPL.
152 */
153 
154 unsigned char*
xpm2rgb(const char ** xpm,uint32_t & w,uint32_t & h)155 ARDOUR_UI_UTILS::xpm2rgb (const char** xpm, uint32_t& w, uint32_t& h)
156 {
157 	static long vals[256], val;
158 	uint32_t t, x, y, colors, cpp;
159 	unsigned char c;
160 	unsigned char *savergb, *rgb;
161 
162 	// PARSE HEADER
163 
164 	if ( sscanf(xpm[0], "%u%u%u%u", &w, &h, &colors, &cpp) != 4 ) {
165 		error << string_compose (_("bad XPM header %1"), xpm[0])
166 		      << endmsg;
167 		return 0;
168 	}
169 
170 	savergb = rgb = (unsigned char*) malloc (h * w * 3);
171 
172 	// LOAD XPM COLORMAP LONG ENOUGH TO DO CONVERSION
173 	for (t = 0; t < colors; ++t) {
174 		sscanf (xpm[t+1], "%c c #%lx", &c, &val);
175 		vals[c] = val;
176 	}
177 
178 	// COLORMAP -> RGB CONVERSION
179 	//    Get low 3 bytes from vals[]
180 	//
181 
182 	const char *p;
183 	for (y = h-1; y > 0; --y) {
184 
185 		for (p = xpm[1+colors+(h-y-1)], x = 0; x < w; x++, rgb += 3) {
186 			val = vals[(int)*p++];
187 			*(rgb+2) = val & 0xff; val >>= 8;  // 2:B
188 			*(rgb+1) = val & 0xff; val >>= 8;  // 1:G
189 			*(rgb+0) = val & 0xff;             // 0:R
190 		}
191 	}
192 
193 	return (savergb);
194 }
195 
196 unsigned char*
xpm2rgba(const char ** xpm,uint32_t & w,uint32_t & h)197 ARDOUR_UI_UTILS::xpm2rgba (const char** xpm, uint32_t& w, uint32_t& h)
198 {
199 	static long vals[256], val;
200 	uint32_t t, x, y, colors, cpp;
201 	unsigned char c;
202 	unsigned char *savergb, *rgb;
203 	char transparent;
204 
205 	// PARSE HEADER
206 
207 	if ( sscanf(xpm[0], "%u%u%u%u", &w, &h, &colors, &cpp) != 4 ) {
208 		error << string_compose (_("bad XPM header %1"), xpm[0])
209 		      << endmsg;
210 		return 0;
211 	}
212 
213 	savergb = rgb = (unsigned char*) malloc (h * w * 4);
214 
215 	// LOAD XPM COLORMAP LONG ENOUGH TO DO CONVERSION
216 
217 	if (strstr (xpm[1], "None")) {
218 		sscanf (xpm[1], "%c", &transparent);
219 		t = 1;
220 	} else {
221 		transparent = 0;
222 		t = 0;
223 	}
224 
225 	for (; t < colors; ++t) {
226 		sscanf (xpm[t+1], "%c c #%lx", &c, &val);
227 		vals[c] = val;
228 	}
229 
230 	// COLORMAP -> RGB CONVERSION
231 	//    Get low 3 bytes from vals[]
232 	//
233 
234 	const char *p;
235 	for (y = h-1; y > 0; --y) {
236 
237 		char alpha;
238 
239 		for (p = xpm[1+colors+(h-y-1)], x = 0; x < w; x++, rgb += 4) {
240 
241 			if (transparent && (*p++ == transparent)) {
242 				alpha = 0;
243 				val = 0;
244 			} else {
245 				alpha = 255;
246 				val = vals[(int)*p];
247 			}
248 
249 			*(rgb+3) = alpha;                  // 3: alpha
250 			*(rgb+2) = val & 0xff; val >>= 8;  // 2:B
251 			*(rgb+1) = val & 0xff; val >>= 8;  // 1:G
252 			*(rgb+0) = val & 0xff;             // 0:R
253 		}
254 	}
255 
256 	return (savergb);
257 }
258 
259 /** Returns a Pango::FontDescription given a string describing the font.
260  *
261  * If the returned FontDescription does not specify a family, then
262  * the family is set to "Sans". This mirrors GTK's behaviour in
263  * gtkstyle.c.
264  *
265  * Some environments will force Pango to specify the family
266  * even if it was not specified in the string describing the font.
267  * Such environments should be left unaffected by this function,
268  * since the font family will be left alone.
269  *
270  * There may be other similar font specification enforcement
271  * that we might add here later.
272  */
273 Pango::FontDescription
sanitized_font(std::string const & name)274 ARDOUR_UI_UTILS::sanitized_font (std::string const& name)
275 {
276 	Pango::FontDescription fd (name);
277 
278 	if (fd.get_family().empty()) {
279 		/* default: "Sans" or "ArdourSans" */
280 		fd.set_family (UIConfiguration::instance ().get_ui_font_family ());
281 	}
282 
283 	return fd;
284 }
285 
286 Pango::FontDescription
get_font_for_style(string widgetname)287 ARDOUR_UI_UTILS::get_font_for_style (string widgetname)
288 {
289 	Gtk::Window window (WINDOW_TOPLEVEL);
290 	Gtk::Label foobar;
291 	Glib::RefPtr<Gtk::Style> style;
292 
293 	window.add (foobar);
294 	foobar.set_name (widgetname);
295 	foobar.ensure_style();
296 
297 	style = foobar.get_style ();
298 
299 	Glib::RefPtr<const Pango::Layout> layout = foobar.get_layout();
300 
301 	PangoFontDescription *pfd = const_cast<PangoFontDescription *> (pango_layout_get_font_description(const_cast<PangoLayout *>(layout->gobj())));
302 
303 	if (!pfd) {
304 
305 		/* layout inherited its font description from a PangoContext */
306 
307 		PangoContext* ctxt = (PangoContext*) pango_layout_get_context (const_cast<PangoLayout*>(layout->gobj()));
308 		pfd =  pango_context_get_font_description (ctxt);
309 		return Pango::FontDescription (pfd); /* make a copy */
310 	}
311 
312 	return Pango::FontDescription (pfd); /* make a copy */
313 }
314 
315 Gdk::Color
gdk_color_from_rgb(uint32_t rgb)316 ARDOUR_UI_UTILS::gdk_color_from_rgb (uint32_t rgb)
317 {
318 	Gdk::Color c;
319 	set_color_from_rgb (c, rgb);
320 	return c;
321 }
322 
323 Gdk::Color
gdk_color_from_rgba(uint32_t rgba)324 ARDOUR_UI_UTILS::gdk_color_from_rgba (uint32_t rgba)
325 {
326 	Gdk::Color c;
327 	set_color_from_rgb (c, rgba >> 8);
328 	return c;
329 }
330 
331 void
set_color_from_rgb(Gdk::Color & c,uint32_t rgb)332 ARDOUR_UI_UTILS::set_color_from_rgb (Gdk::Color& c, uint32_t rgb)
333 {
334 	/* Gdk::Color color ranges are 16 bit, so scale from 8 bit by
335 	   multiplying by 256.
336 	*/
337 	c.set_rgb ((rgb >> 16)*256, ((rgb & 0xff00) >> 8)*256, (rgb & 0xff)*256);
338 }
339 
340 void
set_color_from_rgba(Gdk::Color & c,uint32_t rgba)341 ARDOUR_UI_UTILS::set_color_from_rgba (Gdk::Color& c, uint32_t rgba)
342 {
343 	/* Gdk::Color color ranges are 16 bit, so scale from 8 bit by
344 	   multiplying by 256.
345 	*/
346 	c.set_rgb ((rgba >> 24)*256, ((rgba & 0xff0000) >> 16)*256, ((rgba & 0xff00) >> 8)*256);
347 }
348 
349 uint32_t
gdk_color_to_rgba(Gdk::Color const & c)350 ARDOUR_UI_UTILS::gdk_color_to_rgba (Gdk::Color const& c)
351 {
352 	/* since alpha value is not available from a Gdk::Color, it is
353 	   hardcoded as 0xff (aka 255 or 1.0)
354 	*/
355 
356 	const uint32_t r = c.get_red_p () * 255.0;
357 	const uint32_t g = c.get_green_p () * 255.0;
358 	const uint32_t b = c.get_blue_p () * 255.0;
359 	const uint32_t a = 0xff;
360 
361 	return RGBA_TO_UINT (r,g,b,a);
362 }
363 
364 bool
relay_key_press(GdkEventKey * ev,Gtk::Window * win)365 ARDOUR_UI_UTILS::relay_key_press (GdkEventKey* ev, Gtk::Window* win)
366 {
367 	return ARDOUR_UI::instance()->key_event_handler (ev, win);
368 }
369 
370 bool
emulate_key_event(unsigned int keyval)371 ARDOUR_UI_UTILS::emulate_key_event (unsigned int keyval)
372 {
373 	GdkDisplay  *display = gtk_widget_get_display (GTK_WIDGET(ARDOUR_UI::instance()->main_window().gobj()));
374 	GdkKeymap   *keymap  = gdk_keymap_get_for_display (display);
375 	GdkKeymapKey *keymapkey = NULL;
376 	gint n_keys;
377 
378 	if (!gdk_keymap_get_entries_for_keyval(keymap, keyval, &keymapkey, &n_keys)) return false;
379 	if (n_keys !=1) { g_free(keymapkey); return false;}
380 
381 	Gtk::Window& main_window (ARDOUR_UI::instance()->main_window());
382 
383 	GdkEventKey ev;
384 	ev.type = GDK_KEY_PRESS;
385 	ev.window = main_window.get_window()->gobj();
386 	ev.send_event = FALSE;
387 	ev.time = 0;
388 	ev.state = 0;
389 	ev.keyval = keyval;
390 	ev.length = 0;
391 	ev.string = const_cast<gchar*> ("");
392 	ev.hardware_keycode = keymapkey[0].keycode;
393 	ev.group = keymapkey[0].group;
394 	g_free(keymapkey);
395 
396 	relay_key_press (&ev, &main_window);
397 	ev.type = GDK_KEY_RELEASE;
398 	return relay_key_press(&ev, &main_window);
399 }
400 
401 Glib::RefPtr<Gdk::Pixbuf>
get_xpm(std::string name)402 ARDOUR_UI_UTILS::get_xpm (std::string name)
403 {
404 	if (!xpm_map[name]) {
405 
406 		Searchpath spath(ARDOUR::ardour_data_search_path());
407 
408 		spath.add_subdirectory_to_paths("pixmaps");
409 
410 		std::string data_file_path;
411 
412 		if(!find_file (spath, name, data_file_path)) {
413 			fatal << string_compose (_("cannot find XPM file for %1"), name) << endmsg;
414 		}
415 
416 		try {
417 			xpm_map[name] =  Gdk::Pixbuf::create_from_file (data_file_path);
418 		} catch (const Glib::Error& e) {
419 			warning << "Caught Glib::Error: " << e.what() << endmsg;
420 		}
421 	}
422 
423 	return xpm_map[name];
424 }
425 
426 void
get_color_themes(map<std::string,std::string> & themes)427 ARDOUR_UI_UTILS::get_color_themes (map<std::string,std::string>& themes)
428 {
429 	Searchpath spath(ARDOUR::theme_search_path());
430 
431 	for (vector<string>::iterator s = spath.begin(); s != spath.end(); ++s) {
432 
433 		vector<string> entries;
434 
435 		find_files_matching_pattern (entries, *s, string ("*") + UIConfiguration::color_file_suffix);
436 
437 		for (vector<string>::iterator e = entries.begin(); e != entries.end(); ++e) {
438 
439 			XMLTree tree;
440 
441 			tree.read ((*e).c_str());
442 			XMLNode* root = tree.root();
443 
444 			if (!root || root->name() != X_("Ardour")) {
445 				continue;
446 			}
447 
448 			XMLProperty const* prop = root->property (X_("theme-name"));
449 
450 			if (!prop) {
451 				continue;
452 			}
453 
454 			std::string color_name = basename_nosuffix(*e);
455 			size_t sep = color_name.find_first_of("-");
456 			if (sep != string::npos) {
457 				color_name = color_name.substr (0, sep);
458 			}
459 			themes.insert (make_pair (prop->value(), color_name));
460 		}
461 	}
462 }
463 
464 vector<string>
get_icon_sets()465 ARDOUR_UI_UTILS::get_icon_sets ()
466 {
467 	Searchpath spath(ARDOUR::ardour_data_search_path());
468 	spath.add_subdirectory_to_paths ("icons");
469 	vector<string> r;
470 
471 	r.push_back (_("default"));
472 
473 	for (vector<string>::iterator s = spath.begin(); s != spath.end(); ++s) {
474 
475 		vector<string> entries;
476 
477 		get_paths (entries, *s, false, false);
478 
479 		for (vector<string>::iterator e = entries.begin(); e != entries.end(); ++e) {
480 			if (Glib::file_test (*e, Glib::FILE_TEST_IS_DIR)) {
481 				r.push_back (Glib::filename_to_utf8 (Glib::path_get_basename(*e)));
482 			}
483 		}
484 	}
485 
486 	return r;
487 }
488 
489 std::string
get_icon_path(const char * cname,string icon_set,bool is_image)490 ARDOUR_UI_UTILS::get_icon_path (const char* cname, string icon_set, bool is_image)
491 {
492 	std::string data_file_path;
493 	string name = cname;
494 
495 	if (is_image) {
496 		name += X_(".png");
497 	}
498 
499 	Searchpath spath(ARDOUR::ardour_data_search_path());
500 
501 	if (!icon_set.empty() && icon_set != _("default")) {
502 
503 		/* add "icons/icon_set" but .. not allowed to add both of these at once */
504 		spath.add_subdirectory_to_paths ("icons");
505 		spath.add_subdirectory_to_paths (icon_set);
506 
507 		find_file (spath, name, data_file_path);
508 	} else {
509 		spath.add_subdirectory_to_paths ("icons");
510 		find_file (spath, name, data_file_path);
511 	}
512 
513 	if (data_file_path.empty()) {
514 		Searchpath rc (ARDOUR::ardour_data_search_path());
515 		rc.add_subdirectory_to_paths ("resources");
516 		find_file (rc, name, data_file_path);
517 	}
518 
519 	if (is_image && data_file_path.empty()) {
520 
521 		if (!icon_set.empty() && icon_set != _("default")) {
522 			warning << string_compose (_("icon \"%1\" not found for icon set \"%2\", fallback to default"), cname, icon_set) << endmsg;
523 		}
524 
525 		Searchpath def (ARDOUR::ardour_data_search_path());
526 		def.add_subdirectory_to_paths ("icons");
527 
528 		if (!find_file (def, name, data_file_path)) {
529 			fatal << string_compose (_("cannot find icon image for %1 using %2"), name, spath.to_string()) << endmsg;
530 			abort(); /*NOTREACHED*/
531 		}
532 	}
533 
534 	return data_file_path;
535 }
536 
537 Glib::RefPtr<Gdk::Pixbuf>
get_icon(const char * cname,string icon_set)538 ARDOUR_UI_UTILS::get_icon (const char* cname, string icon_set)
539 {
540 	Glib::RefPtr<Gdk::Pixbuf> img;
541 	try {
542 		img = Gdk::Pixbuf::create_from_file (get_icon_path (cname, icon_set));
543 	} catch (const Gdk::PixbufError &e) {
544 		cerr << "Caught PixbufError: " << e.what() << endl;
545 	} catch (...) {
546 		error << string_compose (_("Caught exception while loading icon named %1"), cname) << endmsg;
547 	}
548 
549 	return img;
550 }
551 
552 namespace ARDOUR_UI_UTILS {
553 Glib::RefPtr<Gdk::Pixbuf>
get_icon(const char * cname)554 get_icon (const char* cname)
555 {
556 	Glib::RefPtr<Gdk::Pixbuf> img;
557 	try {
558 		img = Gdk::Pixbuf::create_from_file (get_icon_path (cname));
559 	} catch (const Gdk::PixbufError &e) {
560 		cerr << "Caught PixbufError: " << e.what() << endl;
561 	} catch (...) {
562 		error << string_compose (_("Caught exception while loading icon named %1"), cname) << endmsg;
563 	}
564 
565 	return img;
566 }
567 }
568 
569 string
longest(vector<string> & strings)570 ARDOUR_UI_UTILS::longest (vector<string>& strings)
571 {
572 	if (strings.empty()) {
573 		return string ("");
574 	}
575 
576 	vector<string>::iterator longest = strings.begin();
577 	string::size_type longest_length = (*longest).length();
578 
579 	vector<string>::iterator i = longest;
580 	++i;
581 
582 	while (i != strings.end()) {
583 
584 		string::size_type len = (*i).length();
585 
586 		if (len > longest_length) {
587 			longest = i;
588 			longest_length = len;
589 		}
590 
591 		++i;
592 	}
593 
594 	return *longest;
595 }
596 
597 bool
key_is_legal_for_numeric_entry(guint keyval)598 ARDOUR_UI_UTILS::key_is_legal_for_numeric_entry (guint keyval)
599 {
600 	/* we assume that this does not change over the life of the process
601 	 */
602 
603 	static int comma_decimal = -1;
604 
605 	switch (keyval) {
606 	case GDK_period:
607 	case GDK_comma:
608 		if (comma_decimal < 0) {
609 			std::lconv* lc = std::localeconv();
610 			if (strchr (lc->decimal_point, ',') != 0) {
611 				comma_decimal = 1;
612 			} else {
613 				comma_decimal = 0;
614 			}
615 		}
616 		break;
617 	default:
618 		break;
619 	}
620 
621 	switch (keyval) {
622 	case GDK_decimalpoint:
623 	case GDK_KP_Separator:
624 		return true;
625 
626 	case GDK_period:
627 		if (comma_decimal) {
628 			return false;
629 		} else {
630 			return true;
631 		}
632 		break;
633 	case GDK_comma:
634 		if (comma_decimal) {
635 			return true;
636 		} else {
637 			return false;
638 		}
639 		break;
640 	case GDK_minus:
641 	case GDK_plus:
642 	case GDK_0:
643 	case GDK_1:
644 	case GDK_2:
645 	case GDK_3:
646 	case GDK_4:
647 	case GDK_5:
648 	case GDK_6:
649 	case GDK_7:
650 	case GDK_8:
651 	case GDK_9:
652 	case GDK_KP_Add:
653 	case GDK_KP_Subtract:
654 	case GDK_KP_Decimal:
655 	case GDK_KP_0:
656 	case GDK_KP_1:
657 	case GDK_KP_2:
658 	case GDK_KP_3:
659 	case GDK_KP_4:
660 	case GDK_KP_5:
661 	case GDK_KP_6:
662 	case GDK_KP_7:
663 	case GDK_KP_8:
664 	case GDK_KP_9:
665 	case GDK_Return:
666 	case GDK_BackSpace:
667 	case GDK_Delete:
668 	case GDK_KP_Enter:
669 	case GDK_Home:
670 	case GDK_End:
671 	case GDK_Left:
672 	case GDK_Right:
673 		return true;
674 
675 	default:
676 		break;
677 	}
678 
679 	return false;
680 }
681 
682 void
resize_window_to_proportion_of_monitor(Gtk::Window * window,int max_width,int max_height)683 ARDOUR_UI_UTILS::resize_window_to_proportion_of_monitor (Gtk::Window* window, int max_width, int max_height)
684 {
685 	Glib::RefPtr<Gdk::Screen> screen = window->get_screen ();
686 	Gdk::Rectangle monitor_rect;
687 	screen->get_monitor_geometry (0, monitor_rect);
688 
689 	int const w = std::min (int (monitor_rect.get_width() * 0.8), max_width);
690 	int const h = std::min (int (monitor_rect.get_height() * 0.8), max_height);
691 
692 	window->resize (w, h);
693 }
694 
695 
696 /** Replace _ with __ in a string; for use with menu item text to make underscores displayed correctly */
697 string
escape_underscores(string const & s)698 ARDOUR_UI_UTILS::escape_underscores (string const & s)
699 {
700 	string o;
701 	string::size_type const N = s.length ();
702 
703 	for (string::size_type i = 0; i < N; ++i) {
704 		if (s[i] == '_') {
705 			o += "__";
706 		} else {
707 			o += s[i];
708 		}
709 	}
710 
711 	return o;
712 }
713 
714 Gdk::Color
unique_random_color(list<Gdk::Color> & used_colors)715 ARDOUR_UI_UTILS::unique_random_color (list<Gdk::Color>& used_colors)
716 {
717 	Gdk::Color newcolor;
718 
719 	while (1) {
720 
721 		double h, s, v;
722 
723 		h = fmod (random(), 360.0);
724 		s = (random() % 65535) / 65535.0;
725 		v = (random() % 65535) / 65535.0;
726 
727 		s = min (0.5, s); /* not too saturated */
728 		v = max (0.9, v);  /* not too bright */
729 		newcolor.set_hsv (h, s, v);
730 
731 		if (used_colors.size() == 0) {
732 			used_colors.push_back (newcolor);
733 			return newcolor;
734 		}
735 
736 		for (list<Gdk::Color>::iterator i = used_colors.begin(); i != used_colors.end(); ++i) {
737 		  Gdk::Color c = *i;
738 			float rdelta, bdelta, gdelta;
739 
740 			rdelta = newcolor.get_red() - c.get_red();
741 			bdelta = newcolor.get_blue() - c.get_blue();
742 			gdelta = newcolor.get_green() - c.get_green();
743 
744 			if (sqrt (rdelta*rdelta + bdelta*bdelta + gdelta*gdelta) > 25.0) {
745 				/* different enough */
746 				used_colors.push_back (newcolor);
747 				return newcolor;
748 			}
749 		}
750 
751 		/* XXX need throttle here to make sure we don't spin for ever */
752 	}
753 }
754 
755 string
rate_as_string(float r)756 ARDOUR_UI_UTILS::rate_as_string (float r)
757 {
758 	char buf[32];
759 	if (fmod (r, 1000.0f)) {
760 		snprintf (buf, sizeof (buf), "%.1f kHz", r/1000.0);
761 	} else {
762 		snprintf (buf, sizeof (buf), "%.0f kHz", r/1000.0);
763 	}
764 	return buf;
765 }
766 
767 string
samples_as_time_string(samplecnt_t s,float rate,bool show_samples)768 ARDOUR_UI_UTILS::samples_as_time_string (samplecnt_t s, float rate, bool show_samples)
769 {
770 	char buf[32];
771 	if (rate <= 0) {
772 		snprintf (buf, sizeof (buf), "--");
773 	} else if (s == 0) {
774 		snprintf (buf, sizeof (buf), "0");
775 	} else if (s < 1000 && show_samples) {
776 		/* 0 .. 999 spl */
777 		snprintf (buf, sizeof (buf), "%" PRId64" spl", s);
778 	} else if (s < (rate / 1000.f)) {
779 		/* 0 .. 999 usec */
780 		snprintf (buf, sizeof (buf), "%.0f \u00B5s", s * 1e+6f / rate);
781 	} else if (s < (rate / 100.f)) {
782 		/* 1.000 .. 9.999 ms */
783 		snprintf (buf, sizeof (buf), "%.3f ms", s * 1e+3f / rate);
784 	} else if (s < (rate / 10.f)) {
785 		/* 1.00 .. 99.99 ms */
786 		snprintf (buf, sizeof (buf), "%.2f ms", s * 1e+3f / rate);
787 	} else if (s < rate) {
788 		/* 100.0 .. 999.9 ms */
789 		snprintf (buf, sizeof (buf), "%.1f ms", s * 1e+3f / rate);
790 	} else if (s < rate * 10.f) {
791 		/* 1.000 s .. 9.999 s */
792 		snprintf (buf, sizeof (buf), "%.3f s", s / rate);
793 	} else if (s < rate * 90.f) {
794 		/* 10.00 s .. 89.99 s */
795 		snprintf (buf, sizeof (buf), "%.2f s", s / rate);
796 	} else {
797 		/* 1m30.0 ...  */
798 		snprintf (buf, sizeof (buf), "'%.0fm%.1f", s / (60.f * rate), fmodf (s / rate, 60));
799 	}
800 	buf[31] = '\0';
801 	return buf;
802 }
803 
804 bool
windows_overlap(Gtk::Window * a,Gtk::Window * b)805 ARDOUR_UI_UTILS::windows_overlap (Gtk::Window *a, Gtk::Window *b)
806 {
807 
808 	if (!a || !b) {
809 		return false;
810 	}
811 	if (a->get_screen() == b->get_screen()) {
812 		gint ex, ey, ew, eh;
813 		gint mx, my, mw, mh;
814 
815 		a->get_position (ex, ey);
816 		a->get_size (ew, eh);
817 		b->get_position (mx, my);
818 		b->get_size (mw, mh);
819 
820 		GdkRectangle e;
821 		GdkRectangle m;
822 		GdkRectangle r;
823 
824 		e.x = ex;
825 		e.y = ey;
826 		e.width = ew;
827 		e.height = eh;
828 
829 		m.x = mx;
830 		m.y = my;
831 		m.width = mw;
832 		m.height = mh;
833 
834 		if (gdk_rectangle_intersect (&e, &m, &r)) {
835 			return true;
836 		}
837 	}
838 	return false;
839 }
840 
841 bool
overwrite_file_dialog(Gtk::Window & parent,string title,string text)842 ARDOUR_UI_UTILS::overwrite_file_dialog (Gtk::Window& parent, string title, string text)
843 {
844 	ArdourDialog dialog (parent, title, true);
845 	Label label (text);
846 
847 	dialog.get_vbox()->pack_start (label, true, true);
848 	dialog.add_button (Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
849 	dialog.add_button (_("Overwrite"), Gtk::RESPONSE_ACCEPT);
850 	dialog.show_all ();
851 
852 	switch (dialog.run()) {
853 	case RESPONSE_ACCEPT:
854 		return true;
855 	default:
856 		return false;
857 	}
858 }
859 
860 bool
running_from_source_tree()861 ARDOUR_UI_UTILS::running_from_source_tree ()
862 {
863 	gchar const *x = g_getenv ("ARDOUR_THEMES_PATH");
864 	return x && (string (x).find ("gtk2_ardour") != string::npos);
865 }
866 
867 Gtk::Menu*
shared_popup_menu()868 ARDOUR_UI_UTILS::shared_popup_menu ()
869 {
870 	return ARDOUR_UI::instance()->shared_popup_menu ();
871 }
872