Qt Creator : generate UUID for c++ header - qt-creator

Is it possible to generate UUID inside Qt Creator editor for c++ header files. For example, I'd like to get something like
#ifndef _f6198c0e_13c3_4641_af52_140d11befb93_
#define _f6198c0e_13c3_4641_af52_140d11befb93_
#endif
where "_f6198c0e_13c3_4641_af52_140d11befb93_" is generaed by IDE.

The only solution I have for the moment is to develop a Qt Creator plugin. Here is my source code to get what I want :
void MyPluginPlugin::triggerAction()
{
auto ret = QUuid::createUuid().toString();
ret = ret.replace('{', '_');
ret = ret.replace('}', '_');
ret = ret.replace('-', '_');
auto clipboard = QApplication::clipboard();
clipboard->setText( ret );
QKeyEvent *event = new QKeyEvent ( QEvent::KeyPress, Qt::Key_V, Qt::ControlModifier );
QCoreApplication::postEvent( QApplication::focusWidget(), event);
}

Related

Unable to load image during WinApi c++ programming

I am doing WinApi C++ programming with my colleague. We are using the visual studio. While I was loading the image, there was an error like the one in the picture below.
While debugging, I found out that this is an error caused by the lack of files on the path. You can simply add a file to the path to resolve the error, but you want to import the image from another specified path. The reason why you don't choose a simple method is that even though your colleagues use the same code, they succeed in importing files from different paths, so they don't get errors.
The path where I import the file is 'D:\BreakTogether\OutPut\bin\Res', and the path where my colleague imports the file is 'D:\BreakTogether\bin\Res'. Below is the code used to get the file path.
#include "pch.h"
#include "ResMgr.h"
#include "PathMgr.h"
#include "Image.h"
ResMgr::ResMgr()
{
}
ResMgr::~ResMgr()
{
/*map<wstring, Image*>::iterator iter;
for (iter = m_mapImg.begin(); iter != m_mapImg.end(); ++iter)
{
delete iter->second;
}*/
Safe_Delete_Map(m_mapImg);
}
Image* ResMgr::ImgLoad(const wstring& _strKey, const wstring& _strRelativePath)
{
Image* pImg = ImgFind(_strKey);
if (nullptr != pImg)
{
return pImg;
}
wstring strFilePath = PathMgr::GetInst()->GetRsrcPath();
strFilePath += _strRelativePath;
pImg = new Image;
pImg->Load(strFilePath);
pImg->SetKey(_strKey);
pImg->SetRelativePath(_strRelativePath);
m_mapImg.insert(make_pair(_strKey, pImg));
// m_mapImg.insert({ _strKey , pImg });
return pImg;
}
Image* ResMgr::ImgFind(const wstring& _strKey)
{
auto iter = m_mapImg.find(_strKey);
if (iter == m_mapImg.end())
{
return nullptr;
}
return static_cast<Image*>(iter->second);
}
#include "pch.h"
#include "PathMgr.h"
#include "Core.h"
PathMgr::PathMgr()
: m_szRsrcPath{}
{
}
PathMgr::~PathMgr()
{
}
void PathMgr::Init()
{
GetCurrentDirectory(255, m_szRsrcPath);
int Length = wcslen(m_szRsrcPath);
for (int i = Length - 1; i >= 0; i--)
{
if (m_szRsrcPath[i] == '\\')
{
m_szRsrcPath[i] = '\0';
break;
}
}
wcscat_s(m_szRsrcPath, 255, L"\\bin\\Res\\");
SetWindowText(Core::GetInst()->GetWndHandle(), m_szRsrcPath);
}
I tried adding an image to the path where I load the file. That will solve the problem. However, it is inefficient because my colleague and I have to add the same file twice because we have different paths to load the image.
If you can load the file normally when the image file is in place, there is no problem with your code.
Go to your Project Property Pages -> Debugging -> Working Directory and align your path with your colleagues.
If the problem is not solved, plz tell me more about your problem.
Have a nice day!

Linking fails with undefined references to wgl functions of the Windows API for OpenGL in Kotlin

