Avoid repetitive code in Objective C - c++

I have two very similar methods in a C++ class. The only difference is the Objective-C methods that get called inside:
void MyClass::loadFromImage(UIImage *image)
{
// ... Prepare dictionary and error
GLKTextureInfo* info = [GLKTextureLoader textureWithCGImage:image.CGImage options:options error:&err];
// ... Use GLKTexureInfo to load a texture
}
void Surface::loadFromImage(const char* imageName)
{
// ... Prepare dictionary and error
GLKTextureInfo* info = [GLKTextureLoader textureWithContentsOfFile:path options:options error:&err];
// ... Use GLKTexureInfo to load a texture
}
How can I combine these two methods to reduce redundant code?
I am hoping to do something similar to this thread, but not sure how the syntax should work out in Objective-C. Thank you for help!

Replace
// ... Prepare dictionary and error
and
// ... Use GLKTexureInfo to load a texture
with methods that can be used by both versions of loadFromImage.
Yay code reuse!

Related

How to use custom C++ attributes with Clang libTooling without modifying Clang code?

I'm writing some kind of tool that extracts the interface definitions of C++ code.
In process of writing, I decided to restrict the parser to process only the code that was explicitly marked for processing, and I thought that C++ attributes are the best way to do it.
I'd prefer to add e.g. [[export]] annotations to entities I want to export, but I realised that libTooling is unable to see custom attributes without registering them in Clang code itself (I mean adding the attribute to tools/clang/include/clang/Basic/Attr.td).
Thus, my question is: is there a way to register the attribute without modifying that file (e.g. by registering the attribute programmatically or writing own Attr.td file)?
UPD: I'm using ASTMatchers library for source code analysis, so visitor-based approach probably does not work for me.
From what I can tell it is not possible to register custom attributes without directly modifying libtooling.
If you're willing to use pre-processor macros instead of attributes there is a workaround that I've done in the past. The basics are that we'll declare an empty macro, write a pre-processor callback to identify the location of the macro and store it in a queue, then in an AST visitor we'll visit records for either classes, methods, or variables, and check to see if preceeding the entity is our macro.
For the preprocessor you'll need to extend clang::PPCallbacks and implement the MacroExpands method.
void MyPreProcessorCallback::MacroExpands(const clang::Token& MacroNameTok, const clang::MacroDefinition&, const clang::SourceRange Range, const clang::MacroArgs* const Args)
{
// Macro is not named for some reason.
if(!MacroNameTok.isAnyIdentifier())
{ return; }
if(MacroNameTok.getIdentifierInfo()->getName() == "EXPORT")
{
// Save Range into a queue.
}
else
{
return;
}
// If you want arguments you can declare the macro to have varargs and loop
// through the tokens, you can have any syntax you want as they're raw tokens.
// /* Get the argument list for this macro, because it's a
// varargs function all arguments are stored in argument 0. */
// const ::clang::Token* token = Args->getUnexpArgument(0u);
// // All tokens for the argument are stored in sequence.
// for(; token->isNot(::clang::tok::eof); ++token)
// {
// }
}
Inside your RecursiveAstVisitor you can implement visitors that will pop off the top of the queue and check to see if the top macro is before in the translation unit. IIRC visitors of a type are all executed in order of declaration, so the queue should maintain the order. It is worth noting that all Decl's of a type are visited in order, so care has to be taken when distinguishing between function, variables, and classes.
bool MyAstVisitor::VisitFunctionDecl(::clang::FunctionDecl* const function)
{
if(::llvm::isa<::clang::CXXMethodDecl>(function))
{
// If you want to handle class member methods separately you
// can check here or implement `VisitCXXMethodDecl` and fast exit here.
}
if(ourExportTags.empty())
{
return true;
}
const ::clang::SourceLocation tagLoc = ourExportTags.front().getBegin();
const ::clang::SourceLocation declLoc = function->getBeginLoc();
if(getAstContext().getSourceManager().isBeforeInTranslationUnit(tagLoc, declLoc))
{
ourExportTags.pop_front();
// Handle export;
}
return true;
}
EDIT
I haven't used ASTMatchers before, but you could probably accomplish a similar result by writing a matcher, storing all of the declarations to a list, sorting based on location, and then comparing to the original export tag queue.
DeclarationMatcher matcher = functionDecl().bind("funcDecl");
class MyFuncMatcher : public clang::ast_matchers::MatchFinder::MatchCallback
{
public:
virtual void run(const clang::ast_matchers::MatchFinder::MatchResult& Result)
{
if(const FunctionDecl* func = Result.Nodes.getNodeAs<clang::FunctionDecl>("funcDecl"))
{
// Add to list for future processing
}
}
};
void joinTagsToDeclarations()
{
// Sort the declaration list
for(auto decl : myDeclList)
{
if(ourExportTags.empty())
{
break;
}
const ::clang::SourceLocation tagLoc = ourExportTags.front().getBegin();
const ::clang::SourceLocation declLoc = decl->getBeginLoc();
if(getAstContext().getSourceManager().isBeforeInTranslationUnit(tagLoc, declLoc))
{
ourExportTags.pop_front();
// Handle export;
}
}
}

