12/09/2013

Another method substitute for Initializer lists


Although, Initializer Lists was introduced in C++ 11, it was not applied to Visual Studio 2010.
So, I can't write below code, in VS2010.(and, may be same in VS2012)
vector<int> v = { 1, 2, 3, 4 };
So, I often used array rather than vector and non-member std::begin()/std::end(), since I prefer to use for_each, lambda, like below,
struct Actor
{
 string name;
 unsigned int age;
} actors[] = { {"joe", 19}, {"bach",24} };

for_each (std::begin(actors), std::end(actors), [](const Actor& a)
{
 //do something
 cout << ' ' << a.name;
 cout << ' ' << a.age;
});
Today, I read below article in StackOverFlow,
http://stackoverflow.com/questions/2236197/c-easiest-way-to-initialize-an-stl-vector-with-hardcoded-elements?rq=1

If I have to use only vector, this method will better solution, however, it will run for only primitive data type such as, int.
For user defined type, other method will be required.
Ref 1. http://en.cppreference.com/w/cpp/utility/initializer_list
Ref 2. http://oopscenities.net/2011/05/09/c0x-initializer-lists/


8/31/2013

Precautions in luainterface 2.0.3


For In visual studio 2010, below section should be added in app.config. Since luainterface was compiled as clr version 2.0, 'useLegacyV2RuntimeActivationPlicy' is must be set to true.
<startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0"/>
</startup>


For reference a C# object in luainterface, the namespace of the reference object should be different with program main interface. For example, if I address the name of project as 'DrwaDesk', the main namespsce will be 'DrawDesk'. If I want to reference 'Book' class in luainterface, the 'Book' class should have different
namespace with 'DrawDesk'.
namespace DrawDesk
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
        }
    }
}
namespace ShredTypes
{
    class Book
    {
    }
}

Lastly, there is no sleep function in lua. So using os.time() or os.clock(), we normaly make sleep function. However, if the function call in several processes, it will throw exception. A possible solution for this, just wrap function which use the sleep function of C# and call this wrap function in Luainterface. 
 
 
 
 

7/17/2013

Using Google C++ Style Guide


Probably, when many people write C++ code for their own project at home, they don't seem like to follow specific guide line. So they write code according to habit or experience. However, as the length of the code is getting longer, various styles are appeared.This is why many developers try to follow Google C++ Style Guide consiciously.

