utils_ui.cc 16.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/* Glom
 *
 * Copyright (C) 2001-2004 Murray Cumming
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this program; if not, write to the
17
18
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA.
19
20
 */

Murray Cumming's avatar
Murray Cumming committed
21
#include "config.h" // For GLOM_ENABLE_CLIENT_ONLY
22
23

#include <glom/utils_ui.h>
24
#include <glom/appwindow.h>
25
26
27
28
#include <libglom/connectionpool.h>
#include <libglom/data_structure/layout/report_parts/layoutitem_fieldsummary.h>
#include <libglom/data_structure/glomconversions.h>

29
30
31
32
#include <libglom/data_structure/layout/layoutitem_image.h> // For GLOM_IMAGE_FORMAT
#include <gdkmm/pixbufloader.h>
#include <libgda/gda-blob-op.h> // For gda_blob_op_read_all()

33
#include <gtkmm/messagedialog.h>
34
35
36
#include <glibmm/convert.h>
#include <glibmm/miscutils.h>
#include <glibmm/fileutils.h>
37

38
#include <giomm/file.h>
39
#include <glibmm/main.h>
40
41
#include <glibmm/i18n.h>

42
43
44
45
46
47
48
49
50
51
52
53
54
#include <string.h> // for strchr
#include <sstream> //For stringstream

#include <iostream>
#include <fstream>

#include <locale>     // for locale, time_put
#include <ctime>     // for struct tm
#include <iostream>   // for cout, endl
#include <iomanip>

#include <stack>

55
56
57
58
59
// For ShellExecute:
#ifdef G_OS_WIN32
# include <windows.h>
#endif

60
61
62
63
64
65
66
67
68
69
namespace
{

// Basically copied from libgnome (gnome-help.c, Copyright (C) 2001 Sid Vicious
// Copyright (C) 2001 Jonathan Blandford <jrb@alum.mit.edu>), but C++ified
std::string locate_help_file(const std::string& path, const std::string& doc_name)
{
  // g_get_language_names seems not to be wrapped by glibmm
  const char* const* lang_list = g_get_language_names ();

70
  for(unsigned int j = 0; lang_list[j] != 0; ++j)
71
72
73
  {
    const char* lang = lang_list[j];

74
    /* This must be a valid language AND a language with
75
76
     * no encoding postfix.  The language will come up without
     * encoding next. */
77
    if(lang == 0 || strchr(lang, '.') != 0)
78
79
      continue;

80
81
    const char* exts[] = { "", ".xml", ".docbook", ".sgml", ".html", 0 };
    for(unsigned i = 0; exts[i] != 0; ++i)
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
    {
      std::string name = doc_name + exts[i];
      std::string full = Glib::build_filename(path, Glib::build_filename(lang, name));

      if(Glib::file_test(full, Glib::FILE_TEST_EXISTS))
        return full;
    }
  }

  return std::string();
}

} //anonymous namespace

