I need to get the keyboard layout being used on Mac OS X. I've found old restonces to this but they all are something like this:
How to change the Mac OS X Keyboard Layout programmatically?
which doesn't work any more. Any help would be much appreciated.
In case someone is interested, I was finally able to get the keyboard layout with the following code:
#include <Carbon/Carbon.h>
int main() {
char layout[128];
memset(layout, '\0', sizeof(layout));
TISInputSourceRef source = TISCopyCurrentKeyboardInputSource();
// get input source id - kTISPropertyInputSourceID
// get layout name - kTISPropertyLocalizedName
CFStringRef layoutID = TISGetInputSourceProperty(source, kTISPropertyInputSourceID);
CFStringGetCString(layoutID, layout, sizeof(layout), kCFStringEncodingUTF8);
printf("%s\n", layout);
return 0;
}
Compiled with:
gcc -o test2 test2.c -framework Carbon
I would try this:
#import <Carbon/Carbon.h>
TISInputSourceRef source = TISCopyCurrentKeyboardInputSource();
NSString *s = (__bridge NSString *)(TISGetInputSourceProperty(source, kTISPropertyInputSourceID));
Related
I am using libconfig to read/wirte config files in my C++ game.
Right now I just have this one config file called video.cfg:
#Video config file
video:
{
fps:
{
limited = true;
value = 20;
};
};
This config file handles the video settings of the game.
I am trying to write a very basic console program that modifies this values based on user input. However I have no idea how to do this. I can't find anything in libconfig manual and nothing on Google.
So how do you edit values in Libconfig?
#include <libconfig.h>
int main() {
config_t cfg;
config_setting_t *vid_fps_lim = 0;
config_setting_t *vid_fps_val = 0;
config_init(&cfg);
if (config_read_file(&cfg, "myconfig") == CONFIG_TRUE) {
/* lookup the settings we want */
vid_fps_lim = config_lookup(&cfg, "video.fps.limited");
vid_fps_val = config_lookup(&cfg, "video.fps.value");
/* print the current settings */
printf("video.fps.limited = %i\n", config_setting_get_bool(vid_fps_lim));
printf("video.fps.value = %i\n", config_setting_get_int(vid_fps_val));
/* modify the settings */
config_setting_set_bool(vid_fps_lim, 1);
config_setting_set_int(vid_fps_val, 60);
/* write the modified config back */
config_write_file(&cfg, "myconfig");
}
config_destroy(&cfg);
return 0;
}
I named the file "lcex.c" and the config file "myconfig" It builds and runs on my Debian Linux machine using the following...
gcc `pkg-config --cflags libconfig` lcex.c -o lcex `pkg-config --libs libconfig`
./lcex
Open your config file after running the app and you should see that the values have been updated.
Disclaimer...error handling left out to make it easier to read. I didn't build with -Wall, etc. As with any API, read the docs and handle potential errors.
I came across this question while searching for a way to have libconfig write output to a string instead of a file. I see that there's no acceptable answer here, so I thought I would provide one for posterity, even though the question is over 3 years old.
#include <stdint.h>
#include <string>
#include "libconfig.h++"
int32_t
main (void) {
libconfig::Config config;
std::string file = "test.conf";
try {
config.readFile(file.c_str());
libconfig::Setting &limited = config.lookup("video.fps.limited");
libconfig::Setting &value = config.lookup("video.fps.value");
limited = false;
value = 60;
config.writeFile(file.c_str());
}
catch (...) {
// Do something reasonable with exceptions here. Do not catch (...)
}
return 0;
}
Hope that helps someone!
I am using libpoppler to parse PDF file to plain text,and I want to output page header,page footer and content separately,how can I do this??
Is there any structure or class that hold them?
Thanks in advance!!
You can get text in a page with poppler_page_get_text(). Can you parse pure text afterwards? Here is a sample code. It's not a C++ but hope you can see the idea.
Tested on a Debian Unstable amd64, libpoppler-glib-dev 0.18.4-3, gcc 4.7.1-7
$ gcc -Wall -g -Wextra get-text.c $(pkg-config --cflags --libs poppler-glib)
#include <poppler.h>
#include <glib.h>
int main(int argc, char *argv[])
{
GError *error = NULL;
PopplerDocument *d;
PopplerPage *p;
gchar *f;
gchar *u;
g_type_init();
if (argc < 2)
g_error("oops: no file name given");
if (g_path_is_absolute(argv[1]))
f = argv[1];
else
f = g_build_filename(g_get_current_dir(), argv[1], NULL);
u = g_filename_to_uri(f, NULL, &error);
if (!u)
g_error("oops: %s", error->message);
d = poppler_document_new_from_file(u, NULL, &error);
if (!d)
return -1;
p = poppler_document_get_page(d, 1);
g_print("%s\n", poppler_page_get_text(p));
return 0;
}
Disclaimer: This might not be a good answer
Last time I checked libpoppler was just a good renderer that could see a pdf page as a sequence of vector drawing operations. In that sense, it should be possible for it to intercept text-drawing operations, and thus report the text somehow. But I don't think that text in the header/footer of a page be anything special from the vector point of view. Plus, I have seen a loot of very expensive pdf-to-text converter programs to fail miserably at that.
Not really. PDF has no concept of header, footer and body (unless you create tagged PDF).
I'm working on a C++ project using Visual Studio 2010 on Windows. I'm linking dynamically against x264 which I built myself as a shared library using MinGW following the guide at
http://www.ayobamiadewole.com/Blog/Others/x264compilation.aspx
The strange thing is that my x264 code is working perfectly sometimes. Then when I change some line of code (or even change the comments in the file!) and recompile everything crashes on the line
encoder_ = x264_encoder_open(¶m);
With the message
Access violation reading location 0x00000000
I'm not doing anything funky at all so it's probably not my code that is wrong but I guess there is something going wrong with the linking or maybe something is wrong with how I compiled x264.
The full initialization code:
x264_param_t param = { 0 };
if (x264_param_default_preset(¶m, "ultrafast", "zerolatency") < 0) {
throw KStreamerException("x264_param_default_preset failed");
}
param.i_threads = 1;
param.i_width = 640;
param.i_height = 480;
param.i_fps_num = 10;
param.i_fps_den = 1;
encoder_ = x264_encoder_open(¶m); // <-----
if (encoder_ == 0) {
throw KStreamerException("x264_encoder_open failed");
}
x264_picture_alloc(&pic_, X264_CSP_I420, 640, 480);
Edit: It turns out that it always works in Release mode and when using superfast instead of ultrafast it also works in Debug mode 100%. Could it be that the ultrafast mode is doing some crazy optimizations that the debugger doesn't like?
I've met this problem too with libx264-120.
libx264-120 was built on MinGW and configuration option like below.
$ ./configure --disable-cli --enable-shared --extra-ldflags=-Wl,--output-def=libx264-120.def --enable-debug --enable-win32thread
platform: X86
system: WINDOWS
cli: no
libx264: internal
shared: yes
static: no
asm: yes
interlaced: yes
avs: yes
lavf: no
ffms: no
gpac: no
gpl: yes
thread: win32
filters: crop select_every
debug: yes
gprof: no
strip: no
PIC: no
visualize: no
bit depth: 8
chroma format: all
$ make -j8
lib /def:libx264-120.def /machine:x86
#include "stdafx.h"
#include <iostream>
#include <cassert>
using namespace std;
#include <stdint.h>
extern "C"{
#include <x264.h>
}
int _tmain(int argc, _TCHAR* argv[])
{
int width(640);
int height(480);
int err(-1);
x264_param_t x264_param = {0};
//x264_param_default(&x264_param);
err =
x264_param_default_preset(&x264_param, "veryfast", "zerolatency");
assert(0==err);
x264_param.i_threads = 8;
x264_param.i_width = width;
x264_param.i_height = height;
x264_param.i_fps_num = 60;//fps;
x264_param.i_fps_den = 1;
// Intra refres:
x264_param.i_keyint_max = 60;//fps;
x264_param.b_intra_refresh = 1;
//Rate control:
x264_param.rc.i_rc_method = X264_RC_CRF;
x264_param.rc.f_rf_constant = 25;
x264_param.rc.f_rf_constant_max = 35;
//For streaming:
x264_param.b_repeat_headers = 1;
x264_param.b_annexb = 1;
err = x264_param_apply_profile(&x264_param, "baseline");
assert(0==err);
x264_t *x264_encoder = x264_encoder_open(&x264_param);
x264_encoder = x264_encoder;
x264_encoder_close( x264_encoder );
getchar();
return 0;
}
This program succeeds sometime. But will fail often on x264_encoder_open with the access violation.
The information for this is not existing on Google. And how to initialize x264_param_t and how to use x264_encoder_open are unclear.
It seems that behavior caused from x264's setting values, but I can't know these without reading some open source programs that using libx264.
And, this access violation seems doesn't occurs on FIRST TIME EXECUTION and on compilation with MinGW's gcc (e.g gcc -o test test.c -lx264;./test)
Since this behavior, I think that libx264 doing some strange processes of resources in DLL version of ilbx264 that was built on MinGW's gcc.
I had the same problem. The only way I was able to fix it was to build the x264 dll without the asm option (ie. specify --disable-asm)
Lets say my executable is located at /Users/test_user/app on Mac OSX and I am running it from /Users/test_user/Desktop/run_app:
Desktop run_app$ /Users/test_user/app/exec
Within my C++ code how can I find the path to the location of the executable (which in this case would be /users/test_user/app)? I need to reference some other files at this path within my code and do not want to put absolute paths within the code as some users might place the folder in a different location.
man 3 dyld says:
_NSGetExecutablePath() copies the path of the main executable into the
buffer buf. The bufsize parameter should initially be the size of the
buffer. This function returns 0 if the path was successfully copied.
It returns -1 if the buffer is not large enough, and * bufsize is set
to the size required. Note that _NSGetExecutablePath() will return "a
path" to the executable not a "real path" to the executable. That is,
the path may be a symbolic link and not the real file. With deep
directories the total bufsize needed could be more than MAXPATHLEN.
#include <mach-o/dyld.h>
#include <limits.h>
int main(int argc, char **argv)
{
char buf [PATH_MAX];
uint32_t bufsize = PATH_MAX;
if(!_NSGetExecutablePath(buf, &bufsize))
puts(buf);
return 0;
}
Provided I'm understanding you correctly, you should be able to use NSProcessInfo's -arguments method to get the executable path.
To mix in Objective-C code with C++ code, you can just change the filename extension of the source file in question from .cpp to .mm. Then add the Foundation.framework to the Link Binary With Library build phase of your Target.
[EDIT] updated to show the difference between argv[0] and [[[NSProcessInfo processInfo] arguments] objectAtIndex:0].
Then to use the code, you could do something like in the following code:
#include <iostream>
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// print out raw args
NSMutableArray *arguments = [NSMutableArray array];
for (NSUInteger i = 0; i < argc; i++) {
NSString *argument = [NSString stringWithUTF8String:argv[i]];
if (argument) [arguments addObject:argument];
}
NSLog(#"arguments == %#", arguments);
const char *executablePath =
[[[[NSProcessInfo processInfo] arguments] objectAtIndex:0]
fileSystemRepresentation];
printf("executablePath == %s\n", executablePath);
const char *executableDir =
[[[[[NSProcessInfo processInfo] arguments] objectAtIndex:0]
stringByDeletingLastPathComponent] fileSystemRepresentation];
printf("executableDir == %s\n", executableDir);
[pool release];
return 0;
}
If I then cd into the parent directory of the executable, and then execute the executable using a relative path:
MacPro:~ mdouma46$ cd /Users/mdouma46/Library/Developer/Xcode/DerivedData/executablePath-ewememtbkdajumdlpnciyymduoah/Build/Products/Debug
MacPro:Debug mdouma46$ ./executablePath blah blah2
I get the following output:
2011-08-10 12:59:52.161 executablePath[43554:707] arguments == (
"./executablePath",
blah,
blah2
)
executablePath == /Users/mdouma46/Library/Developer/Xcode/DerivedData/executablePath-ewememtbkdajumdlpnciyymduoah/Build/Products/Debug/executablePath
executableDir == /Users/mdouma46/Library/Developer/Xcode/DerivedData/executablePath-ewememtbkdajumdlpnciyymduoah/Build/Products/Debug
So, while argv[0] may not necessarily be a full path, the result returned from [[[NSProcessInfo processInfo] arguments] objectAtIndex:0] will be.
So, there's [[[NSProcessInfo processInfo] arguments] objectAtIndex:0], or a slightly simpler approach is just to use NSBundle itself, even if it is a command-line tool (see What is the "main bundle" of a command-line foundation tool?):
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
const char *executablePath =
[[[NSBundle mainBundle] executablePath] fileSystemRepresentation];
[pool release];
Maybe you could use the which command. http://unixhelp.ed.ac.uk/CGI/man-cgi?which
If it's a "real" OS X application the proper way to do it is to create a bundle:
http://developer.apple.com/library/mac/#documentation/CoreFoundation/Reference/CFBundleRef/Reference/reference.html
I would like to know a way to open the default browser on OS X from a C++ application and then open a requested URL.
EDIT: I solved it like this:
system("open http://www.apple.com");
In case you prefer using the native OS X APIs instead of system("open ...")
You can use this code:
#include <string>
#include <CoreFoundation/CFBundle.h>
#include <ApplicationServices/ApplicationServices.h>
using namespace std;
void openURL(const string &url_str) {
CFURLRef url = CFURLCreateWithBytes (
NULL, // allocator
(UInt8*)url_str.c_str(), // URLBytes
url_str.length(), // length
kCFStringEncodingASCII, // encoding
NULL // baseURL
);
LSOpenCFURLRef(url,0);
CFRelease(url);
}
int main() {
string str("http://www.example.com");
openURL(str);
}
Which you have to compile with the proper OS X frameworks:
g++ file.cpp -framework CoreFoundation -framework ApplicationServices
Look at the docs for Launch Services.