cpplint.py is a python file for identifying whether follow Google C++ Style Guide. For using, just install Python 2.7(2013-07-17 currently, it doesn't work in higher version.)

The direction is simple.

Also, you can use filter option for reducing unimportant style checking.

7/07/2013

Factory method pattern

This pattern is used with polymorphism and template which are representative feature of C++ language. The main advantage of factory method is that when making new object or extending previous object, define new sublayer class and then just overriding member function which is defined as a factory method. Therefore, we don't need to analyze existing source code detaily.

Here is a sample class diagram using Factory method pattern.

Implementation code is below.
sample.h
#include <map>

using namespace std;

typedef struct _controlInfo
{
    unsigned int ctrlId;
    struct _positionInfo
    {
        unsigned int x;
        unsigned int y;
    }Position;
    struct _sizeInfo
    {
        unsigned int width;
        unsigned int height;
    }Size;

}ControlInfo;

class CControlBase
{
public:
    virtual bool Create(const ControlInfo* info) = 0;
};

class CButton : public CControlBase
{
public :
    bool Create(const ControlInfo* info)
    {
        //Make Button
        //...
        //...

        return true;
    }
};

class ControlMaker
{
public :
    void Make(const ControlInfo* info)
    {
        CControlBase *base = CreateControl();
        base->Create(info);
        ctrlMap[info->ctrlId] = base;
    }

protected :
    virtual CControlBase* CreateControl() = 0;

private :
    map<unsigned int, CControlBase *>ctrlMap;
};

template <class ctrlType>
class ConcreteControlMaker : public ControlMaker
{
protected :
    CControlBase* CreateControl() { return new ctrlType; }
};
 

sample.cpp
//
#include "stdafx.h"
#include "Sample.h"

int _tmain(int argc, _TCHAR* argv[])
{  
    //get contrl info by using xml or ini
    ControlInfo* info = NULL;
    GetControlInfo(info);
   
    //if need to make a button
    ConcreteControlMaker<CButton> btn;
    btn.Make(info);
   
    return 0;
}
 
 
Because this pattern delegates sublayer classes to create object, therefore, factory method pattern has advantages when need to divide the responsibility of object creation.

7/06/2013

[VC++]How can I expand or collapse when click item in tree control?

The simplest way is to set 'single expand' style on tree ctrl. Without 'single expand', if you just use Expand() function, you will not receive notify such as TVN_ITEMEXPANDED, TVN_ITEMEXPANDING.

However, setting 'single expand' style has also a drawback. It is that expanded item once will be collapsed again when it is unselected. This behaviour is different with usual applications' behaviour. Therefore, if remaining unselected item, you should write code like below.

void CExpandTestDlg::OnItemexpandingTree(NMHDR* pNMHDR, LRESULT* pResult)
{
    NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
    // TODO: Add your control notification handler code here

    //Getting a current item
    HTREEITEM hCurItem = m_Tree.GetSelectedItem();

    //Comparing to a received item and then,
    //if the received item is not same,
    //just return for protecting notify TVN_ITEMEXPANDED
    if(hCurItem != pNMTreeView->itemNew.hItem)
    {
        *pResult = 1;
        return;
    }

    *pResult = 0;
}
 

reference from MSDN


6/18/2013

Catch the boomerang(for attending 'Intel perceptual computing challenge')

Recently, I'm preparing to enter Intel perceptual computing challenge. One of my ideas is a simple gesture game. It's called 'Catch The Boomerang'. Some brief sketches are below.

Users can throw the boomerang by rotating their wrist. Distance of flying, speed and the count of caught boomerang are displayed on the game screen.

Of course, the thrown boomerang will be returned, so that users should catch the returning boomerang by grasping gesture.
I hope to get an opportunity which can attend next stage.

6/02/2013

When computer is locked in XP, proceeding redrawing.

During the time that computer is locked in XP, if application's size is altered or do other drawing work, these works will not reflect after the computer is unlocked. Although, it will be changed in Vista or Win 7.

In normal case, it will be solved by managing WM_ACTIVEAPP, but during the time, through executing other program + altering size + redrawing, if z-order is changed, unfortunately other program will be received WM_ACTIVEAPP.

Therefore, the most effective soluting is to manage WM_WCSSESSION_CHANGE.
After checking the WPARAM value of the message is WTS_SESSION_UNLOCK,  doing redraw will be solved this issue.

5/07/2013

Rule for using c++ 0x auto?

'auto' is one of popular keywords in c++ 0x. Now, one of envy lists, which we feel when we see c# or such as script languages, can be reduced. The most typical example of using is when declare 'iterator' in STL.
//when declared typical iter
for (map&ltstring, int>::const_iterator iter = MapScores.begin(); iter != MapScores.end(); ++iter)
{
    cout << "Name = " << iter->first << ", Score = " << iter->second << endl;
}
 
//when used auto
for (auto iter = MapScores.begin(); iter != MapScores.end(); ++iter)
{
    cout << "Name = " << iter->first << ", Score = " << iter->second << endl;
}
(In first one, instead of 'const_iterator', using of cbegin(), cend() is also fine for const appliance. cbegin(), cend() are also added containers of c++ 0x.)

The problem is that lots of c++ developers are already used for one rule, which type of variables always have to be declared. Therefore, inordinate using of 'auto' might bring about confusing and annoying. Furthermore, because of operation through misunderstanding, proportion of debugging time may be longer.

So, I make a rule for me.

  1. when immediately know 'return type' like above code and such as 'for', 'while' loop, when use local variable which available in short scope only.
  2. As much as possible, use 'const auto'. So that, if possible, it uses for 'read only'. I think it can aid to protect wrong operation by means of misunderstanding.

Below link is a stackoverflow thread which discussed for 'guideline using auto'.

http://stackoverflow.com/questions/6434971/how-much-is-too-much-with-c0x-auto-keyword
Personally, I believe that the use of at least is better way.

5/06/2013

The best way to appear dialog invisibly when dialog is created

For this, 'WM_WINDOWPOSCHANGING' is used.

If we use WM_CREATE or WM_INITDIALOG and then, call ShowWindow(SW_HIDE),
we will firstly see a dialog, after that, it will be disappear.

Below code shows how to use WM_WINDOWPOSCHANGING in WTL.

LRESULT CHideDialog::OnWindowPosChanging(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/)
{
 LPWINDOWPOS lpwndpos = (LPWINDOWPOS)lParam;
 if (FALSE == m_isVisible)
 {
  lpwndpos->flags &= ~SWP_SHOWWINDOW;
 }
 else
 {
  lpwndpos->flags |= SWP_SHOWWINDOW;
 }
 return 0;
}

As we see, the value of  m_isVisible decides on whether dialog is visible.
So, if we call below function, after setting the value of m_isVisible to TRUE,
the dialog will be appear again.

::SetWindowPos(m_hWnd, NULL, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);

5/02/2013

How can I make a transparent window in WPF?

We will make a transparent window, which can be adjusted the opicity by slider control, llike below picture.



To begin with, it is required to adjust 3 of properties. They are 'AllowsTransparency', 'Background' and 'WindowStyle'.
<Window x:class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" 
        AllowsTransparency="True" Background="Transparent"
        WindowStyle="None" >


And then, the opacity of window bind to slider control, like this,
<Window x:class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" 
        AllowsTransparency="True" Background="Transparent"
        WindowStyle="None"
        Height="550" Width="400" Opacity="{Binding Value, ElementName=slider}" >

Here is all xaml code.
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" 
        AllowsTransparency="True" Background="Transparent"
        WindowStyle="None"
        Height="550" Width="400" Opacity="{Binding Value, ElementName=slider}" >
    <Border BorderBrush="Gray" BorderThickness="1" CornerRadius="6" Background="Gray">
        <Border BorderBrush="White" BorderThickness="1" CornerRadius="6">
            <DockPanel Background="#303030" Margin="2,2,2,2" >
                <Border Height="100" MouseMove="Header_MouseMove" DockPanel.Dock="Top" VerticalAlignment="Top">
                    <Button  Click="Button_Close" HorizontalAlignment="Right" Margin="0,0,0,80" Width="15" Height="20" VerticalAlignment="Bottom" BorderThickness="1">X</Button>
                    <Border.Background>
                        <LinearGradientBrush StartPoint="0,0" EndPoint="0,2">
                            <GradientStop Color="#C0C0C0" Offset="0." />
                            <GradientStop Color="#303030" Offset="0.1" />
                        </LinearGradientBrush>
                    </Border.Background>
                </Border>
                <Slider x:Name="slider" Height="20" DockPanel.Dock="Bottom" Maximum="1" Minimum="0.5" TickFrequency="0.2" Value="0.9"/>
                <Border Height="100" MouseMove="Header_MouseMove" DockPanel.Dock="Bottom" VerticalAlignment="Bottom">
                    <Border.Background>
                        <LinearGradientBrush StartPoint="0,0" EndPoint="0,18">
                            <GradientStop Color="#303030" Offset="0." />
                            <GradientStop Color="#C0C0C0" Offset="0.1" />
                        </LinearGradientBrush>
                    </Border.Background>
                </Border>
            </DockPanel>
        </Border>
    </Border>
</Window>



4/30/2013

A problem of link error in release mode of WTL

Although, it is well compiled in debug mode without any link error, we will see below link error in release mode of WTL.

LIBCMT.lib(tidtable.obj) : error LNK2005: __encode_pointer already defined in atlmincrt.lib(atlinit.obj)
LIBCMT.lib(tidtable.obj) : error LNK2005: __encoded_null already defined in atlmincrt.lib(atlinit.obj)
LIBCMT.lib(tidtable.obj) : error LNK2005: __decode_pointer already defined in atlmincrt.lib(atlinit.obj)
LIBCMT.lib(crt0dat.obj) : error LNK2005: __get_osplatform already defined in atlmincrt.lib(atlinit.obj)


Some typical solution to tackle for this,
1)Set 'Minimize CRT in Use in ATL' to 'NO' in project setting.
   In this case, the size of file will be slightly increased.

