Example #1
0
static void dnd_drag_data_recieved_handler(GtkWidget *widget,
	GdkDragContext *context, gint x, gint y,
	GtkSelectionData *selection_data, guint info, guint time)
{
	static gboolean flag_called_once = FALSE;
	gchar **files;
	gchar *filename;
	gchar *comline;
	gint i = 0, j = 0;
	gchar *filename_sh;
	gchar **strs;
#ifdef ENABLE_CSDI
	j = 1;
#endif
DV(g_print("DND start!\n"));
	
#if GTK_CHECK_VERSION(2, 10, 0)
	if (g_strcasecmp(gdk_atom_name(context->targets->data),
	    "GTK_TEXT_BUFFER_CONTENTS") != 0) {
#else
	if (info != TARGET_SELF) {
#endif
		if (flag_called_once) {
			flag_called_once = FALSE;
			g_signal_stop_emission_by_name(widget, "drag_data_received");
DV(g_print("second drop signal killed.\n"));
			return;
		} else
			flag_called_once = TRUE;
	}
	
DV({	
	g_print("info                      = %d\n", info);
	g_print("time                      = %d\n", time);
	g_print("context->protocol         = %d\n", context->protocol);
	g_print("context->is_source        = %d\n", context->is_source);
	g_print("context->targets          = %d\n", g_list_length(context->targets));
	g_print("context->target           = %s\n", gdk_atom_name(context->targets->data));
/*	g_print("context->target           = %s\n", gdk_atom_name(context->targets->next->data));
	g_print("context->target           = %s\n", gdk_atom_name(context->targets->next->next->data));
	g_print("context->actions          = %d\n", context->actions);
	g_print("context->suggested_action = %d\n", context->suggested_action);
	g_print("context->action           = %d\n", context->action);
	g_print("selection_data->selection = %s\n", gdk_atom_name(selection_data->selection));
	g_print("selection_data->target    = %s\n", gdk_atom_name(selection_data->target));
*/	g_print("selection_data->type      = %s\n", gdk_atom_name(selection_data->type));
	g_print("selection_data->format    = %d\n", selection_data->format);
	g_print("selection_data->length    = %d\n", selection_data->length);
	g_print("%s\n", selection_data->data);
});	
	
	if (selection_data->data && info == TARGET_URI_LIST) {
		files = g_strsplit((gchar *)selection_data->data, "\n" , -1);
		while (files[i]) {
			if (strlen(files[i]) == 0)
				break;
			filename = g_strstrip(parse_file_uri(files[i]));
			if (i + j == 0)
				dnd_open_first_file(filename);
			else {
				if (i + j == 1)
					save_config_file();
				if (strstr(filename, " ")) {
					strs = g_strsplit(filename, " ", -1);
					filename_sh = g_strjoinv("\\ ", strs);
					g_strfreev(strs);
				} else
					filename_sh = g_strdup(filename);
				comline = g_strdup_printf("%s %s", PACKAGE, filename_sh);
DV(g_print(">%s\n", comline));
				g_free(filename_sh);
				g_spawn_command_line_async(comline, NULL);
				g_free(comline);
			}
			g_free(filename);
			i++;
		}
		g_strfreev(files);
	}
	else {
		clear_current_keyval();
		undo_set_sequency(FALSE);
#if GTK_CHECK_VERSION(2, 10, 0)
		if (info == TARGET_UTF8_STRING) {
#else
		if (info == TARGET_SELF) {
#endif
			undo_set_sequency_reserve();
			context->action = GDK_ACTION_MOVE;
		} else if (info == TARGET_PLAIN 
			&& g_utf8_validate((gchar *)selection_data->data, -1, NULL)) {
			selection_data->type =
				gdk_atom_intern("UTF8_STRING", FALSE);
		}
	}
	
	return;
}

static gboolean dnd_drag_motion_handler(GtkWidget *widget,
	GdkDragContext *context, gint x, gint y, guint time)
{
	GList *targets;
	gchar *name;
	gboolean flag = FALSE;
	
	targets = context->targets;
	while (targets) {
		name = gdk_atom_name(targets->data);
DV(g_print("%s\n", name));
		if (g_ascii_strcasecmp(name, "text/uri-list") == 0)
			flag = TRUE;
		g_free(name);
		targets = targets->next;
	}
/*	if (flag)
		context->action = GDK_ACTION_DEFAULT;
	else
		context->action = GDK_ACTION_COPY;
//	g_signal_stop_emission_by_name(widget, "drag_motion");
*/	
/*	if (!flag) {
		gint bx, by;
		GtkTextIter iter;
		
		gtk_text_view_window_to_buffer_coords(GTK_TEXT_VIEW(widget),
			GTK_TEXT_WINDOW_WIDGET,
			x, y, &bx, &by);
		gtk_text_view_get_iter_at_location(GTK_TEXT_VIEW(widget), &iter, bx, by);
		if (!dnd_mark) {
			dnd_mark = gtk_text_buffer_create_mark(GTK_TEXT_VIEW(widget)->buffer,
			    NULL, &iter, TRUE);
			gtk_text_mark_set_visible(dnd_mark, TRUE);
		} else
			gtk_text_mark_set_visible(dnd_mark, FALSE);
			gtk_text_buffer_move_mark(GTK_TEXT_VIEW(widget)->buffer,
			    dnd_mark, &iter);
			gtk_text_mark_set_visible(dnd_mark, TRUE);
	}
*/	
	return flag;
}
Example #2
0
static void
drag_data_received_callback (GtkWidget *widget,
			     GdkDragContext *context,
			     int x,
			     int y,
			     GtkSelectionData *data,
			     guint info,
			     guint32 time,
			     gpointer user_data)
{
    	NemoDragInfo *drag_info;
	guchar *tmp;
	const guchar *tmp_raw;
	int length;
	gboolean success;

	drag_info = &(NEMO_ICON_CONTAINER (widget)->details->dnd_info->drag_info);

	drag_info->got_drop_data_type = TRUE;
	drag_info->data_type = info;

	switch (info) {
	case NEMO_ICON_DND_GNOME_ICON_LIST:
		nemo_icon_container_dropped_icon_feedback (widget, data, x, y);
		break;
	case NEMO_ICON_DND_URI_LIST:
	case NEMO_ICON_DND_TEXT:
	case NEMO_ICON_DND_XDNDDIRECTSAVE:
	case NEMO_ICON_DND_RAW:
		/* Save the data so we can do the actual work on drop. */
		if (drag_info->selection_data != NULL) {
			gtk_selection_data_free (drag_info->selection_data);
		}
		drag_info->selection_data = gtk_selection_data_copy (data);
		break;

	/* Netscape keeps sending us the data, even though we accept the first drag */
	case NEMO_ICON_DND_NETSCAPE_URL:
		if (drag_info->selection_data != NULL) {
			gtk_selection_data_free (drag_info->selection_data);
			drag_info->selection_data = gtk_selection_data_copy (data);
		}
		break;
	case NEMO_ICON_DND_ROOTWINDOW_DROP:
		/* Do nothing, this won't even happen, since we don't want to call get_data twice */
		break;
	}

	/* this is the second use case of this callback.
	 * we have to do the actual work for the drop.
	 */
	if (drag_info->drop_occured) {

		success = FALSE;
		switch (info) {
		case NEMO_ICON_DND_GNOME_ICON_LIST:
			nemo_icon_container_receive_dropped_icons
				(NEMO_ICON_CONTAINER (widget),
				 context, x, y);
			break;
		case NEMO_ICON_DND_NETSCAPE_URL:
			receive_dropped_netscape_url
				(NEMO_ICON_CONTAINER (widget),
				 (char *) gtk_selection_data_get_data (data), context, x, y);
			success = TRUE;
			break;
		case NEMO_ICON_DND_URI_LIST:
			receive_dropped_uri_list
				(NEMO_ICON_CONTAINER (widget),
				 (char *) gtk_selection_data_get_data (data), context, x, y);
			success = TRUE;
			break;
		case NEMO_ICON_DND_TEXT:
			tmp = gtk_selection_data_get_text (data);
			receive_dropped_text
				(NEMO_ICON_CONTAINER (widget),
				 (char *) tmp, context, x, y);
			success = TRUE;
			g_free (tmp);
			break;
		case NEMO_ICON_DND_RAW:
			length = gtk_selection_data_get_length (data);
			tmp_raw = gtk_selection_data_get_data (data);
			receive_dropped_raw
				(NEMO_ICON_CONTAINER (widget),
				 (const gchar *) tmp_raw, length, drag_info->direct_save_uri,
				 context, x, y);
			success = TRUE;
			break;
		case NEMO_ICON_DND_ROOTWINDOW_DROP:
			/* Do nothing, everything is done by the sender */
			break;
		case NEMO_ICON_DND_XDNDDIRECTSAVE:
		{
			const guchar *selection_data;
			gint selection_length;
			gint selection_format;

			selection_data = gtk_selection_data_get_data (drag_info->selection_data);
			selection_length = gtk_selection_data_get_length (drag_info->selection_data);
			selection_format = gtk_selection_data_get_format (drag_info->selection_data);

			if (selection_format == 8 &&
			    selection_length == 1 &&
			    selection_data[0] == 'F') {
				gtk_drag_get_data (widget, context,
				                  gdk_atom_intern (NEMO_ICON_DND_RAW_TYPE,
				                                   FALSE),
				                  time);
				return;
			} else if (selection_format == 8 &&
				   selection_length == 1 &&
				   selection_data[0] == 'F' &&
			           drag_info->direct_save_uri != NULL) {
				GdkPoint p;
				GFile *location;

				location = g_file_new_for_uri (drag_info->direct_save_uri);

				nemo_file_changes_queue_file_added (location);
				p.x = x; p.y = y;
                nemo_file_changes_queue_schedule_position_set (
                                 location,
                                 p,
                                 nemo_desktop_utils_get_monitor_for_widget (widget));
				g_object_unref (location);
				nemo_file_changes_consume_changes (TRUE);
				success = TRUE;
			}
			break;
		} /* NEMO_ICON_DND_XDNDDIRECTSAVE */
		}
		gtk_drag_finish (context, success, FALSE, time);
		
		nemo_icon_container_free_drag_data (NEMO_ICON_CONTAINER (widget));
		
		set_drop_target (NEMO_ICON_CONTAINER (widget), NULL);

		/* reinitialise it for the next dnd */
		drag_info->drop_occured = FALSE;
	}

}
Example #3
0
NS_IMETHODIMP
nsClipboard::GetData(nsITransferable *aTransferable, PRInt32 aWhichClipboard)
{
    if (!aTransferable)
        return NS_ERROR_FAILURE;

    GtkClipboard *clipboard;
    clipboard = gtk_clipboard_get(GetSelectionAtom(aWhichClipboard));

    guchar        *data = NULL;
    gint           length = 0;
    PRBool         foundData = PR_FALSE;
    nsCAutoString  foundFlavor;

    // Get a list of flavors this transferable can import
    nsCOMPtr<nsISupportsArray> flavors;
    nsresult rv;
    rv = aTransferable->FlavorsTransferableCanImport(getter_AddRefs(flavors));
    if (!flavors || NS_FAILED(rv))
        return NS_ERROR_FAILURE;

    PRUint32 count;
    flavors->Count(&count);
    for (PRUint32 i=0; i < count; i++) {
        nsCOMPtr<nsISupports> genericFlavor;
        flavors->GetElementAt(i, getter_AddRefs(genericFlavor));

        nsCOMPtr<nsISupportsCString> currentFlavor;
        currentFlavor = do_QueryInterface(genericFlavor);

        if (currentFlavor) {
            nsXPIDLCString flavorStr;
            currentFlavor->ToString(getter_Copies(flavorStr));

            // Special case text/unicode since we can convert any
            // string into text/unicode
            if (!strcmp(flavorStr, kUnicodeMime)) {
                gchar* new_text = wait_for_text(clipboard);
                if (new_text) {
                    // Convert utf-8 into our unicode format.
                    NS_ConvertUTF8toUCS2 ucs2string(new_text);
                    data = (guchar *)ToNewUnicode(ucs2string);
                    length = ucs2string.Length() * 2;
                    g_free(new_text);
                    foundData = PR_TRUE;
                    foundFlavor = kUnicodeMime;
                    break;
                }
                // If the type was text/unicode and we couldn't get
                // text off the clipboard, run the next loop
                // iteration.
                continue;
            }

            // Get the atom for this type and try to request it off
            // the clipboard.
            GdkAtom atom = gdk_atom_intern(flavorStr, FALSE);
            GtkSelectionData *selectionData;
            selectionData = wait_for_contents(clipboard, atom);
            if (selectionData) {
                length = selectionData->length;
                // Special case text/html since we can convert into UCS2
                if (!strcmp(flavorStr, kHTMLMime)) {
                    PRUnichar* htmlBody= nsnull;
                    PRInt32 htmlBodyLen = 0;
                    // Convert text/html into our unicode format
                    ConvertHTMLtoUCS2((guchar *)selectionData->data, length,
                                      &htmlBody, htmlBodyLen);
                    if (!htmlBodyLen)
                        break;
                    data = (guchar *)htmlBody;
                    length = htmlBodyLen * 2;
                } else {
                    data = (guchar *)nsMemory::Alloc(length);
                    if (!data)
                        break;
                    memcpy(data, selectionData->data, length);
                }
                foundData = PR_TRUE;
                foundFlavor = flavorStr;
                break;
            }
        }
    }

    if (foundData) {
        nsCOMPtr<nsISupports> wrapper;
        nsPrimitiveHelpers::CreatePrimitiveForData(foundFlavor.get(),
                data, length,
                getter_AddRefs(wrapper));
        aTransferable->SetTransferData(foundFlavor.get(),
                                       wrapper, length);
    }

    if (data)
        nsMemory::Free(data);

    return NS_OK;
}
static void
xfdesktop_clipboard_manager_init (XfdesktopClipboardManager *manager)
{
  manager->x_special_gnome_copied_files = gdk_atom_intern ("x-special/gnome-copied-files", FALSE);
}
Example #5
0
static gboolean
na_tray_manager_manage_screen_x11 (NaTrayManager *manager,
				   GdkScreen     *screen)
{
  GdkDisplay *display;
  Screen     *xscreen;
  GtkWidget  *invisible;
  char       *selection_atom_name;
  guint32     timestamp;
  
  g_return_val_if_fail (NA_IS_TRAY_MANAGER (manager), FALSE);
  g_return_val_if_fail (manager->screen == NULL, FALSE);

  /* If there's already a manager running on the screen
   * we can't create another one.
   */
#if 0
  if (na_tray_manager_check_running_screen_x11 (screen))
    return FALSE;
#endif
  
  manager->screen = screen;

  display = gdk_screen_get_display (screen);
  xscreen = GDK_SCREEN_XSCREEN (screen);
  
  invisible = gtk_invisible_new_for_screen (screen);
  gtk_widget_realize (invisible);
  
  gtk_widget_add_events (invisible,
                         GDK_PROPERTY_CHANGE_MASK | GDK_STRUCTURE_MASK);

  selection_atom_name = g_strdup_printf ("_NET_SYSTEM_TRAY_S%d",
					 gdk_screen_get_number (screen));
  manager->selection_atom = gdk_atom_intern (selection_atom_name, FALSE);
  g_free (selection_atom_name);

  manager->invisible = invisible;
  g_object_ref (G_OBJECT (manager->invisible));

  na_tray_manager_set_orientation_property (manager);
  na_tray_manager_set_visual_property (manager);
  na_tray_manager_set_padding_property (manager);
  
  timestamp = gdk_x11_get_server_time (invisible->window);

  /* Check if we could set the selection owner successfully */
  if (gdk_selection_owner_set_for_display (display,
                                           invisible->window,
                                           manager->selection_atom,
                                           timestamp,
                                           TRUE))
    {
      XClientMessageEvent xev;
      GdkAtom             opcode_atom;
      GdkAtom             message_data_atom;

      xev.type = ClientMessage;
      xev.window = RootWindowOfScreen (xscreen);
      xev.message_type = gdk_x11_get_xatom_by_name_for_display (display,
                                                                "MANAGER");

      xev.format = 32;
      xev.data.l[0] = timestamp;
      xev.data.l[1] = gdk_x11_atom_to_xatom_for_display (display,
                                                         manager->selection_atom);
      xev.data.l[2] = GDK_WINDOW_XWINDOW (invisible->window);
      xev.data.l[3] = 0;	/* manager specific data */
      xev.data.l[4] = 0;	/* manager specific data */

      XSendEvent (GDK_DISPLAY_XDISPLAY (display),
		  RootWindowOfScreen (xscreen),
		  False, StructureNotifyMask, (XEvent *)&xev);

      opcode_atom = gdk_atom_intern ("_NET_SYSTEM_TRAY_OPCODE", FALSE);
      manager->opcode_atom = gdk_x11_atom_to_xatom_for_display (display,
                                                                opcode_atom);

      message_data_atom = gdk_atom_intern ("_NET_SYSTEM_TRAY_MESSAGE_DATA",
                                           FALSE);

      /* Add a window filter */
#if 0
      /* This is for when we lose the selection of _NET_SYSTEM_TRAY_Sx */
      g_signal_connect (invisible, "selection-clear-event",
                        G_CALLBACK (na_tray_manager_selection_clear_event),
                        manager);
#endif
      /* This is for SYSTEM_TRAY_REQUEST_DOCK and SelectionClear */
      gdk_window_add_filter (invisible->window,
                             na_tray_manager_window_filter, manager);
      /* This is for SYSTEM_TRAY_BEGIN_MESSAGE and SYSTEM_TRAY_CANCEL_MESSAGE */
      gdk_display_add_client_message_filter (display, opcode_atom,
                                             na_tray_manager_handle_client_message_opcode,
                                             manager);
      /* This is for _NET_SYSTEM_TRAY_MESSAGE_DATA */
      gdk_display_add_client_message_filter (display, message_data_atom,
                                             na_tray_manager_handle_client_message_message_data,
                                             manager);
      return TRUE;
    }
  else
    {
      gtk_widget_destroy (invisible);
      g_object_unref (invisible);
      manager->invisible = NULL;

      manager->screen = NULL;
 
      return FALSE;
    }
}
Example #6
0
static void
notebook_drag_data_received_cb (GtkWidget        *widget,
                                GdkDragContext   *context,
                                int               x,
                                int               y,
                                GtkSelectionData *selection_data,
                                guint             info,
                                guint             time,
                                EphyEmbed        *embed)
{
  EphyWindow *window;
  GtkWidget *notebook;
  GdkAtom target;
  const guchar *data;

  target = gtk_selection_data_get_target (selection_data);
  if (target == gdk_atom_intern_static_string ("GTK_NOTEBOOK_TAB"))
    return;

  g_signal_stop_emission_by_name (widget, "drag-data-received");

  if (g_settings_get_boolean (EPHY_SETTINGS_LOCKDOWN,
                              EPHY_PREFS_LOCKDOWN_ARBITRARY_URL))
    return;

  data = gtk_selection_data_get_data (selection_data);
  if (gtk_selection_data_get_length (selection_data) <= 0 || data == NULL)
    return;

  window = EPHY_WINDOW (gtk_widget_get_toplevel (widget));
  notebook = ephy_window_get_notebook (window);

  if (target == gdk_atom_intern (EPHY_DND_URL_TYPE, FALSE)) {
    char **split;

    /* URL_TYPE has format: url \n title */
    split = g_strsplit ((const gchar *)data, "\n", 2);
    if (split != NULL && split[0] != NULL && split[0][0] != '\0') {
      ephy_link_open (EPHY_LINK (notebook), split[0], embed,
                      embed ? 0 : EPHY_LINK_NEW_TAB);
    }
    g_strfreev (split);
  } else if (target == gdk_atom_intern (EPHY_DND_URI_LIST_TYPE, FALSE)) {
    char **uris;
    int i;

    uris = gtk_selection_data_get_uris (selection_data);
    if (uris == NULL)
      return;

    for (i = 0; i < INSANE_NUMBER_OF_URLS && uris[i] != NULL; i++) {
      embed = ephy_link_open (EPHY_LINK (notebook), uris[i], embed,
                              (embed && i == 0) ? 0 : EPHY_LINK_NEW_TAB);
    }

    g_strfreev (uris);
  } else {
    char *text;

    text = (char *)gtk_selection_data_get_text (selection_data);
    if (text != NULL) {
      char *address;

      address = ephy_embed_utils_normalize_or_autosearch_address (text);
      ephy_link_open (EPHY_LINK (notebook), address, embed,
                      embed ? 0 : EPHY_LINK_NEW_TAB);
      g_free (address);
      g_free (text);
    }
  }
}
void
nsClipboard::SelectionGetEvent(GtkClipboard     *aClipboard,
                               GtkSelectionData *aSelectionData)
{
    // Someone has asked us to hand them something.  The first thing
    // that we want to do is see if that something includes text.  If
    // it does, try to give it text/unicode after converting it to
    // utf-8.

    PRInt32 whichClipboard;

    // which clipboard?
    if (aSelectionData->selection == GDK_SELECTION_PRIMARY)
        whichClipboard = kSelectionClipboard;
    else if (aSelectionData->selection == GDK_SELECTION_CLIPBOARD)
        whichClipboard = kGlobalClipboard;
    else
        return; // THAT AIN'T NO CLIPBOARD I EVER HEARD OF

    nsCOMPtr<nsITransferable> trans = GetTransferable(whichClipboard);
    if (!trans) {
      // We have nothing to serve
#ifdef DEBUG_CLIPBOARD
      printf("nsClipboard::SelectionGetEvent() - %s clipboard is empty!\n",
             whichClipboard == kSelectionClipboard ? "Selection" : "Global");
#endif
      return;
    }

    nsresult rv;
    nsCOMPtr<nsISupports> item;
    PRUint32 len;

    // Check to see if the selection data includes any of the string
    // types that we support.
    if (aSelectionData->target == gdk_atom_intern ("STRING", FALSE) ||
        aSelectionData->target == gdk_atom_intern ("TEXT", FALSE) ||
        aSelectionData->target == gdk_atom_intern ("COMPOUND_TEXT", FALSE) ||
        aSelectionData->target == gdk_atom_intern ("UTF8_STRING", FALSE)) {
        // Try to convert our internal type into a text string.  Get
        // the transferable for this clipboard and try to get the
        // text/unicode type for it.
        rv = trans->GetTransferData("text/unicode", getter_AddRefs(item),
                                    &len);
        if (!item || NS_FAILED(rv))
            return;
        
        nsCOMPtr<nsISupportsString> wideString;
        wideString = do_QueryInterface(item);
        if (!wideString)
            return;

        nsAutoString ucs2string;
        wideString->GetData(ucs2string);
        char *utf8string = ToNewUTF8String(ucs2string);
        if (!utf8string)
            return;
        
        gtk_selection_data_set_text (aSelectionData, utf8string,
                                     strlen(utf8string));

        nsMemory::Free(utf8string);
        return;
    }

    // Check to see if the selection data is an image type
    if (gtk_targets_include_image(&aSelectionData->target, 1, TRUE)) {
        // Look through our transfer data for the image
        static const char* const imageMimeTypes[] = {
            kNativeImageMime, kPNGImageMime, kJPEGImageMime, kGIFImageMime };
        nsCOMPtr<nsISupports> item;
        PRUint32 len;
        nsCOMPtr<nsISupportsInterfacePointer> ptrPrimitive;
        for (PRUint32 i = 0; !ptrPrimitive && i < NS_ARRAY_LENGTH(imageMimeTypes); i++) {
            rv = trans->GetTransferData(imageMimeTypes[i], getter_AddRefs(item), &len);
            ptrPrimitive = do_QueryInterface(item);
        }
        if (!ptrPrimitive)
            return;

        nsCOMPtr<nsISupports> primitiveData;
        ptrPrimitive->GetData(getter_AddRefs(primitiveData));
        nsCOMPtr<imgIContainer> image(do_QueryInterface(primitiveData));
        if (!image) // Not getting an image for an image mime type!?
            return;

        GdkPixbuf* pixbuf = nsImageToPixbuf::ImageToPixbuf(image);
        if (!pixbuf)
            return;

        gtk_selection_data_set_pixbuf(aSelectionData, pixbuf);
        g_object_unref(pixbuf);
        return;
    }

    // Try to match up the selection data target to something our
    // transferable provides.
    gchar *target_name = gdk_atom_name(aSelectionData->target);
    if (!target_name)
        return;

    rv = trans->GetTransferData(target_name, getter_AddRefs(item), &len);
    // nothing found?
    if (!item || NS_FAILED(rv)) {
        g_free(target_name);
        return;
    }

    void *primitive_data = nsnull;
    nsPrimitiveHelpers::CreateDataFromPrimitive(target_name, item,
                                                &primitive_data, len);

    if (primitive_data) {
        // Check to see if the selection data is text/html
        if (aSelectionData->target == gdk_atom_intern (kHTMLMime, FALSE)) {
            /*
             * "text/html" can be encoded UCS2. It is recommended that
             * documents transmitted as UCS2 always begin with a ZERO-WIDTH
             * NON-BREAKING SPACE character (hexadecimal FEFF, also called
             * Byte Order Mark (BOM)). Adding BOM can help other app to
             * detect mozilla use UCS2 encoding when copy-paste.
             */
            guchar *buffer = (guchar *)
                    nsMemory::Alloc((len * sizeof(guchar)) + sizeof(PRUnichar));
            if (!buffer)
                return;
            PRUnichar prefix = 0xFEFF;
            memcpy(buffer, &prefix, sizeof(prefix));
            memcpy(buffer + sizeof(prefix), primitive_data, len);
            nsMemory::Free((guchar *)primitive_data);
            primitive_data = (guchar *)buffer;
            len += sizeof(prefix);
        }
  
        gtk_selection_data_set(aSelectionData, aSelectionData->target,
                               8, /* 8 bits in a unit */
                               (const guchar *)primitive_data, len);
        nsMemory::Free(primitive_data);
    }

    g_free(target_name);
                           
}
Example #8
0
/**
\author     Peter G. Baum
**/
int gnoclClipboardCmd (
	ClientData data,
	Tcl_Interp *interp,
	int objc,
	Tcl_Obj * const objv[] )
{
	GnoclOption options[] =
	{
		{ "-primary", GNOCL_BOOL, NULL },
		{ NULL }
	};
	const int usePrimaryIdx = 0;

	static const char *cmd[] = { "hasText", "setText", "getText", "clear",
								 NULL
							   };
	enum optIdx { HasTextIdx, SetTextIdx, GetTextIdx, ClearIdx };
	int idx;
	int optNum;
	GtkClipboard *clip;
	int usePrimary = 0;

	if ( objc < 2 )
	{
		Tcl_WrongNumArgs ( interp, 1, objv, "option" );
		return TCL_ERROR;
	}

	if ( Tcl_GetIndexFromObj ( interp, objv[1], cmd, "option", TCL_EXACT,
							   &idx ) != TCL_OK )
		return TCL_ERROR;

	if ( idx == SetTextIdx )
	{
		optNum = 2;

		if ( objc < 3 )
		{
			Tcl_WrongNumArgs ( interp, 1, objv, "text ?option value?" );
			return TCL_ERROR;
		}
	}

	else
	{
		optNum = 1;

		if ( objc < 2 )
		{
			Tcl_WrongNumArgs ( interp, 1, objv, NULL );
			return TCL_ERROR;
		}
	}

	if ( gnoclParseOptions ( interp, objc - optNum, objv + optNum, options )
			!= TCL_OK )
		return TCL_ERROR;

	if ( options[usePrimaryIdx].status == GNOCL_STATUS_CHANGED )
		usePrimary = options[usePrimaryIdx].val.b;

	clip = gtk_clipboard_get ( usePrimary ? gdk_atom_intern ( "PRIMARY", 1 )
							   : GDK_NONE );

	switch ( idx )
	{
		case HasTextIdx:
			{
				int ret = gtk_clipboard_wait_is_text_available ( clip );
				Tcl_SetObjResult ( interp, Tcl_NewBooleanObj ( ret ) );
			}

			break;
		case SetTextIdx:
			gtk_clipboard_set_text ( clip, Tcl_GetString ( objv[2] ), -1 );
			break;
		case GetTextIdx:
			{
				char *txt = gtk_clipboard_wait_for_text ( clip );

				if ( txt )
				{
					Tcl_SetObjResult ( interp, Tcl_NewStringObj ( txt, -1 ) );
					g_free ( txt );
				}

				/* FIXME? else error? */
			}

			break;
		case ClearIdx:
			gtk_clipboard_clear ( clip );
			break;
	}

	return TCL_OK;
}
static void
contact_list_view_setup (EmpathyContactListView *view)
{
	EmpathyContactListViewPriv *priv;
	GtkCellRenderer           *cell;
	GtkTreeViewColumn         *col;
	gint                       i;

	priv = GET_PRIV (view);

	gtk_tree_view_set_search_equal_func (GTK_TREE_VIEW (view),
					     empathy_contact_list_store_search_equal_func,
					     NULL, NULL);

	g_signal_connect (priv->store, "row-has-child-toggled",
			  G_CALLBACK (contact_list_view_row_has_child_toggled_cb),
			  view);
	gtk_tree_view_set_model (GTK_TREE_VIEW (view),
				 GTK_TREE_MODEL (priv->store));

	/* Setup view */
	g_object_set (view,
		      "headers-visible", FALSE,
		      "reorderable", TRUE,
		      "show-expanders", FALSE,
		      NULL);

	col = gtk_tree_view_column_new ();

	/* State */
	cell = gtk_cell_renderer_pixbuf_new ();
	gtk_tree_view_column_pack_start (col, cell, FALSE);
	gtk_tree_view_column_set_cell_data_func (
		col, cell,
		(GtkTreeCellDataFunc) contact_list_view_pixbuf_cell_data_func,
		view, NULL);

	g_object_set (cell,
		      "xpad", 5,
		      "ypad", 1,
		      "visible", FALSE,
		      NULL);

	/* Name */
	cell = empathy_cell_renderer_text_new ();
	gtk_tree_view_column_pack_start (col, cell, TRUE);
	gtk_tree_view_column_set_cell_data_func (
		col, cell,
		(GtkTreeCellDataFunc) contact_list_view_text_cell_data_func,
		view, NULL);

	gtk_tree_view_column_add_attribute (col, cell,
					    "name", EMPATHY_CONTACT_LIST_STORE_COL_NAME);
	gtk_tree_view_column_add_attribute (col, cell,
					    "status", EMPATHY_CONTACT_LIST_STORE_COL_STATUS);
	gtk_tree_view_column_add_attribute (col, cell,
					    "is_group", EMPATHY_CONTACT_LIST_STORE_COL_IS_GROUP);

	/* Audio Call Icon */
	cell = empathy_cell_renderer_activatable_new ();
	gtk_tree_view_column_pack_start (col, cell, FALSE);
	gtk_tree_view_column_set_cell_data_func (
		col, cell,
		(GtkTreeCellDataFunc) contact_list_view_audio_call_cell_data_func,
		view, NULL);

	g_object_set (cell,
		      "visible", FALSE,
		      NULL);

	g_signal_connect (cell, "path-activated",
			  G_CALLBACK (contact_list_view_audio_call_activated_cb),
			  view);

	/* Video Call Icon */
	cell = empathy_cell_renderer_activatable_new ();
	gtk_tree_view_column_pack_start (col, cell, FALSE);
	gtk_tree_view_column_set_cell_data_func (
		col, cell,
		(GtkTreeCellDataFunc) contact_list_view_video_call_cell_data_func,
		view, NULL);

	g_object_set (cell,
		      "visible", FALSE,
		      NULL);

	g_signal_connect (cell, "path-activated",
			  G_CALLBACK (contact_list_view_video_call_activated_cb),
			  view);

	/* Avatar */
	cell = gtk_cell_renderer_pixbuf_new ();
	gtk_tree_view_column_pack_start (col, cell, FALSE);
	gtk_tree_view_column_set_cell_data_func (
		col, cell,
		(GtkTreeCellDataFunc) contact_list_view_avatar_cell_data_func,
		view, NULL);

	g_object_set (cell,
		      "xpad", 0,
		      "ypad", 0,
		      "visible", FALSE,
		      "width", 32,
		      "height", 32,
		      NULL);

	/* Expander */
	cell = empathy_cell_renderer_expander_new ();
	gtk_tree_view_column_pack_end (col, cell, FALSE);
	gtk_tree_view_column_set_cell_data_func (
		col, cell,
		(GtkTreeCellDataFunc) contact_list_view_expander_cell_data_func,
		view, NULL);

	/* Actually add the column now we have added all cell renderers */
	gtk_tree_view_append_column (GTK_TREE_VIEW (view), col);

	/* Drag & Drop. */
	for (i = 0; i < G_N_ELEMENTS (drag_types_dest); ++i) {
		drag_atoms_dest[i] = gdk_atom_intern (drag_types_dest[i].target,
						      FALSE);
	}

	for (i = 0; i < G_N_ELEMENTS (drag_types_source); ++i) {
		drag_atoms_source[i] = gdk_atom_intern (drag_types_source[i].target,
							FALSE);
	}
}
Example #10
0
void clipboard_paste( ClipboardPasteFunc paste ){
	GtkClipboard* clipboard = gtk_clipboard_get( GDK_SELECTION_CLIPBOARD );

	g_clipboardPasteFunc = paste;
	gtk_clipboard_request_contents( clipboard, gdk_atom_intern( clipboard_targets[0].target, FALSE ), clipboard_received, &g_clipboardPasteFunc );
}
static void
constructed (GObject *object)
{
  EmpathyPersonaView *self = EMPATHY_PERSONA_VIEW (object);
  GtkCellRenderer *cell;
  GtkTreeViewColumn *col;
  guint i;

  /* Set up view */
  g_object_set (self,
      "headers-visible", FALSE,
      "show-expanders", FALSE,
      NULL);

  col = gtk_tree_view_column_new ();

  /* State */
  cell = gtk_cell_renderer_pixbuf_new ();
  gtk_tree_view_column_pack_start (col, cell, FALSE);
  gtk_tree_view_column_set_cell_data_func (col, cell,
      (GtkTreeCellDataFunc) pixbuf_cell_data_func, self, NULL);

  g_object_set (cell,
      "xpad", 5,
      "ypad", 1,
      "visible", TRUE,
      NULL);

  /* Name */
  cell = empathy_cell_renderer_text_new ();
  gtk_tree_view_column_pack_start (col, cell, TRUE);
  gtk_tree_view_column_set_cell_data_func (col, cell,
      (GtkTreeCellDataFunc) text_cell_data_func, self, NULL);

  /* We (ab)use the name and status properties here to display display ID and
   * account name, respectively. Harmless. */
  gtk_tree_view_column_add_attribute (col, cell,
      "name", EMPATHY_PERSONA_STORE_COL_DISPLAY_ID);
  gtk_tree_view_column_add_attribute (col, cell,
      "text", EMPATHY_PERSONA_STORE_COL_DISPLAY_ID);
  gtk_tree_view_column_add_attribute (col, cell,
      "presence-type", EMPATHY_PERSONA_STORE_COL_PRESENCE_TYPE);
  gtk_tree_view_column_add_attribute (col, cell,
      "status", EMPATHY_PERSONA_STORE_COL_ACCOUNT_NAME);

  /* Audio Call Icon */
  cell = empathy_cell_renderer_activatable_new ();
  gtk_tree_view_column_pack_start (col, cell, FALSE);
  gtk_tree_view_column_set_cell_data_func (col, cell,
      (GtkTreeCellDataFunc) audio_call_cell_data_func, self, NULL);

  g_object_set (cell,
      "visible", FALSE,
      NULL);

  /* Avatar */
  cell = gtk_cell_renderer_pixbuf_new ();
  gtk_tree_view_column_pack_start (col, cell, FALSE);
  gtk_tree_view_column_set_cell_data_func (col, cell,
      (GtkTreeCellDataFunc) avatar_cell_data_func, self, NULL);

  g_object_set (cell,
      "xpad", 0,
      "ypad", 0,
      "visible", FALSE,
      "width", 32,
      "height", 32,
      NULL);

  /* Actually add the column now we have added all cell renderers */
  gtk_tree_view_append_column (GTK_TREE_VIEW (self), col);

  /* Drag & Drop. */
  for (i = 0; i < G_N_ELEMENTS (drag_types_dest); ++i)
    drag_atoms_dest[i] = gdk_atom_intern (drag_types_dest[i].target, FALSE);
}
Example #12
0
void
nsRetrievalContextWayland::AddMIMEType(const char *aMimeType)
{
  GdkAtom atom = gdk_atom_intern(aMimeType, FALSE);
  mTargetMIMETypes.AppendElement(atom);
}
Example #13
0
static gboolean
charpicker_applet_fill (MatePanelApplet *applet)
{
  MatePanelAppletOrient orientation;
  charpick_data *curr_data;
  GdkAtom utf8_atom;
  GList *list;
  gchar *string;
  GtkActionGroup *action_group;
  gchar *ui_path;

  g_set_application_name (_("Character Palette"));
  
  gtk_window_set_default_icon_name ("accessories-character-map");

  mate_panel_applet_set_background_widget (applet, GTK_WIDGET (applet));

  mate_panel_applet_set_flags (applet, MATE_PANEL_APPLET_EXPAND_MINOR);
   
  curr_data = g_new0 (charpick_data, 1);
  curr_data->last_index = NO_LAST_INDEX;
  curr_data->applet = GTK_WIDGET (applet);
  curr_data->about_dialog = NULL;
  curr_data->add_edit_dialog = NULL;
  curr_data->settings = mate_panel_applet_settings_new (applet, "org.mate.panel.applet.charpick");
 
  get_chartable (curr_data);
  
  string  = g_settings_get_string (curr_data->settings, "current-list");
  if (string) {
  	list = curr_data->chartable;
  	while (list) {
  		if (g_ascii_strcasecmp (list->data, string) == 0)
  			curr_data->charlist = list->data;
  		list = g_list_next (list);
  	}
	/* FIXME: yeah leak, but this code is full of leaks and evil
	   point shuffling.  This should really be rewritten
	   -George */
	if (curr_data->charlist == NULL)
		curr_data->charlist = string;
	else
		g_free (string);
  } else {
  	curr_data->charlist = curr_data->chartable->data;  
  }
 
  curr_data->panel_size = mate_panel_applet_get_size (applet);
  
  orientation = mate_panel_applet_get_orient (applet);
  curr_data->panel_vertical = (orientation == MATE_PANEL_APPLET_ORIENT_LEFT) 
                              || (orientation == MATE_PANEL_APPLET_ORIENT_RIGHT);
  build_table (curr_data);
    
  g_signal_connect (G_OBJECT (curr_data->applet), "key_press_event",
		             G_CALLBACK (key_press_event), curr_data);

  utf8_atom = gdk_atom_intern ("UTF8_STRING", FALSE);
  gtk_selection_add_target (curr_data->applet, 
			    GDK_SELECTION_PRIMARY,
                            utf8_atom,
			    0);
  gtk_selection_add_target (curr_data->applet, 
			    GDK_SELECTION_CLIPBOARD,
                            utf8_atom,
			    0);
  g_signal_connect (GTK_OBJECT (curr_data->applet), "selection_get",
		      G_CALLBACK (charpick_selection_handler),
		      curr_data);
  g_signal_connect (GTK_OBJECT (curr_data->applet), "selection_clear_event",
		      G_CALLBACK (selection_clear_cb),
		      curr_data);
 
  make_applet_accessible (GTK_WIDGET (applet));

  /* session save signal */ 
  g_signal_connect (G_OBJECT (applet), "change_orient",
		    G_CALLBACK (applet_change_orient), curr_data);

  g_signal_connect (G_OBJECT (applet), "size_allocate",
		    G_CALLBACK (applet_size_allocate), curr_data);
		    
  g_signal_connect (G_OBJECT (applet), "destroy",
  		    G_CALLBACK (applet_destroy), curr_data);
  
  gtk_widget_show_all (GTK_WIDGET (applet));

  action_group = gtk_action_group_new ("Charpicker Applet Actions");
  gtk_action_group_set_translation_domain (action_group, GETTEXT_PACKAGE);
  gtk_action_group_add_actions (action_group,
				charpick_applet_menu_actions,
				G_N_ELEMENTS (charpick_applet_menu_actions),
				curr_data);
  ui_path = g_build_filename (CHARPICK_MENU_UI_DIR, "charpick-applet-menu.xml", NULL);
  mate_panel_applet_setup_menu_from_file (MATE_PANEL_APPLET (applet),
                                     ui_path, action_group);
  g_free (ui_path);

  if (mate_panel_applet_get_locked_down (MATE_PANEL_APPLET (applet))) {
	  GtkAction *action;

	  action = gtk_action_group_get_action (action_group, "Preferences");
	  gtk_action_set_visible (action, FALSE);
  }
  g_object_unref (action_group);

  register_stock_for_edit ();			             
  populate_menu (curr_data);
  
  return TRUE;
}
void switcher_button_copy_to_clipboard(SwitcherButton *self)
{
    GtkClipboard *selection = gtk_clipboard_get(gdk_atom_intern("PRIMARY", FALSE));
    gtk_clipboard_request_text(selection, switcher_button_on_selection_requested, self);
}
Example #15
0
	(GInstanceInitFunc) gtk_savebox_init
      };

      my_type = g_type_register_static(GTK_TYPE_DIALOG, "GtkSavebox", &info, 0);
    }

  return my_type;
}

