imageglom.cc 27.2 KB
Newer Older
1
2
/* Glom
 *
3
 * Copyright (C) 2001-2011 Murray Cumming
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 *
 * 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
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#include "imageglom.h"
#include <glibmm/i18n.h>
23
#include <glom/application.h>
24
#include <glom/utils_ui.h>
25
#include <glom/glade_utils.h>
26
#include <libglom/data_structure/glomconversions.h>
27
28
#include <glom/utility_widgets/dialog_image_load_progress.h>
#include <glom/utility_widgets/dialog_image_save_progress.h>
29
30
31
#include <gtkmm/appchooserdialog.h>
#include <gtkmm/filechooserdialog.h>
#include <gtkmm/stock.h>
32
33
34
#include <giomm/file.h>
#include <giomm/contenttype.h>
#include <glibmm/convert.h>
35
36
37

#include <iostream>   // for cout, endl

38
39
40
namespace Glom
{

41
ImageGlom::type_vec_ustrings ImageGlom::m_evince_supported_mime_types;
42
ImageGlom::type_vec_ustrings ImageGlom::m_gdkpixbuf_supported_mime_types;
43

44
ImageGlom::ImageGlom()
45
46
: m_ev_view(0),
  m_ev_document_model(0),
47
  m_pMenuPopup_UserMode(0)
48
{
49
50
51
  init();
}

52
ImageGlom::ImageGlom(BaseObjectType* cobject, const Glib::RefPtr<Gtk::Builder>& /* builder */)
53
: Gtk::EventBox(cobject),
54
55
  m_ev_view(0),
  m_ev_document_model(0),
56
  m_pMenuPopup_UserMode(0)
57
58
59
60
61
62
{
  init();
}

void ImageGlom::init()
{
63
  m_ev_view = EV_VIEW(ev_view_new());
64
65
66
67
68
69
70
71
  //gtk_widget_add_events(GTK_WIDGET(m_ev_view), GDK_BUTTON_PRESS_MASK);

  //Connect the the EvView's button-press-event signal, 
  //because we don't get it otherwise.
  //For some reason this is not necessary with the GtkImage.
  Gtk::Widget* cppEvView = Glib::wrap(GTK_WIDGET(m_ev_view));
  cppEvView->signal_button_press_event().connect(
    sigc::mem_fun(*this, &ImageGlom::on_button_press_event), false);
72

73
74
  m_read_only = false;

75
#ifndef GLOM_ENABLE_CLIENT_ONLY
76
  setup_menu();
77
78
#endif // !GLOM_ENABLE_CLIENT_ONLY

79
  setup_menu_usermode();
80

81
  //m_image.set_size_request(150, 150);
82

83

84
85
  m_frame.set_shadow_type(Gtk::SHADOW_ETCHED_IN); //Without this, the image widget has no borders and is completely invisible when empty.
  m_frame.show();
86

87
  add(m_frame);
88
89
}

90
91


92
93
94
95
ImageGlom::~ImageGlom()
{
}

96
97
98
void ImageGlom::set_layout_item(const sharedptr<LayoutItem>& layout_item, const Glib::ustring& table_name)
{
  LayoutWidgetField::set_layout_item(layout_item, table_name);
99
#ifdef GTKMM_ATKMM_ENABLED
100
  get_accessible()->set_name(layout_item->get_name());
101
#endif  
102
}
103
104
105
106

bool ImageGlom::on_button_press_event(GdkEventButton *event)
{
  GdkModifierType mods;
107
  gdk_window_get_device_position( gtk_widget_get_window (Gtk::Widget::gobj()), event->device, 0, 0, &mods );
108

109
110
  //Enable/Disable items.
  //We did this earlier, but get_application is more likely to work now:
111
  Application* pApp = get_application();
112
113
  if(pApp)
  {
114
#ifndef GLOM_ENABLE_CLIENT_ONLY
115
116
117
118
119
120
    pApp->add_developer_action(m_refContextLayout); //So that it can be disabled when not in developer mode.
    pApp->add_developer_action(m_refContextAddField);
    pApp->add_developer_action(m_refContextAddRelatedRecords);
    pApp->add_developer_action(m_refContextAddGroup);

    pApp->update_userlevel_ui(); //Update our action's sensitivity.
121
#endif // !GLOM_ENABLE_CLIENT_ONLY
122
123
124

    //Only show this popup in developer mode, so operators still see the default GtkEntry context menu.
    //TODO: It would be better to add it somehow to the standard context menu.
125
#ifndef GLOM_ENABLE_CLIENT_ONLY
126
127
128
129
130
131
132
133
134
    if(pApp->get_userlevel() == AppState::USERLEVEL_DEVELOPER)
    {
      if(mods & GDK_BUTTON3_MASK)
      {
        //Give user choices of actions on this item:
        m_pMenuPopup->popup(event->button, event->time);
        return true; //We handled this event.
      }
    }
135
    else
136
#endif // !GLOM_ENABLE_CLIENT_ONLY
137
    {
138
      // We cannot be in developer mode in client only mode.
139
140
141
142
143
144
145
      if(mods & GDK_BUTTON3_MASK)
      {
        //Give user choices of actions on this item:
        m_pMenuPopup_UserMode->popup(event->button, event->time);
        return true; //We handled this event.
      }
    }
146

147
148
    //Single-click to select file:
    if(mods & GDK_BUTTON1_MASK)
149
    {
150
151
152
      on_menupopup_activate_select_file();
      return true; //We handled this event.

153
154
155
156
157
158
    }
  }

  return Gtk::EventBox::on_button_press_event(event);
}

