xref: /haiku/src/apps/networkstatus/NetworkStatusView.cpp (revision 7d6915b4d08ffe728cd38af02843d5e98ddfe0db)
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(void);
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_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 	if (Parent() != NULL) {
236 		if ((Parent()->Flags() & B_DRAW_ON_CHILDREN) != 0)
237 			SetViewColor(B_TRANSPARENT_COLOR);
238 		else
239 			SetViewColor(Parent()->ViewColor());
240 	} else
241 		SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
242 
243 	SetLowColor(ViewColor());
244 
245 	start_watching_network(
246 		B_WATCH_NETWORK_INTERFACE_CHANGES | B_WATCH_NETWORK_LINK_CHANGES, this);
247 
248 	_Update();
249 }
250 
251 
252 void
253 NetworkStatusView::DetachedFromWindow()
254 {
255 	stop_watching_network(this);
256 }
257 
258 
259 void
260 NetworkStatusView::MessageReceived(BMessage* message)
261 {
262 	switch (message->what) {
263 		case B_NETWORK_MONITOR:
264 			_Update();
265 			break;
266 
267 		case kMsgShowConfiguration:
268 			_ShowConfiguration(message);
269 			break;
270 
271 		case kMsgOpenNetworkPreferences:
272 			_OpenNetworksPreferences();
273 			break;
274 
275 		case kMsgJoinNetwork:
276 		{
277 			const char* deviceName;
278 			const char* name;
279 			BNetworkAddress address;
280 			if (message->FindString("device", &deviceName) == B_OK
281 				&& message->FindString("name", &name) == B_OK
282 				&& message->FindFlat("address", &address) == B_OK) {
283 				BNetworkDevice device(deviceName);
284 				status_t status = device.JoinNetwork(address);
285 				if (status != B_OK) {
286 					BString text
287 						= B_TRANSLATE("Could not join wireless network:\n");
288 					text << strerror(status);
289 					BAlert* alert = new BAlert(name, text.String(),
290 						B_TRANSLATE("OK"), NULL, NULL, B_WIDTH_AS_USUAL,
291 						B_STOP_ALERT);
292 					alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE);
293 					alert->Go(NULL);
294 				}
295 			}
296 			break;
297 		}
298 
299 		case B_ABOUT_REQUESTED:
300 			_AboutRequested();
301 			break;
302 
303 		case B_QUIT_REQUESTED:
304 			_Quit();
305 			break;
306 
307 		default:
308 			BView::MessageReceived(message);
309 	}
310 }
311 
312 
313 void
314 NetworkStatusView::FrameResized(float width, float height)
315 {
316 	_UpdateBitmaps();
317 	Invalidate();
318 }
319 
320 
321 void
322 NetworkStatusView::Draw(BRect updateRect)
323 {
324 	int32 status = kStatusUnknown;
325 	for (std::map<BString, int32>::const_iterator it
326 		= fInterfaceStatuses.begin(); it != fInterfaceStatuses.end(); ++it) {
327 		if (it->second > status)
328 			status = it->second;
329 	}
330 
331 	if (fTrayIcons[status] == NULL)
332 		return;
333 
334 	SetDrawingMode(B_OP_ALPHA);
335 	DrawBitmap(fTrayIcons[status]);
336 	SetDrawingMode(B_OP_COPY);
337 }
338 
339 
340 void
341 NetworkStatusView::_ShowConfiguration(BMessage* message)
342 {
343 	const char* name;
344 	if (message->FindString("interface", &name) != B_OK)
345 		return;
346 
347 	BNetworkInterface networkInterface(name);
348 	if (!networkInterface.Exists())
349 		return;
350 
351 	BNetworkInterfaceAddress address;
352 	networkInterface.GetAddressAt(0, address);
353 		// TODO: We should get all addresses,
354 		// not just the first one.
355 	BString text(B_TRANSLATE("%ifaceName information:\n"));
356 	text.ReplaceFirst("%ifaceName", name);
357 
358 	size_t boldLength = text.Length();
359 
360 	text << "\n" << B_TRANSLATE("Address") << ": " << address.Address().ToString();
361 	text << "\n" << B_TRANSLATE("Broadcast") << ": " << address.Broadcast().ToString();
362 	text << "\n" << B_TRANSLATE("Netmask") << ": " << address.Mask().ToString();
363 
364 	BAlert* alert = new BAlert(name, text.String(), B_TRANSLATE("OK"));
365 	alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE);
366 	BTextView* view = alert->TextView();
367 	BFont font;
368 
369 	view->SetStylable(true);
370 	view->GetFont(&font);
371 	font.SetFace(B_BOLD_FACE);
372 	view->SetFontAndColor(0, boldLength, &font);
373 
374 	alert->Go(NULL);
375 }
376 
377 
378 void
379 NetworkStatusView::MouseDown(BPoint point)
380 {
381 	BPopUpMenu* menu = new BPopUpMenu(B_EMPTY_STRING, false, false);
382 	menu->SetAsyncAutoDestruct(true);
383 	menu->SetFont(be_plain_font);
384 	BString wifiInterface;
385 	BNetworkDevice wifiDevice;
386 
387 	// Add interfaces
388 
389 	for (std::map<BString, int32>::const_iterator it
390 		= fInterfaceStatuses.begin(); it != fInterfaceStatuses.end(); ++it) {
391 		const BString& name = it->first;
392 
393 		BString label = name;
394 		label += ": ";
395 		label += kStatusDescriptions[
396 			_DetermineInterfaceStatus(name.String())];
397 
398 		BMessage* info = new BMessage(kMsgShowConfiguration);
399 		info->AddString("interface", name.String());
400 		menu->AddItem(new BMenuItem(label.String(), info));
401 
402 		// We only show the networks of the first wireless device we find.
403 		if (wifiInterface.IsEmpty()) {
404 			wifiDevice.SetTo(name);
405 			if (wifiDevice.IsWireless())
406 				wifiInterface = name;
407 		}
408 	}
409 
410 	if (!fInterfaceStatuses.empty())
411 		menu->AddSeparatorItem();
412 
413 	// Add wireless networks, if any
414 
415 	if (!wifiInterface.IsEmpty()) {
416 		std::set<BNetworkAddress> associated;
417 		BNetworkAddress address;
418 		uint32 cookie = 0;
419 		while (wifiDevice.GetNextAssociatedNetwork(cookie, address) == B_OK)
420 			associated.insert(address);
421 
422 		cookie = 0;
423 		wireless_network network;
424 		typedef std::vector<wireless_network> WirelessNetworkVector;
425 		WirelessNetworkVector wirelessNetworks;
426 		while (wifiDevice.GetNextNetwork(cookie, network) == B_OK)
427 			wirelessNetworks.push_back(network);
428 
429 		std::sort(wirelessNetworks.begin(), wirelessNetworks.end(),
430 			signal_strength_compare);
431 
432 		int32 count = 0;
433 		for (WirelessNetworkVector::iterator it = wirelessNetworks.begin();
434 				it != wirelessNetworks.end(); it++) {
435 			wireless_network &network = *it;
436 
437 			BMessage* message = new BMessage(kMsgJoinNetwork);
438 			message->AddString("device", wifiInterface);
439 			message->AddString("name", network.name);
440 			message->AddFlat("address", &network.address);
441 
442 			BMenuItem* item = new WirelessNetworkMenuItem(network.name,
443 				network.signal_strength, network.authentication_mode, message);
444 			menu->AddItem(item);
445 			if (associated.find(network.address) != associated.end())
446 				item->SetMarked(true);
447 
448 			count++;
449 		}
450 		if (count == 0) {
451 			BMenuItem* item = new BMenuItem(
452 				B_TRANSLATE("<no wireless networks found>"), NULL);
453 			item->SetEnabled(false);
454 			menu->AddItem(item);
455 		}
456 		menu->AddSeparatorItem();
457 	}
458 
459 	menu->AddItem(new BMenuItem(B_TRANSLATE(
460 		"Open network preferences" B_UTF8_ELLIPSIS),
461 		new BMessage(kMsgOpenNetworkPreferences)));
462 
463 	if (fInDeskbar) {
464 		menu->AddItem(new BMenuItem(B_TRANSLATE("Quit"),
465 			new BMessage(B_QUIT_REQUESTED)));
466 	}
467 	menu->SetTargetForItems(this);
468 
469 	ConvertToScreen(&point);
470 	menu->Go(point, true, true, true);
471 }
472 
473 
474 void
475 NetworkStatusView::_AboutRequested()
476 {
477 	BAboutWindow* window = new BAboutWindow(
478 		B_TRANSLATE_SYSTEM_NAME("NetworkStatus"), kSignature);
479 
480 	const char* authors[] = {
481 		"Axel Dörfler",
482 		"Hugo Santos",
483 		NULL
484 	};
485 
486 	window->AddCopyright(2007, "Haiku, Inc.");
487 	window->AddAuthors(authors);
488 
489 	window->Show();
490 }
491 
492 
493 int32
494 NetworkStatusView::_DetermineInterfaceStatus(
495 	const BNetworkInterface& interface)
496 {
497 	uint32 flags = interface.Flags();
498 	int32 status = kStatusNoLink;
499 
500 	// TODO: no kStatusLinkNoConfig yet
501 
502 	if (flags & IFF_CONFIGURING)
503 		status = kStatusConnecting;
504 	else if ((flags & (IFF_UP | IFF_LINK)) == (IFF_UP | IFF_LINK))
505 		status = kStatusReady;
506 
507 	return status;
508 }
509 
510 
511 void
512 NetworkStatusView::_Update(bool force)
513 {
514 	BNetworkRoster& roster = BNetworkRoster::Default();
515 	BNetworkInterface interface;
516 	uint32 cookie = 0;
517 
518 	while (roster.GetNextInterface(&cookie, interface) == B_OK) {
519 		if ((interface.Flags() & IFF_LOOPBACK) == 0) {
520 			int32 oldStatus = kStatusUnknown;
521 			if (fInterfaceStatuses.find(interface.Name())
522 				!= fInterfaceStatuses.end()) {
523 				oldStatus = fInterfaceStatuses[interface.Name()];
524 			}
525 			int32 status = _DetermineInterfaceStatus(interface);
526 			if (oldStatus != status) {
527 				BNotification notification(B_INFORMATION_NOTIFICATION);
528 				notification.SetGroup(B_TRANSLATE("Network Status"));
529 				notification.SetTitle(interface.Name());
530 				notification.SetMessageID(interface.Name());
531 				notification.SetIcon(fNotifyIcons[status]);
532 				if (status == kStatusConnecting
533 					|| (status == kStatusReady
534 						&& oldStatus == kStatusConnecting)
535 					|| (status == kStatusNoLink
536 						&& oldStatus == kStatusReady)
537 					|| (status == kStatusNoLink
538 						&& oldStatus == kStatusConnecting)) {
539 					// A significant state change, raise notification.
540 					notification.SetContent(kStatusDescriptions[status]);
541 					notification.Send();
542 				}
543 				Invalidate();
544 			}
545 			fInterfaceStatuses[interface.Name()] = status;
546 		}
547 	}
548 }
549 
550 
551 void
552 NetworkStatusView::_OpenNetworksPreferences()
553 {
554 	status_t status = be_roster->Launch("application/x-vnd.Haiku-Network");
555 	if (status != B_OK && status != B_ALREADY_RUNNING) {
556 		BString errorMessage(B_TRANSLATE("Launching the network preflet "
557 			"failed.\n\nError: "));
558 		errorMessage << strerror(status);
559 		BAlert* alert = new BAlert("launch error", errorMessage.String(),
560 			B_TRANSLATE("OK"));
561 		alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE);
562 
563 		// asynchronous alert in order to not block replicant host application
564 		alert->Go(NULL);
565 	}
566 }
567 
568 
569 //	#pragma mark -
570 
571 
572 extern "C" _EXPORT BView *
573 instantiate_deskbar_item(void)
574 {
575 	return new NetworkStatusView(BRect(0, 0, 15, 15),
576 		B_FOLLOW_LEFT | B_FOLLOW_TOP, true);
577 }
578 
579