2)Or Set 'ignore', the item of 'atlmincrt.lib' in linker option.


4/29/2013

How can we reduce the repetitive style declaration in WPF?

Xaml is also needed refactoring. Especially for the style, there is a 'BasedOn' property.
It seems like enum or #define of  c++.

Let's look below xaml code,
   <Style TargetType="{x:Type Label}">
      <Setter Property="FontFamily" Value="Arial" />
      <Setter Property="FontSize" Value="10" />
      <Setter Property="HorizontalAlignment" Value="Right" />
      <Setter Property="FontWeight" Value="Bold" />
   </Style>

   <Style TargetType="{x:Type Button}">
      <Setter Property="FontFamily" Value="Arial" />
      <Setter Property="FontSize" Value="10" />
      <Setter Property="Margin" Value="4" />
   </Style>


In the above code, line 2, 3 and line 9, 10 are exactly the same. In case, by means of  'BasedOn' property, the duplicate can be removed.
  <Style x:Key="defaultControlStyle" 
          TargetType="{x:Type Control}">
      <Setter Property="FontFamily" Value="Arial" />
      <Setter Property="FontSize" Value="10" />
  </Style>
  
  <Style TargetType="{x:Type Label}"
           BasedOn="{StaticResource defaultControlStyle}">
      <Setter Property="HorizontalAlignment" Value="Left" />
      <Setter Property="FontWeight" Value="Bold" />
  </Style>
  <Style TargetType="{x:Type Button}"
           BasedOn="{StaticResource defaultControlStyle}">
      <Setter Property="Margin" Value="2" />
  </Style>
 
 To begin with, 'defaultControlStyle' is declared as a common style, and then each control style are using by 'BasedOn' property.
 