159
Application* ImageGlom::get_application()
160
161
162
163
{
  Gtk::Container* pWindow = get_toplevel();
  //TODO: This only works when the child widget is already in its parent.

164
  return dynamic_cast<Application*>(pWindow);
165
166
}

167
168
169
170
bool ImageGlom::get_has_original_data() const
{
  return true; //TODO.
}
171

172
/*
173
174
175
void ImageGlom::set_pixbuf(const Glib::RefPtr<Gdk::Pixbuf>& pixbuf)
{
  m_pixbuf_original = pixbuf;
176
  show_image_data();
177
}
178
*/
179

180
void ImageGlom::set_value(const Gnome::Gda::Value& value)
181
{
Armin Burgmeier's avatar
Armin Burgmeier committed
182
183
184
  // Remember original data 
  m_original_data = Gnome::Gda::Value();
  m_original_data = value;
185
  show_image_data();
186
187
188
189
}

Gnome::Gda::Value ImageGlom::get_value() const
{
190
  return m_original_data;
191
}
192

193
void ImageGlom::on_size_allocate(Gtk::Allocation& allocation)
194
{
195
  Gtk::EventBox::on_size_allocate(allocation);
196

197
  //Resize the GtkImage if necessary:
Murray Cumming's avatar
Murray Cumming committed
198
  if(m_pixbuf_original)
199
  {
200
    const Glib::RefPtr<Gdk::Pixbuf> pixbuf_scaled = get_scaled_image();
201
202
    m_image.set(pixbuf_scaled);
  }
203
204
}

205
static void image_glom_ev_job_finished(EvJob* job, void* user_data)
206
{
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
  g_assert(job);
  
  ImageGlom* self = (ImageGlom*)user_data;
  g_assert(self);
  
  self->on_ev_job_finished(job);
}
  
void ImageGlom::on_ev_job_finished(EvJob* job)
{
	if (ev_job_is_failed (job)) {
		g_warning ("%s", job->error->message);
		g_object_unref (job);

		return;
	}

	ev_document_model_set_document(m_ev_document_model, job->document);
	ev_document_model_set_page(m_ev_document_model, 1);
	g_object_unref (job);
	
	ev_view_set_loading(m_ev_view, FALSE);
}
230

231
232
233
234
235
236
237
238
239
const GdaBinary* ImageGlom::get_binary() const
{
  const GdaBinary* gda_binary = 0;
  if(m_original_data.get_value_type() == GDA_TYPE_BINARY)
    gda_binary = gda_value_get_binary(m_original_data.gobj());
  
  return gda_binary;
}

240
241
Glib::ustring ImageGlom::get_mime_type() const
{
242
243
  const GdaBinary* gda_binary = get_binary();

244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
  if(!gda_binary)
    return Glib::ustring();
    
  if(!gda_binary->data)
    return Glib::ustring();

  bool uncertain = false;
  const Glib::ustring result = Gio::content_type_guess(std::string(),
    gda_binary->data, gda_binary->binary_length,
    uncertain);

  //std::cout << G_STRFUNC << ": mime_type=" << result << ", uncertain=" << uncertain << std::endl;
  return result;  
}

void ImageGlom::fill_evince_supported_mime_types()
{
  //Fill the static list if it has not already been filled:
  if(!m_evince_supported_mime_types.empty())
    return;

  //Discover what mime types libevview can support.
  //Older versions supported image types too, via GdkPixbuf,
  //but that support was then removed.  
  GList* types_list = ev_backends_manager_get_all_types_info();
  if(!types_list)
  {
    return;
  }
  
  for(GList* l = types_list; l; l = g_list_next(l))
  {
	  EvTypeInfo *info = (EvTypeInfo *)l->data;
	  if(!info)
	    continue;

	  const char* mime_type = 0;
	  int i = 0;
	  while((mime_type = info->mime_types[i++]))
	  {
	    if(mime_type)
	      m_evince_supported_mime_types.push_back(mime_type);
	    //std::cout << "evince supported mime_type=" << mime_type << std::endl; 
	  }
	}  
}