When I was trying out OpenGL context-creation with the Windows API and Kotlin, an error occurred when the linking task was executed. I posted the output of that task on pastebin (expires in a month) and these two lines of the output stand out:
... undefined reference to '__imp_wglCreateContext'
... undefined reference to '__imp_wglMakeCurrent'
For every wgl function I use, clang (the LLVM compiler frontend) prints such lines. Compiling works fine, but when it comes to linking, the task either fails (Kotlin 1.3.71) or never ends with nothing happening (Kotlin 1.4-M1).
Note that this is not a runtime problem and any other Windows API function works correctly and also that Kotlin provides bindings for the wgl functions.
If all wgl functions get removed, the following code I made compiles and links fine and a blank window gets produced as expected (comment out wgl functions):
import kotlinx.cinterop.*
import platform.windows.*
#OptIn(ExperimentalUnsignedTypes::class)
fun main() {
memScoped {
val className = "OpenGLLinkErrorDemo"
// create an instance of the window class
val wc = cValue<WNDCLASS> {
lpfnWndProc = staticCFunction { hwnd, uMsg, wParam, lParam ->
when (uMsg) {
WM_DESTROY.toUInt() -> {
PostQuitMessage(0)
0
}
WM_PAINT.toUInt() -> {
memScoped {
val ps = alloc<PAINTSTRUCT>()
val hdc = BeginPaint(hwnd, ps.ptr)
val brush = alloc<HBRUSH__> {
unused = COLOR_WINDOW + 1
}
FillRect(hdc, ps.rcPaint.ptr, brush.ptr)
EndPaint(hwnd, ps.ptr)
}
0
}
else -> DefWindowProc!!(hwnd, uMsg, wParam, lParam)
}
}
hInstance = GetModuleHandle!!(null)
lpszClassName = className.wcstr.ptr
}
// register the window class instance
RegisterClass!!(wc.ptr)
val hwnd = CreateWindowEx!!(
0u, // optional window styles
className.wcstr.ptr, // window class
className.wcstr.ptr, // window text
CS_OWNDC.toUInt(), // window style (this one in particular is needed for OpenGL)
// size and position
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
null, // parent window
null, // menu
GetModuleHandle!!(null), // instance handle
null // additional application data
)
?: throw RuntimeException("Failed to create window")
// create a pixelformat descriptor with opengl compatible settings
val pfd = alloc<PIXELFORMATDESCRIPTOR> {
nSize = sizeOf<PIXELFORMATDESCRIPTOR>().toUShort()
nVersion = 1u
dwFlags = (PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER).toUInt()
iPixelType = PFD_TYPE_RGBA.toUByte()
cColorBits = 32u
cRedBits = 0u; cRedShift = 0u; cGreenBits = 0u; cGreenShift = 0u; cBlueBits = 0u; cBlueShift = 0u; cAlphaBits = 0u; cAlphaShift = 0u
cAccumBits = 0u
cAccumRedBits = 0u; cAccumGreenBits = 0u; cAccumBlueBits = 0u; cAccumAlphaBits = 0u
cDepthBits = 24u
cStencilBits = 8u
cAuxBuffers = 0u
iLayerType = PFD_MAIN_PLANE.toUByte()
bReserved = 0u
dwLayerMask = 0u; dwVisibleMask = 0u; dwDamageMask = 0u
}
SetPixelFormat(GetDC(hwnd), ChoosePixelFormat(GetDC(hwnd), pfd.ptr), pfd.ptr)
// the source of evil. using the function to create an opengl context, but the linker doesn't know the wgl functions
val openGLContext = wglCreateContext(GetDC(hwnd)) ?: throw RuntimeException("Failed to create OpenGL context")
wglMakeCurrent(GetDC(hwnd), openGLContext)
ShowWindow(hwnd, 1)
// run the message loop
val msg = alloc<MSG>()
while (GetMessage!!(msg.ptr, null, 0u, 0u) == 1) {
TranslateMessage(msg.ptr)
DispatchMessage!!(msg.ptr)
}
}
}
So I checked the documentations and of course this requires the OpenGL library to work. But any other OpenGL function from the platform.opengl32 package works and because Kotlin checks at compilation which libraries are used and includes them automatically, everything should have worked fine. However, clang still didn't like it and couldn't find the implementations for the wgl functions.
Then I searched the internet for any solutions, and a few people had the same output, but their cases weren't entirely like mine and I didn't find anyone who tried OpenGL context-creation with Kotlin at all
(I know it might not be the best choice to use a high-level language for something like this and that I could have used another library for what I'm trying to accomplish, but I want to see how much Kotlin is able to do).
Next I checked if the Kotlin issue tracker has something about this already (nope) and the LLVM version Kotlin uses and the LLVM changelogs if they say anything about that (nope, and I know it doesn't make much sense, but you never know), so I figured that the problem must be on my side.
I came up with the following possible causes:
I am using the wrong version of OpenGL (should be the latest one for my graphics card, I updated my graphics driver)
I need to do something extra with dependencies
I am using deprecated API
I am too dumb
I am out of luck, and it just doesn't work on my PC
Those are all the things I didn't check yet because I couldn't, so of course I don't know if any them are true. I've been trying to get this to work for a couple of days now, so now I seek help or advice. Maybe someone could try to compile this too. The following script is the necessary build script for gradle:
#file:Suppress("UNUSED_VARIABLE")
plugins {
kotlin("multiplatform") version "1.3.71"
}
repositories {
mavenCentral()
}
kotlin {
mingwX64("openGLErrorDemo") {
binaries {
executable {
entryPoint = "main"
}
}
val main by compilations.getting {
kotlinOptions {
freeCompilerArgs = listOf("-Xopt-in=kotlin.RequiresOptIn")
}
}
}
sourceSets {
val commonMain by getting {
dependencies {
implementation(kotlin("stdlib-common"))
}
}
}
}
Put that script in a file called build.gradle.kts, then create the following folder structure next to it:
src
\- openGLErrorDemoMain
\- kotlin
and put a *.kt file in the kotlin folder with the first code shown. Then run the :runReleaseExecutableOpenGLErrorDemo task and see if it compiles and links, then try commenting the wgl function calls out and running it again. This was built using the latest versions of IntelliJ and Gradle.
Of course if anyone knows what the problem is, let me know, or comment if you need more information. And please also tell me what the result of compiling the above code was.
Thanks in advance!

How to detect Windows 10 light/dark mode in Win32 application?

A bit of context: Sciter (pure win32 application) is already capable to render UWP alike UIs:
in dark mode:
in light mode:
Windows 10.1803 introduces Dark/Light switch in Settings applet as seen here for example.
Question: how do I determine current type of that "app mode" in Win32 application?
Well, it looks like this option is not exposed to regular Win32 applications directly, however it can be set / retrieved through the AppsUseLightTheme key at the HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Themes\Personalize registry path.
The Microsoft.Windows.SDK.Contracts NuGet package gives .NET Framework 4.5+ and .NET Core 3.0+ applications access to Windows 10 WinRT APIs, including Windows.UI.ViewManagement.Settings mentioned in the answer by jarjar. With this package added to a .NET Core 3.0 console app that consists of this code:
using System;
using Windows.UI.ViewManagement;
namespace WhatColourAmI
{
class Program
{
static void Main(string[] args)
{
var settings = new UISettings();
var foreground = settings.GetColorValue(UIColorType.Foreground);
var background = settings.GetColorValue(UIColorType.Background);
Console.WriteLine($"Foreground {foreground} Background {background}");
}
}
}
The output when the theme is set to Dark is:
Foreground #FFFFFFFF Background #FF000000
When the theme is set to Light it's:
Foreground #FF000000 Background #FFFFFFFF
As this is exposed via a Microsoft provided package that states:
This package includes all the supported Windows Runtime APIs up to Windows 10 version 1903
It's a pretty safe bet that it's intentional that this API is accessible!
Note: This isn't explicitly checking whether the theme is Light or Dark but checking for a pair of values that suggest that the theme in use is one of the two, so,.. the correctness of this method is mildly questionable but it's at least a "pure" C# way of achieving what's been outlined elsewhere with C++
EDIT: Calling out that this works in all Win32 projects as long as you're building with c++17 enabled.
If you're using the latest SDK, this worked for me.
#include <winrt/Windows.UI.ViewManagement.h>
using namespace winrt::Windows::UI::ViewManagement;
if (RUNNING_ON_WINDOWS_10) {
UISettings settings;
auto background = settings.GetColorValue(UIColorType::Background);
auto foreground = settings.GetColorValue(UIColorType::Foreground);
}
To add to the solution suggested by #user7860670, i.e: checking the registry key AppsUseLightTheme, I think it is worth having some code example.
To read from the registry Win32 has RegGetValue.
C++
bool is_light_theme() {
// based on https://stackoverflow.com/questions/51334674/how-to-detect-windows-10-light-dark-mode-in-win32-application
// The value is expected to be a REG_DWORD, which is a signed 32-bit little-endian
auto buffer = std::vector<char>(4);
auto cbData = static_cast<DWORD>(buffer.size() * sizeof(char));
auto res = RegGetValueW(
HKEY_CURRENT_USER,
L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize",
L"AppsUseLightTheme",
RRF_RT_REG_DWORD, // expected value type
nullptr,
buffer.data(),
&cbData);
if (res != ERROR_SUCCESS) {
throw std::runtime_error("Error: error_code=" + std::to_string(res));
}
// convert bytes written to our buffer to an int, assuming little-endian
auto i = int(buffer[3] << 24 |
buffer[2] << 16 |
buffer[1] << 8 |
buffer[0]);
return i == 1;
}
Rust
Using the windows-rs projection crate:
pub fn is_light_theme() -> bool {
// based on https://stackoverflow.com/a/51336913/709884
let mut buffer: [u8; 4] = [0; 4];
let mut cb_data: u32 = (buffer.len()).try_into().unwrap();
let res = unsafe {
RegGetValueW(
HKEY_CURRENT_USER,
r#"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"#
.to_wide()
.as_pwstr(),
"AppsUseLightTheme".to_wide().as_pwstr(),
RRF_RT_REG_DWORD,
std::ptr::null_mut(),
buffer.as_mut_ptr() as _,
&mut cb_data as *mut _,
)
};
assert_eq!(
res,
ERROR_SUCCESS,
format!("failed to read key from registry: err_code={}", res).as_str(),
);
// REG_DWORD is signed 32-bit, using little endian
let light_mode = i32::from_le_bytes(buffer) == 1;
light_mode
}
pub fn is_dark_theme() -> bool {
!is_light_theme()
}
// convert &str to Win32 PWSTR
#[derive(Default)]
pub struct WideString(pub Vec<u16>);
pub trait ToWide {
fn to_wide(&self) -> WideString;
}
impl ToWide for &str {
fn to_wide(&self) -> WideString {
let mut result: Vec<u16> = self.encode_utf16().collect();
result.push(0);
WideString(result)
}
}
impl ToWide for String {
fn to_wide(&self) -> WideString {
let mut result: Vec<u16> = self.encode_utf16().collect();
result.push(0);
WideString(result)
}
}
impl WideString {
pub fn as_pwstr(&self) -> PWSTR {
PWSTR(self.0.as_ptr() as *mut _)
}
}
Here is a C# solution for the answer of #user7860670
using Microsoft.Win32;
try
{
int res = (int)Registry.GetValue("HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", "AppsUseLightTheme", -1);
}
catch
{
//Exception Handling
}
res contains the value for the default theme on windows
0 : dark theme
1 : light theme
-1 : AppsUseLightTheme could not be found

Blackberry 10 image upload

I am getting this error when trying to upload image Process 1780056901 (Zain) terminated SIGSEGV code=1 fltno=11 ip=00000000. I am getting no help from blackberry forums, and most of blackberry documention is next to trash..and so many codes they have put are flat out wrong documentation and dont work.
void ApplicationUI::getPicture()
{
FilePicker* filePicker = new FilePicker();
filePicker->setType(FileType::Picture);
filePicker->setTitle("Select Picture");
filePicker->setMode(FilePickerMode::Picker);
filePicker->open();
QObject::connect(filePicker,
SIGNAL(fileSelected(const QStringList&)),
this,
SLOT(onFileSelected(const QStringList&)));
}
void ApplicationUI::onFileSelected(const QStringList& list) {
try
{
QFile file (list[0]);
ImageView* ay = root->findChild<ImageView*>("imageName");
if(ay != NULL)
ay->setImage(Image(list[0]));
QString body = "" ;
QSettings settings("Netvariant", "Zain");
QString locale_string = settings.value("lang").toString();
if(locale_string == "ar")
locale_string == "ar";
else
locale_string = "en";
const QUrl url("myurl");
QHttpPart imagePart;
imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/jpeg"));
imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"imageFile\""));
imagePart.setRawHeader("Content-ID", "my#content.id"); // add any headers you like via setRawHeader()
file.open(QIODevice::ReadOnly);
imagePart.setBodyDevice(&file);
QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
file.setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart
multiPart->append(imagePart);
QNetworkRequest request(url);
QNetworkAccessManager* netManager = new QNetworkAccessManager(this);
QNetworkReply *reply = netManager->post(request, multiPart);
}
catch(...)
{
}
}

