xref: /haiku/src/apps/haikudepot/util/AppUtils.cpp (revision 151de9ff9b93267bfaf53123004c013fef3e79eb)
1 /*
2  * Copyright 2018-2020, Andrew Lindesay <apl@lindesay.co.nz>.
3  * All rights reserved. Distributed under the terms of the MIT License.
4  */
5 
6 
7 #include "AppUtils.h"
8 
9 #include <string.h>
10 
11 #include <Application.h>
12 #include <MenuItem.h>
13 #include <String.h>
14 
15 #include "HaikuDepotConstants.h"
16 #include "Logger.h"
17 
18 
19 /*! This method can be called to pop up an error in the user interface;
20     typically in a background thread.
21  */
22 
23 /*static*/ void
24 AppUtils::NotifySimpleError(const char* title, const char* text)
25 {
26 	BMessage message(MSG_ALERT_SIMPLE_ERROR);
27 
28 	if (title != NULL && strlen(title) != 0)
29 		message.AddString(KEY_ALERT_TITLE, title);
30 
31 	if (text != NULL && strlen(text) != 0)
32 		message.AddString(KEY_ALERT_TEXT, text);
33 
34 	be_app->PostMessage(&message);
35 }
36 
37 
38 /*static*/ status_t
39 AppUtils::MarkItemWithCodeInMenuOrFirst(const BString& code, BMenu* menu)
40 {
41 	status_t result = AppUtils::MarkItemWithCodeInMenu(code, menu);
42 	if (result != B_OK)
43 		menu->ItemAt(0)->SetMarked(true);
44 	return result;
45 }
46 
47 
48 /*static*/ status_t
49 AppUtils::MarkItemWithCodeInMenu(const BString& code, BMenu* menu)
50 {
51 	if (menu->CountItems() == 0)
52 		HDFATAL("menu contains no items; not able to mark the item");
53 
54 	int32 index = AppUtils::IndexOfCodeInMenu(code, menu);
55 
56 	if (index == -1) {
57 		HDINFO("unable to find the menu item [%s]", code.String());
58 		return B_ERROR;
59 	}
60 
61 	menu->ItemAt(index)->SetMarked(true);
62 	return B_OK;
63 }
64 
65 
66 /*static*/ int32
67 AppUtils::IndexOfCodeInMenu(const BString& code, BMenu* menu)
68 {
69 	BString itemCode;
70 	for (int32 i = 0; i < menu->CountItems(); i++) {
71 		if (AppUtils::GetCodeAtIndexInMenu(menu, i, &itemCode) == B_OK
72 				&& itemCode == code) {
73 			return i;
74 		}
75 	}
76 
77 	return -1;
78 }
79 
80 
81 /*static*/ status_t
82 AppUtils::GetCodeAtIndexInMenu(BMenu* menu, int32 index, BString* result)
83 {
84 	BMessage *itemMessage = menu->ItemAt(index)->Message();
85 	if (itemMessage == NULL)
86 		return B_ERROR;
87 	return itemMessage->FindString("code", result);
88 }
89