291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
void ImageGlom::fill_gdkpixbuf_supported_mime_types()
{
  //Fill the static list if it has not already been filled:
  if(!m_gdkpixbuf_supported_mime_types.empty())
    return;
    
  typedef std::vector<Gdk::PixbufFormat> type_vec_formats;
  const type_vec_formats formats = Gdk::Pixbuf::get_formats();
  
  for(type_vec_formats::const_iterator iter = formats.begin();
    iter != formats.end(); ++iter)
  {
    const Gdk::PixbufFormat& format = *iter;
    const std::vector<Glib::ustring> mime_types = format.get_mime_types();
    m_gdkpixbuf_supported_mime_types.insert(
      m_gdkpixbuf_supported_mime_types.end(),
      mime_types.begin(), mime_types.end());
  }
}

311
312
313
314
void ImageGlom::show_image_data()
{
  bool use_evince = false;
  
315
316
317
  const Glib::ustring mime_type = get_mime_type();

  //std::cout << "mime_type=" << mime_type << std::endl; 
318
  
319
320
321
322
323
324
  fill_evince_supported_mime_types();
  const type_vec_ustrings::iterator iterFind = 
    std::find(m_evince_supported_mime_types.begin(),
      m_evince_supported_mime_types.end(),
      mime_type);
  if(iterFind != m_evince_supported_mime_types.end())
325
  {
326
327
    use_evince = true;
  }  
328
  
329
330
  m_frame.remove();
    
331
332
  //Clear all possible display widgets:
  m_pixbuf_original.reset();
333
  m_image.set(Glib::RefPtr<Gdk::Pixbuf>()); //TODO: Add an unset() to gtkmm.
334
335
336
337
338
339
340
341
342
343
344
  
  if(m_ev_document_model)
  {
    g_object_unref(m_ev_document_model);
    m_ev_document_model = 0;
  }

  if(use_evince)
  {
    //Use EvView:
    m_image.hide();
345
    
346
347
348
    gtk_widget_show(GTK_WIDGET(m_ev_view));
    gtk_container_add(GTK_CONTAINER(m_frame.gobj()), GTK_WIDGET(m_ev_view));

349
350
351
    // Try loading from data in memory:
    // TODO: Uncomment this if this API is added: https://bugzilla.gnome.org/show_bug.cgi?id=654832
    /*
352
    const GdaBinary* gda_binary = get_binary();
353
354
355
356
357
358
359
360
361
362
363
    if(!gda_binary || !gda_binary->data || !gda_binary->binary_length)
    {
       std::cerr << G_STRFUNC << "Data was null or empty." << std::endl;
      return;
    }
    
    EvJob *job = ev_job_load_new_with_data(
      (char*)gda_binary->data, gda_binary->binary_length);
    */
    //TODO: Test failure asynchronously.
    
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
    const Glib::ustring uri = save_to_temp_file(false /* don't show progress */);
    if(uri.empty())
    {
      std::cerr << G_STRFUNC << "Could not save temp file to show in the EvView." << std::endl;
    }
  
    EvJob *job = ev_job_load_new(uri.c_str());
  
    m_ev_document_model = ev_document_model_new();
    ev_view_set_model(m_ev_view, m_ev_document_model);
	  ev_document_model_set_continuous(m_ev_document_model, FALSE); //Show only one page.
	  ev_view_set_loading(m_ev_view, TRUE);
	
    g_signal_connect (job, "finished",
		  G_CALLBACK (image_glom_ev_job_finished), this);
	  ev_job_scheduler_push_job (job, EV_JOB_PRIORITY_NONE);
  }
  else
  {
    //Use GtkImage instead:
384
    gtk_widget_hide(GTK_WIDGET(m_ev_view));  
385
386
    m_image.show();
    m_frame.add(m_image);
387
388
    
    Glib::RefPtr<const Gio::Icon> icon;
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
      
    bool use_gdkpixbuf = false;
    fill_gdkpixbuf_supported_mime_types();
    const type_vec_ustrings::iterator iterFind = 
      std::find(m_gdkpixbuf_supported_mime_types.begin(),
        m_gdkpixbuf_supported_mime_types.end(),
        mime_type);
    if(iterFind != m_gdkpixbuf_supported_mime_types.end())
    {
      use_gdkpixbuf = true;
    }
    
    if(use_gdkpixbuf)
    {
      //Try to use GdkPixbuf's loader:
      m_pixbuf_original = Utils::get_pixbuf_for_gda_value(m_original_data);
    }
    else
    {
408
409
      //Get an icon for the file type;
      icon = Gio::content_type_get_icon(mime_type);
410
    }
411
    
412
    if(m_pixbuf_original)
413
414
415
416
    {
      Glib::RefPtr<Gdk::Pixbuf> pixbuf_scaled = get_scaled_image();
      m_image.set(pixbuf_scaled);
    }
417
418
419
420
    else if(icon)
    {
      m_image.set(icon, Gtk::ICON_SIZE_DIALOG);
    }
421
    else
422
    {
423
      m_image.set(Gtk::Stock::MISSING_IMAGE, Gtk::ICON_SIZE_DIALOG);
424
    }
425
426
427
  }
}

