Text language based decision making - c

I am currently developing with MPLAB X (IDE) on PIC32 platforms using C programming language.
I have a MAJOR project coming up which includes displaying graphics and text on a TFT screen.
We develop our systems for multiple languages ,including languages written "right to left" & "left to right".
So some symbols also change their position, and texts change their alignments on the screen.
So far Iv'e seen my former developer implement the code in a way that every screen displayed, or every object presented on the screen is tested for the language selected and then takes actions accordingly.
e.g:
/**Some actions shared by all the languages**/
.
.
/* language specific actions: */
if(language == lang1){
.
.
/* Performs some actions */
/* e.g: */
displayText(txt, LEFT_ALIGNED);
.
.
} else if(language == lang2){
.
.
/**SAME** actions with only minor changes depending on the language selected. */
/* e.g: */
displayText(txt, RIGHT_ALIGNED);
.
.
} else if.... (and so on)
As you can see, it seems quite an overhead, and the code this way has a lot of superfluous code duplication, especially when this structure is repeated inside almost every function/source file.
I am trying to think of an approach for developing more of a "polymorphic" structure that would not require so many "if else" statements.
I tried to search the internet for some examples implementing text based decision making, but was unable to find what I need, mostly due to the fact that I find it hard to describe my question.
I hope this is not somewhat a vague question,
but is there any structural consensus for implementing this kind of situations?
Many Thanks,
Tsoof A.

I would go for an array of language/action structures, then search the array for the language in question, and execute the associated action:
typedef struct {
char *lang;
void (*action)();
} action_t;
action_t actions[] = {{"en", func1}, {"de", func2}, ...};
...
for(int i = 0; i < sizeof(actions)/sizeof(actions[0]); i++)
if(!strcmp(actions[i].lang, language)) {
actions[i].action();
break;
}

Related

How do I get access to GUI elements in a IUP dialog loaded from a LED file?

I’m in love with IUP! However I cannot figure out how to get programmatic access (in C) to GUI elements in a dialog loaded by IupLoad() from a LED file.
One extremely laborious way would be to edit the LED file so as to manually give handle names to each single GUI element, then manually define corresponding variables for each element in C, then manually load handles into each variable by using IupGetHandle().
One comfortable way to do it would be to convert the LED file to a C header file using the built-in Layout Dialog tool. The resulting code makes each element available to the application in a simple array called Ihandle* containers[]. But this way deprives us of the benefits of LED files, such as the ability to edit GUI of a binary application by the user and keeping the C code small.
Is there no good way to do it?
Do I overrate the benefits of a third way, if it existed?
I cannot find any IupLoad() example in the directory with C examples.
My own example below explicitly defines one handle name for the top element (dialog) only. It features a very simple dialog where defining each element manually wouldn’t be a hard work at all. But this is only a test example for Stack Overflow and my question is relevant to complex dialogs.
C file:
#include <stdlib.h>
#include <iup.h>
int main(int argc, char **argv)
{
IupSetGlobal("UTF8MODE", "YES");
// IupSetGlobal("UTF8MODE_FILE", "YES");
IupOpen(&argc, &argv);
if(IupLoad("dropdown.led")) IupMessage("Error", "Failed to load LED.");
else {
Ihandle *dropdown = IupGetHandle("dropdown");
IupShow(dropdown);
IupMainLoop();
}
IupClose();
return EXIT_SUCCESS;
}
Corresponding dropdown.led file:
dropdown = DIALOG[TITLE=dropdown.led](
HBOX[CMARGIN=10x10,CGAP=10](
LIST[VALUE=3, 1=я, 2=ты, 3=оно, 4=мы, 5=вы, 6=они, DROPDOWN=YES](do_nothing),
LIST[VALUE=3, 1=ik, 2=je, 3=hij, 4=we, DROPDOWN=YES](do_nothing)
)
)
Which brings us to another question: how can I make Russian characters visible? But this issue is owed a separate thread which I will accordingly create.
All questions that pertain to this particular example:
How do I get access to GUI elements in a IUP dialog loaded from a LED file? (current)
How can I make Russian letters visible in a IUP dialog loaded from a LED file?
A gap in IUP dropdown lists
The way os to use IupGetHandle to get access to some element then use IupGetChild*, GetBrother, GetParent functions to get the element you want.
Another option is to use the NAME attribute. You set it on the element you want then use IupGetDialogChild to retrieve the element given the NAME value.

How to draw flowchart for code involving opening from text file and reading them

