Monday, May 2, 2011

NSArray NSMutableArray sortUsingSelector example objc

This article explains how to use sortUsingSelector and what parameter it takes.
> Hello;
> I am new to apple and ObjectiveC and started by playing around with
> NSArray and NSMutableArray to learn something about the native
> datatypes.
>
> The question I have How do I sort a NSArray using
> - (void)sortUsingSelector:(SEL)comparator
>
> What does (SEL)comparator mean??

It means that comparator is a method (or a message).

It should be a method like this one:

- (NSComparisonResult) comparator:(ClassInTheArray *) inObject

You can either write your own for your type of Object or use a Category
like for this one:

@interface NSString (InsensitiveSearch)

- (NSComparisonResult)compareInsensitive:(NSString *)aString;

@end

@implementation NSString(InsensitiveSearch)

- (NSComparisonResult)compareInsensitive:(NSString *)aString
{
    return [self compare:aString options:NSCaseInsensitiveSearch];
}

@end

Sorting the array will be then done with this code:

[myArray sortUsingSelector:@selector(compareInsensitive:)];

Sunday, May 1, 2011

SendMessage example win32

This is a SendMessage example to control window of another application.
The sequence you follow is simple.
First, find out the target window handle by using FindWindow() function.
Second, send desired message to the target window using SendMessage() or PostMessage() function.

Example code to control "calculator" window.

void    FindWindowAndSendMessage(void)
{
    HWND        hWnd;
    LRESULT        result;
    UINT        uMsg;
    WPARAM        wParam;
    LPARAM        lParam;
    int            i, j;
    WINDOWPOS    winPos;


    hWnd = FindWindow(NULL, TEXT("calculator"));
    if( hWnd )
    {
        // It works, I can handle to another window and control them.
        //


        // Change windows text.
        //
        SendMessage(hWnd, WM_SETTEXT, NULL, (LPARAM)TEXT("my own calculator"));

        // Close
        //
        uMsg = WM_CLOSE;
        SendMessage(hWnd, uMsg, NULL, NULL);


    }
    return;
}

Windows Screen Capture sample code

Following code is a vc++ example for Screen Capture function.
Collected from http://www.ham-radio-deluxe.com/Support/SourceCode/WindowsScreenCapture.aspx
Introduction
The guts of this code is basic Windows programming, the clever part is saving to a BMP on disk then converting the BMP to JPG using custom code taken from www.codeproject.com .
The code uses a few custom classes for saving and converting from BMP to JPG, to do this see http://www.codeproject.com/KB/graphics/cximage.aspx . The code to save a BMP to a file is below. Take it, make it your own.
The main function is ScreenCapture() which I put in CMainFrame.

class CSaveBitmapToFile 
{
public:
 CSaveBitmapToFile();
 virtual ~CSaveBitmapToFile();

 PBITMAPINFO CreateBitmapInfoStruct(CWnd*, HBITMAP hBmp);
 void        CreateBMPFile(CWnd*, LPCTSTR pszFile, PBITMAPINFO pbi, HBITMAP hBMP, HDC hDC);
};


//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CSaveBitmapToFile::CSaveBitmapToFile()
{
}

CSaveBitmapToFile::~CSaveBitmapToFile()
{
}