428
Glib::RefPtr<Gdk::Pixbuf> ImageGlom::get_scaled_image()
429
430
431
432
{
  Glib::RefPtr<Gdk::Pixbuf> pixbuf = m_pixbuf_original;

  if(!pixbuf)
433
    return pixbuf;
434
435
436
437
438
 
  const Gtk::Allocation allocation = m_image.get_allocation();
  const int pixbuf_height = pixbuf->get_height();
  const int pixbuf_width = pixbuf->get_width();
    
Murray Cumming's avatar
Murray Cumming committed
439
440
  const int allocation_height = allocation.get_height();
  const int allocation_width = allocation.get_width();
441
      
Murray Cumming's avatar
Murray Cumming committed
442
443
  //std::cout << "pixbuf_height=" << pixbuf_height << ", pixbuf_width=" << pixbuf_width << std::endl;
  //std::cout << "allocation_height=" << allocation.get_height() << ", allocation_width=" << allocation.get_width() << std::endl;
444

445
  if( (pixbuf_height > allocation_height) ||
446
447
      (pixbuf_width > allocation_width) )
  {
448
    if(true) //allocation_height > 10 || allocation_width > 10)
449
    {
450
451
452
      Glib::RefPtr<Gdk::Pixbuf> pixbuf_scaled = Utils::image_scale_keeping_ratio(pixbuf, allocation_height, allocation_width);
      
      //Don't set a new pixbuf if the dimensions have not changed:
453
      Glib::RefPtr<Gdk::Pixbuf> pixbuf_in_image;
454
455
456
457
458

      if(m_image.get_storage_type() == Gtk::IMAGE_PIXBUF) //Prevent warning.
        pixbuf_in_image = m_image.get_pixbuf();

      if( !pixbuf_in_image || !pixbuf_scaled || (pixbuf_in_image->get_height() != pixbuf_scaled->get_height()) || (pixbuf_in_image->get_width() != pixbuf_scaled->get_width()) )
459
      {
Murray Cumming's avatar
Murray Cumming committed
460
        /*
461
462
463
464
465
        std::cout << "get_scale(): returning scaled" << std::endl;
        if(pixbuf_scaled)
        {
          std::cout << "scaled height=" << pixbuf_scaled->get_height() << ", scaled width=" << pixbuf_scaled->get_width() << std::endl;
        }
Murray Cumming's avatar
Murray Cumming committed
466
        */
467
468
        
        return pixbuf_scaled;
469
      }
470
      else
471
      {
472
473
474
475
        //Return the existing one, 
        //instead of a new one with the same contents,
        //so no unnecessary changes will be triggered.
        return pixbuf_in_image;
476
      }
477
    }
478
  }
479
  
Murray Cumming's avatar
Murray Cumming committed
480
  //std::cout << "get_scaled(): returning original" << std::endl;
481
  return pixbuf;
482
483
}

484
void ImageGlom::on_menupopup_activate_open_file()
485
{
486
487
488
489
490
491
492
493
  open_with();
}

void ImageGlom::on_menupopup_activate_open_file_with()
{
  Application* pApp = get_application();

  //Offer the user a choice of suitable applications:
494
495
496
497
498
499
500
  const Glib::ustring mime_type = get_mime_type();
  if(mime_type.empty())
  {
    std::cerr << G_STRFUNC << ": mime_type is empty." << std::endl;
  }
  
  Gtk::AppChooserDialog dialog(mime_type);
501
502
503
504
  if(pApp)
    dialog.set_transient_for(*pApp);

  if(dialog.run() != Gtk::RESPONSE_OK)
505
    return;
506
507
508
509
510
511
512
513
514
  
  Glib::RefPtr<Gio::AppInfo> app_info = dialog.get_app_info();
  if(!app_info)
  {
    std::cerr << G_STRFUNC << ": app_info was null." << std::endl;
  }
  
  open_with(app_info);
}
515