like this code
fp1=fopen("Fruit.txt","r");
if(fp1==NULL)
{
printf("ERROR in opening file\n");
return 1;
}
else
{
for(i=0;i<lines;i++)//reads Fruits.txt database
{
fgets(product,sizeof(product),fp1);
id[i]=atoi(strtok(product,","));
strcpy(name[i],strtok(NULL,","));
price[i]=atof(strtok(NULL,","));
stock[i]=atoi(strtok(NULL,"\n"));
}
}
fclose(fp1);
These symbols sound too similar to differentiate their function,can anyone helps me by any method, or use names of shape according to this site http://www.breezetree.com/article-excel-flowchart-shapes.htm
REF:
Used a random online tool to generate this flowchart from your code. http://code2flow.com/
Study more about flowcharts here : http://creately.com/blog/diagrams/flowchart-guide-flowchart-tutorial/
See sample flowcharts here : http://www.conceptdraw.com/samples/flowcharts
Back in the days of FORTRAN, we used that hexagonal symbol on the page you linked to for the "DO" loop, which is basically the same as the modern "for" loop.
So, to draw the loop part of your program I would use that symbol, with a note inside like this:
for i = 0 --> (lines - 1)
Read this as "for i from 0 to (lines - 1)" with the increment of 1 implied by default.
Then the bottom-most box in the loop would have two arrows coming out of it: one straight down to the next statement, and one out the side heading back up to the side of the hexagon.
You could use the diamond to represent "if", but that can obscure the meaning of what you are trying to do, namely execute the loop a certain number of times.
BTW, I don't have high enough reputation yet to post images, so you will have to either follow the link or visualize a hexagon whose center section has been stretched horizontally.
Update: I see that, while I was typing my answer, thecbuilder has also answered this, with a real flowchart. His illustrates how the loop actually works internally, which is fine; mine was intended to show the meaning of the loop on a slightly higher level of abstraction.

embedded software structure for sublevel screens and menus