How to modularize shaders in Processing 3.x

I'd like to use the same noise function throughout various .glsl files without copying and pasting code every time.
What is the processing way to achieve this ?
Afaik, there is no way to do this dynamically in Processing. However, you can separately compile your shaders with glslify, which is a GLSL compile-time include system.
glslify (https://github.com/glslify/glslify) is a bit of overkill, though. Whenever I make an OpenGL / GLSL application, I roll my own system.
Something like this (taken from my Java OpenGL Minecraft clone here):
private static String process(String code){
String[]lines=code.split("\n");
for(int i=0;i<lines.length;i++){
if(lines[i].startsWith("#include : ")){
lines[i]=process(Utils.loadFile("path_to_include_directory/"+lines[i].replace("#include : ","")+".glsl"));
}
}
StringBuilder str= new StringBuilder();
for(String s:lines){
str.append(s).append("\n");
}
return str.toString();
}
This code does a copy-paste on includes. Usage:
///// MAIN FILE
#include : bar_module
float foo(vec3 p){
return bar(p * 5.0);
}
///// path_to_include_directory/bar_module.glsl
float bar(vec3 p) {
/* ... ... */
}
This is a recursive includes mechanism, fairly efficient, at runtime. No static compilation needed!
The only downside is that circular dependencies aren't detected. But you shouldn't be in a situation with circular dependencies anyway :)
DISCLAIMER
I don't actually remember how this stuff works, but I think this is the general idea:
File file=new File("my_shader.vert");
file.setContents(process(file.readContents()));
PShader my_shader=new PShader("my_shader");
NOTE: setContents and readContents don't actually exist, but you get the idea :)
PS
Utils.loadFile returns the contents of the filename passed in as a String.

Creating and freeing a temporary dummy variable in C++