516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
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
static void make_file_read_only(const Glib::ustring& uri)
{
  std::string filepath;

  try
  {
    filepath = Glib::filename_from_uri(uri);
  }
  catch(const Glib::Error& ex)
  {
    std::cerr << G_STRFUNC << "Exception: " << ex.what() << std::endl;
    return;
  }
  
  if(filepath.empty())
  {
    std::cerr << G_STRFUNC << ": filepath is empty." << std::endl;
  }
  
  const int result = chmod(filepath.c_str(), S_IRUSR);
  if(result != 0)
  {
    std::cerr << G_STRFUNC << ": chmod() failed." << std::endl;
  }
  
  //Setting the attribute via gio gives us this exception:
  //"Setting attribute access::can-write not supported"
  /*
  Glib::RefPtr<Gio::File> file = Gio::File::create_for_uri(uri);

  Glib::RefPtr<Gio::FileInfo> file_info;

  try
  {
    file_info = file->query_info(G_FILE_ATTRIBUTE_ACCESS_CAN_WRITE);
  }
  catch(const Glib::Error& ex)
  {
    std::cerr << G_STRFUNC << ": query_info() failed: " << ex.what() << std::endl;
    return;
  }
  
  if(!file_info)
  {
    std::cerr << ": file_info is null" << std::endl;
    return;
  }
  
  const bool can_write =
    file_info->get_attribute_boolean(G_FILE_ATTRIBUTE_ACCESS_CAN_WRITE);
  if(!can_write)
    return;
    
  file_info->set_attribute_boolean(G_FILE_ATTRIBUTE_ACCESS_CAN_WRITE, false);
  
  try
  {
    file->set_attributes_from_info(file_info);
  }
  catch(const Glib::Error& ex)
  {
    std::cerr << G_STRFUNC << ": set_attributes_from_info() failed: " << ex.what() << std::endl;
  }
  */
}

582
Glib::ustring ImageGlom::save_to_temp_file(bool show_progress)
583
{
584
585
  Glib::ustring uri;
  
586
587
  //Get a temporary file path:
  std::string filepath;
588
589
590
591
592
593
594
595
596
  try
  {
    const int filehandle = Glib::file_open_tmp(filepath);
    ::close(filehandle);
  }
  catch(const Glib::Error& ex)
  {
    std::cerr << G_STRFUNC << ": Glib::file_open_tmp() failed" << std::endl;
  }
597
598
599
600
  
  if(filepath.empty())
  {
    std::cerr << G_STRFUNC << ": Glib::file_open_tmp() returned an empty filepath" << std::endl;
601
    return uri;
602
603
  }
  
604
605
606
607
608
609
610
  uri = Glib::filename_to_uri(filepath);
  
  bool saved = false;
  if(show_progress)
    saved = save_file(uri);
  else
    saved = save_file_sync(uri);
611
  
612
613
614
615
616
  if(!saved)
  {
    uri = Glib::ustring();
    std::cerr << G_STRFUNC << ": save_file() failed." << std::endl;
  }
617
618
619
620
621
622
623
  else
  {
    //Don't let people easily edit the saved file,
    //because they would lose data when it is automatically deleted later.
    //Also they might think that editing it will change it in the database.
    make_file_read_only(uri);
  }
624
625
626
627
628
629
630
631

  return uri;
}

void ImageGlom::open_with(const Glib::RefPtr<Gio::AppInfo>& app_info)
{
  const Glib::ustring uri = save_to_temp_file();
  if(uri.empty())
632
633
634
635
636
637
638
    return;

  if(app_info)
  {
    std::vector<std::string> vec_uris;
    vec_uris.push_back(uri);
    app_info->launch_uris(vec_uris, 0); //TODO: Get a GdkAppLaunchContext?
639
640
641
    
    //TODO Use this instead when we can use glibmm 3.2:
    //app_info->launch_uri(uri);
642
643
644
645
646
647
648
649
  }
  else
  {
    //TODO: Avoid duplication in xsl_utils.cc, by moving this into a utility function:  
#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.
650
651
    // TODO: and this might not be necessary with Gio::AppInfo::launch_default_for_uri().
    //   Previously we used gtk_show_uri().
652
653
    ShellExecute(0, "open", uri.c_str(), 0, 0, SW_SHOW);
#else
654
    Gio::AppInfo::launch_default_for_uri(uri);
655
656
657
#endif //G_OS_WIN32
  }
}
658