Manual Animation doesn't work in Cocos2d-x

I'm testing manual animation. However, the animation seems to have some issues, so it doesn't work.
These are the code. Can you take a look and let me where I'm wrong.
HelloWorldScene.h
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
#include <string>
USING_NS_CC;
class HelloWorld : public cocos2d::CCLayerColor{
public:
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();
// there's no 'id' in cpp, so we recommend returning the class instance pointer
static cocos2d::CCScene* scene();
// a selector callback
void menuCloseCallback(CCObject* pSender);
// implement the "static node()" method manually
CREATE_FUNC(HelloWorld);
virtual void onEnter();
protected:
CCSprite* m_grossini;
};
#endif // __HELLOWORLD_SCENE_H__
HelloWorldScene.cpp
#include "HelloWorldScene.h"
USING_NS_CC;
CCScene* HelloWorld::scene()
{
CCScene *scene = CCScene::create();
HelloWorld *layer = HelloWorld::create();
scene->addChild(layer);
return scene;
}
bool HelloWorld::init()
{
if ( !CCLayerColor::initWithColor( ccc4(255,255,255,255) ) )
{
return false;
}
CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();
CCMenuItemImage *pCloseItem = CCMenuItemImage::create(
"CloseNormal.png",
"CloseSelected.png",
this,
menu_selector(HelloWorld::menuCloseCallback));
pCloseItem->setPosition(ccp(origin.x + visibleSize.width - pCloseItem->getContentSize().width/2 ,
origin.y + pCloseItem->getContentSize().height/2));
CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);
pMenu->setPosition(CCPointZero);
this->addChild(pMenu, 1);
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
m_grossini = CCSprite::create("grossini.png");
m_grossini->retain();
this->addChild(m_grossini);
m_grossini->setPosition(ccp(winSize.width/2, winSize.height/2));
return true;
}
void HelloWorld::menuCloseCallback(CCObject* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8)
CCMessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
#else
CCDirector::sharedDirector()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
#endif
}
void HelloWorld::onEnter(){
CCAnimation* animation = CCAnimation::create();
for( int i=1;i<15;i++)
{
char szName[100] = {0};
sprintf(szName, "grossini_dance_%02d.png", i);
animation->addSpriteFrameWithFileName(szName);
}
// should last 2.8 seconds. And there are 14 frames.
animation->setDelayPerUnit(2.8f / 14.0f);
animation->setRestoreOriginalFrame(true);
CCAnimate* action = CCAnimate::create(animation);
m_grossini->runAction(CCSequence::create(action, action->reverse(), NULL));
}
I hope you can help me. Thank you so much!
Try following things:..
First of all remove this line m_grossini->retain(); because addchild automatically increase its retain count.
Found the problem..
As you are overriding the OnEnter method you need to call it manually for the base class. In your case adding the line:-
CCLayerColor::onEnter();
in the OnEnter method will do the work.
In future be careful while overriding base class methods.
try this code:
CCAnimation* animation = CCAnimation::create();
for( int i=1;i<15;i++)
animation->addSpriteFrameWithFileName((CCString::createWithFormat("grossini_dance_%02d.png",i)->getCString()));
// should last 2.8 seconds. And there are 14 frames.
animation->setDelayPerUnit(2.8f / 14.0f);
animation->setRestoreOriginalFrame(true);
CCAnimate* action = CCAnimate::create(animation);
m_grossini->runAction(action); //Run once all frame(OR)
m_grossini->runAction(CCRepeatForever::create(action)); //Run RepeatForever

Resources