//
// Create structures.
//
PBITMAPINFO CSaveBitmapToFile::CreateBitmapInfoStruct(CWnd* pParent, HBITMAP hBmp)
{
    BITMAP  bmp      = {0};
    PBITMAPINFO pbmi     = NULL;
    WORD  cClrBits = 0;

 //
    // Retrieve the bitmap's color format, width, and height.
 //
    if (!::GetObject(hBmp, sizeof(BITMAP), (LPSTR)&bmp))
 {
  CErrorText err;
  CString    strText;

  strText.Format(_T("Error getting bitmap colour format, width and height: %s"), err.Text());
  pParent->MessageBox(strText, _T("Error"), MB_OK | MB_ICONERROR);
        return NULL;
 }

 //
    // Convert the color format to a count of bits.
 //
    cClrBits = (WORD)(bmp.bmPlanes * bmp.bmBitsPixel);

    if (cClrBits == 1)
        cClrBits = 1;
    else if (cClrBits <= 4)
        cClrBits = 4;
    else if (cClrBits <= 8)
        cClrBits = 8;
    else if (cClrBits <= 16)
        cClrBits = 16;
    else if (cClrBits <= 24)
        cClrBits = 24;
    else cClrBits = 32;

 //
    // Allocate memory for the BITMAPINFO structure. (This structure
    // contains a BITMAPINFOHEADER structure and an array of RGBQUAD
    // data structures.)
 //
 if (cClrBits != 24)
 {
  pbmi = (PBITMAPINFO)LocalAlloc(LPTR, sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * (1 << cClrBits));
 }

 //
 // There is no RGBQUAD array for the 24-bit-per-pixel format.
 //
 else
 {
         pbmi = (PBITMAPINFO)LocalAlloc(LPTR, sizeof(BITMAPINFOHEADER));
 }

 //
    // Initialize the fields in the BITMAPINFO structure.
 ///
    pbmi->bmiHeader.biSize     = sizeof(BITMAPINFOHEADER);
    pbmi->bmiHeader.biWidth    = bmp.bmWidth;
    pbmi->bmiHeader.biHeight   = bmp.bmHeight;
    pbmi->bmiHeader.biPlanes   = bmp.bmPlanes;
    pbmi->bmiHeader.biBitCount = bmp.bmBitsPixel;

    if (cClrBits < 24)
        pbmi->bmiHeader.biClrUsed = (1 << cClrBits);

 //
    // If the bitmap is not compressed, set the BI_RGB flag.
 //
    pbmi->bmiHeader.biCompression = BI_RGB;

 //
    // Compute the number of bytes in the array of color
    // indices and store the result in biSizeImage.
    // For Windows NT/2000, the width must be DWORD aligned unless
    // the bitmap is RLE compressed. This example shows this.
    // For Windows 95/98, the width must be WORD aligned unless the
    // bitmap is RLE compressed.
 //
    pbmi->bmiHeader.biSizeImage = ((pbmi->bmiHeader.biWidth * cClrBits + 31) & ~31) / 8 * pbmi->bmiHeader.biHeight;

 //
    // Set biClrImportant to 0, indicating that all of the
    // device colors are important.
 //
 pbmi->bmiHeader.biClrImportant = 0;

 return pbmi;
}