659

660
static void set_file_filter_images(Gtk::FileChooser& file_chooser)
661
{
662
  //Get image formats only:
663
664
665
  Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
  filter->set_name(_("Images"));
  filter->add_pixbuf_formats();
666
  file_chooser.add_filter(filter);
667
  
668
669
  ev_document_factory_add_filters(GTK_WIDGET(file_chooser.gobj()), 0);
  
670
671
672
  //Make Images the currently-selected one:
  file_chooser.set_filter(filter);
  
673
  /*  ev_document_factory_add_filters() add this already:
674
675
676
677
  filter = Gtk::FileFilter::create();
  filter->set_name(_("All Files"));
  filter->add_pattern("*");
  file_chooser.add_filter(filter);
678
  */
679
680
681
682
683
684
685
686
687
688
}

void ImageGlom::on_menupopup_activate_save_file()
{
  Application* pApp = get_application();

  Gtk::FileChooserDialog dialog(_("Save Image"), Gtk::FILE_CHOOSER_ACTION_SAVE);
  if(pApp)
    dialog.set_transient_for(*pApp);
          
689
  set_file_filter_images(dialog);
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704

  dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
  dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);
  const int response = dialog.run();
  dialog.hide();
  if(response != Gtk::RESPONSE_OK)
    return;
    
  const Glib::ustring uri = dialog.get_uri();
  if(uri.empty())
    return;
    
  save_file(uri);
}

705
706
707
708
709
710
711
bool ImageGlom::save_file_sync(const Glib::ustring& uri)
{
  //TODO: We should still do this asynchronously, 
  //even when we don't use the dialog's run() to do that
  //because we don't want to offer feedback.
  //Ideally, EvView would just load from data anyway.
  
712
  const GdaBinary* gda_binary = get_binary();
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
  if(!gda_binary)
  {
    std::cerr << G_STRFUNC << ": GdaBinary is null" << std::endl;
    return false;
  }
    
  if(!gda_binary->data)
  {
    std::cerr << G_STRFUNC << ": GdaBinary::data is null" << std::endl;
    return false;
  }

  try
  {
    const std::string filepath = Glib::filename_from_uri(uri);
    Glib::file_set_contents(filepath, (const char*)gda_binary->data, gda_binary->binary_length);
  }
  catch(const Glib::Error& ex)
  {
    std::cerr << G_STRFUNC << "Exception: " << ex.what() << std::endl;
    return false;
  }
  
  return true;
}

739
740
741
742
743
744
745
746
747
748
749
750
751
752
bool ImageGlom::save_file(const Glib::ustring& uri)
{
  DialogImageSaveProgress* dialog_save = 0;
  Utils::get_glade_widget_derived_with_warning(dialog_save);
  if(!dialog_save)
    return false;
    
  // Automatically delete the dialog when we no longer need it:
  std::auto_ptr<Gtk::Dialog> dialog_keeper(dialog_save);

  Application* pApp = get_application();
  if(pApp)
    dialog_save->set_transient_for(*pApp);

753
  const GdaBinary* gda_binary = get_binary();
754
755
756
757
  if(!gda_binary)
    return false;

  dialog_save->set_image_data(*gda_binary);
758
759
  dialog_save->save(uri);

760
  dialog_save->run();
761

762
763
764
765
766
767
768
769
770
771
772
773
774
775
  return true;
}

void ImageGlom::on_menupopup_activate_select_file()
{
  if(m_read_only)
    return;
    
  Application* pApp = get_application();

  Gtk::FileChooserDialog dialog(_("Choose Image"), Gtk::FILE_CHOOSER_ACTION_OPEN);
  if(pApp)
    dialog.set_transient_for(*pApp);
          
776
  set_file_filter_images(dialog);
777

778
779
780
781
  dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
  dialog.add_button(_("Select"), Gtk::RESPONSE_OK);
  int response = dialog.run();
  dialog.hide();
782

783
  if((response != Gtk::RESPONSE_CANCEL) && (response != Gtk::RESPONSE_DELETE_EVENT))
784
  {
785
786
    const Glib::ustring uri = dialog.get_uri();
    if(!uri.empty())
787
    {
788
      DialogImageLoadProgress* dialog;
789
      Utils::get_glade_widget_derived_with_warning(dialog);
790
      if(dialog)
791
      {
792
793
        // Automatically delete the dialog when we no longer need it:
        std::auto_ptr<Gtk::Dialog> dialog_keeper(dialog);
Armin Burgmeier's avatar
Armin Burgmeier committed
794

795
796
797
        if(pApp)
          dialog->set_transient_for(*pApp);

798
        dialog->load(uri);
Armin Burgmeier's avatar
Armin Burgmeier committed
799

800
        if(dialog->run() == Gtk::RESPONSE_ACCEPT)
Armin Burgmeier's avatar
Armin Burgmeier committed
801
        {
802
803
804
805
806
807
          GdaBinary* bin = g_new(GdaBinary, 1);
          std::auto_ptr<GdaBinary> image_data = dialog->get_image_data();
          bin->data = image_data->data;
          bin->binary_length = image_data->binary_length;

          m_original_data = Gnome::Gda::Value();
808
809
810
          
          g_value_unset(m_original_data.gobj());
          g_value_init(m_original_data.gobj(), GDA_TYPE_BINARY);
811
812
          gda_value_take_binary(m_original_data.gobj(), bin);

813
          show_image_data();
Armin Burgmeier's avatar
Armin Burgmeier committed
814
815
          signal_edited().emit();
        }
816
817
      }
    }
818
  }
819
820
}