namespace Glom
{

99
// Run dialog and response on Help if appropriate.
100
int UiUtils::dialog_run_with_help(Gtk::Dialog* dialog, const Glib::ustring& id)
101
{
Murray Cumming's avatar
Murray Cumming committed
102
  int result = dialog->run();
103
  
Murray Cumming's avatar
Murray Cumming committed
104
  while (result == Gtk::RESPONSE_HELP)
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
  {
    show_help(id);
    result = dialog->run();
  }

  dialog->hide();
  return result;
}

/*
 * Help::show_help(const std::string& id)
 *
 * Launch a help browser with the glom help and load the given id if given
 * If the help cannot be found an error dialog will be shown
 */
120
void UiUtils::show_help(const Glib::ustring& id)
121
122
123
124
125
126
127
128
129
130
131
132
133
134
{
  GError* err = 0;
  const gchar* pId;
  if(id.length())
  {
    pId = id.c_str();
  }
  else
  {
    pId = 0;
  }

  try
  {
135
136
137
    const char path[] = GLOM_DATADIR G_DIR_SEPARATOR_S "gnome"
                                     G_DIR_SEPARATOR_S "help"
                                     G_DIR_SEPARATOR_S "glom";
138
139
140
141
142
143
144
145
    std::string help_file = locate_help_file(path, "glom.xml");
    if(help_file.empty())
    {
      throw std::runtime_error(_("No help file available"));
    }
    else
    {
      std::string uri = "ghelp:" + help_file;
146
      if(pId) { uri += '?'; uri += pId; }
147
148

      // g_app_info_launch_default_for_uri seems not to be wrapped by giomm
149
      if(!g_app_info_launch_default_for_uri(uri.c_str(), 0, &err))
150
151
152
153
154
155
156
157
158
      {
        std::string message(err->message);
        g_error_free(err);
        throw std::runtime_error(message);
      }
    }
  }
  catch(const std::exception& ex)
  {
159
    const Glib::ustring message = Glib::ustring::compose(_("Could not display help: %1"), Glib::ustring(ex.what()));
160
161
162
163
164
    Gtk::MessageDialog dialog(message, false, Gtk::MESSAGE_ERROR);
    dialog.run();
  }
}

165
void UiUtils::show_ok_dialog(const Glib::ustring& title, const Glib::ustring& message, Gtk::Window* parent, Gtk::MessageType message_type)
166
167
168
169
170
171
172
173
174
{
  Gtk::MessageDialog dialog("<b>" + title + "</b>", true /* markup */, message_type, Gtk::BUTTONS_OK);
  dialog.set_secondary_text(message);
  if(parent)
    dialog.set_transient_for(*parent);

  dialog.run();
}

175
void UiUtils::show_ok_dialog(const Glib::ustring& title, const Glib::ustring& message, Gtk::Window& parent, Gtk::MessageType message_type)
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
{
  show_ok_dialog(title, message, &parent, message_type);
}

namespace
{

static void on_window_hide(Glib::RefPtr<Glib::MainLoop> main_loop, sigc::connection handler_connection)
{
  handler_connection.disconnect(); //This should release a main_loop reference.
  main_loop->quit();

  //main_loop should be destroyed soon, because nothing else is using it.
}

} //anonymous namespace.

193
void UiUtils::show_window_until_hide(Gtk::Window* window)
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
{
  if(!window)
    return;

  Glib::RefPtr<Glib::MainLoop> main_loop = Glib::MainLoop::create(false /* not running */);

  //Stop the main_loop when the window is hidden:
  sigc::connection handler_connection; //TODO: There seems to be a crash if this is on the same line.
  handler_connection = window->signal_hide().connect( 
    sigc::bind(
      sigc::ptr_fun(&on_window_hide),
      main_loop, handler_connection
    ) );
  
  window->show();
  main_loop->run(); //Run and block until it is stopped by the hide signal handler.
}

212
Glib::ustring UiUtils::bold_message(const Glib::ustring& message)
213
214
215
216
217
{
  return "<b>" + message + "</b>";
}


218
Glib::RefPtr<Gdk::Pixbuf> UiUtils::get_pixbuf_for_gda_value(const Gnome::Gda::Value& value)
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
{
  Glib::RefPtr<Gdk::Pixbuf> result;

  if(value.get_value_type() == GDA_TYPE_BINARY || value.get_value_type() == GDA_TYPE_BLOB)
  {
    glong buffer_binary_length;
    gconstpointer buffer_binary;
    if(value.get_value_type() == GDA_TYPE_BLOB)
    {
      const GdaBlob* blob = value.get_blob();
      if(gda_blob_op_read_all(blob->op, const_cast<GdaBlob*>(blob)))
      {
        buffer_binary_length = blob->data.binary_length;
        buffer_binary = blob->data.data;
      }
      else
      {
        buffer_binary_length = 0;
237
        buffer_binary = 0;
238
        std::cerr << G_STRFUNC << ": Failed to read BLOB data" << std::endl;
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
      }
    }
    else
    {
      buffer_binary = value.get_binary(buffer_binary_length);
    }

    /* Note that this is regular binary data, not escaped text representing the binary data: */
    if(buffer_binary && buffer_binary_length)
    {
      //typedef std::list<Gdk::PixbufFormat> type_list_formats;
      //const type_list_formats formats = Gdk::Pixbuf::get_formats();
      //std::cout << "Debug: Supported pixbuf formats:" << std::endl;
      //for(type_list_formats::const_iterator iter = formats.begin(); iter != formats.end(); ++iter)
      //{
      //  std::cout << " name=" << iter->get_name() << ", writable=" << iter->is_writable() << std::endl;
      //}

257
      Glib::RefPtr<Gdk::PixbufLoader> refPixbufLoader;      
258
259
      try
      {
Armin Burgmeier's avatar
Armin Burgmeier committed
260
        refPixbufLoader = Gdk::PixbufLoader::create();
261
262
263
264
      }
      catch(const Gdk::PixbufError& ex)
      {
        refPixbufLoader.reset();
265
        std::cerr << G_STRFUNC << ": PixbufLoader::create failed: " << ex.what() << std::endl;
266
267
268
269
270
271
272
      }

      if(refPixbufLoader)
      {
        guint8* puiData = (guint8*)buffer_binary;
        try
        {
273
          refPixbufLoader->write(puiData, static_cast<gsize>(buffer_binary_length));
274
275
276
277
278
279
280
          result = refPixbufLoader->get_pixbuf();

          refPixbufLoader->close(); //This throws if write() threw, so it must be inside the try block.
        }

        catch(const Glib::Exception& ex)
        {
281
          std::cerr << G_STRFUNC << ": PixbufLoader::write() failed: " << ex.what() << std::endl;
282
283
284
285
286
287
288
289
290
291
292
293
        }
      }

      //TODO: load the image, using the mime type stored elsewhere.
      //pixbuf = Gdk::Pixbuf::create_from_data(
    }

  }

  return result;
}

294
295
namespace {

296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
static int get_width_for_text(Gtk::Widget& widget, const Glib::ustring& text)
{
  //Get the width required for this string in the current font:
  Glib::RefPtr<Pango::Layout> refLayout = widget.create_pango_layout(text);
  int width = 0;
  int height = 0;
  refLayout->get_pixel_size(width, height);
  int result = width;

  //Add a bit more:
  result += 10;

  return result;
}

311
312
313
} //anonymous namespace

int UiUtils::get_suitable_field_width_for_widget(Gtk::Widget& widget, const sharedptr<const LayoutItem_Field>& field_layout, bool or_title, bool for_treeview)
314
{
315
  int result = 150; //Suitable default.
316
317
318
319
320
321
322
323

  const Field::glom_field_type field_type = field_layout->get_glom_type();

  Glib::ustring example_text;
  switch(field_type)
  {
    case(Field::TYPE_DATE):
    {
324
      const Glib::Date date(31, Glib::Date::Month(12), 2000);
325
326
327
328
329
330
331
332
333
334
335
336
337
338
      example_text = Conversions::get_text_for_gda_value(field_type, Gnome::Gda::Value(date));
      break;
    }
    case(Field::TYPE_TIME):
    {
      Gnome::Gda::Time time = {0, 0, 0, 0, 0};
      time.hour = 24;
      time.minute = 59;
      time.second = 59;
      example_text = Conversions::get_text_for_gda_value(field_type, Gnome::Gda::Value(time));
      break;
    }
    case(Field::TYPE_NUMERIC):
    {
339
340
341
342
343
      if(for_treeview)
        example_text = "EUR 999.99";
      else
        example_text = "EUR 9999999999";
        
344
345
346
347
348
      break;
    }
    case(Field::TYPE_TEXT):
    case(Field::TYPE_IMAGE): //Give images the same width as text fields, so they will often line up.
    {
349
350
351
      if(for_treeview)
        example_text = "AAAAAAAAAAAA";
      else
352
        example_text = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
353

354
355
356
357
358
359
360
361
362
363
364
      break;
    }
    default:
    {
      break;
    }
  }

  if(!example_text.empty())
  {
    //Get the width required for this string in the current font:
365
    result = get_width_for_text(widget, example_text);
366
367
368
369
370
  }

  if(or_title)
  {
    //Make sure that there's enough space for the title too.
371
    const int title_width = get_width_for_text(widget, item_get_title(field_layout));
372
373
    if(title_width > result)
      result = title_width;
374
375
376
377
378
379
  }

  return result;
}


380
std::string UiUtils::get_filepath_with_extension(const std::string& filepath, const std::string& extension)
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
{
  std::string result = filepath;

  bool add_ext = false;
  const std::string str_ext = "." + extension;

  if(result.size() < str_ext.size()) //It can't have the ext already if it's not long enough.
  {
    add_ext = true; //It isn't there already.
  }
  else
  {
    const Glib::ustring strEnd = result.substr(result.size() - str_ext.size());
    if(strEnd != str_ext) //If it doesn't already have the extension
      add_ext = true;
  }

  //Add extension if necessay.
  if(add_ext)
    result += str_ext;

  //TODO: Do not replace existing extensions, so it could be e.g. 'something.blah.theext'

  return result;
}

Murray Cumming's avatar
Merged.    
Murray Cumming committed
407

408
//static:
409
Glib::RefPtr<Gdk::Pixbuf> UiUtils::image_scale_keeping_ratio(const Glib::RefPtr<Gdk::Pixbuf>& pixbuf, int target_height, int target_width)
410
411
412
413
414
415
416
417
418
419
420
{
  if( (target_height == 0) || (target_width == 0) )
    return Glib::RefPtr<Gdk::Pixbuf>(); //This shouldn't happen anyway.

  if(!pixbuf)
    return pixbuf;

  enum enum_scale_mode
  {
    SCALE_WIDTH,
    SCALE_HEIGHT,
421
    SCALE_BOTH,
422
423
424
425
426
427
428
429
430
431
432
433
    SCALE_NONE
  };

  enum_scale_mode scale_mode = SCALE_NONE; //Start with either the width or height, and scale the other according to the ratio.

  const int pixbuf_height = pixbuf->get_height();
  const int pixbuf_width = pixbuf->get_width();

  if(pixbuf_height > target_height)
  {
    if(pixbuf_width > target_width)
    {
434
      scale_mode = SCALE_BOTH;
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
    }
    else
    {
      //Only the height is bigger:
      scale_mode = SCALE_HEIGHT;
    }
  }
  else if(pixbuf_width > target_width)
  {
    //Only the height is bigger:
    scale_mode = SCALE_WIDTH;
  }

  if(scale_mode == SCALE_NONE)
    return pixbuf;
  else if(scale_mode == SCALE_HEIGHT)
  {
    const float ratio = (float)target_height / (float)pixbuf_height; 
    target_width = (int)((float)pixbuf_width * ratio);
  }
  else if(scale_mode == SCALE_WIDTH)
  {
    const float ratio = (float)target_width / (float) pixbuf_width;
    target_height = (int)((float)pixbuf_height * ratio);
459
460
461
462
463
464
465
466
  }
  else if(scale_mode == SCALE_BOTH)
  {
    const float ratio = std::min(
      (float)target_width / (float) pixbuf_width,
      (float)target_height / (float) pixbuf_height);
    target_width = (int)((float)pixbuf_width * ratio);
    target_height = (int)((float)pixbuf_height * ratio);
467
468
469
470
471
472
473
474
475
476
  }

 if( (target_height == 0) || (target_width == 0) )
 {
   return Glib::RefPtr<Gdk::Pixbuf>(); //This shouldn't happen anyway. It seems to happen sometimes though, when ratio is very small.
 }

  return pixbuf->scale_simple(target_width, target_height, Gdk::INTERP_NEAREST);
}

477
bool UiUtils::show_warning_no_records_found(Gtk::Window& transient_for)
478
479
480
{
  const Glib::ustring message = _("Your find criteria did not match any records in the table.");

481
  Gtk::MessageDialog dialog(UiUtils::bold_message(_("No Records Found")), true, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);
482
483
  dialog.set_secondary_text(message);
  dialog.set_transient_for(transient_for);
484

485
  dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
486
487
488
489
490
491
  dialog.add_button(_("New Find"), Gtk::RESPONSE_OK);

  const bool find_again = (dialog.run() == Gtk::RESPONSE_OK);
  return find_again;
}

492

493
void UiUtils::show_report_in_browser(const std::string& filepath, Gtk::Window* parent_window)
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
{
  //Give the user a clue, in case the web browser opens in the background, for instance in a new tab:
  if(parent_window)
    show_ok_dialog(_("Report Finished"), _("The report will now be opened in your web browser."), *parent_window, Gtk::MESSAGE_INFO);

#ifdef G_OS_WIN32
  // gtk_show_uri doesn't seem to work on Win32, at least not for local files
  // We use Windows API instead.
  // TODO: Check it again and file a bug if necessary.
  ShellExecute(0, "open", filepath.c_str(), 0, 0, SW_SHOW);
#else

  Glib::ustring uri;
  try
  {
    uri = Glib::filename_to_uri(filepath);
  }
  catch(const Glib::ConvertError& ex)
  {
    std::cerr << G_STRFUNC << ": Could not convert filepath to URI: " << filepath << std::endl;
    return;
  }

  //Use the GNOME browser:
  GError* gerror = 0;
  if(!gtk_show_uri(0 /* screen */, uri.c_str(), GDK_CURRENT_TIME, &gerror))
  {
    std::cerr << G_STRFUNC << ": " << gerror->message << std::endl;
    g_error_free(gerror);
  }
#endif //G_OS_WIN32
}

527
std::string UiUtils::get_icon_path(const Glib::ustring& filename)
528
{
529
  return  "/org/gnome/glom/data/icons/" + filename;
530
531
}

532
bool UiUtils::script_check_for_pygtk2_with_warning(const Glib::ustring& script, Gtk::Window* parent_window)
533
534
535
{
  if(!Utils::script_check_for_pygtk2(script))
  {
536
    UiUtils::show_ok_dialog(_("Script Uses PyGTK 2"),
537
538
539
540
541
542
543
      _("Glom cannot run this script because it uses pygtk 2, but Glom uses GTK+ 3, and attempting to use pygtk 2 would cause Glom to crash."), parent_window, Gtk::MESSAGE_ERROR);
    return false;
  }

  return true;
}

544
void UiUtils::treeview_delete_all_columns(Gtk::TreeView* treeview)
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
{
  if(!treeview)
    return;

  //We use this instead of just Gtk::TreeView::remove_all_columns()
  //because that deletes columns as a side-effect of unreferencing them,
  //and that behaviour might be fixed in gtkmm sometime,
  //and whether they should be deleted by that would depend on whether we used Gtk::manage().
  //Deleting them explicitly is safer and clearer. murrayc.

  //Remove all View columns:
  typedef std::vector<Gtk::TreeView::Column*> type_vec_columns;
  type_vec_columns vecViewColumns (treeview->get_columns());

  for (type_vec_columns::iterator iter (vecViewColumns.begin ()), columns_end (vecViewColumns.end ());
    iter != columns_end;
    ++iter)
  {
    Gtk::TreeView::Column* pViewColumn (*iter);
    if(!pViewColumn)
      continue;

    GtkTreeViewColumn* weak_ptr = 0;
    g_object_add_weak_pointer (G_OBJECT (pViewColumn->gobj()), (gpointer*)&weak_ptr);

    //Keep the object alive, instead of letting gtk_tree_view_remove_column() delete it by reducing its reference to 0,
    //so we can explicitly delete it.
    //This feels safer, considering some strange crashes I've seen when using Gtk::TreeView::remove_all_columns(),
    //though that might have been just because we didn't reset m_treeviewcolumn_button. murrayc.
    pViewColumn->reference();
    treeview->remove_column(*pViewColumn);
    delete pViewColumn; //This should cause it to be removed.

    if(weak_ptr)
    {
      std::cerr << G_STRFUNC << ": The GtkTreeViewColumn was not destroyed as expected." << std::endl;
    }
  }
}

585
} //namespace Glom