• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "ash/system/chromeos/network/network_icon.h"
6 
7 #include "ash/shell.h"
8 #include "ash/system/chromeos/network/network_icon_animation.h"
9 #include "ash/system/chromeos/network/network_icon_animation_observer.h"
10 #include "ash/system/tray/system_tray_delegate.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "chromeos/network/device_state.h"
13 #include "chromeos/network/network_connection_handler.h"
14 #include "chromeos/network/network_state.h"
15 #include "chromeos/network/network_state_handler.h"
16 #include "grit/ash_resources.h"
17 #include "grit/ash_strings.h"
18 #include "third_party/cros_system_api/dbus/service_constants.h"
19 #include "ui/base/l10n/l10n_util.h"
20 #include "ui/base/resource/resource_bundle.h"
21 #include "ui/base/webui/web_ui_util.h"
22 #include "ui/gfx/canvas.h"
23 #include "ui/gfx/image/image_skia_operations.h"
24 #include "ui/gfx/image/image_skia_source.h"
25 #include "ui/gfx/rect.h"
26 #include "ui/gfx/size_conversions.h"
27 
28 using chromeos::DeviceState;
29 using chromeos::NetworkConnectionHandler;
30 using chromeos::NetworkHandler;
31 using chromeos::NetworkState;
32 using chromeos::NetworkStateHandler;
33 using chromeos::NetworkTypePattern;
34 
35 namespace ash {
36 namespace network_icon {
37 
38 namespace {
39 
40 //------------------------------------------------------------------------------
41 // Struct to pass icon badges to NetworkIconImageSource.
42 struct Badges {
Badgesash::network_icon::__anon72827d3c0111::Badges43   Badges()
44       : top_left(NULL),
45         top_right(NULL),
46         bottom_left(NULL),
47         bottom_right(NULL) {
48   }
49   const gfx::ImageSkia* top_left;
50   const gfx::ImageSkia* top_right;
51   const gfx::ImageSkia* bottom_left;
52   const gfx::ImageSkia* bottom_right;
53 };
54 
55 //------------------------------------------------------------------------------
56 // class used for maintaining a map of network state and images.
57 class NetworkIconImpl {
58  public:
59   NetworkIconImpl(const std::string& path, IconType icon_type);
60 
61   // Determines whether or not the associated network might be dirty and if so
62   // updates and generates the icon. Does nothing if network no longer exists.
63   void Update(const chromeos::NetworkState* network);
64 
65   // Returns the cached image url for |image_| based on |scale_factor|.
66   const std::string& GetImageUrl(float scale_factor);
67 
image() const68   const gfx::ImageSkia& image() const { return image_; }
69 
70  private:
71   typedef std::map<float, std::string> ImageUrlMap;
72 
73   // Updates |strength_index_| for wireless networks. Returns true if changed.
74   bool UpdateWirelessStrengthIndex(const chromeos::NetworkState* network);
75 
76   // Updates the local state for cellular networks. Returns true if changed.
77   bool UpdateCellularState(const chromeos::NetworkState* network);
78 
79   // Updates the portal state for wireless networks. Returns true if changed.
80   bool UpdatePortalState(const chromeos::NetworkState* network);
81 
82   // Updates the VPN badge. Returns true if changed.
83   bool UpdateVPNBadge();
84 
85   // Gets |badges| based on |network| and the current state.
86   void GetBadges(const NetworkState* network, Badges* badges);
87 
88   // Gets the appropriate icon and badges and composites the image.
89   void GenerateImage(const chromeos::NetworkState* network);
90 
91   // Network path, used for debugging.
92   std::string network_path_;
93 
94   // Defines color theme and VPN badging
95   const IconType icon_type_;
96 
97   // Cached state of the network when the icon was last generated.
98   std::string state_;
99 
100   // Cached strength index of the network when the icon was last generated.
101   int strength_index_;
102 
103   // Cached technology badge for the network when the icon was last generated.
104   const gfx::ImageSkia* technology_badge_;
105 
106   // Cached vpn badge for the network when the icon was last generated.
107   const gfx::ImageSkia* vpn_badge_;
108 
109   // Cached roaming state of the network when the icon was last generated.
110   std::string roaming_state_;
111 
112   // Cached portal state of the network when the icon was last generated.
113   bool behind_captive_portal_;
114 
115   // Generated icon image.
116   gfx::ImageSkia image_;
117 
118   // Map of cached image urls by scale factor. Cleared whenever image_ is
119   // generated.
120   ImageUrlMap image_urls_;
121 
122   DISALLOW_COPY_AND_ASSIGN(NetworkIconImpl);
123 };
124 
125 //------------------------------------------------------------------------------
126 // Maintain a static (global) icon map. Note: Icons are never destroyed;
127 // it is assumed that a finite and reasonable number of network icons will be
128 // created during a session.
129 
130 typedef std::map<std::string, NetworkIconImpl*> NetworkIconMap;
131 
GetIconMapInstance(IconType icon_type,bool create)132 NetworkIconMap* GetIconMapInstance(IconType icon_type, bool create) {
133   typedef std::map<IconType, NetworkIconMap*> IconTypeMap;
134   static IconTypeMap* s_icon_map = NULL;
135   if (s_icon_map == NULL) {
136     if (!create)
137       return NULL;
138     s_icon_map = new IconTypeMap;
139   }
140   if (s_icon_map->count(icon_type) == 0) {
141     if (!create)
142       return NULL;
143     (*s_icon_map)[icon_type] = new NetworkIconMap;
144   }
145   return (*s_icon_map)[icon_type];
146 }
147 
GetIconMap(IconType icon_type)148 NetworkIconMap* GetIconMap(IconType icon_type) {
149   return GetIconMapInstance(icon_type, true);
150 }
151 
PurgeIconMap(IconType icon_type,const std::set<std::string> & network_paths)152 void PurgeIconMap(IconType icon_type,
153                   const std::set<std::string>& network_paths) {
154   NetworkIconMap* icon_map = GetIconMapInstance(icon_type, false);
155   if (!icon_map)
156     return;
157   for (NetworkIconMap::iterator loop_iter = icon_map->begin();
158        loop_iter != icon_map->end(); ) {
159     NetworkIconMap::iterator cur_iter = loop_iter++;
160     if (network_paths.count(cur_iter->first) == 0) {
161       delete cur_iter->second;
162       icon_map->erase(cur_iter);
163     }
164   }
165 }
166 
167 //------------------------------------------------------------------------------
168 // Utilities for generating icon images.
169 
170 // 'NONE' will default to ARCS behavior where appropriate (e.g. no network or
171 // if a new type gets added).
172 enum ImageType {
173   ARCS,
174   BARS,
175   NONE
176 };
177 
178 // Amount to fade icons while connecting.
179 const double kConnectingImageAlpha = 0.5;
180 
181 // Images for strength bars for wired networks.
182 const int kNumBarsImages = 5;
183 
184 // Imagaes for strength arcs for wireless networks.
185 const int kNumArcsImages = 5;
186 
187 // Number of discrete images to use for alpha fade animation
188 const int kNumFadeImages = 10;
189 
190 //------------------------------------------------------------------------------
191 // Classes for generating scaled images.
192 
GetEmptyBitmap(const gfx::Size pixel_size)193 const SkBitmap GetEmptyBitmap(const gfx::Size pixel_size) {
194   typedef std::pair<int, int> SizeKey;
195   typedef std::map<SizeKey, SkBitmap> SizeBitmapMap;
196   static SizeBitmapMap* s_empty_bitmaps = new SizeBitmapMap;
197 
198   SizeKey key(pixel_size.width(), pixel_size.height());
199 
200   SizeBitmapMap::iterator iter = s_empty_bitmaps->find(key);
201   if (iter != s_empty_bitmaps->end())
202     return iter->second;
203 
204   SkBitmap empty;
205   empty.setConfig(SkBitmap::kARGB_8888_Config, key.first, key.second);
206   empty.allocPixels();
207   empty.eraseARGB(0, 0, 0, 0);
208   (*s_empty_bitmaps)[key] = empty;
209   return empty;
210 }
211 
212 class EmptyImageSource: public gfx::ImageSkiaSource {
213  public:
EmptyImageSource(const gfx::Size & size)214   explicit EmptyImageSource(const gfx::Size& size)
215       : size_(size) {
216   }
217 
GetImageForScale(float scale)218   virtual gfx::ImageSkiaRep GetImageForScale(float scale) OVERRIDE {
219     gfx::Size pixel_size = gfx::ToFlooredSize(gfx::ScaleSize(size_, scale));
220     SkBitmap empty_bitmap = GetEmptyBitmap(pixel_size);
221     return gfx::ImageSkiaRep(empty_bitmap, scale);
222   }
223 
224  private:
225   const gfx::Size size_;
226 
227   DISALLOW_COPY_AND_ASSIGN(EmptyImageSource);
228 };
229 
230 // This defines how we assemble a network icon.
231 class NetworkIconImageSource : public gfx::ImageSkiaSource {
232  public:
NetworkIconImageSource(const gfx::ImageSkia & icon,const Badges & badges)233   NetworkIconImageSource(const gfx::ImageSkia& icon, const Badges& badges)
234       : icon_(icon),
235         badges_(badges) {
236   }
~NetworkIconImageSource()237   virtual ~NetworkIconImageSource() {}
238 
239   // TODO(pkotwicz): Figure out what to do when a new image resolution becomes
240   // available.
GetImageForScale(float scale)241   virtual gfx::ImageSkiaRep GetImageForScale(float scale) OVERRIDE {
242     gfx::ImageSkiaRep icon_rep = icon_.GetRepresentation(scale);
243     if (icon_rep.is_null())
244       return gfx::ImageSkiaRep();
245     gfx::Canvas canvas(icon_rep, false);
246     if (badges_.top_left)
247       canvas.DrawImageInt(*badges_.top_left, 0, 0);
248     if (badges_.top_right)
249       canvas.DrawImageInt(*badges_.top_right,
250                           icon_.width() - badges_.top_right->width(), 0);
251     if (badges_.bottom_left) {
252       canvas.DrawImageInt(*badges_.bottom_left,
253                           0, icon_.height() - badges_.bottom_left->height());
254     }
255     if (badges_.bottom_right) {
256       canvas.DrawImageInt(*badges_.bottom_right,
257                           icon_.width() - badges_.bottom_right->width(),
258                           icon_.height() - badges_.bottom_right->height());
259     }
260     return canvas.ExtractImageRep();
261   }
262 
263  private:
264   const gfx::ImageSkia icon_;
265   const Badges badges_;
266 
267   DISALLOW_COPY_AND_ASSIGN(NetworkIconImageSource);
268 };
269 
270 //------------------------------------------------------------------------------
271 // Utilities for extracting icon images.
272 
273 // A struct used for caching image urls.
274 struct ImageIdForNetworkType {
ImageIdForNetworkTypeash::network_icon::__anon72827d3c0111::ImageIdForNetworkType275   ImageIdForNetworkType(IconType icon_type,
276                         const std::string& network_type,
277                         float scale_factor) :
278       icon_type(icon_type),
279       network_type(network_type),
280       scale_factor(scale_factor) {}
operator <ash::network_icon::__anon72827d3c0111::ImageIdForNetworkType281   bool operator<(const ImageIdForNetworkType& other) const {
282     if (icon_type != other.icon_type)
283       return icon_type < other.icon_type;
284     if (network_type != other.network_type)
285       return network_type < other.network_type;
286     return scale_factor < other.scale_factor;
287   }
288   IconType icon_type;
289   std::string network_type;
290   float scale_factor;
291 };
292 
293 typedef std::map<ImageIdForNetworkType, std::string> ImageIdUrlMap;
294 
IconTypeIsDark(IconType icon_type)295 bool IconTypeIsDark(IconType icon_type) {
296   return (icon_type != ICON_TYPE_TRAY);
297 }
298 
IconTypeHasVPNBadge(IconType icon_type)299 bool IconTypeHasVPNBadge(IconType icon_type) {
300   return (icon_type != ICON_TYPE_LIST);
301 }
302 
NumImagesForType(ImageType type)303 int NumImagesForType(ImageType type) {
304   return (type == BARS) ? kNumBarsImages : kNumArcsImages;
305 }
306 
BaseImageForType(ImageType image_type,IconType icon_type)307 gfx::ImageSkia* BaseImageForType(ImageType image_type, IconType icon_type) {
308   gfx::ImageSkia* image;
309   if (image_type == BARS) {
310     image =  ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
311         IconTypeIsDark(icon_type) ?
312         IDR_AURA_UBER_TRAY_NETWORK_BARS_DARK :
313         IDR_AURA_UBER_TRAY_NETWORK_BARS_LIGHT);
314   } else {
315     image =  ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
316         IconTypeIsDark(icon_type) ?
317         IDR_AURA_UBER_TRAY_NETWORK_ARCS_DARK :
318         IDR_AURA_UBER_TRAY_NETWORK_ARCS_LIGHT);
319   }
320   return image;
321 }
322 
ImageTypeForNetworkType(const std::string & type)323 ImageType ImageTypeForNetworkType(const std::string& type) {
324   if (type == shill::kTypeWifi)
325     return ARCS;
326   else if (type == shill::kTypeCellular || type == shill::kTypeWimax)
327     return BARS;
328   return NONE;
329 }
330 
GetImageForIndex(ImageType image_type,IconType icon_type,int index)331 gfx::ImageSkia GetImageForIndex(ImageType image_type,
332                                 IconType icon_type,
333                                 int index) {
334   int num_images = NumImagesForType(image_type);
335   if (index < 0 || index >= num_images)
336     return gfx::ImageSkia();
337   gfx::ImageSkia* images = BaseImageForType(image_type, icon_type);
338   int width = images->width();
339   int height = images->height() / num_images;
340   return gfx::ImageSkiaOperations::ExtractSubset(*images,
341       gfx::Rect(0, index * height, width, height));
342 }
343 
GetConnectedImage(IconType icon_type,const std::string & network_type)344 const gfx::ImageSkia GetConnectedImage(IconType icon_type,
345                                        const std::string& network_type) {
346   if (network_type == shill::kTypeVPN) {
347     return *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
348         IDR_AURA_UBER_TRAY_NETWORK_VPN);
349   }
350   ImageType image_type = ImageTypeForNetworkType(network_type);
351   const int connected_index = NumImagesForType(image_type) - 1;
352   return GetImageForIndex(image_type, icon_type, connected_index);
353 }
354 
GetDisconnectedImage(IconType icon_type,const std::string & network_type)355 const gfx::ImageSkia GetDisconnectedImage(IconType icon_type,
356                                           const std::string& network_type) {
357   if (network_type == shill::kTypeVPN) {
358     // Note: same as connected image, shouldn't normally be seen.
359     return *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
360         IDR_AURA_UBER_TRAY_NETWORK_VPN);
361   }
362   ImageType image_type = ImageTypeForNetworkType(network_type);
363   const int disconnected_index = 0;
364   return GetImageForIndex(image_type, icon_type, disconnected_index);
365 }
366 
ConnectingWirelessImage(ImageType image_type,IconType icon_type,double animation)367 gfx::ImageSkia* ConnectingWirelessImage(ImageType image_type,
368                                         IconType icon_type,
369                                         double animation) {
370   static gfx::ImageSkia* s_bars_images_dark[kNumBarsImages - 1];
371   static gfx::ImageSkia* s_bars_images_light[kNumBarsImages - 1];
372   static gfx::ImageSkia* s_arcs_images_dark[kNumArcsImages - 1];
373   static gfx::ImageSkia* s_arcs_images_light[kNumArcsImages - 1];
374   int image_count = NumImagesForType(image_type) - 1;
375   int index = animation * nextafter(static_cast<float>(image_count), 0);
376   index = std::max(std::min(index, image_count - 1), 0);
377   gfx::ImageSkia** images;
378   bool dark = IconTypeIsDark(icon_type);
379   if (image_type == BARS)
380     images = dark ? s_bars_images_dark : s_bars_images_light;
381   else
382     images = dark ? s_arcs_images_dark : s_arcs_images_light;
383   if (!images[index]) {
384     // Lazily cache images.
385     gfx::ImageSkia source = GetImageForIndex(image_type, icon_type, index + 1);
386     images[index] = new gfx::ImageSkia(
387         gfx::ImageSkiaOperations::CreateBlendedImage(
388             gfx::ImageSkia(new EmptyImageSource(source.size()), source.size()),
389             source,
390             kConnectingImageAlpha));
391   }
392   return images[index];
393 }
394 
ConnectingVpnImage(double animation)395 gfx::ImageSkia* ConnectingVpnImage(double animation) {
396   int index = animation * nextafter(static_cast<float>(kNumFadeImages), 0);
397   static gfx::ImageSkia* s_vpn_images[kNumFadeImages];
398   if (!s_vpn_images[index]) {
399     // Lazily cache images.
400     ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
401     gfx::ImageSkia* icon = rb.GetImageSkiaNamed(IDR_AURA_UBER_TRAY_NETWORK_VPN);
402     s_vpn_images[index] = new gfx::ImageSkia(
403         gfx::ImageSkiaOperations::CreateBlendedImage(
404             gfx::ImageSkia(new EmptyImageSource(icon->size()), icon->size()),
405             *icon,
406             animation));
407   }
408   return s_vpn_images[index];
409 }
410 
ConnectingVpnBadge(double animation)411 gfx::ImageSkia* ConnectingVpnBadge(double animation) {
412   int index = animation * nextafter(static_cast<float>(kNumFadeImages), 0);
413   static gfx::ImageSkia* s_vpn_badges[kNumFadeImages];
414   if (!s_vpn_badges[index]) {
415     // Lazily cache images.
416     ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
417     gfx::ImageSkia* icon =
418         rb.GetImageSkiaNamed(IDR_AURA_UBER_TRAY_NETWORK_WIRED);  // For size
419     gfx::ImageSkia* badge =
420         rb.GetImageSkiaNamed(IDR_AURA_UBER_TRAY_NETWORK_VPN_BADGE);
421     s_vpn_badges[index] = new gfx::ImageSkia(
422         gfx::ImageSkiaOperations::CreateBlendedImage(
423             gfx::ImageSkia(new EmptyImageSource(icon->size()), icon->size()),
424             *badge,
425             animation));
426   }
427   return s_vpn_badges[index];
428 }
429 
StrengthIndex(int strength,int count)430 int StrengthIndex(int strength, int count) {
431   // Return an index in the range [1, count-1].
432   const float findex = (static_cast<float>(strength) / 100.0f) *
433       nextafter(static_cast<float>(count - 1), 0);
434   int index = 1 + static_cast<int>(findex);
435   index = std::max(std::min(index, count - 1), 1);
436   return index;
437 }
438 
GetStrengthIndex(const NetworkState * network)439 int GetStrengthIndex(const NetworkState* network) {
440   ImageType image_type = ImageTypeForNetworkType(network->type());
441   if (image_type == ARCS)
442     return StrengthIndex(network->signal_strength(), kNumArcsImages);
443   else if (image_type == BARS)
444     return StrengthIndex(network->signal_strength(), kNumBarsImages);
445   return 0;
446 }
447 
BadgeForNetworkTechnology(const NetworkState * network,IconType icon_type)448 const gfx::ImageSkia* BadgeForNetworkTechnology(const NetworkState* network,
449                                                 IconType icon_type) {
450   const int kUnknownBadgeType = -1;
451   int id = kUnknownBadgeType;
452   const std::string& technology = network->network_technology();
453   if (technology == shill::kNetworkTechnologyEvdo) {
454     id = IconTypeIsDark(icon_type) ?
455         IDR_AURA_UBER_TRAY_NETWORK_EVDO_DARK :
456         IDR_AURA_UBER_TRAY_NETWORK_EVDO_LIGHT;
457   } else if (technology == shill::kNetworkTechnology1Xrtt) {
458     id = IDR_AURA_UBER_TRAY_NETWORK_1X;
459   } else if (technology == shill::kNetworkTechnologyGprs) {
460     id = IconTypeIsDark(icon_type) ?
461         IDR_AURA_UBER_TRAY_NETWORK_GPRS_DARK :
462         IDR_AURA_UBER_TRAY_NETWORK_GPRS_LIGHT;
463   } else if (technology == shill::kNetworkTechnologyEdge) {
464     id = IconTypeIsDark(icon_type) ?
465         IDR_AURA_UBER_TRAY_NETWORK_EDGE_DARK :
466         IDR_AURA_UBER_TRAY_NETWORK_EDGE_LIGHT;
467   } else if (technology == shill::kNetworkTechnologyUmts) {
468     id = IconTypeIsDark(icon_type) ?
469         IDR_AURA_UBER_TRAY_NETWORK_3G_DARK :
470         IDR_AURA_UBER_TRAY_NETWORK_3G_LIGHT;
471   } else if (technology == shill::kNetworkTechnologyHspa) {
472     id = IconTypeIsDark(icon_type) ?
473         IDR_AURA_UBER_TRAY_NETWORK_HSPA_DARK :
474         IDR_AURA_UBER_TRAY_NETWORK_HSPA_LIGHT;
475   } else if (technology == shill::kNetworkTechnologyHspaPlus) {
476     id = IconTypeIsDark(icon_type) ?
477         IDR_AURA_UBER_TRAY_NETWORK_HSPA_PLUS_DARK :
478         IDR_AURA_UBER_TRAY_NETWORK_HSPA_PLUS_LIGHT;
479   } else if (technology == shill::kNetworkTechnologyLte) {
480     id = IconTypeIsDark(icon_type) ?
481         IDR_AURA_UBER_TRAY_NETWORK_LTE_DARK :
482         IDR_AURA_UBER_TRAY_NETWORK_LTE_LIGHT;
483   } else if (technology == shill::kNetworkTechnologyLteAdvanced) {
484     id = IconTypeIsDark(icon_type) ?
485         IDR_AURA_UBER_TRAY_NETWORK_LTE_ADVANCED_DARK :
486         IDR_AURA_UBER_TRAY_NETWORK_LTE_ADVANCED_LIGHT;
487   } else if (technology == shill::kNetworkTechnologyGsm) {
488     id = IconTypeIsDark(icon_type) ?
489         IDR_AURA_UBER_TRAY_NETWORK_GPRS_DARK :
490         IDR_AURA_UBER_TRAY_NETWORK_GPRS_LIGHT;
491   }
492   if (id == kUnknownBadgeType)
493     return NULL;
494   else
495     return ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(id);
496 }
497 
BadgeForVPN(IconType icon_type)498 const gfx::ImageSkia* BadgeForVPN(IconType icon_type) {
499   return ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
500       IDR_AURA_UBER_TRAY_NETWORK_VPN_BADGE);
501 }
502 
GetIcon(const NetworkState * network,IconType icon_type,int strength_index)503 gfx::ImageSkia GetIcon(const NetworkState* network,
504                        IconType icon_type,
505                        int strength_index) {
506   ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
507   if (network->Matches(NetworkTypePattern::Ethernet())) {
508     return *rb.GetImageSkiaNamed(IDR_AURA_UBER_TRAY_NETWORK_WIRED);
509   } else if (network->Matches(NetworkTypePattern::Wireless())) {
510     DCHECK(strength_index > 0);
511     return GetImageForIndex(
512         ImageTypeForNetworkType(network->type()), icon_type, strength_index);
513   } else if (network->Matches(NetworkTypePattern::VPN())) {
514     return *rb.GetImageSkiaNamed(IDR_AURA_UBER_TRAY_NETWORK_VPN);
515   } else {
516     LOG(WARNING) << "Request for icon for unsupported type: "
517                  << network->type();
518     return *rb.GetImageSkiaNamed(IDR_AURA_UBER_TRAY_NETWORK_WIRED);
519   }
520 }
521 
522 //------------------------------------------------------------------------------
523 // Get connecting images
524 
GetConnectingVpnImage(IconType icon_type)525 gfx::ImageSkia GetConnectingVpnImage(IconType icon_type) {
526   NetworkStateHandler* handler = NetworkHandler::Get()->network_state_handler();
527   const NetworkState* connected_network = NULL;
528   if (icon_type == ICON_TYPE_TRAY) {
529     connected_network =
530         handler->ConnectedNetworkByType(NetworkTypePattern::NonVirtual());
531   }
532   double animation = NetworkIconAnimation::GetInstance()->GetAnimation();
533 
534   if (connected_network) {
535     gfx::ImageSkia icon = GetImageForNetwork(connected_network, icon_type);
536     Badges badges;
537     badges.bottom_left = ConnectingVpnBadge(animation);
538     return gfx::ImageSkia(
539         new NetworkIconImageSource(icon, badges), icon.size());
540   } else {
541     gfx::ImageSkia* icon = ConnectingVpnImage(animation);
542     return gfx::ImageSkia(
543         new NetworkIconImageSource(*icon, Badges()), icon->size());
544   }
545 }
546 
GetConnectingImage(IconType icon_type,const std::string & network_type)547 gfx::ImageSkia GetConnectingImage(IconType icon_type,
548                                   const std::string& network_type) {
549   if (network_type == shill::kTypeVPN)
550     return GetConnectingVpnImage(icon_type);
551 
552   ImageType image_type = ImageTypeForNetworkType(network_type);
553   double animation = NetworkIconAnimation::GetInstance()->GetAnimation();
554 
555   gfx::ImageSkia* icon = ConnectingWirelessImage(
556       image_type, icon_type, animation);
557   return gfx::ImageSkia(
558       new NetworkIconImageSource(*icon, Badges()), icon->size());
559 }
560 
GetConnectingImageUrl(IconType icon_type,const std::string & network_type,float scale_factor)561 std::string GetConnectingImageUrl(IconType icon_type,
562                                   const std::string& network_type,
563                                   float scale_factor) {
564   // Caching the connecting image is complicated and we will never draw more
565   // than a few per frame, so just generate the image url each time.
566   gfx::ImageSkia image = GetConnectingImage(icon_type, network_type);
567   gfx::ImageSkiaRep image_rep = image.GetRepresentation(scale_factor);
568   return webui::GetBitmapDataUrl(image_rep.sk_bitmap());
569 }
570 
571 }  // namespace
572 
573 //------------------------------------------------------------------------------
574 // NetworkIconImpl
575 
NetworkIconImpl(const std::string & path,IconType icon_type)576 NetworkIconImpl::NetworkIconImpl(const std::string& path, IconType icon_type)
577     : network_path_(path),
578       icon_type_(icon_type),
579       strength_index_(-1),
580       technology_badge_(NULL),
581       vpn_badge_(NULL),
582       behind_captive_portal_(false) {
583   // Default image
584   image_ = GetDisconnectedImage(icon_type, shill::kTypeWifi);
585 }
586 
Update(const NetworkState * network)587 void NetworkIconImpl::Update(const NetworkState* network) {
588   DCHECK(network);
589   // Determine whether or not we need to update the icon.
590   bool dirty = image_.isNull();
591 
592   // If the network state has changed, the icon needs updating.
593   if (state_ != network->connection_state()) {
594     state_ = network->connection_state();
595     dirty = true;
596   }
597 
598   dirty |= UpdatePortalState(network);
599 
600   if (network->Matches(NetworkTypePattern::Wireless())) {
601     dirty |= UpdateWirelessStrengthIndex(network);
602   }
603 
604   if (network->Matches(NetworkTypePattern::Cellular()))
605     dirty |= UpdateCellularState(network);
606 
607   if (IconTypeHasVPNBadge(icon_type_) &&
608       network->Matches(NetworkTypePattern::NonVirtual())) {
609     dirty |= UpdateVPNBadge();
610   }
611 
612   if (dirty) {
613     // Set the icon and badges based on the network and generate the image.
614     GenerateImage(network);
615   }
616 }
617 
UpdateWirelessStrengthIndex(const NetworkState * network)618 bool NetworkIconImpl::UpdateWirelessStrengthIndex(const NetworkState* network) {
619   int index = GetStrengthIndex(network);
620   if (index != strength_index_) {
621     strength_index_ = index;
622     return true;
623   }
624   return false;
625 }
626 
UpdateCellularState(const NetworkState * network)627 bool NetworkIconImpl::UpdateCellularState(const NetworkState* network) {
628   bool dirty = false;
629   const gfx::ImageSkia* technology_badge =
630       BadgeForNetworkTechnology(network, icon_type_);
631   if (technology_badge != technology_badge_) {
632     technology_badge_ = technology_badge;
633     dirty = true;
634   }
635   std::string roaming_state = network->roaming();
636   if (roaming_state != roaming_state_) {
637     roaming_state_ = roaming_state;
638     dirty = true;
639   }
640   return dirty;
641 }
642 
UpdatePortalState(const NetworkState * network)643 bool NetworkIconImpl::UpdatePortalState(const NetworkState* network) {
644   bool behind_captive_portal = false;
645   if (network) {
646     SystemTrayDelegate* delegate = Shell::GetInstance()->system_tray_delegate();
647     behind_captive_portal =
648         delegate->IsNetworkBehindCaptivePortal(network->path());
649   }
650 
651   if (behind_captive_portal == behind_captive_portal_)
652     return false;
653   behind_captive_portal_ = behind_captive_portal;
654   return true;
655 }
656 
UpdateVPNBadge()657 bool NetworkIconImpl::UpdateVPNBadge() {
658   const NetworkState* vpn = NetworkHandler::Get()->network_state_handler()->
659       ConnectedNetworkByType(NetworkTypePattern::VPN());
660   if (vpn && vpn_badge_ == NULL) {
661     vpn_badge_ = BadgeForVPN(icon_type_);
662     return true;
663   } else if (!vpn && vpn_badge_ != NULL) {
664     vpn_badge_ = NULL;
665     return true;
666   }
667   return false;
668 }
669 
GetBadges(const NetworkState * network,Badges * badges)670 void NetworkIconImpl::GetBadges(const NetworkState* network, Badges* badges) {
671   DCHECK(network);
672   ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
673   NetworkStateHandler* handler = NetworkHandler::Get()->network_state_handler();
674 
675   const std::string& type = network->type();
676   if (type == shill::kTypeWifi) {
677     if (network->security() != shill::kSecurityNone &&
678         IconTypeIsDark(icon_type_)) {
679       badges->bottom_right = rb.GetImageSkiaNamed(
680           IDR_AURA_UBER_TRAY_NETWORK_SECURE_DARK);
681     }
682   } else if (type == shill::kTypeWimax) {
683     technology_badge_ = rb.GetImageSkiaNamed(
684         IconTypeIsDark(icon_type_) ?
685         IDR_AURA_UBER_TRAY_NETWORK_4G_DARK :
686         IDR_AURA_UBER_TRAY_NETWORK_4G_LIGHT);
687   } else if (type == shill::kTypeCellular) {
688     if (network->roaming() == shill::kRoamingStateRoaming) {
689       // For networks that are always in roaming don't show roaming badge.
690       const DeviceState* device =
691           handler->GetDeviceState(network->device_path());
692       LOG_IF(WARNING, !device) << "Could not find device state for "
693                                << network->device_path();
694       if (!device || !device->provider_requires_roaming()) {
695         badges->bottom_right = rb.GetImageSkiaNamed(
696             IconTypeIsDark(icon_type_) ?
697             IDR_AURA_UBER_TRAY_NETWORK_ROAMING_DARK :
698             IDR_AURA_UBER_TRAY_NETWORK_ROAMING_LIGHT);
699       }
700     }
701   }
702   if (!network->IsConnectingState()) {
703     badges->top_left = technology_badge_;
704     badges->bottom_left = vpn_badge_;
705   }
706 
707   if (behind_captive_portal_) {
708     gfx::ImageSkia* badge = rb.GetImageSkiaNamed(
709        IconTypeIsDark(icon_type_) ?
710        IDR_AURA_UBER_TRAY_NETWORK_PORTAL_DARK :
711        IDR_AURA_UBER_TRAY_NETWORK_PORTAL_LIGHT);
712     badges->bottom_right = badge;
713   }
714 }
715 
GenerateImage(const NetworkState * network)716 void NetworkIconImpl::GenerateImage(const NetworkState* network) {
717   DCHECK(network);
718   gfx::ImageSkia icon = GetIcon(network, icon_type_, strength_index_);
719   Badges badges;
720   GetBadges(network, &badges);
721   image_ = gfx::ImageSkia(
722       new NetworkIconImageSource(icon, badges), icon.size());
723   image_urls_.clear();
724 }
725 
GetImageUrl(float scale_factor)726 const std::string& NetworkIconImpl::GetImageUrl(float scale_factor) {
727   ImageUrlMap::iterator iter = image_urls_.find(scale_factor);
728   if (iter != image_urls_.end())
729     return iter->second;
730 
731   VLOG(2) << "Generating bitmap URL for: " << network_path_;
732   gfx::ImageSkiaRep image_rep = image_.GetRepresentation(scale_factor);
733   iter = image_urls_.insert(std::make_pair(
734       scale_factor, webui::GetBitmapDataUrl(image_rep.sk_bitmap()))).first;
735   return iter->second;
736 }
737 
738 namespace {
739 
FindAndUpdateImageImpl(const NetworkState * network,IconType icon_type)740 NetworkIconImpl* FindAndUpdateImageImpl(const NetworkState* network,
741                                         IconType icon_type) {
742   // Find or add the icon.
743   NetworkIconMap* icon_map = GetIconMap(icon_type);
744   NetworkIconImpl* icon;
745   NetworkIconMap::iterator iter = icon_map->find(network->path());
746   if (iter == icon_map->end()) {
747     icon = new NetworkIconImpl(network->path(), icon_type);
748     icon_map->insert(std::make_pair(network->path(), icon));
749   } else {
750     icon = iter->second;
751   }
752 
753   // Update and return the icon's image.
754   icon->Update(network);
755   return icon;
756 }
757 
758 }  // namespace
759 
760 //------------------------------------------------------------------------------
761 // Public interface
762 
GetImageForNetwork(const NetworkState * network,IconType icon_type)763 gfx::ImageSkia GetImageForNetwork(const NetworkState* network,
764                                   IconType icon_type) {
765   DCHECK(network);
766   if (!network->visible())
767     return GetDisconnectedImage(icon_type, network->type());
768 
769   if (network->IsConnectingState())
770     return GetConnectingImage(icon_type, network->type());
771 
772   NetworkIconImpl* icon = FindAndUpdateImageImpl(network, icon_type);
773   return icon->image();
774 }
775 
GetImageUrlForNetwork(const NetworkState * network,IconType icon_type,float scale_factor)776 std::string GetImageUrlForNetwork(const NetworkState* network,
777                                   IconType icon_type,
778                                   float scale_factor) {
779   DCHECK(network);
780   // Handle connecting icons.
781   if (network->IsConnectingState())
782     return GetConnectingImageUrl(icon_type, network->type(), scale_factor);
783 
784   NetworkIconImpl* icon = FindAndUpdateImageImpl(network, icon_type);
785   return icon->GetImageUrl(scale_factor);
786 }
787 
GetImageForConnectedNetwork(IconType icon_type,const std::string & network_type)788 gfx::ImageSkia GetImageForConnectedNetwork(IconType icon_type,
789                                            const std::string& network_type) {
790   return GetConnectedImage(icon_type, network_type);
791 }
792 
GetImageForConnectingNetwork(IconType icon_type,const std::string & network_type)793 gfx::ImageSkia GetImageForConnectingNetwork(IconType icon_type,
794                                             const std::string& network_type) {
795   return GetConnectingImage(icon_type, network_type);
796 }
797 
GetImageForDisconnectedNetwork(IconType icon_type,const std::string & network_type)798 gfx::ImageSkia GetImageForDisconnectedNetwork(IconType icon_type,
799                                               const std::string& network_type) {
800   return GetDisconnectedImage(icon_type, network_type);
801 }
802 
GetLabelForNetwork(const chromeos::NetworkState * network,IconType icon_type)803 base::string16 GetLabelForNetwork(const chromeos::NetworkState* network,
804                                   IconType icon_type) {
805   DCHECK(network);
806   std::string activation_state = network->activation_state();
807   if (icon_type == ICON_TYPE_LIST) {
808     // Show "<network>: [Connecting|Activating]..."
809     if (network->IsConnectingState()) {
810       return l10n_util::GetStringFUTF16(
811           IDS_ASH_STATUS_TRAY_NETWORK_LIST_CONNECTING,
812           base::UTF8ToUTF16(network->name()));
813     }
814     if (activation_state == shill::kActivationStateActivating) {
815       return l10n_util::GetStringFUTF16(
816           IDS_ASH_STATUS_TRAY_NETWORK_LIST_ACTIVATING,
817           base::UTF8ToUTF16(network->name()));
818     }
819     // Show "Activate <network>" in list view only.
820     if (activation_state == shill::kActivationStateNotActivated ||
821         activation_state == shill::kActivationStatePartiallyActivated) {
822       return l10n_util::GetStringFUTF16(
823           IDS_ASH_STATUS_TRAY_NETWORK_LIST_ACTIVATE,
824           base::UTF8ToUTF16(network->name()));
825     }
826   } else {
827     // Show "[Connected to|Connecting to|Activating] <network>" (non-list view).
828     if (network->IsConnectedState()) {
829       return l10n_util::GetStringFUTF16(IDS_ASH_STATUS_TRAY_NETWORK_CONNECTED,
830                                         base::UTF8ToUTF16(network->name()));
831     }
832     if (network->IsConnectingState()) {
833       return l10n_util::GetStringFUTF16(IDS_ASH_STATUS_TRAY_NETWORK_CONNECTING,
834                                         base::UTF8ToUTF16(network->name()));
835     }
836     if (activation_state == shill::kActivationStateActivating) {
837       return l10n_util::GetStringFUTF16(IDS_ASH_STATUS_TRAY_NETWORK_ACTIVATING,
838                                         base::UTF8ToUTF16(network->name()));
839     }
840   }
841 
842   // Otherwise just show the network name or 'Ethernet'.
843   if (network->Matches(NetworkTypePattern::Ethernet())) {
844     return l10n_util::GetStringUTF16(IDS_ASH_STATUS_TRAY_ETHERNET);
845   } else {
846     return base::UTF8ToUTF16(network->name());
847   }
848 }
849 
GetCellularUninitializedMsg()850 int GetCellularUninitializedMsg() {
851   static base::Time s_uninitialized_state_time;
852   static int s_uninitialized_msg(0);
853 
854   NetworkStateHandler* handler = NetworkHandler::Get()->network_state_handler();
855   if (handler->GetTechnologyState(NetworkTypePattern::Mobile())
856       == NetworkStateHandler::TECHNOLOGY_UNINITIALIZED) {
857     s_uninitialized_msg = IDS_ASH_STATUS_TRAY_INITIALIZING_CELLULAR;
858     s_uninitialized_state_time = base::Time::Now();
859     return s_uninitialized_msg;
860   } else if (handler->GetScanningByType(NetworkTypePattern::Mobile())) {
861     s_uninitialized_msg = IDS_ASH_STATUS_TRAY_CELLULAR_SCANNING;
862     s_uninitialized_state_time = base::Time::Now();
863     return s_uninitialized_msg;
864   }
865   // There can be a delay between leaving the Initializing state and when
866   // a Cellular device shows up, so keep showing the initializing
867   // animation for a bit to avoid flashing the disconnect icon.
868   const int kInitializingDelaySeconds = 1;
869   base::TimeDelta dtime = base::Time::Now() - s_uninitialized_state_time;
870   if (dtime.InSeconds() < kInitializingDelaySeconds)
871     return s_uninitialized_msg;
872   return 0;
873 }
874 
GetDefaultNetworkImageAndLabel(IconType icon_type,gfx::ImageSkia * image,base::string16 * label,bool * animating)875 void GetDefaultNetworkImageAndLabel(IconType icon_type,
876                                     gfx::ImageSkia* image,
877                                     base::string16* label,
878                                     bool* animating) {
879   NetworkStateHandler* state_handler =
880       NetworkHandler::Get()->network_state_handler();
881   NetworkConnectionHandler* connect_handler =
882       NetworkHandler::Get()->network_connection_handler();
883   const NetworkState* connected_network =
884       state_handler->ConnectedNetworkByType(NetworkTypePattern::NonVirtual());
885   const NetworkState* connecting_network =
886       state_handler->ConnectingNetworkByType(NetworkTypePattern::Wireless());
887   if (!connecting_network && icon_type == ICON_TYPE_TRAY) {
888     connecting_network =
889         state_handler->ConnectingNetworkByType(NetworkTypePattern::VPN());
890   }
891 
892   const NetworkState* network;
893   // If we are connecting to a network, and there is either no connected
894   // network, or the connection was user requested, use the connecting
895   // network.
896   if (connecting_network &&
897       (!connected_network ||
898        connect_handler->HasConnectingNetwork(connecting_network->path()))) {
899     network = connecting_network;
900   } else {
901     network = connected_network;
902   }
903 
904   // Don't show ethernet in the tray
905   if (icon_type == ICON_TYPE_TRAY && network &&
906       network->Matches(NetworkTypePattern::Ethernet())) {
907     *image = gfx::ImageSkia();
908     *animating = false;
909     return;
910   }
911 
912   if (!network) {
913     // If no connecting network, check if we are activating a network.
914     const NetworkState* mobile_network =
915         state_handler->FirstNetworkByType(NetworkTypePattern::Mobile());
916     if (mobile_network && (mobile_network->activation_state() ==
917                            shill::kActivationStateActivating)) {
918       network = mobile_network;
919     }
920   }
921   if (!network) {
922     // If no connecting network, check for cellular initializing.
923     int uninitialized_msg = GetCellularUninitializedMsg();
924     if (uninitialized_msg != 0) {
925       *image = GetImageForConnectingNetwork(icon_type, shill::kTypeCellular);
926       if (label)
927         *label = l10n_util::GetStringUTF16(uninitialized_msg);
928       *animating = true;
929     } else {
930       // Otherwise show the disconnected wifi icon.
931       *image = GetImageForDisconnectedNetwork(icon_type, shill::kTypeWifi);
932       if (label) {
933         *label = l10n_util::GetStringUTF16(
934             IDS_ASH_STATUS_TRAY_NETWORK_NOT_CONNECTED);
935       }
936       *animating = false;
937     }
938     return;
939   }
940   *animating = network->IsConnectingState();
941   // Get icon and label for connected or connecting network.
942   *image = GetImageForNetwork(network, icon_type);
943   if (label)
944     *label = GetLabelForNetwork(network, icon_type);
945 }
946 
PurgeNetworkIconCache()947 void PurgeNetworkIconCache() {
948   NetworkStateHandler::NetworkStateList networks;
949   NetworkHandler::Get()->network_state_handler()->GetVisibleNetworkList(
950       &networks);
951   std::set<std::string> network_paths;
952   for (NetworkStateHandler::NetworkStateList::iterator iter = networks.begin();
953        iter != networks.end(); ++iter) {
954     network_paths.insert((*iter)->path());
955   }
956   PurgeIconMap(ICON_TYPE_TRAY, network_paths);
957   PurgeIconMap(ICON_TYPE_DEFAULT_VIEW, network_paths);
958   PurgeIconMap(ICON_TYPE_LIST, network_paths);
959 }
960 
961 }  // namespace network_icon
962 }  // namespace ash
963