821
822
823
824
825
826
827
void ImageGlom::on_clipboard_get(Gtk::SelectionData& selection_data, guint /* info */)
{
  //info is meant to indicate the target, but it seems to be always 0,
  //so we use the selection_data's target instead.

  const std::string target = selection_data.get_target(); 

828
829
830
831
832
833
834
  const Glib::ustring mime_type = get_mime_type();
  if(mime_type.empty())
  {
    std::cerr << G_STRFUNC << ": mime_type is empty." << std::endl;
  }
  
  if(target == mime_type)
835
  {
836
    const GdaBinary* gda_binary = get_binary();
837
838
839
840
841
842
843
844
    if(!gda_binary)
      return;
    
    if(!gda_binary->data)
      return;
    
    selection_data.set(mime_type, 8, gda_binary->data, gda_binary->binary_length);

845
    // This set() override uses an 8-bit text format for the data.
846
    //selection_data.set_pixbuf(m_pixbuf_clipboard);
847
848
849
  }
  else
  {
850
    std::cout << "ExampleWindow::on_clipboard_get(): Unexpected clipboard target format. expected: " << mime_type << std::endl;
851
  }
852
853
854
855
}

void ImageGlom::on_clipboard_clear()
{
856
857
858
  if(m_read_only)
    return;

859
  m_pixbuf_clipboard.reset();
860
861
}

862
863
void ImageGlom::on_menupopup_activate_copy()
{
864
865
866
867
868
869
  if(m_pixbuf_original)
  {
    //When copy is used, store it here until it is pasted.
    m_pixbuf_clipboard = m_pixbuf_original->copy(); //TODO: Get it from the DB, when we stop storing the original here instead of just the preview.
  }
  else
870
    m_pixbuf_clipboard.reset();
871

872
873
874
  Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();

  //Targets:
875
876
877
878
879
880
  const Glib::ustring mime_type = get_mime_type();
  if(mime_type.empty())
  {
    std::cerr << G_STRFUNC << ": mime_type is empty." << std::endl;
  }
  
881
  std::vector<Gtk::TargetEntry> listTargets;
882
  listTargets.push_back( Gtk::TargetEntry(mime_type) );
883

884
885
  refClipboard->set( listTargets, sigc::mem_fun(*this, &ImageGlom::on_clipboard_get), sigc::mem_fun(*this, &ImageGlom::on_clipboard_clear) );
}
886

887
888
void ImageGlom::on_clipboard_received_image(const Glib::RefPtr<Gdk::Pixbuf>& pixbuf)
{
889
890
891
  if(m_read_only)
    return;

892
893
  if(pixbuf)
  {
Armin Burgmeier's avatar
Armin Burgmeier committed
894
895
896
    // Clear original data of previous image
    m_original_data = Gnome::Gda::Value();

897
    m_pixbuf_original = pixbuf;
898
    show_image_data();
899

900
901
    signal_edited().emit();
  }
902
903
}

904

905
906
void ImageGlom::on_menupopup_activate_paste()
{
907
908
909
  if(m_read_only)
    return;

910
911
  //Tell the clipboard to call our method when it is ready:
  Glib::RefPtr<Gtk::Clipboard> refClipboard = Gtk::Clipboard::get();
912

913
914
  if(refClipboard)
    refClipboard->request_image( sigc::mem_fun(*this, &ImageGlom::on_clipboard_received_image) );
915
916
}