static void
gtk_savebox_class_init (GtkSaveboxClass *class)
{
  GObjectClass	 *object_class;
  GtkDialogClass *dialog = (GtkDialogClass *) class;
  
  XdndDirectSave = gdk_atom_intern ("XdndDirectSave0", FALSE);
  text_plain = gdk_atom_intern ("text/plain", FALSE);
  xa_string = gdk_atom_intern ("STRING", FALSE);

  parent_class = g_type_class_peek_parent (class);

  class->saved_to_uri = NULL;
  class->save_to_file = NULL;
  dialog->response = gtk_savebox_response;

  object_class = G_OBJECT_CLASS(class);

  savebox_signals[SAVE_TO_FILE] = g_signal_new(
					"save_to_file",
					G_TYPE_FROM_CLASS(object_class),
					G_SIGNAL_RUN_LAST,
namespace WebKit {

static GdkAtom gdkMarkupAtom = gdk_atom_intern("text/html", FALSE);

PasteboardHelperGtk::PasteboardHelperGtk()
    : m_targetList(gtk_target_list_new(0, 0))
{
    gtk_target_list_add_text_targets(m_targetList, WEBKIT_WEB_VIEW_TARGET_INFO_TEXT);
    gtk_target_list_add(m_targetList, gdkMarkupAtom, 0, WEBKIT_WEB_VIEW_TARGET_INFO_HTML);
}

PasteboardHelperGtk::~PasteboardHelperGtk()
{
    gtk_target_list_unref(m_targetList);
}

GtkClipboard* PasteboardHelperGtk::getCurrentTarget(Frame* frame) const
{
    WebKitWebView* webView = webkit_web_frame_get_web_view(kit(frame));

    if (webkit_web_view_use_primary_for_paste(webView))
        return getPrimary(frame);
    else
        return getClipboard(frame);
}

GtkClipboard* PasteboardHelperGtk::getClipboard(Frame* frame) const
{
    WebKitWebView* webView = webkit_web_frame_get_web_view(kit(frame));
    return gtk_widget_get_clipboard(GTK_WIDGET (webView),
                                    GDK_SELECTION_CLIPBOARD);
}

GtkClipboard* PasteboardHelperGtk::getPrimary(Frame* frame) const
{
    WebKitWebView* webView = webkit_web_frame_get_web_view(kit(frame));
    return gtk_widget_get_clipboard(GTK_WIDGET (webView),
                                    GDK_SELECTION_PRIMARY);
}

GtkTargetList* PasteboardHelperGtk::targetList() const
{
    return m_targetList;
}

gint PasteboardHelperGtk::getWebViewTargetInfoHtml() const
{
    return WEBKIT_WEB_VIEW_TARGET_INFO_HTML;
}

static void fillSelectionData(GtkSelectionData* selectionData, guint info, DataObjectGtk* dataObject)
{
    if (info == WEBKIT_WEB_VIEW_TARGET_INFO_TEXT)
        gtk_selection_data_set_text(selectionData, dataObject->text().utf8().data(), -1);
    else if (info == WEBKIT_WEB_VIEW_TARGET_INFO_HTML) {
        GOwnPtr<gchar> markup(g_strdup(dataObject->markup().utf8().data()));
        gtk_selection_data_set(selectionData, selectionData->target, 8,
                               reinterpret_cast<const guchar*>(markup.get()),
                               strlen(markup.get()));
    }
}

static GtkTargetList* targetListForDataObject(DataObjectGtk* dataObject)
{
    GtkTargetList* list = gtk_target_list_new(0, 0);

    if (dataObject->hasText())
        gtk_target_list_add_text_targets(list, WEBKIT_WEB_VIEW_TARGET_INFO_TEXT);

    if (dataObject->hasMarkup())
        gtk_target_list_add(list, gdkMarkupAtom, 0, WEBKIT_WEB_VIEW_TARGET_INFO_HTML);

    return list;
}

static DataObjectGtk* settingClipboardDataObject = 0;
static gpointer settingClipboardData = 0;
static void getClipboardContentsCallback(GtkClipboard* clipboard, GtkSelectionData *selectionData, guint info, gpointer data)
{
    DataObjectGtk* dataObject = DataObjectGtk::forClipboard(clipboard);
    ASSERT(dataObject);
    fillSelectionData(selectionData, info, dataObject);
}

static void clearClipboardContentsCallback(GtkClipboard* clipboard, gpointer data)
{
    DataObjectGtk* dataObject = DataObjectGtk::forClipboard(clipboard);
    ASSERT(dataObject);

    // Only clear the DataObject for this clipboard if we are not currently setting it.
    if (dataObject != settingClipboardDataObject)
        dataObject->clear();

    // Only collapse the selection if this is an X11 primary clipboard
    // and we aren't currently setting the clipboard for this WebView.
    if (!data || data == settingClipboardData)
        return;

    WebKitWebView* webView = reinterpret_cast<WebKitWebView*>(data);
    WebCore::Page* corePage = core(webView);

    if (!corePage || !corePage->focusController()) {
        g_object_unref(webView);
        return;
    }

    Frame* frame = corePage->focusController()->focusedOrMainFrame();

    // Collapse the selection without clearing it
    ASSERT(frame);
    frame->selection()->setBase(frame->selection()->extent(), frame->selection()->affinity());

    g_object_unref(webView);
}

void PasteboardHelperGtk::writeClipboardContents(GtkClipboard* clipboard, gpointer data)
{
    DataObjectGtk* dataObject = DataObjectGtk::forClipboard(clipboard);
    GtkTargetList* list = targetListForDataObject(dataObject);

    int numberOfTargets;
    GtkTargetEntry* table = gtk_target_table_new_from_list(list, &numberOfTargets);

    if (numberOfTargets > 0 && table) {
        settingClipboardDataObject = dataObject;
        settingClipboardData = data;

        // Protect the web view from being destroyed before one of the clipboard callbacks
        // is called. Balanced in both getClipboardContentsCallback and
        // clearClipboardContentsCallback.
        WebKitWebView* webView = static_cast<WebKitWebView*>(data);
        g_object_ref(webView);

        gboolean succeeded = gtk_clipboard_set_with_data(clipboard, table, numberOfTargets,
                                                         getClipboardContentsCallback,
                                                         clearClipboardContentsCallback, data);
        if (!succeeded)
            g_object_unref(webView);

        settingClipboardDataObject = 0;
        settingClipboardData = 0;
    } else
        gtk_clipboard_clear(clipboard);

    if (table)
        gtk_target_table_free(table, numberOfTargets);

    gtk_target_list_unref(list);
}

}
Example #17
0
int main( int argc, char *argv[] )
{
  GtkWidget *vbox;

  gtk_init( &argc, &argv );

  if( client_open( NULL ) )
    exit( 1 );
  atexit( client_close );

  window = argc == 2 ?
    gtk_plug_new( strtol( argv[1], NULL, 10 )) :
    gtk_window_new( GTK_WINDOW_TOPLEVEL );
  vbox = gtk_vbox_new( FALSE, 0 );
  gtk_container_add( GTK_CONTAINER( window ), vbox );
  drawing_area = gtk_drawing_area_new();

  /* Get the dimensions and colors of the pager and viewport and focus */
  parse_stdin();

  update_rect.x = update_rect.y = 0;

  gtk_drawing_area_size( GTK_DRAWING_AREA( drawing_area ), width, height );
  gtk_box_pack_start( GTK_BOX( vbox ), drawing_area, FALSE, FALSE, 0 );

  /* Signals to quit */
  g_signal_connect( GTK_OBJECT( window ), "delete_event",
		      G_CALLBACK( delete_event ), NULL );
  g_signal_connect( GTK_OBJECT( window ), "destroy",
		      G_CALLBACK( destroy_event ), NULL );

  /* Wait for input from standard input */
  gdk_input_add( 0, GDK_INPUT_READ,
		 &wait_stdin,
		 drawing_area );

  /* Change the viewport when a button is pressed */
  g_signal_connect( GTK_OBJECT( drawing_area ), "motion_notify_event",
		     (GCallback) motion_notify_event, NULL );
  g_signal_connect( GTK_OBJECT( drawing_area ), "button_press_event",
		     (GCallback) button_press_event, NULL );
  g_signal_connect( GTK_OBJECT( drawing_area ), "button_release_event",
		     (GCallback) button_release_event, NULL );
  g_signal_connect( GTK_OBJECT( drawing_area ), "leave_notify_event",
		     (GCallback) leave_notify_event, NULL );
  g_signal_connect ( GTK_OBJECT( drawing_area), "scroll_event",
                     (GCallback) scroll_event, NULL );
  gtk_widget_set_events( drawing_area, GDK_EXPOSURE_MASK
			            | GDK_LEAVE_NOTIFY_MASK
			            | GDK_BUTTON_PRESS_MASK
                                    | GDK_BUTTON_RELEASE_MASK
		                    | GDK_POINTER_MOTION_MASK
		                    | GDK_POINTER_MOTION_HINT_MASK
                                    | GDK_SCROLL_MASK );

  /* Initialize and draw the pixmap */
  g_signal_connect( GTK_OBJECT( drawing_area ), "expose_event",
		     (GCallback) expose_event, NULL );
  g_signal_connect( GTK_OBJECT( drawing_area ), "configure_event",
		     (GCallback) configure_event, NULL );

  gtk_widget_show( drawing_area );
  gtk_widget_show( vbox );

  wmspec_change_state(TRUE, window->window,
		  gdk_atom_intern( "_NET_WM_STATE_SKIP_PAGER", FALSE ),
		  gdk_atom_intern( "_NET_WM_STATE_SKIP_TASKBAR", FALSE ));

  gtk_window_set_type_hint( GTK_WINDOW(window), GDK_WINDOW_TYPE_HINT_DOCK);

  gtk_widget_show( window );
  gtk_main();
  return 0;
}
Example #18
0
static UINT remmina_rdp_cliprdr_server_format_list(CliprdrClientContext* context, CLIPRDR_FORMAT_LIST* formatList)
{
	TRACE_CALL(__func__);

	/* Called when a user do a "Copy" on the server: we collect all formats
	 * the server send us and then setup the local clipboard with the appropiate
	 * functions to request server data */

	RemminaPluginRdpUiObject* ui;
	RemminaProtocolWidget* gp;
	rfClipboard* clipboard;
	CLIPRDR_FORMAT* format;
	CLIPRDR_FORMAT_LIST_RESPONSE formatListResponse;

	int i;

	clipboard = (rfClipboard*)context->custom;
	gp = clipboard->rfi->protocol_widget;
	GtkTargetList* list = gtk_target_list_new(NULL, 0);

	for (i = 0; i < formatList->numFormats; i++) {
		format = &formatList->formats[i];
		if (format->formatId == CF_UNICODETEXT) {
			GdkAtom atom = gdk_atom_intern("UTF8_STRING", TRUE);
			gtk_target_list_add(list, atom, 0, CF_UNICODETEXT);
		}else if (format->formatId == CF_TEXT) {
			GdkAtom atom = gdk_atom_intern("TEXT", TRUE);
			gtk_target_list_add(list, atom, 0, CF_TEXT);
		}else if (format->formatId == CF_DIB) {
			GdkAtom atom = gdk_atom_intern("image/bmp", TRUE);
			gtk_target_list_add(list, atom, 0, CF_DIB);
		}else if (format->formatId == CF_DIBV5) {
			GdkAtom atom = gdk_atom_intern("image/bmp", TRUE);
			gtk_target_list_add(list, atom, 0, CF_DIBV5);
		}else if (format->formatId == CB_FORMAT_JPEG) {
			GdkAtom atom = gdk_atom_intern("image/jpeg", TRUE);
			gtk_target_list_add(list, atom, 0, CB_FORMAT_JPEG);
		}else if (format->formatId == CB_FORMAT_PNG) {
			GdkAtom atom = gdk_atom_intern("image/png", TRUE);
			gtk_target_list_add(list, atom, 0, CB_FORMAT_PNG);
		}else if (format->formatId == CB_FORMAT_HTML) {
			GdkAtom atom = gdk_atom_intern("text/html", TRUE);
			gtk_target_list_add(list, atom, 0, CB_FORMAT_HTML);
		}
	}

	/* Now we tell GTK to change the local keyboard calling gtk_clipboard_set_with_owner
	 * via REMMINA_RDP_UI_CLIPBOARD_SET_DATA
	 * GTK will immediately fire an "owner-change" event, that we should ignore */

	ui = g_new0(RemminaPluginRdpUiObject, 1);
	ui->type = REMMINA_RDP_UI_CLIPBOARD;
	ui->clipboard.clipboard = clipboard;
	ui->clipboard.type = REMMINA_RDP_UI_CLIPBOARD_SET_DATA;
	ui->clipboard.targetlist = list;
	remmina_rdp_event_queue_ui_sync_retint(gp, ui);

	/* Send FormatListResponse to server */

	formatListResponse.msgType = CB_FORMAT_LIST_RESPONSE;
	formatListResponse.msgFlags = CB_RESPONSE_OK; // Can be CB_RESPONSE_FAIL in case of error
	formatListResponse.dataLen = 0;

	return clipboard->context->ClientFormatListResponse(clipboard->context, &formatListResponse);

}
NS_IMETHODIMP
nsClipboard::SetData(nsITransferable *aTransferable,
                     nsIClipboardOwner *aOwner, PRInt32 aWhichClipboard)
{
    // See if we can short cut
    if ((aWhichClipboard == kGlobalClipboard &&
         aTransferable == mGlobalTransferable.get() &&
         aOwner == mGlobalOwner.get()) ||
        (aWhichClipboard == kSelectionClipboard &&
         aTransferable == mSelectionTransferable.get() &&
         aOwner == mSelectionOwner.get())) {
        return NS_OK;
    }

    nsresult rv;
    if (!mPrivacyHandler) {
        rv = NS_NewClipboardPrivacyHandler(getter_AddRefs(mPrivacyHandler));
        NS_ENSURE_SUCCESS(rv, rv);
    }
    rv = mPrivacyHandler->PrepareDataForClipboard(aTransferable);
    NS_ENSURE_SUCCESS(rv, rv);

    // Clear out the clipboard in order to set the new data
    EmptyClipboard(aWhichClipboard);

    // List of suported targets
    GtkTargetList *list = gtk_target_list_new(NULL, 0);

    // Get the types of supported flavors
    nsCOMPtr<nsISupportsArray> flavors;

    rv = aTransferable->FlavorsTransferableCanExport(getter_AddRefs(flavors));
    if (!flavors || NS_FAILED(rv))
        return NS_ERROR_FAILURE;

    // Add all the flavors to this widget's supported type.
    PRBool imagesAdded = PR_FALSE;
    PRUint32 count;
    flavors->Count(&count);
    for (PRUint32 i=0; i < count; i++) {
        nsCOMPtr<nsISupports> tastesLike;
        flavors->GetElementAt(i, getter_AddRefs(tastesLike));
        nsCOMPtr<nsISupportsCString> flavor = do_QueryInterface(tastesLike);

        if (flavor) {
            nsXPIDLCString flavorStr;
            flavor->ToString(getter_Copies(flavorStr));

            // special case text/unicode since we can handle all of
            // the string types
            if (!strcmp(flavorStr, kUnicodeMime)) {
                gtk_target_list_add(list, gdk_atom_intern("UTF8_STRING", FALSE), 0, 0);
                gtk_target_list_add(list, gdk_atom_intern("COMPOUND_TEXT", FALSE), 0, 0);
                gtk_target_list_add(list, gdk_atom_intern("TEXT", FALSE), 0, 0);
                gtk_target_list_add(list, GDK_SELECTION_TYPE_STRING, 0, 0);
                continue;
            }

            if (flavorStr.EqualsLiteral(kNativeImageMime) ||
                flavorStr.EqualsLiteral(kPNGImageMime) ||
                flavorStr.EqualsLiteral(kJPEGImageMime) ||
                flavorStr.EqualsLiteral(kGIFImageMime)) {
                // don't bother adding image targets twice
                if (!imagesAdded) {
                    // accept any writable image type
                    gtk_target_list_add_image_targets(list, 0, TRUE);
                    imagesAdded = PR_TRUE;
                }
                continue;
            }

            // Add this to our list of valid targets
            GdkAtom atom = gdk_atom_intern(flavorStr, FALSE);
            gtk_target_list_add(list, atom, 0, 0);
        }
    }
    
    // Get GTK clipboard (CLIPBOARD or PRIMARY)
    GtkClipboard *gtkClipboard = gtk_clipboard_get(GetSelectionAtom(aWhichClipboard));
  
    gint numTargets;
    GtkTargetEntry *gtkTargets = gtk_target_table_new_from_list(list, &numTargets);
          
    // Set getcallback and request to store data after an application exit
    if (gtk_clipboard_set_with_data(gtkClipboard, gtkTargets, numTargets, 
                                    clipboard_get_cb, clipboard_clear_cb, this))
    {
        // We managed to set-up the clipboard so update internal state
        // We have to set it now because gtk_clipboard_set_with_data() calls clipboard_clear_cb()
        // which reset our internal state 
        if (aWhichClipboard == kSelectionClipboard) {
            mSelectionOwner = aOwner;
            mSelectionTransferable = aTransferable;
        }
        else {
            mGlobalOwner = aOwner;
            mGlobalTransferable = aTransferable;
            gtk_clipboard_set_can_store(gtkClipboard, gtkTargets, numTargets);
        }

        rv = NS_OK;
    }
    else {  
        rv = NS_ERROR_FAILURE;
    }

    gtk_target_table_free(gtkTargets, numTargets);
    gtk_target_list_unref(list);
  
    return rv;
}
Example #20
0
bool wxTopLevelWindowGTK::Show( bool show )
{
    wxASSERT_MSG( (m_widget != NULL), wxT("invalid frame") );

#ifdef GDK_WINDOWING_X11
    bool deferShow = show && !m_isShown && m_deferShow;
    if (deferShow)
    {
        deferShow = m_deferShowAllowed && gs_requestFrameExtentsStatus != 2 &&
            !gtk_widget_get_realized(m_widget) &&
            g_signal_handler_find(m_widget,
                GSignalMatchType(G_SIGNAL_MATCH_ID | G_SIGNAL_MATCH_DATA),
                g_signal_lookup("property_notify_event", GTK_TYPE_WIDGET),
                0, NULL, NULL, this);
        if (deferShow)
        {
            GdkScreen* screen = gtk_widget_get_screen(m_widget);
            GdkAtom atom = gdk_atom_intern("_NET_REQUEST_FRAME_EXTENTS", false);
            deferShow = gdk_x11_screen_supports_net_wm_hint(screen, atom) != 0;

            // If _NET_REQUEST_FRAME_EXTENTS not supported, don't allow changes
            // to m_decorSize, it breaks saving/restoring window size with
            // GetSize()/SetSize() because it makes window bigger between each
            // restore and save.
            m_updateDecorSize = deferShow;
        }

        m_deferShow = deferShow;
    }
    if (deferShow)
    {
        // Initial show. If WM supports _NET_REQUEST_FRAME_EXTENTS, defer
        // calling gtk_widget_show() until _NET_FRAME_EXTENTS property
        // notification is received, so correct frame extents are known.
        // This allows resizing m_widget to keep the overall size in sync with
        // what wxWidgets expects it to be without an obvious change in the
        // window size immediately after it becomes visible.

        // Realize m_widget, so m_widget->window can be used. Realizing normally
        // causes the widget tree to be size_allocated, which generates size
        // events in the wrong order. However, the size_allocates will not be
        // done if the allocation is not the default (1,1).
        GtkAllocation alloc;
        gtk_widget_get_allocation(m_widget, &alloc);
        const int alloc_width = alloc.width;
        if (alloc_width == 1)
        {
            alloc.width = 2;
            gtk_widget_set_allocation(m_widget, &alloc);
        }
        gtk_widget_realize(m_widget);
        if (alloc_width == 1)
        {
            alloc.width = 1;
            gtk_widget_set_allocation(m_widget, &alloc);
        }

        // send _NET_REQUEST_FRAME_EXTENTS
        XClientMessageEvent xevent;
        memset(&xevent, 0, sizeof(xevent));
        xevent.type = ClientMessage;
        GdkWindow* window = gtk_widget_get_window(m_widget);
        xevent.window = GDK_WINDOW_XID(window);
        xevent.message_type = gdk_x11_atom_to_xatom_for_display(
            gdk_window_get_display(window),
            gdk_atom_intern("_NET_REQUEST_FRAME_EXTENTS", false));
        xevent.format = 32;
        Display* display = GDK_DISPLAY_XDISPLAY(gdk_window_get_display(window));
        XSendEvent(display, DefaultRootWindow(display), false,
            SubstructureNotifyMask | SubstructureRedirectMask,
            (XEvent*)&xevent);

        if (gs_requestFrameExtentsStatus == 0)
        {
            // if WM does not respond to request within 1 second,
            // we assume support for _NET_REQUEST_FRAME_EXTENTS is not working
            m_netFrameExtentsTimerId =
                g_timeout_add(1000, request_frame_extents_timeout, this);
        }

        // defer calling gtk_widget_show()
        m_isShown = true;
        return true;
    }
#endif // GDK_WINDOWING_X11

    if (show && !gtk_widget_get_realized(m_widget))
    {
        // size_allocate signals occur in reverse order (bottom to top).
        // Things work better if the initial wxSizeEvents are sent (from the
        // top down), before the initial size_allocate signals occur.
        wxSizeEvent event(GetSize(), GetId());
        event.SetEventObject(this);
        HandleWindowEvent(event);
    }

    bool change = base_type::Show(show);

    if (change && !show)
    {
        // make sure window has a non-default position, so when it is shown
        // again, it won't be repositioned by WM as if it were a new window
        // Note that this must be done _after_ the window is hidden.
        gtk_window_move((GtkWindow*)m_widget, m_x, m_y);
    }

    return change;
}
static PRBool
wait_for_retrieval(GtkClipboard *clipboard, retrieval_context *r_context)
{
    if (r_context->completed)  // the request completed synchronously
        return PR_TRUE;

    Display *xDisplay = GDK_DISPLAY();
    checkEventContext context;
    context.cbWidget = NULL;
    context.selAtom = gdk_x11_atom_to_xatom(gdk_atom_intern("GDK_SELECTION",
                                                            FALSE));

    // Send X events which are relevant to the ongoing selection retrieval
    // to the clipboard widget.  Wait until either the operation completes, or
    // we hit our timeout.  All other X events remain queued.

    int select_result;

#ifdef POLL_WITH_XCONNECTIONNUMBER
    struct pollfd fds[1];
    fds[0].fd = XConnectionNumber(xDisplay);
    fds[0].events = POLLIN;
#else
    int cnumber = ConnectionNumber(xDisplay);
    fd_set select_set;
    FD_ZERO(&select_set);
    FD_SET(cnumber, &select_set);
    ++cnumber;
    struct timeval tv;
#endif

    do {
        XEvent xevent;

        while (XCheckIfEvent(xDisplay, &xevent, checkEventProc,
                             (XPointer) &context)) {

            if (xevent.xany.type == SelectionNotify)
                DispatchSelectionNotifyEvent(context.cbWidget, &xevent);
            else
                DispatchPropertyNotifyEvent(context.cbWidget, &xevent);

            if (r_context->completed)
                return PR_TRUE;
        }

#ifdef POLL_WITH_XCONNECTIONNUMBER
        select_result = poll(fds, 1, kClipboardTimeout / 1000);
#else
        tv.tv_sec = 0;
        tv.tv_usec = kClipboardTimeout;
        select_result = select(cnumber, &select_set, NULL, NULL, &tv);
#endif
    } while (select_result == 1);

#ifdef DEBUG_CLIPBOARD
    printf("exceeded clipboard timeout\n");
#endif
    r_context->timed_out = PR_TRUE;
    return PR_FALSE;
}
gboolean
gimp_remote_drop_files (GdkDisplay *display,
                        GdkWindow  *window,
                        GString    *file_list)
{
  GdkDragContext  *context;
  GdkDragProtocol  protocol;
  GtkWidget       *source;
  GdkAtom          sel_type;
  GdkAtom          sel_id;
  GList           *targetlist;
  guint            timeout;

  gdk_drag_get_protocol_for_display (display,
                                     GDK_WINDOW_XID (window),
                                     &protocol);
  if (protocol != GDK_DRAG_PROTO_XDND)
    {
      g_printerr ("GIMP Window doesnt use Xdnd-Protocol - huh?\n");
      return FALSE;
    }

  /*  Problem: If the Toolbox is hidden via Tab (gtk_widget_hide)
   *  it does not accept DnD-Operations and gtk_main() will not be
   *  terminated. If the Toolbox is simply unmapped (by the WM)
   *  DnD works. But in both cases gdk_window_is_visible() returns
   *  FALSE. To work around this we add a timeout and abort after
   *  5 seconds.
   */

  timeout = g_timeout_add (5000, toolbox_hidden, NULL);

  /*  set up an DND-source  */
  source = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  g_signal_connect (source, "selection-get",
                    G_CALLBACK (source_selection_get),
                    file_list->str);
  gtk_widget_realize (source);


  /*  specify the id and the content-type of the selection used to
   *  pass the URIs to GIMP.
   */
  sel_id   = gdk_atom_intern ("XdndSelection", FALSE);
  sel_type = gdk_atom_intern ("text/uri-list", FALSE);
  targetlist = g_list_prepend (NULL, GUINT_TO_POINTER (sel_type));

  /*  assign the selection to our DnD-source  */
  gtk_selection_owner_set (source, sel_id, GDK_CURRENT_TIME);
  gtk_selection_add_target (source, sel_id, sel_type, 0);

  /*  drag_begin/motion/drop  */
  context = gdk_drag_begin (gtk_widget_get_window (source), targetlist);

  gdk_drag_motion (context, window, protocol, 0, 0,
                   GDK_ACTION_COPY, GDK_ACTION_COPY, GDK_CURRENT_TIME);

  gdk_drag_drop (context, GDK_CURRENT_TIME);

  /*  finally enter the mainloop to handle the events  */
  gtk_main ();

  g_source_remove (timeout);

  return TRUE;
}
static void pasting_test_get_data_callback(GtkClipboard* clipboard, GtkSelectionData* selection_data, guint info, gpointer data)
{
    gtk_selection_data_set(selection_data, gdk_atom_intern("text/html", FALSE), 8, (const guchar*) data, strlen((char*)data) + 1);
}
Example #24
0
/* Code to find the active window in order to collect stats for social
 * application browsing.
 */
static void
get_active_application_properties(HippoIdleMonitor *monitor,
                                  char            **wm_class,
                                  char            **title)
{
    Display *xdisplay = GDK_DISPLAY_XDISPLAY(monitor->display);
    int n_screens = gdk_display_get_n_screens(monitor->display);
    Atom net_active_window_x = gdk_x11_get_xatom_by_name_for_display(monitor->display,
                                                                     "_NET_ACTIVE_WINDOW");
    GdkAtom net_active_window_gdk = gdk_atom_intern("_NET_ACTIVE_WINDOW", FALSE);
    Window active_window = None;
    int i;

    Atom type;
    int format;
    unsigned long n_items;
    unsigned long bytes_after;
    guchar *data;
    gboolean is_desktop = FALSE;
        
    if (wm_class)
        *wm_class = NULL;
    if (title)
        *title = NULL;

    /* Find the currently focused window by looking at the _NET_ACTIVE_WINDOW property
     * on all the screens of the display.
     */
    for (i = 0; i < n_screens; i++) {
        GdkScreen *screen = gdk_display_get_screen(monitor->display, i);
        GdkWindow *root = gdk_screen_get_root_window(screen);

        if (!gdk_x11_screen_supports_net_wm_hint (screen, net_active_window_gdk))
            continue;

        XGetWindowProperty (xdisplay, GDK_DRAWABLE_XID(root),
                            net_active_window_x,
                            0, 1, False, XA_WINDOW,
                            &type, &format, &n_items, &bytes_after, &data);
        if (type == XA_WINDOW) {
            active_window = *(Window *)data;
            XFree(data);
            break;
        }
    }

    /* Now that we have the active window, figure out the application name and WM class
     */
    gdk_error_trap_push();
        
    if (active_window && wm_class) {
        if (XGetWindowProperty (xdisplay, active_window,
                                XA_WM_CLASS,
                                0, G_MAXLONG, False, XA_STRING,
                                &type, &format, &n_items, &bytes_after, &data) == Success &&
            type == XA_STRING)
        {
            if (format == 8) {
                char **list;
                int count;
                
                count = gdk_text_property_to_utf8_list_for_display(monitor->display, GDK_TARGET_STRING,
                                                                   8, data, n_items, &list);

                if (count > 1) {
		    /* This is a check for Nautilus, which sets the instance to this
		     * value for the desktop window; we do this rather than check for
		     * the more general _NET_WM_WINDOW_TYPE_DESKTOP to avoid having
		     * to do another XGetProperty on every iteration. We generally
		     * don't want to count the desktop being focused as application
		     * usage because it frequently can be a false-positive of an
		     * empty workspace.
		     */
		    if (strcmp(list[0], "desktop_window") == 0)
			is_desktop = TRUE;
		    else
			*wm_class = g_strdup(list[1]);
		}

                if (list)
                    g_strfreev(list);
            }
            
            XFree(data);
        }
    }

    if (is_desktop)
	active_window = None;

    if (active_window && title) {
        Atom utf8_string = gdk_x11_get_xatom_by_name_for_display(monitor->display, "UTF8_STRING");
        
        if (XGetWindowProperty (xdisplay, active_window,
                                gdk_x11_get_xatom_by_name_for_display(monitor->display, "_NET_WM_NAME"),
                                0, G_MAXLONG, False, utf8_string,
                                &type, &format, &n_items, &bytes_after, &data) == Success &&
            type == utf8_string)
        {
            if (format == 8 && g_utf8_validate((char *)data, -1, NULL)) {
                *title = g_strdup((char *)data);
            }
            
            XFree(data);
        }
    }

    if (active_window && title && *title == NULL) {
        if (XGetWindowProperty (xdisplay, active_window,
                                XA_WM_NAME,
                                0, G_MAXLONG, False, AnyPropertyType,
                                &type, &format, &n_items, &bytes_after, &data) == Success &&
            type != None)
        {
            if (format == 8) {
                char **list;
                int count;
                
                count = gdk_text_property_to_utf8_list_for_display(monitor->display,
                                                                   gdk_x11_xatom_to_atom_for_display(monitor->display, type),
                                                                   8, data, n_items, &list);

                if (count > 0)
                    *title = g_strdup(list[0]);
                
                if (list)
                    g_strfreev(list);
            }
            
            XFree(data);
        }
    }
        
    gdk_error_trap_pop();
}
Example #25
0
int wxSystemSettingsNative::GetMetric( wxSystemMetric index, wxWindow* win )
{
    guchar *data = NULL;
    Atom type;
    int format;
    gulong nitems;
    GdkWindow *window = NULL;
    if(win && GTK_WIDGET_REALIZED(win->GetHandle()))
        window = win->GetHandle()->window;

    switch (index)
    {
        case wxSYS_BORDER_X:
        case wxSYS_BORDER_Y:
        case wxSYS_EDGE_X:
        case wxSYS_EDGE_Y:
        case wxSYS_FRAMESIZE_X:
        case wxSYS_FRAMESIZE_Y:
            // If a window is specified/realized, and it is a toplevel window, we can query from wm.
            // The returned border thickness is outside the client area in that case.
            if (window)
            {
                wxTopLevelWindow *tlw = wxDynamicCast(win, wxTopLevelWindow);
                if (!tlw)
                    return -1; // not a tlw, not sure how to approach
                else
                {
                    // Check if wm supports frame extents - we can't know
                    // the border widths if it does not.
#if GTK_CHECK_VERSION(2,2,0)
                    if (!gtk_check_version(2,2,0))
                    {
                        if (!gdk_x11_screen_supports_net_wm_hint(
                                gdk_drawable_get_screen(window),
                                gdk_atom_intern("_NET_FRAME_EXTENTS", false) ) )
                            return -1;
                    }
                    else
#endif
                    {
                        if (!gdk_net_wm_supports(gdk_atom_intern("_NET_FRAME_EXTENTS", false)))
                            return -1;
                    }

                    // Get the frame extents from the windowmanager.
                    // In most cases the top extent is the titlebar, so we use the bottom extent
                    // for the heights.
                    if (wxXGetWindowProperty(window, type, format, nitems, data))
                    {
                        int border_return = -1;

                        if ((type == XA_CARDINAL) && (format == 32) && (nitems >= 4) && (data))
                        {
                            switch(index)
                            {
                                case wxSYS_BORDER_X:
                                case wxSYS_EDGE_X:
                                case wxSYS_FRAMESIZE_X:
                                    border_return = ((long*)data)[1]; // width of right extent
                                    break;
                                default:
                                    border_return = ((long*)data)[3]; // height of bottom extent
                                    break;
                            }
                        }

                        if (data)
                            XFree(data);

                        return border_return;
                    }
                }
            }

            return -1; // no window specified

        case wxSYS_CURSOR_X:
        case wxSYS_CURSOR_Y:
#ifdef __WXGTK24__
            if (!gtk_check_version(2,4,0))
            {
                if (window)
                    return gdk_display_get_default_cursor_size(gdk_drawable_get_display(window));
                else
                    return gdk_display_get_default_cursor_size(gdk_display_get_default());
            }
            else
#endif
                return 16;

        case wxSYS_DCLICK_X:
        case wxSYS_DCLICK_Y:
            gint dclick_distance;
#if GTK_CHECK_VERSION(2,2,0)
            if (window && !gtk_check_version(2,2,0))
                g_object_get(gtk_settings_get_for_screen(gdk_drawable_get_screen(window)),
                                "gtk-double-click-distance", &dclick_distance, NULL);
            else
#endif
                g_object_get(gtk_settings_get_default(),
                                "gtk-double-click-distance", &dclick_distance, NULL);

            return dclick_distance * 2;

        case wxSYS_DRAG_X:
        case wxSYS_DRAG_Y:
            gint drag_threshold;
#if GTK_CHECK_VERSION(2,2,0)
            if (window && !gtk_check_version(2,2,0))
            {
                g_object_get(
                        gtk_settings_get_for_screen(gdk_drawable_get_screen(window)),
                        "gtk-dnd-drag-threshold",
                        &drag_threshold, NULL);
            }
            else
#endif
            {
                g_object_get(gtk_settings_get_default(),
                             "gtk-dnd-drag-threshold", &drag_threshold, NULL);
            }

            // The correct thing here would be to double the value
            // since that is what the API wants. But the values
            // are much bigger under GNOME than under Windows and
            // just seem to much in many cases to be useful.
            // drag_threshold *= 2;

            return drag_threshold;

        // MBN: ditto for icons
        case wxSYS_ICON_X:     return 32;
        case wxSYS_ICON_Y:     return 32;

        case wxSYS_SCREEN_X:
#if GTK_CHECK_VERSION(2,2,0)
            if (window && !gtk_check_version(2,2,0))
                return gdk_screen_get_width(gdk_drawable_get_screen(window));
            else
#endif
                return gdk_screen_width();

        case wxSYS_SCREEN_Y:
#if GTK_CHECK_VERSION(2,2,0)
            if (window && !gtk_check_version(2,2,0))
                return gdk_screen_get_height(gdk_drawable_get_screen(window));
            else
#endif
                return gdk_screen_height();

        case wxSYS_HSCROLL_Y:  return 15;
        case wxSYS_VSCROLL_X:  return 15;

        case wxSYS_CAPTION_Y:
            if (!window)
                // No realized window specified, and no implementation for that case yet.
                return -1;

            // Check if wm supports frame extents - we can't know the caption height if it does not.
#if GTK_CHECK_VERSION(2,2,0)
            if (!gtk_check_version(2,2,0))
            {
                if (!gdk_x11_screen_supports_net_wm_hint(
                        gdk_drawable_get_screen(window),
                        gdk_atom_intern("_NET_FRAME_EXTENTS", false) ) )
                    return -1;
            }
            else
#endif
            {
                if (!gdk_net_wm_supports(gdk_atom_intern("_NET_FRAME_EXTENTS", false)))
                    return -1;
            }

            wxASSERT_MSG( wxDynamicCast(win, wxTopLevelWindow),
                          wxT("Asking for caption height of a non toplevel window") );

            // Get the height of the top windowmanager border.
            // This is the titlebar in most cases. The titlebar might be elsewhere, and
            // we could check which is the thickest wm border to decide on which side the
            // titlebar is, but this might lead to interesting behaviours in used code.
            // Reconsider when we have a way to report to the user on which side it is.
            if (wxXGetWindowProperty(window, type, format, nitems, data))
            {
                int caption_height = -1;

                if ((type == XA_CARDINAL) && (format == 32) && (nitems >= 3) && (data))
                {
                    caption_height = ((long*)data)[2]; // top frame extent
                }

                if (data)
                    XFree(data);

                return caption_height;
            }

            // Try a default approach without a window pointer, if possible
            // ...

            return -1;

        case wxSYS_PENWINDOWS_PRESENT:
            // No MS Windows for Pen computing extension available in X11 based gtk+.
            return 0;

        default:
            return -1;   // metric is unknown
    }
}
Example #26
0
NS_IMETHODIMP
nsClipboard::GetData(nsITransferable *aTransferable, PRInt32 aWhichClipboard)
{
    if (!aTransferable)
        return NS_ERROR_FAILURE;

    GtkClipboard *clipboard;
    clipboard = gtk_clipboard_get(GetSelectionAtom(aWhichClipboard));

    guchar        *data = NULL;
    gint           length = 0;
    bool           foundData = false;
    nsCAutoString  foundFlavor;

    // Get a list of flavors this transferable can import
    nsCOMPtr<nsISupportsArray> flavors;
    nsresult rv;
    rv = aTransferable->FlavorsTransferableCanImport(getter_AddRefs(flavors));
    if (!flavors || NS_FAILED(rv))
        return NS_ERROR_FAILURE;

    PRUint32 count;
    flavors->Count(&count);
    for (PRUint32 i=0; i < count; i++) {
        nsCOMPtr<nsISupports> genericFlavor;
        flavors->GetElementAt(i, getter_AddRefs(genericFlavor));

        nsCOMPtr<nsISupportsCString> currentFlavor;
        currentFlavor = do_QueryInterface(genericFlavor);

        if (currentFlavor) {
            nsXPIDLCString flavorStr;
            currentFlavor->ToString(getter_Copies(flavorStr));

            // Special case text/unicode since we can convert any
            // string into text/unicode
            if (!strcmp(flavorStr, kUnicodeMime)) {
                gchar* new_text = wait_for_text(clipboard);
                if (new_text) {
                    // Convert utf-8 into our unicode format.
                    NS_ConvertUTF8toUTF16 ucs2string(new_text);
                    data = (guchar *)ToNewUnicode(ucs2string);
                    length = ucs2string.Length() * 2;
                    g_free(new_text);
                    foundData = true;
                    foundFlavor = kUnicodeMime;
                    break;
                }
                // If the type was text/unicode and we couldn't get
                // text off the clipboard, run the next loop
                // iteration.
                continue;
            }

            // For images, we must wrap the data in an nsIInputStream then return instead of break,
            // because that code below won't help us.
            if (!strcmp(flavorStr, kJPEGImageMime) || !strcmp(flavorStr, kPNGImageMime) || !strcmp(flavorStr, kGIFImageMime)) {
                GdkAtom atom;
                if (!strcmp(flavorStr, kJPEGImageMime)) // This is image/jpg, but X only understands image/jpeg
                    atom = gdk_atom_intern("image/jpeg", FALSE);
                else
                    atom = gdk_atom_intern(flavorStr, FALSE);

                GtkSelectionData *selectionData = wait_for_contents(clipboard, atom);
                if (!selectionData)
                    continue;

                nsCOMPtr<nsIInputStream> byteStream;
                NS_NewByteInputStream(getter_AddRefs(byteStream), (const char*)selectionData->data,
                                      selectionData->length, NS_ASSIGNMENT_COPY);
                aTransferable->SetTransferData(flavorStr, byteStream, sizeof(nsIInputStream*));
                gtk_selection_data_free(selectionData);
                return NS_OK;
            }

            // Get the atom for this type and try to request it off
            // the clipboard.
            GdkAtom atom = gdk_atom_intern(flavorStr, FALSE);
            GtkSelectionData *selectionData;
            selectionData = wait_for_contents(clipboard, atom);
            if (selectionData) {
                length = selectionData->length;
                // Special case text/html since we can convert into UCS2
                if (!strcmp(flavorStr, kHTMLMime)) {
                    PRUnichar* htmlBody= nsnull;
                    PRInt32 htmlBodyLen = 0;
                    // Convert text/html into our unicode format
                    ConvertHTMLtoUCS2((guchar *)selectionData->data, length,
                                      &htmlBody, htmlBodyLen);
                    // Try next data format?
                    if (!htmlBodyLen)
                        continue;
                    data = (guchar *)htmlBody;
                    length = htmlBodyLen * 2;
                } else {
                    data = (guchar *)nsMemory::Alloc(length);
                    if (!data)
                        break;
                    memcpy(data, selectionData->data, length);
                }
                foundData = true;
                foundFlavor = flavorStr;
                break;
            }
        }
    }

    if (foundData) {
        nsCOMPtr<nsISupports> wrapper;
        nsPrimitiveHelpers::CreatePrimitiveForData(foundFlavor.get(),
                                                   data, length,
                                                   getter_AddRefs(wrapper));
        aTransferable->SetTransferData(foundFlavor.get(),
                                       wrapper, length);
    }

    if (data)
        nsMemory::Free(data);

    return NS_OK;
}
Example #27
0
NS_IMETHODIMP
nsClipboard::SetData(nsITransferable *aTransferable,
                     nsIClipboardOwner *aOwner, PRInt32 aWhichClipboard)
{
    // See if we can short cut
    if ((aWhichClipboard == kGlobalClipboard &&
            aTransferable == mGlobalTransferable.get() &&
            aOwner == mGlobalOwner.get()) ||
            (aWhichClipboard == kSelectionClipboard &&
             aTransferable == mSelectionTransferable.get() &&
             aOwner == mSelectionOwner.get())) {
        return NS_OK;
    }

    // Clear out the clipboard in order to set the new data
    EmptyClipboard(aWhichClipboard);

    if (aWhichClipboard == kSelectionClipboard) {
        mSelectionOwner = aOwner;
        mSelectionTransferable = aTransferable;
    }
    else {
        mGlobalOwner = aOwner;
        mGlobalTransferable = aTransferable;
    }

    // Which selection are we about to claim, CLIPBOARD or PRIMARY?
    GdkAtom selectionAtom = GetSelectionAtom(aWhichClipboard);

    // Make ourselves the owner.  If we fail to, return.
    if (!gtk_selection_owner_set(mWidget, selectionAtom, GDK_CURRENT_TIME))
        return NS_ERROR_FAILURE;

    // Clear the old selection target list.
    gtk_selection_clear_targets(mWidget, selectionAtom);

    // Get the types of supported flavors
    nsresult rv;
    nsCOMPtr<nsISupportsArray> flavors;

    rv = aTransferable->FlavorsTransferableCanExport(getter_AddRefs(flavors));
    if (!flavors || NS_FAILED(rv))
        return NS_ERROR_FAILURE;

    // Add all the flavors to this widget's supported type.
    PRUint32 count;
    flavors->Count(&count);
    for (PRUint32 i=0; i < count; i++) {
        nsCOMPtr<nsISupports> tastesLike;
        flavors->GetElementAt(i, getter_AddRefs(tastesLike));
        nsCOMPtr<nsISupportsCString> flavor = do_QueryInterface(tastesLike);

        if (flavor) {
            nsXPIDLCString flavorStr;
            flavor->ToString(getter_Copies(flavorStr));

            // special case text/unicode since we can handle all of
            // the string types
            if (!strcmp(flavorStr, kUnicodeMime)) {
                AddTarget(gdk_atom_intern("UTF8_STRING", FALSE),
                          selectionAtom);
                AddTarget(gdk_atom_intern("COMPOUND_TEXT", FALSE),
                          selectionAtom);
                AddTarget(gdk_atom_intern("TEXT", FALSE), selectionAtom);
                AddTarget(GDK_SELECTION_TYPE_STRING, selectionAtom);
                // next loop iteration
                continue;
            }

            // Add this to our list of valid targets
            GdkAtom atom = gdk_atom_intern(flavorStr, FALSE);
            AddTarget(atom, selectionAtom);
        }
    }

    return NS_OK;
}
Example #28
0
void
nsScreenGtk :: Init (GdkWindow *aRootWindow)
{
  // We listen for configure events on the root window to pick up
  // changes to this rect.  We could listen for "size_changed" signals
  // on the default screen to do this, except that doesn't work with
  // versions of GDK predating the GdkScreen object.  See bug 256646.
  mAvailRect = mRect = nsIntRect(0, 0, gdk_screen_width(), gdk_screen_height());

#ifdef MOZ_X11
  // We need to account for the taskbar, etc in the available rect.
  // See http://freedesktop.org/Standards/wm-spec/index.html#id2767771

  // XXX do we care about _NET_WM_STRUT_PARTIAL?  That will
  // add much more complexity to the code here (our screen
  // could have a non-rectangular shape), but should
  // lead to greater accuracy.

  long *workareas;
  GdkAtom type_returned;
  int format_returned;
  int length_returned;

#if GTK_CHECK_VERSION(2,0,0)
  GdkAtom cardinal_atom = gdk_x11_xatom_to_atom(XA_CARDINAL);
#else
  GdkAtom cardinal_atom = (GdkAtom) XA_CARDINAL;
#endif

  gdk_error_trap_push();

  // gdk_property_get uses (length + 3) / 4, hence G_MAXLONG - 3 here.
  if (!gdk_property_get(aRootWindow,
                        gdk_atom_intern ("_NET_WORKAREA", FALSE),
                        cardinal_atom,
                        0, G_MAXLONG - 3, FALSE,
                        &type_returned,
                        &format_returned,
                        &length_returned,
                        (guchar **) &workareas)) {
    // This window manager doesn't support the freedesktop standard.
    // Nothing we can do about it, so assume full screen size.
    return;
  }

  // Flush the X queue to catch errors now.
  gdk_flush();

  if (!gdk_error_trap_pop() &&
      type_returned == cardinal_atom &&
      length_returned && (length_returned % 4) == 0 &&
      format_returned == 32) {
    int num_items = length_returned / sizeof(long);

    for (int i = 0; i < num_items; i += 4) {
      nsIntRect workarea(workareas[i],     workareas[i + 1],
                         workareas[i + 2], workareas[i + 3]);
      if (!mRect.Contains(workarea)) {
        // Note that we hit this when processing screen size changes,
        // since we'll get the configure event before the toolbars have
        // been moved.  We'll end up cleaning this up when we get the
        // change notification to the _NET_WORKAREA property.  However,
        // we still want to listen to both, so we'll handle changes
        // properly for desktop environments that don't set the
        // _NET_WORKAREA property.
        NS_WARNING("Invalid bounds");
        continue;
      }

      mAvailRect.IntersectRect(mAvailRect, workarea);
    }
  }
  g_free (workareas);
#endif
}
Example #29
0
/* static */
GtkSelectionData *
nsClipboard::GetTargets(GdkAtom aWhichClipboard)
{
    GtkClipboard *clipboard = gtk_clipboard_get(aWhichClipboard);
    return wait_for_contents(clipboard, gdk_atom_intern("TARGETS", FALSE));
}
Example #30
0
// Get the display ICC profile of the monitor associated with the widget.
// For X display, uses the ICC profile specifications version 0.2 from
// http://burtonini.com/blog/computers/xicc
// Based on code from Gimp's modules/cdisplay_lcms.c
void dt_ctl_set_display_profile()
{
  if(!dt_control_running()) return;
  // make sure that no one gets a broken profile
  // FIXME: benchmark if the try is really needed when moving/resizing the window. Maybe we can just lock it
  // and block
  if(pthread_rwlock_trywrlock(&darktable.control->xprofile_lock))
    return; // we are already updating the profile. Or someone is reading right now. Too bad we can't
            // distinguish that. Whatever ...

  GtkWidget *widget = dt_ui_center(darktable.gui->ui);
  guint8 *buffer = NULL;
  gint buffer_size = 0;
  gchar *profile_source = NULL;

#if defined GDK_WINDOWING_X11

  // we will use the xatom no matter what configured when compiled without colord
  gboolean use_xatom = TRUE;
#if defined USE_COLORDGTK
  gboolean use_colord = TRUE;
  gchar *display_profile_source = dt_conf_get_string("ui_last/display_profile_source");
  if(display_profile_source)
  {
    if(!strcmp(display_profile_source, "xatom"))
      use_colord = FALSE;
    else if(!strcmp(display_profile_source, "colord"))
      use_xatom = FALSE;
    g_free(display_profile_source);
  }
#endif

  /* let's have a look at the xatom, just in case ... */
  if(use_xatom)
  {
    GdkScreen *screen = gtk_widget_get_screen(widget);
    if(screen == NULL) screen = gdk_screen_get_default();
    int monitor = gdk_screen_get_monitor_at_window(screen, gtk_widget_get_window(widget));
    char *atom_name;
    if(monitor > 0)
      atom_name = g_strdup_printf("_ICC_PROFILE_%d", monitor);
    else
      atom_name = g_strdup("_ICC_PROFILE");

    profile_source = g_strdup_printf("xatom %s", atom_name);

    GdkAtom type = GDK_NONE;
    gint format = 0;
    gdk_property_get(gdk_screen_get_root_window(screen), gdk_atom_intern(atom_name, FALSE), GDK_NONE, 0,
                     64 * 1024 * 1024, FALSE, &type, &format, &buffer_size, &buffer);
    g_free(atom_name);
  }

#ifdef USE_COLORDGTK
  /* also try to get the profile from colord. this will set the value asynchronously! */
  if(use_colord)
  {
    CdWindow *window = cd_window_new();
    GtkWidget *center_widget = dt_ui_center(darktable.gui->ui);
    cd_window_get_profile(window, center_widget, NULL, dt_ctl_get_display_profile_colord_callback, NULL);
  }
#endif

#elif defined GDK_WINDOWING_QUARTZ
  GdkScreen *screen = gtk_widget_get_screen(widget);
  if(screen == NULL) screen = gdk_screen_get_default();
  int monitor = gdk_screen_get_monitor_at_window(screen, gtk_widget_get_window(widget));

  CGDirectDisplayID ids[monitor + 1];
  uint32_t total_ids;
  CMProfileRef prof = NULL;
  if(CGGetOnlineDisplayList(monitor + 1, &ids[0], &total_ids) == kCGErrorSuccess && total_ids == monitor + 1)
    CMGetProfileByAVID(ids[monitor], &prof);
  if(prof != NULL)
  {
    CFDataRef data;
    data = CMProfileCopyICCData(NULL, prof);
    CMCloseProfile(prof);

    UInt8 *tmp_buffer = (UInt8 *)g_malloc(CFDataGetLength(data));
    CFDataGetBytes(data, CFRangeMake(0, CFDataGetLength(data)), tmp_buffer);

    buffer = (guint8 *)tmp_buffer;
    buffer_size = CFDataGetLength(data);

    CFRelease(data);
  }
  profile_source = g_strdup("osx color profile api");
#elif defined G_OS_WIN32
  (void)widget;
  HDC hdc = GetDC(NULL);
  if(hdc != NULL)
  {
    DWORD len = 0;
    GetICMProfile(hdc, &len, NULL);
    gchar *path = g_new(gchar, len);

    if(GetICMProfile(hdc, &len, path))
    {
      gsize size;
      g_file_get_contents(path, (gchar **)&buffer, &size, NULL);
      buffer_size = size;
    }
    g_free(path);
    ReleaseDC(NULL, hdc);
  }
  profile_source = g_strdup("windows color profile api");
#endif

  int profile_changed = buffer_size > 0
                        && (darktable.control->xprofile_size != buffer_size
                            || memcmp(darktable.control->xprofile_data, buffer, buffer_size) != 0);
  if(profile_changed)
  {
    cmsHPROFILE profile = NULL;
    char name[512] = { 0 };
    // thanks to ufraw for this!
    g_free(darktable.control->xprofile_data);
    darktable.control->xprofile_data = buffer;
    darktable.control->xprofile_size = buffer_size;
    profile = cmsOpenProfileFromMem(buffer, buffer_size);
    if(profile)
    {
      dt_colorspaces_get_profile_name(profile, "en", "US", name, sizeof(name));
      cmsCloseProfile(profile);
    }
    dt_print(DT_DEBUG_CONTROL, "[color profile] we got a new screen profile `%s' from the %s (size: %d)\n",
             *name ? name : "(unknown)", profile_source, buffer_size);
  }
  pthread_rwlock_unlock(&darktable.control->xprofile_lock);
  if(profile_changed) dt_control_signal_raise(darktable.signals, DT_SIGNAL_CONTROL_PROFILE_CHANGED);
  g_free(profile_source);
}