I'm new into embedded c programming and I need some advice.
I'm trying to create a menu structure with underneath screens on an embedded system, the OS code and the drawing/menu libraries are ready, but I can't figure out how I'd design this system.
it'll have :
menus and submenus
password screens that user can authenticate before entering some menu items
and the screens beneath them.
I wrote some code that's working and still feels like I'm writing procedural spagetti code. And I'm new to embedded c systems so I don't know if I can use classes or objects inside the code. I'd be grateful if someone shows me the right way to do this. I'm experienced about programming anything else BTW so feel free with the tech talk. ;)
BTW the menu code is structured like this:
menu myMenu;
entry* myMenuEntries;
int selection = 0;
myMenuEntries[0] = [entry definer code];
...
myMenu.entries = (entry *) myMenuEntries;
selection = DisplayMenu(myMenu);
switch(selection){
case 0: exit(); break;
}
How can I create an object in embedded c like it's used in myMenu.entries?
I would definitely use object oriented C here, like you suspect is possible. There are lots of references to how to do oop in C on stack overflow. You make classes out of structs and use function pointers as the member functions which can then be overridden if you want polymorphism.
Each screen could have on onEnter(), for example, to initialize stuff when the screen is loaded, and you could have a drawable class that can encompass strings, primitives, images, etc that know how to draw themselves at any x,y coordinate. You could also have a standard screen object which is made up of a list of the objects on the screen, their coordinates, and contents. These could be initialized at compile time, too, in a big table.
(I've done all this on a DSP using C and ASM)
There are also ready made libraries that can do this. I know that micrium has one. I'm on my phone or I'd Google it and put the link here.

Using Windows Forms and VC++ with Unmanaged Static Libraries

I am currently trying to write a UI for a Data Acquistion System in Visual Studio C++ 2010, and I am having a lot of trouble dealing with the interfacing of the third party libraries I am using and Windows Forms. The two libraries I am using are DAQX, a C library for a Data Acqustion System, and VITCam, a C++ library for a 1394 High Speed Camera. It's extremely frustrating trying to work with these libraries and any UI library that VS has to offer, as none of the function arguments ever get along.
DAQX uses windows types like WORD and DWORD, in normal C fashion, and when I'm writing a normal program, no UI involved, it works fine, but Windows Forms seems to hate anytime I want to make a simple DWORD Array inside the class.
VITCam is even worse. I can open the camera fine, but I am completely lost when it comes to trying to put the image on the screen somehow. I haven't uncovered an equivalanet, easy to follow way for putting it to the screen as to how the documentation puts it:
CDC* pDC=GetDC(); // obtain the device context for your window...
// move the image data
::SetDIBitsToDevice(pDC->m_hDC,0,0,
(int) (MyCam.GetDispBuf()->bmiHeader.biWidth),
(int) (MyCam.GetDispBuf()->bmiHeader.biHeight),
0,0,0,(WORD) (WORD) MyCam.GetDispBuf()->bmiHeader.biHeight,
MyCam.GetDispPixels(),MyCam.GetDispBuf(),
DIB_RGB_COLORS);
I can barely follow it as is. So, without doing to much blathering, How do most people work with static unmanaged libraries that were not developed with Windows Forms in mind? I've tried MFC as the VITCam documentations mentioned it, but it makes very little sense and isn't as intuitive as Windows Forms feels.
Edit:
This is the error message I get when trying to use a normal (at least to me) array.
Error 1 error C4368: cannot define 'buffer' as a member of managed 'WirelessHeadImpact::Form1': mixed types are not supported
And it points to this line:
private:
WORD buffer[BUFFSIZE*CHANCOUNT];
What I had before was this:
static array<WORD>^ _buffer;
And within a function I create the former array, pass it to the function, then return the latter after looping through and updating the array.
WORD buffer[BUFFSIZE*CHANCOUNT];
DWORD scansCollected = 0;
while (total_scans < SCANS) {
daqAdcTransferBufData(_handle, buffer, BUFFSIZE, DabtmWait, &scansCollected);
if (scansCollected > 0) {
for (WORD i=0;i<scansCollected;i++) {
_buffer[i] = buffer[i];
}
mixed type support is removed in Visual C++ 2005. If you want to associate a DWORD array to a managed class, use new (not gcnew) to allocate the array itself on the native heap and save the pointer of the array in the class.
by the way, you cannot pass addresses of objects on the managed heap to a native function without pinning the object, otherwise the GC is free to move the object at any time. If you want to pass a managed value to a native function, make sure your pass by value or the object is pinned.
It helps the readers if you post the actual error message you are getting, instead of having to guess out from your question.

Does bracket placement affect readability? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicates:
Formatting of if Statements
Is there a best coding style for identations (same line, next line)?
Best way to code stackoverflow style 'questions' / 'tags' rollover buttons
public void Method {
}
or
public void Method
{
}
Besides personal preference is there any benefit of one style over another? I used to swear by the second method though now use the first style for work and personal projects.
By readability I mean imagine code in those methods - if/else etc...
Google C++ Style Guide suggests
Return type on the same line as function name, parameters on the same line if they fit.
Functions look like this:
ReturnType ClassName::FunctionName(Type par_name1, Type par_name2) {
DoSomething();
...
}
WebKit Coding Style Guidelines suggests
Function definitions: place each brace on its own line.
Right:
int main()
{
...
}
Wrong:
int main() {
...
}
They suggest braces-on-same-line for everything else, though.
GNU Coding Standards suggests
It is important to put the open-brace that starts the body of a C function in column one, so that they will start a defun. Several tools look for open-braces in column one to find the beginnings of C functions. These tools will not work on code not formatted that way.
Avoid putting open-brace, open-parenthesis or open-bracket in column one when they are inside a function, so that they won't start a defun. The open-brace that starts a struct body can go in column one if you find it useful to treat that definition as a defun.
It is also important for function definitions to start the name of the function in column one. This helps people to search for function definitions, and may also help certain tools recognize them. Thus, using Standard C syntax, the format is this:
static char *
concat (char *s1, char *s2)
{
...
}
or, if you want to use traditional C syntax, format the definition like this:
static char *
concat (s1, s2) /* Name starts in column one here */
char *s1, *s2;
{ /* Open brace in column one here */
...
}
As you can see, everybody has their own opinions. Personally, I prefer the Perl-ish braces-on-same-line-except-for-else, but as long as everybody working on the code can cooperate, it really doesn't matter.
I think it is completely subjective, however, I think it is important to establish code standards for your team and have everyone use the same style. That being said I like the second one (and have made my team use it) because it seems easier to read when it is not your code.
In the old days we used to use the first style (K & R style) because screens were smaller and code was often printed onto this stuff called paper.
These days we have big screen and the second method (ANSI style) makes it easier to see if your brackets match up.
See HERE and HERE for more information.
First one is smaller in terms of number of lines (maybe that is why development -Java- books tend to use that syntax)
Second one is, IMHO easier to read as you always have two aligned brackets.
Anyway both of them are widely used, it's a matter of your personal preferences.
I use the if statement as something to reason on in this highly emotive subject.
if (cond) {
//code
}
by just asking what does the else statement look like? The logical extension of the above is:-
if (cond) {
//code
} else {
//more code
}
Is that readable? I don't think so and its just plain ugly too.
More lines is != less readable. Hence I'd go with your latter option.
Personally I find the second one more readable (aligned curlys).
Its always easiest for a team to go with the defaults, and since Visual Studio and I agree on this, thats my argument. ;-)
Your lines of code count will be considerably less with the first option. :)

Resources