Murray Cumming's avatar
0.8.34:    
Murray Cumming committed
917
918
void ImageGlom::on_menupopup_activate_clear()
{
919
920
921
  if(m_read_only)
    return;

922
  m_original_data = Gnome::Gda::Value();
923
  show_image_data();
924
  signal_edited().emit();
Murray Cumming's avatar
0.8.34:    
Murray Cumming committed
925
926
}

927
928
929
void ImageGlom::setup_menu_usermode()
{
  m_refActionGroup_UserModePopup = Gtk::ActionGroup::create();
930

931
  m_refActionGroup_UserModePopup->add(Gtk::Action::create("ContextMenu_UserMode", "Context Menu") );
932
933
934
935
  
  m_refActionOpenFile =  Gtk::Action::create("ContextOpenFile", Gtk::Stock::OPEN);
  m_refActionOpenFileWith =  Gtk::Action::create("ContextOpenFileWith", Gtk::Stock::OPEN, _("Open With"));
  m_refActionSaveFile =  Gtk::Action::create("ContextSaveFile", Gtk::Stock::SAVE);
936
937
938
  m_refActionSelectFile =  Gtk::Action::create("ContextSelectFile", Gtk::Stock::EDIT, _("Choose File"));
  m_refActionCopy = Gtk::Action::create("ContextCopy", Gtk::Stock::COPY);
  m_refActionPaste = Gtk::Action::create("ContextPaste", Gtk::Stock::PASTE);
Murray Cumming's avatar
0.8.34:    
Murray Cumming committed
939
  m_refActionClear = Gtk::Action::create("ContextClear", Gtk::Stock::CLEAR);
940

941
942
943
944
945
946
947
948
949
  m_refActionGroup_UserModePopup->add(m_refActionOpenFile,
    sigc::mem_fun(*this, &ImageGlom::on_menupopup_activate_open_file) );

  m_refActionGroup_UserModePopup->add(m_refActionOpenFileWith,
    sigc::mem_fun(*this, &ImageGlom::on_menupopup_activate_open_file_with) );
    
  m_refActionGroup_UserModePopup->add(m_refActionSaveFile,
    sigc::mem_fun(*this, &ImageGlom::on_menupopup_activate_save_file) );
    
950
951
952
953
954
955
956
957
  m_refActionGroup_UserModePopup->add(m_refActionSelectFile,
    sigc::mem_fun(*this, &ImageGlom::on_menupopup_activate_select_file) );

  m_refActionGroup_UserModePopup->add(m_refActionCopy,
    sigc::mem_fun(*this, &ImageGlom::on_menupopup_activate_copy) );

  m_refActionGroup_UserModePopup->add(m_refActionPaste,
    sigc::mem_fun(*this, &ImageGlom::on_menupopup_activate_paste) );
958

Murray Cumming's avatar
0.8.34:    
Murray Cumming committed
959
960
  m_refActionGroup_UserModePopup->add(m_refActionClear,
    sigc::mem_fun(*this, &ImageGlom::on_menupopup_activate_clear) );
961
962
963
964
965
966
967
968
969
970
971
972

  m_refUIManager_UserModePopup = Gtk::UIManager::create();

  m_refUIManager_UserModePopup->insert_action_group(m_refActionGroup_UserModePopup);

  //TODO: add_accel_group(m_refUIManager_UserModePopup->get_accel_group());

  try
  {
    Glib::ustring ui_info = 
        "<ui>"
        "  <popup name='ContextMenu_UserMode'>"
973
974
975
        "    <menuitem action='ContextOpenFile'/>"
        "    <menuitem action='ContextOpenFileWith'/>"
        "    <menuitem action='ContextSaveFile'/>"
976
977
978
        "    <menuitem action='ContextSelectFile'/>"
        "    <menuitem action='ContextCopy'/>"
        "    <menuitem action='ContextPaste'/>"
Murray Cumming's avatar
0.8.34:    
Murray Cumming committed
979
        "    <menuitem action='ContextClear'/>"
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
        "  </popup>"
        "</ui>";

    m_refUIManager_UserModePopup->add_ui_from_string(ui_info);
  }
  catch(const Glib::Error& ex)
  {
    std::cerr << "building menus failed: " <<  ex.what();
  }

  //Get the menu:
  m_pMenuPopup_UserMode = dynamic_cast<Gtk::Menu*>( m_refUIManager_UserModePopup->get_widget("/ContextMenu_UserMode") ); 
  if(!m_pMenuPopup_UserMode)
    g_warning("menu not found");
}
995
996
997
998
999
1000
1001
1002
1003
1004
1005

void ImageGlom::do_choose_image()
{
  on_menupopup_activate_select_file();
}

void ImageGlom::set_read_only(bool read_only)
{
  m_read_only = read_only;
}

1006
1007

} //namespace Glom