//
// The following example code defines a function that initializes the remaining structures,
// retrieves the array of palette indices, opens the file, copies the data, and closes the file.
//
void CSaveBitmapToFile::CreateBMPFile(CWnd*       pParent,
           LPCTSTR     pszFile,
           PBITMAPINFO pbi,
           HBITMAP     hBMP,
           HDC         hDC)
{
 HANDLE    hf      = NULL;  // File handle
 BITMAPFILEHEADER hdr     = {0};  // Bitmap file-header
 PBITMAPINFOHEADER pbih    = NULL;  // Bitmap info-header
 LPBYTE    lpBits  = NULL;  // Memory pointer
 DWORD    dwTotal = 0;  // Total count of bytes
 DWORD    cb      = 0;  // Incremental count of bytes
 BYTE*    hp      = NULL;  // Byte pointer
 DWORD    dwTmp   = 0;

 pbih   = (PBITMAPINFOHEADER) pbi;
 lpBits = (LPBYTE)GlobalAlloc(GMEM_FIXED, pbih->biSizeImage);

 if (!lpBits)
 {
  pParent->MessageBox(_T("Error allocating temporary storage."),
       _T("Error"),
       MB_OK | MB_ICONERROR);
  return;
 }

 //
 // Retrieve the color table (RGBQUAD array) and the bits
 // (array of palette indices) from the DIB.
 //
 if (!GetDIBits(hDC, hBMP, 0, (WORD) pbih->biHeight, lpBits, pbi, DIB_RGB_COLORS))
 {
  pParent->MessageBox(_T("Error retrieving colour table and bits."),
       _T("Error"),
       MB_OK | MB_ICONERROR);

  GlobalFree((HGLOBAL)lpBits);
  return;
 }

 //
 // Create the .BMP file.
 //
 hf = CreateFile(pszFile,
     GENERIC_READ | GENERIC_WRITE,
     (DWORD)0,
     NULL,
     CREATE_ALWAYS,
     FILE_ATTRIBUTE_NORMAL,
     (HANDLE) NULL);

 if (hf == INVALID_HANDLE_VALUE)
 {
  CString  strText;
  CErrorText error;

  strText.Format(_T("Error creating output file: %s -\n%s"),
        pszFile,
        error.Text());

  pParent->MessageBox(strText,
       _T("Error"),
       MB_OK | MB_ICONERROR);

  GlobalFree((HGLOBAL)lpBits);
  return;
 }

 //
 // BM 0x42 = "B" 0x4d = "M".
 //
 hdr.bfType = 0x4d42;

 //
 // Compute the size of the entire file.
 //
 hdr.bfSize      = (DWORD)(sizeof(BITMAPFILEHEADER) +  pbih->biSize + pbih->biClrUsed * sizeof(RGBQUAD) + pbih->biSizeImage);
 hdr.bfReserved1 = 0;
 hdr.bfReserved2 = 0;

 //
 // Compute the offset to the array of color indices.
 //
 hdr.bfOffBits = (DWORD) sizeof(BITMAPFILEHEADER) + pbih->biSize + pbih->biClrUsed * sizeof (RGBQUAD);

 //
 // Copy the BITMAPFILEHEADER into the .BMP file.
 //
 if (!WriteFile(hf,
       (LPVOID)&hdr,
       sizeof(BITMAPFILEHEADER),
       (LPDWORD) &dwTmp,  NULL))
 {
  pParent->MessageBox(_T("Error writing to output file."),
       _T("Error"),
       MB_OK | MB_ICONERROR);

  GlobalFree((HGLOBAL)lpBits);
  CloseHandle(hf);
  return;
 }

 //
 // Copy the BITMAPINFOHEADER and RGBQUAD array into the file.
 //
 if (!WriteFile(hf,
       (LPVOID)pbih,
       sizeof(BITMAPINFOHEADER) + pbih->biClrUsed * sizeof (RGBQUAD),
       (LPDWORD)&dwTmp,
       (NULL)))
 {
  pParent->MessageBox(_T("Error writing to output file."),
       _T("Error"),
       MB_OK | MB_ICONERROR);

  GlobalFree((HGLOBAL)lpBits);
  CloseHandle(hf);
  return;
 }

 //
 // Copy the array of color indices into the .BMP file.
 //
 dwTotal = cb = pbih->biSizeImage;
 hp      = lpBits;

 if (!WriteFile(hf,
       (LPSTR)hp,
       (int)cb,
       (LPDWORD)&dwTmp,
       NULL))
 {
  pParent->MessageBox(_T("Error writing to output file."),
       _T("Error"),
       MB_OK | MB_ICONERROR);

  GlobalFree((HGLOBAL)lpBits);
  CloseHandle(hf);
  return;
 }

 //
 // Close the .BMP file.
 //
 CloseHandle(hf);

 //
 // Free memory.
 //
 GlobalFree((HGLOBAL)lpBits);
}








The Code - from MainFrm.cpp
// MainFrm.cpp : implementation of the CMainFrame class
//

#include "stdafx.h"
#include "HRDLogbook.h"

#include "MainFrm.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

//
// Clipboard.
//
void CMainFrame::OnToolsScreenCapture()
{
 ScreenCapture(this, TRUE, FALSE);
}

//
// File.
//
void CMainFrame::OnToolsScreenCaptureFile()
{
 ScreenCapture(this, FALSE, TRUE);
}