The use of repetitive code is a stairway to overwork in all IT fields.

4/28/2013

Why does WPF have strong points in UI programming, when comparing with WINFORM, MFC, WTL ?

  • The feature of declarable UI

First of all, the power of WPF is that it can aid to develop impressive user interface faster and easily. We are able to construct the ui of application using a markup language called XAML. The XAML is similar with HTML or XML. So that, if you already have some experience for them, learning XAML will just take a day! Here is an sample short code.


<Window
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          Title="Hello, there" Height="240" Width="300">
         <DockPanel>
                 <Border DockPanel.Dock="Top" BorderThickness="3" 
                          BorderBrush="White" CornerRadius="5" 
                          Padding="5" Background="Gray">
                     <TextBlock FontSize="10" TextWrapping="Wrap" 
                                Foreground="White">
                     Hello! There.
                     </TextBlock>
                 </Border>
                 <Button Background="LightGray" Width="80" 
                          Height="40" Content="Click"/>
          </DockPanel>
</Window>


Even if you haven't never meet XAML code before, you could estmate what above code is doing.
'DockPanel' and 'Border' are one of a number of rich controls which are provided by WPF. This sample code will make a window like a below picture.



Although, WinForm, MFC, WTL are supporting design tools for constructing UI easily, the quality of default controls of them is not relevant for using real workplace. Actually, the quality of WPF's default controls is also unattractive, but this point can be weighed out by using mark up language, because the use of markup language means that it can be available to bring the feature of web development such as CSS.
 

  • The power of Style

For a long time, one of distinct trends in UI programming is to provide the skin function. It allows to change the appearance of the application during the running time. The use of information file such as ini or xml is frequently used as a common method. Here is a drawback.
a typical example is below.

<Skin name="Gloomy">
 <Edit name="Input" position="10,40" size="100,40" color="128,128,128" />
 <Button name="Commit" position="115,40" size="70,40" color="128,128,128" /></Skin>


Above approach requires some extra processes. For example, indicated color value have to be translated relevant value for using in application code. So that, altering skin process usually follows the following sequence.First loading XML, next finding selected skin name, and then  by means of iterating, changing the look of all controls. Furthermore, C++ requires extra library for parsing xml, such as tinyXML.

On the other hand, all approaches for skin function change dramatically in WPF.
To begin with, we can declare some skin set like below,

-DefaultStyle.xaml
<Style x:Key="groupBoxHeader"
           TargetType="{x:Type Borders}">
       <Setter Property="CornerRadius"
                           Value="4" />
         <Setter Property="TextBlock.Foreground"
                           Value="White" />
</Style>


After that, above style set can be used like below code.
<GroupBox.Header>
         <Border Background="{StaticResource brownBrush}"
                Style="{StaticResource gropBoxHeader}">
             <TextBlock Text="Phone" />
         </Border>
</GroupBox.Header>

For changing style during the running time,
1)
After making several style xaml files, when it is needed, load that.
2)
Or, adopt resources to style as a 'DynamicResource'. And then, make each control's syle property to connect  this 'DynamicResource'.

When comparing to other measures, unnecessary works be reduced surprisingly. Now, we can just concentrate to other valuable work.