xref: /haiku/src/apps/networkstatus/NetworkStatusView.cpp (revision 9f739dd2e868114ce19ae73afcff07caf2ddb8b6)
1 /*
2  * Copyright 2006-2013, Haiku, Inc. All rights reserved.
3  * Distributed under the terms of the MIT License.
4  *
5  * Authors:
6  *		Dario Casalinuovo
7  *		Axel Dörfler, axeld@pinc-software.de
8  *		Rene Gollent, rene@gollent.com
9  *		Hugo Santos, hugosantos@gmail.com
10  */
11 
12 
13 #include "NetworkStatusView.h"
14 
15 #include <algorithm>
16 #include <set>
17 #include <vector>
18 
19 #include <arpa/inet.h>
20 #include <net/if.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <strings.h>
24 #include <sys/socket.h>
25 #include <sys/sockio.h>
26 #include <unistd.h>
27 
28 #include <AboutWindow.h>
29 #include <Alert.h>
30 #include <Application.h>
31 #include <Catalog.h>
32 #include <Bitmap.h>
33 #include <Deskbar.h>
34 #include <Dragger.h>
35 #include <Drivers.h>
36 #include <IconUtils.h>
37 #include <Locale.h>
38 #include <MenuItem.h>
39 #include <MessageRunner.h>
40 #include <NetworkDevice.h>
41 #include <NetworkInterface.h>
42 #include <NetworkRoster.h>
43 #include <PopUpMenu.h>
44 #include <Resources.h>
45 #include <Roster.h>
46 #include <String.h>
47 #include <TextView.h>
48 
49 #include "NetworkStatus.h"
50 #include "NetworkStatusIcons.h"
51 #include "RadioView.h"
52 #include "WirelessNetworkMenuItem.h"
53 
54 
55 #undef B_TRANSLATION_CONTEXT
56 #define B_TRANSLATION_CONTEXT "NetworkStatusView"
57 
58 
59 static const char *kStatusDescriptions[] = {
60 	B_TRANSLATE("Unknown"),
61 	B_TRANSLATE("No link"),
62 	B_TRANSLATE("No stateful configuration"),
63 	B_TRANSLATE("Configuring"),
64 	B_TRANSLATE("Ready")
65 };
66 
67 extern "C" _EXPORT BView *instantiate_deskbar_item(float maxWidth, float maxHeight);
68 
69 
70 const uint32 kMsgShowConfiguration = 'shcf';
71 const uint32 kMsgOpenNetworkPreferences = 'onwp';
72 const uint32 kMsgJoinNetwork = 'join';
73 
74 const uint32 kMinIconWidth = 16;
75 const uint32 kMinIconHeight = 16;
76 
77 
78 //	#pragma mark -
79 
80 
81 static bool
82 signal_strength_compare(const wireless_network &a,
83 	const wireless_network &b)
84 {
85 	if (a.signal_strength == b.signal_strength)
86 		return strcmp(a.name, b.name) > 0;
87 	return a.signal_strength > b.signal_strength;
88 }
89 
90 
91 //	#pragma mark -
92 
93 
94 NetworkStatusView::NetworkStatusView(BRect frame, int32 resizingMode,
95 		bool inDeskbar)
96 	: BView(frame, kDeskbarItemName, resizingMode,
97 		B_WILL_DRAW | B_TRANSPARENT_BACKGROUND | B_FRAME_EVENTS),
98 	fInDeskbar(inDeskbar)
99 {
100 	_Init();
101 
102 	if (!inDeskbar) {
103 		// we were obviously added to a standard window - let's add a dragger
104 		frame.OffsetTo(B_ORIGIN);
105 		frame.top = frame.bottom - 7;
106 		frame.left = frame.right - 7;
107 		BDragger* dragger = new BDragger(frame, this,
108 			B_FOLLOW_RIGHT | B_FOLLOW_BOTTOM);
109 		AddChild(dragger);
110 	} else
111 		_Update();
112 }
113 
114 
115 NetworkStatusView::NetworkStatusView(BMessage* archive)
116 	: BView(archive),
117 	fInDeskbar(false)
118 {
119 	app_info info;
120 	if (be_app->GetAppInfo(&info) == B_OK
121 		&& !strcasecmp(info.signature, "application/x-vnd.Be-TSKB"))
122 		fInDeskbar = true;
123 
124 	_Init();
125 }
126 
127 
128 NetworkStatusView::~NetworkStatusView()
129 {
130 }
131 
132 
133 void
134 NetworkStatusView::_Init()
135 {
136 	for (int i = 0; i < kStatusCount; i++) {
137 		fTrayIcons[i] = NULL;
138 		fNotifyIcons[i] = NULL;
139 	}
140 
141 	_UpdateBitmaps();
142 }
143 
144 
145 void
146 NetworkStatusView::_UpdateBitmaps()
147 {
148 	for (int i = 0; i < kStatusCount; i++) {
149 		delete fTrayIcons[i];
150 		delete fNotifyIcons[i];
151 		fTrayIcons[i] = NULL;
152 		fNotifyIcons[i] = NULL;
153 	}
154 
155 	image_info info;
156 	if (our_image(info) != B_OK)
157 		return;
158 
159 	BFile file(info.name, B_READ_ONLY);
160 	if (file.InitCheck() < B_OK)
161 		return;
162 
163 	BResources resources(&file);
164 #ifdef HAIKU_TARGET_PLATFORM_HAIKU
165 	if (resources.InitCheck() < B_OK)
166 		return;
167 #endif
168 
169 	for (int i = 0; i < kStatusCount; i++) {
170 		const void* data = NULL;
171 		size_t size;
172 		data = resources.LoadResource(B_VECTOR_ICON_TYPE,
173 			kNetworkStatusNoDevice + i, &size);
174 		if (data != NULL) {
175 			// Scale main tray icon
176 			BBitmap* trayIcon = new BBitmap(Bounds(), B_RGBA32);
177 			if (trayIcon->InitCheck() == B_OK
178 				&& BIconUtils::GetVectorIcon((const uint8 *)data,
179 					size, trayIcon) == B_OK) {
180 				fTrayIcons[i] = trayIcon;
181 			} else
182 				delete trayIcon;
183 
184 			// Scale notification icon
185 			BBitmap* notifyIcon = new BBitmap(BRect(0, 0, 31, 31), B_RGBA32);
186 			if (notifyIcon->InitCheck() == B_OK
187 				&& BIconUtils::GetVectorIcon((const uint8 *)data,
188 					size, notifyIcon) == B_OK) {
189 				fNotifyIcons[i] = notifyIcon;
190 			} else
191 				delete notifyIcon;
192 		}
193 	}
194 }
195 
196 
197 void
198 NetworkStatusView::_Quit()
199 {
200 	if (fInDeskbar) {
201 		BDeskbar deskbar;
202 		deskbar.RemoveItem(kDeskbarItemName);
203 	} else
204 		be_app->PostMessage(B_QUIT_REQUESTED);
205 }
206 
207 
208 NetworkStatusView*
209 NetworkStatusView::Instantiate(BMessage* archive)
210 {
211 	if (!validate_instantiation(archive, "NetworkStatusView"))
212 		return NULL;
213 
214 	return new NetworkStatusView(archive);
215 }
216 
217 
218 status_t
219 NetworkStatusView::Archive(BMessage* archive, bool deep) const
220 {
221 	status_t status = BView::Archive(archive, deep);
222 	if (status == B_OK)
223 		status = archive->AddString("add_on", kSignature);
224 	if (status == B_OK)
225 		status = archive->AddString("class", "NetworkStatusView");
226 
227 	return status;
228 }
229 
230 
231 void
232 NetworkStatusView::AttachedToWindow()
233 {
234 	BView::AttachedToWindow();
235 
236 	SetViewColor(B_TRANSPARENT_COLOR);
237 
238 	start_watching_network(
239 		B_WATCH_NETWORK_INTERFACE_CHANGES | B_WATCH_NETWORK_LINK_CHANGES, this);
240 
241 	_Update();
242 }
243 
244 
245 void
246 NetworkStatusView::DetachedFromWindow()
247 {
248 	stop_watching_network(this);
249 }
250 
251 
252 void
253 NetworkStatusView::MessageReceived(BMessage* message)
254 {
255 	switch (message->what) {
256 		case B_NETWORK_MONITOR:
257 			_Update();
258 			break;
259 
260 		case kMsgShowConfiguration:
261 			_ShowConfiguration(message);
262 			break;
263 
264 		case kMsgOpenNetworkPreferences:
265 			_OpenNetworksPreferences();
266 			break;
267 
268 		case kMsgJoinNetwork:
269 		{
270 			const char* deviceName;
271 			const char* name;
272 			BNetworkAddress address;
273 			if (message->FindString("device", &deviceName) == B_OK
274 				&& message->FindString("name", &name) == B_OK
275 				&& message->FindFlat("address", &address) == B_OK) {
276 				BNetworkDevice device(deviceName);
277 				status_t status = device.JoinNetwork(address);
278 				if (status != B_OK) {
279 					BString text
280 						= B_TRANSLATE("Could not join wireless network:\n");
281 					text << strerror(status);
282 					BAlert* alert = new BAlert(name, text.String(),
283 						B_TRANSLATE("OK"), NULL, NULL, B_WIDTH_AS_USUAL,
284 						B_STOP_ALERT);
285 					alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE);
286 					alert->Go(NULL);
287 				}
288 			}
289 			break;
290 		}
291 
292 		case B_ABOUT_REQUESTED:
293 			_AboutRequested();
294 			break;
295 
296 		case B_QUIT_REQUESTED:
297 			_Quit();
298 			break;
299 
300 		default:
301 			BView::MessageReceived(message);
302 	}
303 }
304 
305 
306 void
307 NetworkStatusView::FrameResized(float width, float height)
308 {
309 	_UpdateBitmaps();
310 	Invalidate();
311 }
312 
313 
314 void
315 NetworkStatusView::Draw(BRect updateRect)
316 {
317 	int32 status = kStatusUnknown;
318 	for (std::map<BString, int32>::const_iterator it
319 		= fInterfaceStatuses.begin(); it != fInterfaceStatuses.end(); ++it) {
320 		if (it->second > status)
321 			status = it->second;
322 	}
323 
324 	if (fTrayIcons[status] == NULL)
325 		return;
326 
327 	SetDrawingMode(B_OP_ALPHA);
328 	DrawBitmap(fTrayIcons[status]);
329 	SetDrawingMode(B_OP_COPY);
330 }
331 
332 
333 void
334 NetworkStatusView::_ShowConfiguration(BMessage* message)
335 {
336 	const char* name;
337 	if (message->FindString("interface", &name) != B_OK)
338 		return;
339 
340 	BNetworkInterface networkInterface(name);
341 	if (!networkInterface.Exists())
342 		return;
343 
344 	BNetworkInterfaceAddress address;
345 	networkInterface.GetAddressAt(0, address);
346 		// TODO: We should get all addresses,
347 		// not just the first one.
348 	BString text(B_TRANSLATE("%ifaceName information:\n"));
349 	text.ReplaceFirst("%ifaceName", name);
350 
351 	size_t boldLength = text.Length();
352 
353 	text << "\n" << B_TRANSLATE("Address") << ": " << address.Address().ToString();
354 	text << "\n" << B_TRANSLATE("Broadcast") << ": " << address.Broadcast().ToString();
355 	text << "\n" << B_TRANSLATE("Netmask") << ": " << address.Mask().ToString();
356 
357 	BAlert* alert = new BAlert(name, text.String(), B_TRANSLATE("OK"));
358 	alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE);
359 	BTextView* view = alert->TextView();
360 	BFont font;
361 
362 	view->SetStylable(true);
363 	view->GetFont(&font);
364 	font.SetFace(B_BOLD_FACE);
365 	view->SetFontAndColor(0, boldLength, &font);
366 
367 	alert->Go(NULL);
368 }
369 
370 
371 void
372 NetworkStatusView::MouseDown(BPoint point)
373 {
374 	BPopUpMenu* menu = new BPopUpMenu(B_EMPTY_STRING, false, false);
375 	menu->SetAsyncAutoDestruct(true);
376 	menu->SetFont(be_plain_font);
377 	BString wifiInterface;
378 	BNetworkDevice wifiDevice;
379 
380 	// Add interfaces
381 
382 	for (std::map<BString, int32>::const_iterator it
383 		= fInterfaceStatuses.begin(); it != fInterfaceStatuses.end(); ++it) {
384 		const BString& name = it->first;
385 
386 		BString label = name;
387 		label += ": ";
388 		label += kStatusDescriptions[
389 			_DetermineInterfaceStatus(name.String())];
390 
391 		BMessage* info = new BMessage(kMsgShowConfiguration);
392 		info->AddString("interface", name.String());
393 		menu->AddItem(new BMenuItem(label.String(), info));
394 
395 		// We only show the networks of the first wireless device we find.
396 		if (wifiInterface.IsEmpty()) {
397 			wifiDevice.SetTo(name);
398 			if (wifiDevice.IsWireless())
399 				wifiInterface = name;
400 		}
401 	}
402 
403 	if (!fInterfaceStatuses.empty())
404 		menu->AddSeparatorItem();
405 
406 	// Add wireless networks, if any
407 
408 	if (!wifiInterface.IsEmpty()) {
409 		std::set<BNetworkAddress> associated;
410 		BNetworkAddress address;
411 		uint32 cookie = 0;
412 		while (wifiDevice.GetNextAssociatedNetwork(cookie, address) == B_OK)
413 			associated.insert(address);
414 
415 		cookie = 0;
416 		wireless_network network;
417 		typedef std::vector<wireless_network> WirelessNetworkVector;
418 		WirelessNetworkVector wirelessNetworks;
419 		while (wifiDevice.GetNextNetwork(cookie, network) == B_OK)
420 			wirelessNetworks.push_back(network);
421 
422 		std::sort(wirelessNetworks.begin(), wirelessNetworks.end(),
423 			signal_strength_compare);
424 
425 		int32 count = 0;
426 		for (WirelessNetworkVector::iterator it = wirelessNetworks.begin();
427 				it != wirelessNetworks.end(); it++) {
428 			wireless_network &network = *it;
429 
430 			BMessage* message = new BMessage(kMsgJoinNetwork);
431 			message->AddString("device", wifiInterface);
432 			message->AddString("name", network.name);
433 			message->AddFlat("address", &network.address);
434 
435 			BMenuItem* item = new WirelessNetworkMenuItem(network.name,
436 				network.signal_strength, network.authentication_mode, message);
437 			menu->AddItem(item);
438 			if (associated.find(network.address) != associated.end())
439 				item->SetMarked(true);
440 
441 			count++;
442 		}
443 		if (count == 0) {
444 			BMenuItem* item = new BMenuItem(
445 				B_TRANSLATE("<no wireless networks found>"), NULL);
446 			item->SetEnabled(false);
447 			menu->AddItem(item);
448 		}
449 		menu->AddSeparatorItem();
450 	}
451 
452 	menu->AddItem(new BMenuItem(B_TRANSLATE(
453 		"Open network preferences" B_UTF8_ELLIPSIS),
454 		new BMessage(kMsgOpenNetworkPreferences)));
455 
456 	if (fInDeskbar) {
457 		menu->AddItem(new BMenuItem(B_TRANSLATE("Quit"),
458 			new BMessage(B_QUIT_REQUESTED)));
459 	}
460 	menu->SetTargetForItems(this);
461 
462 	ConvertToScreen(&point);
463 	menu->Go(point, true, true, true);
464 }
465 
466 
467 void
468 NetworkStatusView::_AboutRequested()
469 {
470 	BAboutWindow* window = new BAboutWindow(
471 		B_TRANSLATE_SYSTEM_NAME("NetworkStatus"), kSignature);
472 
473 	const char* authors[] = {
474 		"Axel Dörfler",
475 		"Hugo Santos",
476 		NULL
477 	};
478 
479 	window->AddCopyright(2007, "Haiku, Inc.");
480 	window->AddAuthors(authors);
481 
482 	window->Show();
483 }
484 
485 
486 int32
487 NetworkStatusView::_DetermineInterfaceStatus(
488 	const BNetworkInterface& interface)
489 {
490 	uint32 flags = interface.Flags();
491 
492 	if ((flags & IFF_LINK) == 0)
493 		return kStatusNoLink;
494 	if ((flags & (IFF_UP | IFF_LINK | IFF_CONFIGURING)) == IFF_LINK)
495 		return kStatusLinkNoConfig;
496 	if ((flags & IFF_CONFIGURING) == IFF_CONFIGURING)
497 		return kStatusConnecting;
498 	if ((flags & (IFF_UP | IFF_LINK)) == (IFF_UP | IFF_LINK))
499 		return kStatusReady;
500 
501 	return kStatusUnknown;
502 }
503 
504 
505 void
506 NetworkStatusView::_Update(bool force)
507 {
508 	BNetworkRoster& roster = BNetworkRoster::Default();
509 	BNetworkInterface interface;
510 	uint32 cookie = 0;
511 
512 	while (roster.GetNextInterface(&cookie, interface) == B_OK) {
513 		if ((interface.Flags() & IFF_LOOPBACK) == 0) {
514 			int32 oldStatus = kStatusUnknown;
515 			if (fInterfaceStatuses.find(interface.Name())
516 				!= fInterfaceStatuses.end()) {
517 				oldStatus = fInterfaceStatuses[interface.Name()];
518 			}
519 			int32 status = _DetermineInterfaceStatus(interface);
520 			if (oldStatus != status) {
521 				BNotification notification(B_INFORMATION_NOTIFICATION);
522 				notification.SetGroup(B_TRANSLATE("Network Status"));
523 				notification.SetTitle(interface.Name());
524 				notification.SetMessageID(interface.Name());
525 				notification.SetIcon(fNotifyIcons[status]);
526 				if (status == kStatusConnecting
527 					|| (status == kStatusReady
528 						&& oldStatus == kStatusConnecting)
529 					|| (status == kStatusNoLink
530 						&& oldStatus == kStatusReady)
531 					|| (status == kStatusNoLink
532 						&& oldStatus == kStatusConnecting)) {
533 					// A significant state change, raise notification.
534 					notification.SetContent(kStatusDescriptions[status]);
535 					notification.Send();
536 				}
537 				Invalidate();
538 			}
539 			fInterfaceStatuses[interface.Name()] = status;
540 		}
541 	}
542 }
543 
544 
545 void
546 NetworkStatusView::_OpenNetworksPreferences()
547 {
548 	status_t status = be_roster->Launch("application/x-vnd.Haiku-Network");
549 	if (status != B_OK && status != B_ALREADY_RUNNING) {
550 		BString errorMessage(B_TRANSLATE("Launching the network preflet "
551 			"failed.\n\nError: "));
552 		errorMessage << strerror(status);
553 		BAlert* alert = new BAlert("launch error", errorMessage.String(),
554 			B_TRANSLATE("OK"));
555 		alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE);
556 
557 		// asynchronous alert in order to not block replicant host application
558 		alert->Go(NULL);
559 	}
560 }
561 
562 
563 //	#pragma mark -
564 
565 
566 extern "C" _EXPORT BView *
567 instantiate_deskbar_item(float maxWidth, float maxHeight)
568 {
569 	return new NetworkStatusView(BRect(0, 0, maxHeight - 1, maxHeight - 1),
570 		B_FOLLOW_LEFT | B_FOLLOW_TOP, true);
571 }
572 
573