void CMainFrame::ScreenCapture(CWnd*      pWnd,
          const BOOL bClipboard,
          const BOOL bFile)
{
 CRect rectClient(0,0,0,0);
 CRect rectWindow(0,0,0,0);

 pWnd->GetClientRect(&rectClient);
 pWnd->GetWindowRect(&rectWindow);

 BOOL bZoom          = pWnd->IsZoomed();
 int  x              = (rectWindow.Width()  - rectClient.Width()) / 2;
 int  y              = (rectWindow.Height() - rectClient.Height()) - x;
 HWND hDesktopWnd    = pWnd->m_hWnd;
 HDC  hDesktopDC     = ::GetDC(hDesktopWnd);
 HDC  hCaptureDC     = ::CreateCompatibleDC(hDesktopDC);

 int xSrc          = bZoom ? 0 : -x;
 int ySrc          = bZoom ? 0 : -y;
 int nScreenWidth  = bZoom ? (rectWindow.Width()  - x - x) : rectWindow.Width();
 int nScreenHeight = bZoom ? (rectWindow.Height() - y - x) : rectWindow.Height();

// nScreenWidth  = rectWindow.Width();
// nScreenHeight = rectWindow.Height();

 HBITMAP hCaptureBitmap = ::CreateCompatibleBitmap(hDesktopDC,
               nScreenWidth,
               nScreenHeight);
 SelectObject(hCaptureDC, hCaptureBitmap);

 BitBlt(hCaptureDC,
     0,
     0,
     nScreenWidth,
     nScreenHeight,
     hDesktopDC,
     xSrc,
     ySrc,
     SRCCOPY | CAPTUREBLT);

 //
 // Copy to clipboard.
 //
 if (bClipboard)
 {
  //
  // Open clipboard and empty its contents.
  //
  OpenClipboard();
  EmptyClipboard();

  //
  // Copy bitmap to clipboard and close it.
  //
  SetClipboardData(CF_BITMAP, hCaptureBitmap);
  CloseClipboard();
 }

 //
 // Save to file.
 //
 if (bFile)
 {
  CSaveBitmapToFile save;
  CString    strFilenameBmp;
  CString    strFilenameJpg;
  CString    strFolderBmp;
  CString    strFolderJpg;
  CTime    now = CTime::GetCurrentTime();
  PBITMAPINFO   pbi = save.CreateBitmapInfoStruct(this, hCaptureBitmap);

  if (pbi)
  {
   Dirs().GetFolderPath(CSIDL_MYPICTURES,    strFolderJpg);
   Dirs().GetFolderPath(CSIDL_LOCAL_APPDATA, strFolderBmp);

   strFilenameBmp.Format(_T("%s\\HRD-Logfile-Screenshot-%s.bmp"),
          strFolderBmp,
          now.Format(_T("%Y-%m-%d-%H%M%S")));

   strFilenameJpg.Format(_T("%s\\HRD-Logfile-Screenshot-%s.jpg"),
          strFolderJpg,
          now.Format(_T("%Y-%m-%d-%H%M%S")));

   CFileDialogSave dlg(strFilenameJpg,
        FD_JPG_FILTER,
        _T("Save Screen Capture file..."),
        this);
   if (dlg.DoModal() == IDOK)
   {
    CMyImage image;

    //
    // Create file.
    //
    save.CreateBMPFile(this,
           (LPCTSTR)strFilenameBmp,
           pbi,
           hCaptureBitmap,
           hCaptureDC);

    //
    // Now convert to JPG, 90% is good enough...
    //
    image.ConvertToJPG(strFilenameBmp,
           dlg.Filename(),
           90);

    try
    {
     CFile::Remove(strFilenameBmp);
    }
    catch(...)
    {
    }

    //
    // Display.
    //
    OwnShellExecuteEdit(this, dlg.Filename());
   }

   //
   // Tidy up.
   //
   LocalFree(pbi);
  }
 }

 ::ReleaseDC(hDesktopWnd,hDesktopDC);
 ::DeleteDC(hCaptureDC);
 ::DeleteObject(hCaptureBitmap);
}

Tuesday, April 19, 2011

pthread example - producer/consumer

