get_label_text_dimensions.c 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /*
  2. * Determine the dimensions of a piece of text in the standard
  3. * font used in GTK interface elements like labels. We do this by
  4. * instantiating an actual GtkLabel, and then querying its size.
  5. */
  6. #include <gtk/gtk.h>
  7. #include "putty.h"
  8. #include "gtkcompat.h"
  9. #include "gtkmisc.h"
  10. void get_label_text_dimensions(const char *text, int *width, int *height)
  11. {
  12. GtkWidget *label = gtk_label_new(text);
  13. /*
  14. * GTK2 and GTK3 require us to query the size completely
  15. * differently. I'm sure there ought to be an easier approach than
  16. * the way I'm doing this in GTK3, too!
  17. */
  18. #if GTK_CHECK_VERSION(3,0,0)
  19. PangoLayout *layout = gtk_label_get_layout(GTK_LABEL(label));
  20. PangoRectangle logrect;
  21. pango_layout_get_extents(layout, NULL, &logrect);
  22. if (width)
  23. *width = logrect.width / PANGO_SCALE;
  24. if (height)
  25. *height = logrect.height / PANGO_SCALE;
  26. #else
  27. GtkRequisition req;
  28. gtk_widget_size_request(label, &req);
  29. if (width)
  30. *width = req.width;
  31. if (height)
  32. *height = req.height;
  33. #endif
  34. g_object_ref_sink(G_OBJECT(label));
  35. #if GTK_CHECK_VERSION(2,10,0)
  36. g_object_unref(label);
  37. #endif
  38. }