I'm using the Qt framework to create a ui for my business logic.
The class responsible for building the ui provides several methods which, step by step, initialize the ui elements, layout them, group them and, finally, format (i.e. void MyUi::init3_formatUiElements()) them.
Naturally, some ui elements need numerous layout settings set, so this method might look like
void MyUi::init3_formatUiElements() {
_spinBox_distance->setMinimum(0.0);
_spinBox_distance->setMaximum(10.0);
_spinBox_distance->setSingleStep(0.5);
_spinBox_distance->setSuffix(" meters");
//...
//same for other widgets
return;
}
Objects like QDoubleSpinBox* _spinBox_distance are member fields of the MyUi class.
I would like to have a "temporary alias" for _spinBox_distance, in that the above method body simplifies to
void MyUi::init3_formatUiElements() {
//create alias x for _spinBox_distance here
x->setMinimum(0.0);
x->setMaximum(10.0);
x->setSingleStep(0.5);
x->setSuffix(" meters");
//...
//free alias x here
//same for other widgets: create alias x for next widget
//...
//free alias x here
return;
}
This would speed up the typing process and would make code fragments more copy/paste-able, especially for ui elements of a similar type.
Apart from scoping each block in curly braces
{ QDoubleSpinBox*& x = _spinBox_distance;
x->setMinimum(0.0);
//...
}
{ QLabel*& x = _label_someOtherWidget;
//...
}
is there an elegant way to achieve this?
I tried the above syntax without scoping, but destructing x then of course leads to destruction of the underlying widget.
Maybe
QDoubleSpinBox** x = new QDoubleSpinBox*;
x = &_spinBox_distance;
(*x)->setMinimum(0.0);
//...
delete x;
but that doesn't make things much more type-easy (three extra lines, pointers to pointers, (*x))... :D
EDIT: This one does not work as after delete x, can't be redeclared another type.
What about using a macro ?
#define Set(argument) _spinBox_distance->set##argument
and
Set(Minimum(0.0));
Set(Maximum(10.0));
Set(SingleStep(0.5));
Set(Suffix(" meters"));
Or
#define Set(Argument, Value) _spinBox_distance->set##argument(Value)
Set(Minimum, 0.0);
Set(Maximum, 10.0);
Set(SingleStep, 0.5);
Set(Suffix, " meters");
Collecting the fundamental conceptual thoughts about the problem in question from the comments section, I may post the syntactical/technical answer to the question. This approach, without a doubt, should not be chosen in any kind of "complex" situation (or rather not at all).
bad coding style:
same name for different things
name which doesn't tell you anything about the object
move repeated code to dedicated functions, which...
may specialize on several ui types
are template functions
...
in case of Qt: Use Qt Designer.
...
{ auto x = _spinBox_distance;
x->setMinimum(0.0);
//...
}
{ auto x = _label_someOtherWidget;
//...
}
will do the trick.
I think your code looks fine as it is, I find it much more useful to have the code be easy to read/understand than it is to have the code be easy to write. Remember that you write the code once, then have to read it many times afterwards.
In cases like this I make it easier to write with good old (and oft blamed for mistakes) copy and paste. Grab _spinBox_distance->set and just paste, finish the line, paste, finish the line, etc...
If, however, you find yourself writing those 4 setters in a row over and over again, then put them in 1 function that takes in the 4 parameters.
void SetParameters(QDoubleSpinBox* spinBox_distance, double min, double max, double step, std::string suffix)
{
//the setters
}

How do you abstract the information to be displayed in a screen?

I'm writing an application that requires me to write information to a TFT display (kinda like a gameboy display).
I'm outputting the information to the display line by line. The way I'm doing it now requires me to have a function for each different screen.
Like:
void displayWelcomeMessage();
void displayInsertCoinMessage();
void displayGoodByeMessage();
Each function follows this logic:
void displaWelcomeMessage()
{
writeline(0, "Hi David");
writeline(1, "Welcome");
writeline(2, "Back!");
}
Problem: I hate to have a different function for each screen. It's not scalable at all, imagine if I had 500 different screens.
How do I abstract the process of writing to the display? So that I end up with a single generic function responsible for writing to the display.
Thank you
Update
Following "Useless's" and Michael.P's advice, what I will probably end up doing is storing the format of each message in a file:
DisplayMessages.cfg
WELCOME_MESSAGE_1 = "Hi %name"
WELCOME_MESSAGE_2 = "Welcome"
WELCOME_MESSAGE_3 = "back!"
And in the code I will do something like:
using Message = std::vector<QString>;
void login(){
//Do Stuff...
QString line
Message welcomeMessage;
line=getMessageStructureFromCfg("WELCOME_MESSAGE_1").arg(userName); // loads "Hi %name" and replaces %name with the content of userName
welcomeMessage.pushBack(line); // pushes the first line to welcomeMessage
line=getMessageStructureFromCfg("WELCOME_MESSAGE_2"); // loads "Welcome"
welcomeMessage.pushBack(line); // pushes the second line to welcomeMessage
line=getMessageStructureFromCfg("WELCOME_MESSAGE_3"); // loads "back!"
welcomeMessage.pushBack(line); // pushes the third line to welcomeMessage
displayMessage(welcomeMessage);
}
void displayMessage(Message const &msg) {
int i = 0;
for (auto &line : msg) {
writeline(i, line);
i++;
}
}
Thank you all for your help!
PS: Further improvements can be made if the file containing the messages structure used JSON instead of plain text. This way you could just iterate the child members(the lines) of each message and process accordingly
How do you abstract the information to be displayed in a screen?
The same way you abstract any information - you move the data out of the code and into a data structure.
Your displayXMessage() functions perform a fixed sequence of calls on a fixed sequence of hardcoded string literals. So, split the algorithm from the data the usual way, by passing the data as an argument:
using Message = std::vector<std::pair<int, std::string>>;
void displayMessage(Message const &msg) {
for (auto &line : msg) {
writeline(line.first, line.second);
}
}
and call it with the appropriate data:
Message welcomeMsg { {0, "Hi David"},
{1, "Welcome"},
{2, "Back!"}
};
displayMessage(welcomeMsg);
I think you will find a solution to all those kind of problems by learning design patterns. In this case in particular. Strucural patterns seem to be what you are looking for; you will then have to pick the pattern which fits the most what you are trying to do.