Another simple pthread example. It implements a producer/consumer pattern. Threads are created by calling pthread_create() function. pthread_join() just waits for the specified thread to finish. In this pthread example, one thread produces data and another consumes it. The pthread example is shown below.


// pthread example - producer-consumer pattern.
//
#include <sys/time.h>
#include <stdio.h>
#include <pthread.h> 
#include <errno.h>

pthread_mutex_t region_mutex = PTHREAD_MUTEX_INITIALIZER;

int b;  /* buffer size = 1; */ 
main()  
{
  pthread_t producer_thread; 
  pthread_t consumer_thread; 
  void *producer();
  void *consumer();
  
    pthread_create(&consumer_thread,NULL,consumer,NULL);
    pthread_create(&producer_thread,NULL,producer,NULL);
    pthread_join(consumer_thread,NULL);
}

void add_buffer(int i){
  b = i;
}
int get_buffer(){
  return b ;
}
 
void *producer()
{
int i = 0;
printf("I'm a producer\n");
while (1) {
  pthread_mutex_lock(&region_mutex);
  add_buffer(i);
  pthread_mutex_unlock(&region_mutex);
  i = i + 1;
}
pthread_exit(NULL);
}
void *consumer()
{
int i,v;
printf("I'm a consumer\n");
for (i=0;i<100;i++) {
   pthread_mutex_lock(&region_mutex);
   v = get_buffer();
   pthread_mutex_unlock(&region_mutex);
   printf("got %d  ",v);
}
pthread_exit(NULL);
}
 

pthread example - hello program

Another simple pthread example. Threads are created by calling pthread_create() function. pthread_join() just waits for the specified thread to finish. The program terminates when all the threads are finished. The pthread example is shown below.


/*
 * p_hello.c -- a hello program (in pthread)
 */
#include <stdio.h>
#include <sys/types.h>
#include <pthread.h>

#define MAX_THREAD 1000

typedef struct {
 int id;
} parm;

void *hello(void *arg)
{
 parm *p=(parm *)arg;
 printf("Hello from node %d\n", p->id);
 return (NULL);
}

void main(int argc, char* argv[]) {
 int n,i;
 pthread_t *threads;
 pthread_attr_t pthread_custom_attr;
 parm *p;

 if (argc != 2)
 {
  printf ("Usage: %s n\n  where n is no. of threads\n",argv[0]);
  exit(1);
 }

 n=atoi(argv[1]);

 if ((n < 1) || (n > MAX_THREAD))
 {
  printf ("The no of thread should between 1 and %d.\n",MAX_THREAD);
  exit(1);
 }

 threads=(pthread_t *)malloc(n*sizeof(*threads));
 pthread_attr_init(&pthread_custom_attr);

 p=(parm *)malloc(sizeof(parm)*n);
 /* Start up thread */

 for (i=0; i<n; i++)
 {
  p[i].id=i;
  pthread_create(&threads[i], &pthread_custom_attr, hello, (void *)(p+i));
 }

 /* Synchronize the completion of each thread. */

 for (i=0; i<n; i++)
 {
  pthread_join(threads[i],NULL);
 }
 free(p);
}

pthread example - basic

A simple pthread example. It just creates two threads and wait for the threads to finish. Threads are created by calling pthread_create() function. pthread_join() just waits for the specified thread to finish. The program terminates when all the threads are finished. The pthread example is shown below.



// basic pthread example.
//
#include <stdio.h>
#include <pthread.h> 
main()  {
  pthread_t f2_thread, f1_thread; 
  void *f2(), *f1();
  int i1,i2;
  i1 = 1;
  i2 = 2;
  pthread_create(&f1_thread,NULL,f1,&i1);
  pthread_create(&f2_thread,NULL,f2,&i2);
  pthread_join(f1_thread,NULL);
  pthread_join(f2_thread,NULL);
}
void *f1(int *x){
  int i;
  i = *x;
  sleep(1);
  printf("f1: %d",i);
  pthread_exit(0); 
}
void *f2(int *x){
  int i;
  i = *x;
  sleep(1);
  printf("f2: %d",i);
  pthread_exit(0); 
}

