]> git.street.me.uk Git - andy/viking.git/blob - src/clipboard.c
Fix comment in AC DEFINE
[andy/viking.git] / src / clipboard.c
1 /*
2  * viking -- GPS Data and Topo Analyzer, Explorer, and Manager
3  *
4  * Copyright (C) 2003-2005, Evan Battaglia <gtoevan@gmx.net>
5  * Copyright (C) 2005, Alex Foobarian <foobarian@gmail.com>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  */
22
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26
27 #include <string.h>
28 #include <stdlib.h>
29 #ifdef HAVE_SYS_TYPES_H
30 #include <sys/types.h>
31 #endif
32 #ifdef HAVE_UNISTD_H
33 #include <unistd.h>
34 #endif
35
36 #include <glib/gi18n.h>
37
38 #include "viking.h"
39
40
41 typedef struct {
42   gpointer clipboard;
43   gint pid;
44   VikClipboardDataType type;
45   gint subtype;
46   guint16 layer_type;
47   guint len;
48   gchar *text;
49   guint8 data[0];
50 } vik_clipboard_t;
51
52 static GtkTargetEntry target_table[] = {
53   { "application/viking", 0, 0 },
54   { "STRING", 0, 1 },
55 };
56
57 /*****************************************************************
58  ** functions which send to the clipboard client (we are owner) **
59  *****************************************************************/
60
61 static void clip_get ( GtkClipboard *c, GtkSelectionData *selection_data, guint info, gpointer p ) 
62 {
63   vik_clipboard_t *vc = p;
64   if ( info == 0 ) {
65     // Viking Data Type
66     //    g_print("clip_get: vc = %p, size = %d\n", vc, sizeof(*vc) + vc->len);
67     gtk_selection_data_set ( selection_data, gtk_selection_data_get_target(selection_data), 8, (void *)vc, sizeof(*vc) + vc->len );
68   }
69   if ( info == 1 ) {
70     // Should be a string, but make sure it's something
71     if ( vc->text )
72       gtk_selection_data_set_text ( selection_data, vc->text, -1); // string text is null terminated
73   }
74
75 }
76
77 static void clip_clear ( GtkClipboard *c, gpointer p )
78 {
79   vik_clipboard_t* vc = (vik_clipboard_t*)p;
80   g_free(vc->text);
81   g_free(vc);
82 }
83
84
85 /**************************************************************************
86  ** functions which receive from the clipboard owner (we are the client) **
87  **************************************************************************/
88
89 /* our own data type */
90 static void clip_receive_viking ( GtkClipboard *c, GtkSelectionData *sd, gpointer p ) 
91 {
92   VikLayersPanel *vlp = p;
93   vik_clipboard_t *vc;
94   if (gtk_selection_data_get_length(sd) == -1) {
95     g_warning ( _("paste failed") );
96     return;
97   } 
98   //  g_print("clip receive: target = %s, type = %s\n", gdk_atom_name(gtk_selection_data_get_target(sd), gdk_atom_name(sd->type));
99   //g_assert(!strcmp(gdk_atom_name(gtk_selection_data_get_target(sd)), target_table[0].target));
100
101   vc = (vik_clipboard_t *)gtk_selection_data_get_data(sd);
102   //  g_print("  sd->data = %p, sd->length = %d, vc->len = %d\n", sd->data, sd->length, vc->len);
103
104   if (gtk_selection_data_get_length(sd) != sizeof(*vc) + vc->len) {
105     g_warning ( _("wrong clipboard data size") );
106     return;
107   }
108
109   if ( vc->type == VIK_CLIPBOARD_DATA_LAYER )
110   {
111     VikLayer *new_layer = vik_layer_unmarshall ( vc->data, vc->len, vik_layers_panel_get_viewport(vlp) );
112     vik_layers_panel_add_layer ( vlp, new_layer );
113   }
114   else if ( vc->type == VIK_CLIPBOARD_DATA_SUBLAYER )
115   {
116     VikLayer *sel = vik_layers_panel_get_selected ( vlp );
117     if ( sel && sel->type == vc->layer_type)
118     {
119       if ( vik_layer_get_interface(vc->layer_type)->paste_item )
120         vik_layer_get_interface(vc->layer_type)->paste_item ( sel, vc->subtype, vc->data, vc->len);
121     }
122     else
123       a_dialog_error_msg_extra ( VIK_GTK_WINDOW_FROM_WIDGET(GTK_WIDGET(vlp)),
124                                  _("The clipboard contains sublayer data for %s layers. "
125                                    "You must select a layer of this type to paste the clipboard data."),
126                                  vik_layer_get_interface(vc->layer_type)->name );
127   }
128 }
129
130
131
132 /**
133  * clip_parse_latlon:
134  * @text: text containing LatLon data.
135  * @coord: computed coordinates.
136  *
137  * Utility func to handle pasted text:
138  * search for N dd.dddddd W dd.dddddd, N dd° dd.dddd W dd° dd.ddddd and so forth.
139  *
140  * Returns: TRUE if coordinates are set.
141  */
142 static gboolean clip_parse_latlon ( const gchar *text, struct LatLon *coord ) 
143 {
144   gint latdeg, londeg, latmi, lonmi;
145   gdouble lats, lons;
146   gdouble latm, lonm;
147   gdouble lat, lon;
148   gchar *cand;
149   gint len, i;
150   gchar *s = g_strdup(text);
151
152   //  g_print("parsing %s\n", s);
153
154   len = strlen(s);
155
156   /* remove non-digits following digits; gets rid of degree symbols or whatever people use, and 
157    * punctuation
158    */
159   for (i=0; i<len-2; i++) {
160     if (g_ascii_isdigit (s[i]) && s[i+1] != '.' && !g_ascii_isdigit (s[i+1])) {
161       s[i+1] = ' ';
162       if (!g_ascii_isalnum (s[i+2]) && s[i+2] != '-') {
163         s[i+2] = ' ';
164       }
165     }
166     if ( g_ascii_iscntrl (s[i]) ) {
167       // Replace any control characters (i.e. mainly for tabs) with a space
168       s[i] = ' ';
169     }
170   }
171
172   /* now try reading coordinates */
173   for (i=0; i<len; i++) {
174     if (s[i] == 'N' || s[i] == 'S' || g_ascii_isdigit (s[i])) {
175       gchar latc[2] = "SN";
176       gchar lonc[2] = "WE";
177       gint j, k;
178       cand = s+i;
179
180       // First try matching strings containing the cardinal directions
181       for (j=0; j<2; j++) {
182         for (k=0; k<2; k++) {
183           // DMM
184           gchar fmt1[] = "N %d%*[ ]%lf W %d%*[ ]%lf";
185           gchar fmt2[] = "%d%*[ ]%lf N %d%*[ ]%lf W";
186           // DDD
187           gchar fmt3[] = "N %lf W %lf";
188           gchar fmt4[] = "%lf N %lf W";
189           // DMS
190           gchar fmt5[] = "N%d%*[ ]%d%*[ ]%lf%*[ ]W%d%*[ ]%d%*[ ]%lf";
191
192           // Substitute in 'N','E','S' or 'W' values for each attempt
193           fmt1[0]  = latc[j];     fmt1[13] = lonc[k];
194           fmt2[11] = latc[j];     fmt2[24] = lonc[k];
195           fmt3[0]  = latc[j];     fmt3[6]  = lonc[k];
196           fmt4[4]  = latc[j];     fmt4[10] = lonc[k];
197           fmt5[0]  = latc[j];     fmt5[23] = lonc[k];
198
199           if (sscanf(cand, fmt1, &latdeg, &latm, &londeg, &lonm) == 4 ||
200               sscanf(cand, fmt2, &latdeg, &latm, &londeg, &lonm) == 4) {
201             lat = (j*2-1) * (latdeg + latm / 60);
202             lon = (k*2-1) * (londeg + lonm / 60);
203             break;
204           }
205           if (sscanf(cand, fmt3, &lat, &lon) == 2 ||
206               sscanf(cand, fmt4, &lat, &lon) == 2) {
207             lat *= (j*2-1);
208             lon *= (k*2-1);
209             break;
210           }
211           gint am = sscanf(cand, fmt5, &latdeg, &latmi, &lats, &londeg, &lonmi, &lons);
212           if ( am == 6 ) {
213             lat = (j*2-1) * (latdeg + latmi / 60.0 + lats / 3600.0);
214             lon = (k*2-1) * (londeg + lonmi / 60.0 + lons / 3600.0);
215             break;
216           }
217         }
218         if (k!=2) break;
219       }
220       if (j!=2) break;
221
222       // DMM without Cardinal directions
223       if (sscanf(cand, "%d%*[ ]%lf*[ ]%d%*[ ]%lf", &latdeg, &latm, &londeg, &lonm) == 4) {
224         lat = latdeg/abs(latdeg) * (abs(latdeg) + latm / 60);
225         lon = londeg/abs(londeg) * (abs(londeg) + lonm / 60);
226         break;
227       }
228       // DMS without Cardinal directions
229       if (sscanf(cand, "%d%*[ ]%d%*[ ]%lf%*[ ]%d%*[ ]%d%*[ ]%lf", &latdeg, &latmi, &lats, &londeg, &lonmi, &lons) == 6) {
230         lat = latdeg/abs(latdeg) * (abs(latdeg) + latm / 60.0 + lats / 3600.0);
231         lon = londeg/abs(londeg) * (abs(londeg) + lonm / 60.0 + lons / 3600.0);
232         break;
233       }
234       // Raw values
235       if (sscanf(cand, "%lf %lf", &lat, &lon) == 2) {
236         break;
237       }
238     }
239   }
240   g_free(s);
241
242   /* did we get to the end without actually finding a coordinate? */
243   if (i<len && lat >= -90.0 && lat <= 90.0 && lon >= -180.0 && lon <= 180.0) {
244     coord->lat = lat;
245     coord->lon = lon;
246     return TRUE;
247   }
248   return FALSE;
249 }
250
251 static void clip_add_wp(VikLayersPanel *vlp, struct LatLon *coord) 
252 {
253   VikCoord vc;
254   VikLayer *sel = vik_layers_panel_get_selected ( vlp );
255
256
257   vik_coord_load_from_latlon ( &vc, VIK_COORD_LATLON, coord );
258
259   if (sel && sel->type == VIK_LAYER_TRW) {
260     vik_trw_layer_new_waypoint ( VIK_TRW_LAYER(sel), VIK_GTK_WINDOW_FROM_LAYER(sel), &vc );
261     trw_layer_calculate_bounds_waypoints ( VIK_TRW_LAYER(sel) );
262     vik_layer_emit_update ( VIK_LAYER(sel) );
263   } else {
264     a_dialog_error_msg_extra ( VIK_GTK_WINDOW_FROM_WIDGET(GTK_WIDGET(vlp)), _("In order to paste a waypoint, please select an appropriate layer to paste into."), NULL);
265   }
266 }
267
268 static void clip_receive_text (GtkClipboard *c, const gchar *text, gpointer p)
269 {
270   VikLayersPanel *vlp = p;
271
272   g_debug ( "got text: %s", text );
273
274   VikLayer *sel = vik_layers_panel_get_selected ( vlp );
275   if ( sel && vik_treeview_get_editing ( sel->vt ) ) {
276     GtkTreeIter iter;
277     if ( vik_treeview_get_selected_iter ( sel->vt, &iter ) ) {
278       // Try to sanitize input:
279       gchar *name = g_strescape ( text, NULL );
280       vik_layer_rename ( sel, name );
281       vik_treeview_item_set_name ( sel->vt, &iter, name );
282       g_free ( name );
283     }
284     return;
285   }
286
287   struct LatLon coord;
288   if (clip_parse_latlon(text, &coord)) {
289     clip_add_wp(vlp, &coord);
290   }
291 }
292
293 static void clip_receive_html ( GtkClipboard *c, GtkSelectionData *sd, gpointer p ) 
294 {
295   VikLayersPanel *vlp = p;
296   gsize r, w;
297   GError *err = NULL;
298   gchar *s, *span;
299   gint tag = 0, i;
300   struct LatLon coord;
301
302   if (gtk_selection_data_get_length(sd) == -1) {
303     return;
304   } 
305
306   /* - copying from Mozilla seems to give html in UTF-16. */
307   if (!(s =  g_convert ( (gchar *)gtk_selection_data_get_data(sd), gtk_selection_data_get_length(sd), "UTF-8", "UTF-16", &r, &w, &err))) {
308     return;
309   }
310   //  g_print("html is %d bytes long: %s\n", gtk_selection_data_get_length(sd), s);
311
312   /* scrape a coordinate pasted from a geocaching.com page: look for a 
313    * telltale tag if possible, and then remove tags 
314    */
315   if (!(span = g_strstr_len(s, w, "<span id=\"LatLon\">"))) {
316     span = s;
317   }
318   for (i=0; i<strlen(span); i++) {
319     gchar ch = span[i];
320     if (ch == '<') {
321       tag++;
322     }
323     if (tag>0) {
324       span[i] = ' ';
325     }
326     if (ch == '>') {
327       if (tag>0) tag--;
328     }
329   }
330   if (clip_parse_latlon(span, &coord)) {
331     clip_add_wp(vlp, &coord);
332   }
333
334   g_free(s);
335 }
336
337 /**
338  * clip_receive_targets:
339  *
340  * Deal with various data types a clipboard may hold.
341  */
342 void clip_receive_targets ( GtkClipboard *c, GdkAtom *a, gint n, gpointer p )
343 {
344   VikLayersPanel *vlp = p;
345   gint i;
346
347   for (i=0; i<n; i++) {
348     gchar* name = gdk_atom_name(a[i]);
349     //g_print("  ""%s""\n", name);
350     gboolean breaktime = FALSE;
351     if (!g_strcmp0(name, "text/html")) {
352       gtk_clipboard_request_contents ( c, gdk_atom_intern("text/html", TRUE), clip_receive_html, vlp );
353       breaktime = TRUE;
354     }
355     if (a[i] == GDK_TARGET_STRING) {
356       gtk_clipboard_request_text ( c, clip_receive_text, vlp );
357       breaktime = TRUE;
358     }
359     if (!g_strcmp0(name, "application/viking")) {
360       gtk_clipboard_request_contents ( c, gdk_atom_intern("application/viking", TRUE), clip_receive_viking, vlp );
361       breaktime = TRUE;
362     }
363
364     g_free ( name );
365
366     if ( breaktime )
367       break;
368   }
369 }
370
371 /*********************************************************************************
372  ** public functions                                                            **
373  *********************************************************************************/
374
375 /**
376  * a_clipboard_copy_selected:
377  *
378  * Make a copy of selected object and associate ourselves with the clipboard.
379  */
380 void a_clipboard_copy_selected ( VikLayersPanel *vlp )
381 {
382   VikLayer *sel = vik_layers_panel_get_selected ( vlp );
383   GtkTreeIter iter;
384   VikClipboardDataType type = VIK_CLIPBOARD_DATA_NONE;
385   guint16 layer_type = 0;
386   gint subtype = 0;
387   guint8 *data = NULL;
388   guint len = 0;
389   const gchar *name = NULL;
390
391   if ( ! sel )
392     return;
393
394   if ( !vik_treeview_get_selected_iter ( sel->vt, &iter ) )
395     return;
396   layer_type = sel->type;
397
398   // Since we intercept copy and paste keyboard operations, this is called even when a cell is being edited
399   if ( vik_treeview_get_editing ( sel->vt ) ) {
400     type = VIK_CLIPBOARD_DATA_TEXT;
401     //  I don't think we can access what is actually selected (internal to GTK) so we go for the name of the item
402     // At least this is better than copying the layer data - which is even further away from what the user would be expecting...
403     name = vik_treeview_item_get_name ( sel->vt, &iter );
404     len = 0;
405   }
406   else {
407     if ( vik_treeview_item_get_type ( sel->vt, &iter ) == VIK_TREEVIEW_TYPE_SUBLAYER ) {
408       type = VIK_CLIPBOARD_DATA_SUBLAYER;
409       if ( vik_layer_get_interface(layer_type)->copy_item) {
410         subtype = vik_treeview_item_get_data(sel->vt, &iter);
411         vik_layer_get_interface(layer_type)->copy_item(sel, subtype, vik_treeview_item_get_pointer(sel->vt, &iter), &data, &len );
412         // This name is used in setting the text representation of the item on the clipboard.
413         name = vik_treeview_item_get_name(sel->vt, &iter);
414       }
415     }
416     else {
417       gint ilen;
418       type = VIK_CLIPBOARD_DATA_LAYER;
419       vik_layer_marshall ( sel, &data, &ilen );
420       len = ilen;
421       name = vik_layer_get_name ( vik_treeview_item_get_pointer(sel->vt, &iter) );
422     }
423   }
424   a_clipboard_copy ( type, layer_type, subtype, len, name, data );
425 }
426
427 void a_clipboard_copy( VikClipboardDataType type, guint16 layer_type, gint subtype, guint len, const gchar* text, guint8 * data)
428 {
429   vik_clipboard_t * vc = g_malloc(sizeof(*vc) + len);
430   GtkClipboard *c = gtk_clipboard_get ( GDK_SELECTION_CLIPBOARD );
431
432   vc->type = type;
433   vc->layer_type = layer_type;
434   vc->subtype = subtype;
435   vc->len = len;
436   vc->text = g_strdup (text);
437   if ( data ) {
438     memcpy(vc->data, data, len);
439     g_free(data);
440   }
441   vc->pid = getpid();
442
443   // Simple clipboard copy when necessary
444   if ( type == VIK_CLIPBOARD_DATA_TEXT )
445     gtk_clipboard_set_text ( c, text, -1 );
446   else
447     gtk_clipboard_set_with_data ( c, target_table, G_N_ELEMENTS(target_table), clip_get, clip_clear, vc );
448 }
449
450 /**
451  * a_clipboard_paste:
452  *
453  * To deal with multiple data types, we first request the type of data on the clipboard,
454  * and handle them in the callback.
455  */
456 gboolean a_clipboard_paste ( VikLayersPanel *vlp )
457 {
458   GtkClipboard *c = gtk_clipboard_get ( GDK_SELECTION_CLIPBOARD );
459   gtk_clipboard_request_targets ( c, clip_receive_targets, vlp );
460   return TRUE;
461 }
462
463 /**
464  *
465  * Detect our own data types
466  */
467 static void clip_determine_viking_type ( GtkClipboard *c, GtkSelectionData *sd, gpointer p )
468 {
469   VikClipboardDataType *vdct = p;
470   // Default value
471   *vdct = VIK_CLIPBOARD_DATA_NONE;
472   vik_clipboard_t *vc;
473   if (gtk_selection_data_get_length(sd) == -1) {
474     g_warning ("DETERMINING TYPE: length failure");
475     return;
476   }
477
478   vc = (vik_clipboard_t *)gtk_selection_data_get_data(sd);
479
480   if ( !vc->type )
481     return;
482
483   if ( vc->type == VIK_CLIPBOARD_DATA_LAYER ) {
484     *vdct = VIK_CLIPBOARD_DATA_LAYER;
485   }
486   else if ( vc->type == VIK_CLIPBOARD_DATA_SUBLAYER ) {
487     *vdct = VIK_CLIPBOARD_DATA_SUBLAYER;
488   }
489   else {
490     g_warning ("DETERMINING TYPE: THIS SHOULD NEVER HAPPEN");
491   }
492 }
493
494 static void clip_determine_type ( GtkClipboard *c, GdkAtom *a, gint n, gpointer p )
495 {
496   gint i;
497   for (i=0; i<n; i++) {
498     gchar *name = gdk_atom_name(a[i]);
499     // g_print("  ""%s""\n", name);
500     gboolean breaktime = FALSE;
501     if (!g_strcmp0(name, "application/viking")) {
502       gtk_clipboard_request_contents ( c, gdk_atom_intern("application/viking", TRUE), clip_determine_viking_type, p );
503       breaktime = TRUE;
504     }
505
506     g_free ( name );
507
508     if ( breaktime )
509       break;
510   }
511 }
512
513 /**
514  * a_clipboard_type:
515  *
516  * Return the type of data held in the clipboard if any
517  */
518 VikClipboardDataType a_clipboard_type ( )
519 {
520   GtkClipboard *c = gtk_clipboard_get ( GDK_SELECTION_CLIPBOARD );
521   VikClipboardDataType *vcdt = g_malloc ( sizeof (VikClipboardDataType) );
522
523   gtk_clipboard_request_targets ( c, clip_determine_type, vcdt );
524   gint answer = *vcdt;
525   g_free ( vcdt );
526   return answer;
527 }