Simplest way to bind C++ methods to an existing JS function's prototype?

I have several simple C++ classes, for example:
class Audio {
public:
Audio(const char *filename, bool async = true);
~Audio();
Audio *play(int fade = 0);
Audio *pause();
Audio *loop(int loops = -1);
Audio *volume(float volume);
I have replicated the structure in JavaScript as follows:
var Audio = function(filename, async) {};
Audio.prototype.Play = function(fade) {};
Audio.prototype.Pause = function() {};
Audio.prototype.Loop = function(loops) {};
Audio.prototype.Volume = function(volume) {};
And after reading both the documentation and the sources for v8, v8-juice, and a plethora of blogs... I can't find a single reference on how to "override" a JS function with a C++ method.
Ideally, I'd like JS to be in control of class creation/destruction (is this possible?), and have those objects always point to my native functions (PrototypeTemplate?).
I've seriously spent my entire day today reading articles/blogs/code related to this and can't find, what I should hope is, a simple answer.
For your sakes, a "simple" answer to me would be something along these lines (wrappers are fine with me; if I have to write wrappers for the creation/destruction that's okay):
v8::Local<v8::Function> jsAudioFunction = v8::Local<v8::Function>::Cast(v8::Context::GetCurrent()->Global()->Get(v8::String::New("Audio")));
jsAudioFunction->Setup(/* setup constructor/destructor */);
jsAudioFunction->SetPrototype(/* map native methods to js functions */);
While this doesn't answer the question of binding native code to JS objects, here are the fruits of my labor:
static void jsAudioGC(v8::Persistent<v8::Value> object, void *data) {
v8::Persistent<v8::Object> obj = v8::Persistent<v8::Object>::Cast(object);
Audio *audio = static_cast<Audio*>(obj->GetPointerFromInternalField(0));
if (audio != NULL) {
obj->SetPointerInInternalField(0, NULL);
v8::V8::AdjustAmountOfExternalAllocatedMemory(-sizeof(audio));
delete audio;
}
object.Dispose();
}
v8::Handle<v8::Value> jsAudio(const v8::Arguments &args) {
v8::Persistent<v8::Object>::New(args.This()).MakeWeak(NULL, jsAudioGC);
Audio *audio = new Audio(get(args[0], ""), get(args[1], true));
v8::V8::AdjustAmountOfExternalAllocatedMemory(sizeof(audio));
args.This()->SetPointerInInternalField(0, audio);
return args.This();
}
v8::Handle<v8::Value> jsAudioPlay(const v8::Arguments &args) {
Audio *audio = static_cast<Audio*>(args.This()->GetPointerFromInternalField(0));
if (audio != NULL) audio->play(get(args[0], 0));
return args.This();
}
Inside of my init() function:
v8::Handle<v8::FunctionTemplate> audio = v8::FunctionTemplate::New(&jsAudio);
audio->PrototypeTemplate()->Set("Play", v8::FunctionTemplate::New(&jsAudioPlay));
audio->InstanceTemplate()->SetInternalFieldCount(1);
globals->Set("Audio", audio);
This does everything exactly the way I want it to; including proper instantiation and garbage collection.
The only regret I have with this approach is that I would like to be able to "only use what is defined." That way these function are only available if the JS "class" has been included (making it possible to have all functions defined and documented in a JS IDE).
Well, I had the same problem... but haven't figured out the GC integration stuff yet. For me it was mostly like having two different templates. One FunctionTemplate for the constructor (and instance-generator) and an ObjectTemplate for the generated data with callbacks.
This is an example of a C++ API class:
https://github.com/martensms/lycheeJS-adk/blob/master/v8gl/api/script.cpp
And here's how the JavaScript side looks like:
https://github.com/martensms/lycheeJS-adk/blob/master/v8gl/test/04-script.js
I did it that way because it seems as this is the way the usual data types are implemented. Maybe I move the methods on the prototype later, but I'll see if that makes sense then.