Bezier curve in C/C++

Bezier curve implementation in C. Collected from the internet (the Author is revealed below). Bezier curve is composed of two anchor points (start, end) and two control points which bends the curve like a magnet. See following code for details.



/* Subroutine to generate a Bezier curve.
    Copyright (c) 2000 David F. Rogers. All rights reserved.

    b[]        = array containing the defining polygon vertices
                  b[1] contains the x-component of the vertex
                  b[2] contains the y-component of the vertex
                  b[3] contains the z-component of the vertex
    Basis      = function to calculate the Bernstein basis value (see MECG Eq 5-65)
    cpts       = number of points to be calculated on the curve
    Fractrl    = function to calculate the factorial of a number
    j[]        = array containing the basis functions for a single value of t
    npts       = number of defining polygon vertices
    p[]        = array containing the curve points
                 p[1] contains the x-component of the point
                 p[2] contains the y-component of the point
                 p[3] contains the z-component of the point
    t          = parameter value 0 <= t <= 1
*/

#ifdef HAVE_CONFIG_H
#ifdef WIN32
#include <windows_config.h>
#else
#include <config.h>
#endif
#endif // HAVE_CONFIG_H
#include <math.h>
#include <iostream>

#ifdef _DEBUG
#include <utils/dev/debug_new.h>
#endif // _DEBUG
using namespace std;

/* function to calculate the factorial */

SUMOReal factrl(int n)
{
    static int ntop=6;
    static SUMOReal a[33]={1.0,1.0,2.0,6.0,24.0,120.0,720.0}; /* fill in the first few values */
    int j1;

    if (n < 0) { throw 1; } //cout << "\nNegative factorial in routine FACTRL\n" ;    if (n > 32) { throw 1; } //cout << "\nFactorial value too large in routine FACTRL\n";
    while (ntop < n) { /* use the precalulated value for n = 0....6 */
        j1 = ntop++;
        a[n]=a[j1]*ntop;
    }
    return a[n]; /* returns the value n! as a SUMORealing point number */
}

/* function to calculate the factorial function for Bernstein basis */

SUMOReal Ni(int n,int i)
{
    SUMOReal ni;
    ni = factrl(n)/(factrl(i)*factrl(n-i));
    return ni;
}

/* function to calculate the Bernstein basis */

SUMOReal Basis(int n,int i,SUMOReal t)
{
    SUMOReal basis;
    SUMOReal ti; /* this is t^i */
    SUMOReal tni; /* this is (1 - t)^i */

    /* handle the special cases to avoid domain problem with pow */

    if (t==0. && i == 0) ti=1.0; else ti = pow(t,i);
    if (n==i && t==1.) tni=1.0; else tni = pow((1-t),(n-i));
    basis = Ni(n,i)*ti*tni; /* calculate Bernstein basis function */
    return basis;
}

/* Bezier curve subroutine */
void
bezier(int npts, SUMOReal b[], int cpts, SUMOReal p[])
{
    int i;
    int j;
    int i1;
    int icount;
    int jcount;

    SUMOReal step;
    SUMOReal t;

    SUMOReal factrl(int);
    SUMOReal Ni(int,int);
    SUMOReal Basis(int,int,SUMOReal);

/*    calculate the points on the Bezier curve */

    icount = 0;
    t = 0;
    step = (SUMOReal) 1.0/(cpts -1);

    for (i1 = 1; i1<=cpts; i1++){ /* main loop */

        if ((1.0 - t) < 5e-6) t = 1.0;

        for (j = 1; j <= 3; j++){ /* generate a point on the curve */
            jcount = j;
            p[icount+j] = 0.;
            for (i = 1; i <= npts; i++){ /* Do x,y,z components */
                p[icount + j] = p[icount + j] + Basis(npts-1,i-1,t)*b[jcount];
                jcount = jcount + 3;
            }
        }

        icount = icount + 3;
        t = t + step;
    }
}