1 /* vim:set ts=2 sw=2 sts=2 cin et: */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3  * License, v. 2.0. If a copy of the MPL was not distributed with this
4  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 
6 #include "nsIconChannel.h"
7 
8 #include <stdlib.h>
9 #include <unistd.h>
10 
11 #include "mozilla/DebugOnly.h"
12 #include "mozilla/EndianUtils.h"
13 #include <algorithm>
14 
15 #include <gio/gio.h>
16 
17 #include <gtk/gtk.h>
18 
19 #include "nsMimeTypes.h"
20 #include "nsIMIMEService.h"
21 
22 #include "nsServiceManagerUtils.h"
23 
24 #include "nsNetUtil.h"
25 #include "nsComponentManagerUtils.h"
26 #include "nsIStringStream.h"
27 #include "nsServiceManagerUtils.h"
28 #include "NullPrincipal.h"
29 #include "nsIURL.h"
30 #include "prlink.h"
31 #include "gfxPlatform.h"
32 
NS_IMPL_ISUPPORTS(nsIconChannel,nsIRequest,nsIChannel)33 NS_IMPL_ISUPPORTS(nsIconChannel, nsIRequest, nsIChannel)
34 
35 static nsresult moz_gdk_pixbuf_to_channel(GdkPixbuf* aPixbuf, nsIURI* aURI,
36                                           nsIChannel** aChannel) {
37   int width = gdk_pixbuf_get_width(aPixbuf);
38   int height = gdk_pixbuf_get_height(aPixbuf);
39   NS_ENSURE_TRUE(height < 256 && width < 256 && height > 0 && width > 0 &&
40                      gdk_pixbuf_get_colorspace(aPixbuf) == GDK_COLORSPACE_RGB &&
41                      gdk_pixbuf_get_bits_per_sample(aPixbuf) == 8 &&
42                      gdk_pixbuf_get_has_alpha(aPixbuf) &&
43                      gdk_pixbuf_get_n_channels(aPixbuf) == 4,
44                  NS_ERROR_UNEXPECTED);
45 
46   const int n_channels = 4;
47   gsize buf_size = 2 + n_channels * height * width;
48   uint8_t* const buf = (uint8_t*)moz_xmalloc(buf_size);
49   NS_ENSURE_TRUE(buf, NS_ERROR_OUT_OF_MEMORY);
50   uint8_t* out = buf;
51 
52   *(out++) = width;
53   *(out++) = height;
54 
55   const guchar* const pixels = gdk_pixbuf_get_pixels(aPixbuf);
56   int rowextra = gdk_pixbuf_get_rowstride(aPixbuf) - width * n_channels;
57 
58   // encode the RGB data and the A data
59   const guchar* in = pixels;
60   for (int y = 0; y < height; ++y, in += rowextra) {
61     for (int x = 0; x < width; ++x) {
62       uint8_t r = *(in++);
63       uint8_t g = *(in++);
64       uint8_t b = *(in++);
65       uint8_t a = *(in++);
66 #define DO_PREMULTIPLY(c_) uint8_t(uint16_t(c_) * uint16_t(a) / uint16_t(255))
67 #if MOZ_LITTLE_ENDIAN
68       *(out++) = DO_PREMULTIPLY(b);
69       *(out++) = DO_PREMULTIPLY(g);
70       *(out++) = DO_PREMULTIPLY(r);
71       *(out++) = a;
72 #else
73       *(out++) = a;
74       *(out++) = DO_PREMULTIPLY(r);
75       *(out++) = DO_PREMULTIPLY(g);
76       *(out++) = DO_PREMULTIPLY(b);
77 #endif
78 #undef DO_PREMULTIPLY
79     }
80   }
81 
82   NS_ASSERTION(out == buf + buf_size, "size miscalculation");
83 
84   nsresult rv;
85   nsCOMPtr<nsIStringInputStream> stream =
86       do_CreateInstance("@mozilla.org/io/string-input-stream;1", &rv);
87 
88   // Prevent the leaking of buf
89   if (NS_WARN_IF(NS_FAILED(rv))) {
90     free(buf);
91     return rv;
92   }
93 
94   // stream takes ownership of buf and will free it on destruction.
95   // This function cannot fail.
96   rv = stream->AdoptData((char*)buf, buf_size);
97 
98   // If this no longer holds then re-examine buf's lifetime.
99   MOZ_ASSERT(NS_SUCCEEDED(rv));
100   NS_ENSURE_SUCCESS(rv, rv);
101 
102   // nsIconProtocolHandler::NewChannel2 will provide the correct loadInfo for
103   // this iconChannel. Use the most restrictive security settings for the
104   // temporary loadInfo to make sure the channel can not be openend.
105   nsCOMPtr<nsIPrincipal> nullPrincipal = NullPrincipal::Create();
106   return NS_NewInputStreamChannel(
107       aChannel, aURI, stream.forget(), nullPrincipal,
108       nsILoadInfo::SEC_REQUIRE_SAME_ORIGIN_DATA_IS_BLOCKED,
109       nsIContentPolicy::TYPE_INTERNAL_IMAGE, NS_LITERAL_CSTRING(IMAGE_ICON_MS));
110 }
111 
112 static GtkWidget* gProtoWindow = nullptr;
113 static GtkWidget* gStockImageWidget = nullptr;
114 
ensure_stock_image_widget()115 static void ensure_stock_image_widget() {
116   // Only the style of the GtkImage needs to be used, but the widget is kept
117   // to track dynamic style changes.
118   if (!gProtoWindow) {
119     gProtoWindow = gtk_window_new(GTK_WINDOW_POPUP);
120     GtkWidget* protoLayout = gtk_fixed_new();
121     gtk_container_add(GTK_CONTAINER(gProtoWindow), protoLayout);
122 
123     gStockImageWidget = gtk_image_new();
124     gtk_container_add(GTK_CONTAINER(protoLayout), gStockImageWidget);
125 
126     gtk_widget_ensure_style(gStockImageWidget);
127   }
128 }
129 
moz_gtk_icon_size(const char * name)130 static GtkIconSize moz_gtk_icon_size(const char* name) {
131   if (strcmp(name, "button") == 0) {
132     return GTK_ICON_SIZE_BUTTON;
133   }
134 
135   if (strcmp(name, "menu") == 0) {
136     return GTK_ICON_SIZE_MENU;
137   }
138 
139   if (strcmp(name, "toolbar") == 0) {
140     return GTK_ICON_SIZE_LARGE_TOOLBAR;
141   }
142 
143   if (strcmp(name, "toolbarsmall") == 0) {
144     return GTK_ICON_SIZE_SMALL_TOOLBAR;
145   }
146 
147   if (strcmp(name, "dnd") == 0) {
148     return GTK_ICON_SIZE_DND;
149   }
150 
151   if (strcmp(name, "dialog") == 0) {
152     return GTK_ICON_SIZE_DIALOG;
153   }
154 
155   return GTK_ICON_SIZE_MENU;
156 }
157 
GetIconSize(nsIMozIconURI * aIconURI)158 static int32_t GetIconSize(nsIMozIconURI* aIconURI) {
159   nsAutoCString iconSizeString;
160 
161   aIconURI->GetIconSize(iconSizeString);
162   if (iconSizeString.IsEmpty()) {
163     uint32_t size;
164     mozilla::DebugOnly<nsresult> rv = aIconURI->GetImageSize(&size);
165     NS_ASSERTION(NS_SUCCEEDED(rv), "GetImageSize failed");
166     return size;
167   }
168   int size;
169 
170   GtkIconSize icon_size = moz_gtk_icon_size(iconSizeString.get());
171   gtk_icon_size_lookup(icon_size, &size, nullptr);
172   return size;
173 }
174 
175 /* Scale icon buffer to preferred size */
ScaleIconBuf(GdkPixbuf ** aBuf,int32_t iconSize)176 static nsresult ScaleIconBuf(GdkPixbuf** aBuf, int32_t iconSize) {
177   // Scale buffer only if width or height differ from preferred size
178   if (gdk_pixbuf_get_width(*aBuf) != iconSize &&
179       gdk_pixbuf_get_height(*aBuf) != iconSize) {
180     GdkPixbuf* scaled =
181         gdk_pixbuf_scale_simple(*aBuf, iconSize, iconSize, GDK_INTERP_BILINEAR);
182     // replace original buffer by scaled
183     g_object_unref(*aBuf);
184     *aBuf = scaled;
185     if (!scaled) {
186       return NS_ERROR_OUT_OF_MEMORY;
187     }
188   }
189   return NS_OK;
190 }
191 
InitWithGIO(nsIMozIconURI * aIconURI)192 nsresult nsIconChannel::InitWithGIO(nsIMozIconURI* aIconURI) {
193   GIcon* icon = nullptr;
194   nsCOMPtr<nsIURL> fileURI;
195 
196   // Read icon content
197   aIconURI->GetIconURL(getter_AddRefs(fileURI));
198 
199   // Get icon for file specified by URI
200   if (fileURI) {
201     bool isFile;
202     nsAutoCString spec;
203     fileURI->GetAsciiSpec(spec);
204     if (NS_SUCCEEDED(fileURI->SchemeIs("file", &isFile)) && isFile) {
205       GFile* file = g_file_new_for_uri(spec.get());
206       GFileInfo* fileInfo =
207           g_file_query_info(file, G_FILE_ATTRIBUTE_STANDARD_ICON,
208                             G_FILE_QUERY_INFO_NONE, nullptr, nullptr);
209       g_object_unref(file);
210       if (fileInfo) {
211         // icon from g_content_type_get_icon doesn't need unref
212         icon = g_file_info_get_icon(fileInfo);
213         if (icon) {
214           g_object_ref(icon);
215         }
216         g_object_unref(fileInfo);
217       }
218     }
219   }
220 
221   // Try to get icon by using MIME type
222   if (!icon) {
223     nsAutoCString type;
224     aIconURI->GetContentType(type);
225     // Try to get MIME type from file extension by using nsIMIMEService
226     if (type.IsEmpty()) {
227       nsCOMPtr<nsIMIMEService> ms(do_GetService("@mozilla.org/mime;1"));
228       if (ms) {
229         nsAutoCString fileExt;
230         aIconURI->GetFileExtension(fileExt);
231         ms->GetTypeFromExtension(fileExt, type);
232       }
233     }
234     char* ctype = nullptr;  // character representation of content type
235     if (!type.IsEmpty()) {
236       ctype = g_content_type_from_mime_type(type.get());
237     }
238     if (ctype) {
239       icon = g_content_type_get_icon(ctype);
240       g_free(ctype);
241     }
242   }
243 
244   // Get default icon theme
245   GtkIconTheme* iconTheme = gtk_icon_theme_get_default();
246   GtkIconInfo* iconInfo = nullptr;
247   // Get icon size
248   int32_t iconSize = GetIconSize(aIconURI);
249 
250   if (icon) {
251     // Use icon and theme to get GtkIconInfo
252     iconInfo = gtk_icon_theme_lookup_by_gicon(iconTheme, icon, iconSize,
253                                               (GtkIconLookupFlags)0);
254     g_object_unref(icon);
255   }
256 
257   if (!iconInfo) {
258     // Mozilla's mimetype lookup failed. Try the "unknown" icon.
259     iconInfo = gtk_icon_theme_lookup_icon(iconTheme, "unknown", iconSize,
260                                           (GtkIconLookupFlags)0);
261     if (!iconInfo) {
262       return NS_ERROR_NOT_AVAILABLE;
263     }
264   }
265 
266   // Create a GdkPixbuf buffer containing icon and scale it
267   GdkPixbuf* buf = gtk_icon_info_load_icon(iconInfo, nullptr);
268   gtk_icon_info_free(iconInfo);
269   if (!buf) {
270     return NS_ERROR_UNEXPECTED;
271   }
272 
273   nsresult rv = ScaleIconBuf(&buf, iconSize);
274   NS_ENSURE_SUCCESS(rv, rv);
275 
276   rv = moz_gdk_pixbuf_to_channel(buf, aIconURI, getter_AddRefs(mRealChannel));
277   g_object_unref(buf);
278   return rv;
279 }
280 
Init(nsIURI * aURI)281 nsresult nsIconChannel::Init(nsIURI* aURI) {
282   nsCOMPtr<nsIMozIconURI> iconURI = do_QueryInterface(aURI);
283   NS_ASSERTION(iconURI, "URI is not an nsIMozIconURI");
284 
285   if (gfxPlatform::IsHeadless()) {
286     return NS_ERROR_NOT_AVAILABLE;
287   }
288 
289   nsAutoCString stockIcon;
290   iconURI->GetStockIcon(stockIcon);
291   if (stockIcon.IsEmpty()) {
292     return InitWithGIO(iconURI);
293   }
294 
295   // Search for stockIcon
296   nsAutoCString iconSizeString;
297   iconURI->GetIconSize(iconSizeString);
298 
299   nsAutoCString iconStateString;
300   iconURI->GetIconState(iconStateString);
301 
302   GtkIconSize icon_size = moz_gtk_icon_size(iconSizeString.get());
303   GtkStateType state = iconStateString.EqualsLiteral("disabled")
304                            ? GTK_STATE_INSENSITIVE
305                            : GTK_STATE_NORMAL;
306 
307   // First lookup the icon by stock id and text direction.
308   GtkTextDirection direction = GTK_TEXT_DIR_NONE;
309   if (StringEndsWith(stockIcon, NS_LITERAL_CSTRING("-ltr"))) {
310     direction = GTK_TEXT_DIR_LTR;
311   } else if (StringEndsWith(stockIcon, NS_LITERAL_CSTRING("-rtl"))) {
312     direction = GTK_TEXT_DIR_RTL;
313   }
314 
315   bool forceDirection = direction != GTK_TEXT_DIR_NONE;
316   nsAutoCString stockID;
317   bool useIconName = false;
318   if (!forceDirection) {
319     direction = gtk_widget_get_default_direction();
320     stockID = stockIcon;
321   } else {
322     // GTK versions < 2.22 use icon names from concatenating stock id with
323     // -(rtl|ltr), which is how the moz-icon stock name is interpreted here.
324     stockID = Substring(stockIcon, 0, stockIcon.Length() - 4);
325     // However, if we lookup bidi icons by the stock name, then GTK versions
326     // >= 2.22 will use a bidi lookup convention that most icon themes do not
327     // yet follow.  Therefore, we first check to see if the theme supports the
328     // old icon name as this will have bidi support (if found).
329     GtkIconTheme* icon_theme = gtk_icon_theme_get_default();
330     // Micking what gtk_icon_set_render_icon does with sizes, though it's not
331     // critical as icons will be scaled to suit size.  It just means we follow
332     // the same pathes and so share caches.
333     gint width, height;
334     if (gtk_icon_size_lookup(icon_size, &width, &height)) {
335       gint size = std::min(width, height);
336       // We use gtk_icon_theme_lookup_icon() without
337       // GTK_ICON_LOOKUP_USE_BUILTIN instead of gtk_icon_theme_has_icon() so
338       // we don't pick up fallback icons added by distributions for backward
339       // compatibility.
340       GtkIconInfo* icon = gtk_icon_theme_lookup_icon(
341           icon_theme, stockIcon.get(), size, (GtkIconLookupFlags)0);
342       if (icon) {
343         useIconName = true;
344         gtk_icon_info_free(icon);
345       }
346     }
347   }
348 
349   ensure_stock_image_widget();
350   GtkStyle* style = gtk_widget_get_style(gStockImageWidget);
351   GtkIconSet* icon_set = nullptr;
352   if (!useIconName) {
353     icon_set = gtk_style_lookup_icon_set(style, stockID.get());
354   }
355 
356   if (!icon_set) {
357     // Either we have choosen icon-name lookup for a bidi icon, or stockIcon is
358     // not a stock id so we assume it is an icon name.
359     useIconName = true;
360     // Creating a GtkIconSet is a convenient way to allow the style to
361     // render the icon, possibly with variations suitable for insensitive
362     // states.
363     icon_set = gtk_icon_set_new();
364     GtkIconSource* icon_source = gtk_icon_source_new();
365 
366     gtk_icon_source_set_icon_name(icon_source, stockIcon.get());
367     gtk_icon_set_add_source(icon_set, icon_source);
368     gtk_icon_source_free(icon_source);
369   }
370 
371   GdkPixbuf* icon = gtk_icon_set_render_icon(
372       icon_set, style, direction, state, icon_size, gStockImageWidget, nullptr);
373   if (useIconName) {
374     gtk_icon_set_unref(icon_set);
375   }
376 
377   // According to documentation, gtk_icon_set_render_icon() never returns
378   // nullptr, but it does return nullptr when we have the problem reported
379   // here: https://bugzilla.gnome.org/show_bug.cgi?id=629878#c13
380   if (!icon) {
381     return NS_ERROR_NOT_AVAILABLE;
382   }
383 
384   nsresult rv =
385       moz_gdk_pixbuf_to_channel(icon, iconURI, getter_AddRefs(mRealChannel));
386 
387   g_object_unref(icon);
388 
389   return rv;
390 }
391 
Shutdown()392 void nsIconChannel::Shutdown() {
393   if (gProtoWindow) {
394     gtk_widget_destroy(gProtoWindow);
395     gProtoWindow = nullptr;
396     gStockImageWidget = nullptr;
397   }
398 }
399