Getting Acquainted with Document/View Framework – Simple Image Viewer

In my previous posts here and here I showed how to create a simple application which uses Document/View framework. Now I’m going to show more complex example – image viewer with scrolling and selection rectangle. As far as I can see from wxForum, implementation of selection-related functionality is some kind of complex but very useful task.

So, let’s start from simple part. The simplest task here is modification of our wxDocument-related class.

Continue reading…

wxJSON 0.5.0 Released

This wxJSON release adds support for 64-bits integers on those platforms that have native support for it such as, for example, Windows and GNU/Linux.

You can disable 64-bits integer support if you do not need (or do not want) it. The new version is compatible wih the past: if you do not need 64-bits integers you can still use this new version of the library without the need to rewrite your application.

To know more about the new feature read the this page:

Реализация Job Queue на wxWidgets (+исходник)

При работе с потоками часто приходится делать кучу однотипных задач: создавать класс, производный от wxThread, реализовывать метод Entry() для этого класса, синхронизацию с главным потоком и т.д.

Eran, автор CodeLite IDE поделился кодом класса JobQueue, который реализует пул потоков и позволяет выполнять задачи в фоновом режиме.

class MyJob : public Job {
public: 
        MyJob(){}
        ~MyJob(){}
       
        // Implement your processing code here
        void Process() {
                wxPrintf(wxT("Just doing my work...n"));
        };
};

// define some custom job with progress report
class MyJobWithProgress : public Job {
public: 
        MyJobWithProgress(wxEvtHandler *parent) : Job(parent){}
        ~MyJobWithProgress(){}
       
        // Implement your processing code here
        void Process() {
                // report to parent that we are at stage 0
                Post(0, wxT("Stage Zero"));
                // do the work
                wxPrintf(wxT("Just doing my work...n"));
                // report to parent that we are at stage 1
                Post(1, wxT("Stage Zero Completed!"));
        };
};

// somewhere in your code, start the JobQueue
// for the demo we use pool of size 5
JobQueueSingleton::Instance()->Start(5);

// whenever you want to process MyJob(), just create new instance of MyJob() and add it to the JobQueue
JobQueueSingleton::Instance()->AddJob( new MyJob() );

// at shutdown stop the job queue and release all its resources
JobQueueSingleton::Instance()->Stop();
JobQueueSingleton::Release();

// OR, you can use JobQueue directly without the JobQueueSingleton wrapper class
// so you could have multiple instances of JobQueue 

Главный поток получает уведомления таким вот образом:

// in the event table
EVT_COMMAND(wxID_ANY, wxEVT_CMD_JOB_STATUS, MyFrame::OnJobStatus)

void MyFrame::OnJobStatus(wxCommandEvent &e)
{
wxString msg;
msg < < wxT("Job progress: Stage: ") << e.GetInt() << wxT(" Message: ") << e.GetString(); wxLogMessage(msg) } [/sourcecode] Скачать исходный код
Читать обсуждение на wxForum

wxJSON 0.4 Released

This release adds the ‘copy-on-write’ feature to the copy ctor and assignment operator of JSON value class.
Note that this new feature only affects the internal representation of JSON values and does not add new features in the class’s interface.
Also note that for JSON value objects, COW is not as efficient as expected.
To know more about this topic read this page:

The wxJSON library is now complete and this release should be considered a final beta release.
JSON data format is very stable. It is accredited to be stable forever or, at least, until programming language’s variables are based on numbers, strings, booleans, structures and arrays.

No other feature should have to be added to the library and I think that, after a few months used for discovering and fixing bugs, I will release the stable version 1.0

This will be the good occasion to, eventually, break the compatibility with the old versions 0.x by changing memberfunction’s names and/or parameters.
If you have any comment, suggestion or hint, feel free to write to me or post an answer to this topic.

Regards
Luciano

Getting Acquainted with Document-View architecture – Part II – Simple Text Editor

Today we’ll dig a little bit deeper into Document/View framework provided by wxWidgets and will see how to create a simple text editor using this framework.
We’ll take the source code from the previous article of this series and add some modifications. You will see below that modifications are rather simple and take almost no time.
First of all we have to make wxDocTemplate to handle desired file extensions (in our case it’s TXT).
Continue reading…

Getting Acquainted with Document-View architecture – Part I

A few weeks ago, working on TIFF viewer software, I realized that many developers, who use wxWidgets in their work, spend their time on implementing the functionality which already exists in wxWidgets library. Such tasks as loading/saving documents, edit/copy/paste functionality, separating the GUI from application’s logic, all of them can be performed in a far more simple way than people usually do. Why should I write the code which creates wxFileDialog, checks the current state of application, asks user if he/she wants to save the changes, shows wxFileDialog for saving document into a file and so on? Why should I do everything by hands? Life is too short for spending it to all these things 😉
But there no need to give up because there is a thing (in fact, a set of things ;)) which allow to avoid writing tons of unnecessary code. It is wxWidgets’s Document/View framework.
It is the first article from a set of articles about such an interesting part of wxWidgets as Document/View framework.
As always, I’ll try to explain everything by an example. So, the first step will be creating a skeleton application which utilizes Document/View architecture:

DocViewTestApp.h

#ifndef _DOC_VIEW_TEST_APP_H
#define _DOC_VIEW_TEST_APP_H

#include 
#include 

class DocViewTestApp : public wxApp
{
	wxDocManager * m_DocManager;
public:
	virtual bool OnInit();
	virtual int OnExit();
};

DECLARE_APP(DocViewTestApp)

#endif

DocViewTestApp.cpp

#include "DocViewTestApp.h"
#include "DocViewTestMainFrame.h"

IMPLEMENT_APP(DocViewTestApp);

bool DocViewTestApp::OnInit()
{
	m_DocManager = new wxDocManager;
	m_DocManager->SetMaxDocsOpen(1);

	DocViewTestMainFrame * frame = new DocViewTestMainFrame(m_DocManager, NULL);
	SetTopWindow(frame);
	frame->Centre();
	frame->Show();

	return true;
}

int DocViewTestApp::OnExit()
{
	wxDELETE(m_DocManager);
	return wxApp::OnExit();
}

As you can see, the application class contains a member m_DocManager which is an object of wxDocManager class.

The wxDocManager class is part of the document/view framework supported by wxWidgets, and cooperates with the wxView, wxDocument and wxDocTemplate classes.

DocViewTestMainFrame.h

#ifndef _DOC_VIEW_TEST_MAINFRAME_H
#define _DOC_VIEW_TEST_MAINFRAME_H

#include 
#include 
#include 

#define DocViewTestMainFrameTitle _("DocView Test")

class DocViewTestMainFrame : public wxDocParentFrame
{
	DECLARE_DYNAMIC_CLASS(DocViewTestMainFrame)

	wxAuiManager m_AuiManager;

	void CreateControls();
	wxMenuBar * CreateMenuBar();
public:
	DocViewTestMainFrame();
	DocViewTestMainFrame(wxDocManager * docManager, wxFrame * parent, 
		wxWindowID id = wxID_ANY, 
		const wxString & title = DocViewTestMainFrameTitle);
	~DocViewTestMainFrame();
	bool Create(wxDocManager * docManager, wxFrame * parent, 
		wxWindowID id = wxID_ANY, 
		const wxString & title = DocViewTestMainFrameTitle);

	DECLARE_EVENT_TABLE()
	void OnExit(wxCommandEvent & event);
};

#endif

DocViewTestMainFrame.cpp

#include "DocViewTestMainFrame.h"

IMPLEMENT_DYNAMIC_CLASS(DocViewTestMainFrame, wxDocParentFrame)

BEGIN_EVENT_TABLE(DocViewTestMainFrame, wxDocParentFrame)
EVT_MENU(wxID_EXIT, DocViewTestMainFrame::OnExit)
END_EVENT_TABLE()

DocViewTestMainFrame::DocViewTestMainFrame()
{
}

DocViewTestMainFrame::DocViewTestMainFrame(wxDocManager * docManager, wxFrame * parent, 
	wxWindowID id, const wxString & title)
{
	Create(docManager, parent, id, title);
}

DocViewTestMainFrame::~DocViewTestMainFrame()
{
	m_AuiManager.UnInit();
}

bool DocViewTestMainFrame::Create(wxDocManager * docManager, wxFrame * parent, 
	wxWindowID id, const wxString & title)
{
	bool res = wxDocParentFrame::Create(docManager, parent, id, title, 
		wxDefaultPosition, wxSize(650, 450));
	if(res)
	{
		CreateControls();
	}
	return res;
}

void DocViewTestMainFrame::CreateControls()
{
	SetMenuBar(CreateMenuBar());
	m_AuiManager.SetManagedWindow(this);
	

	m_AuiManager.AddPane(new wxPanel(this, wxID_ANY), 
		wxAuiPaneInfo().CenterPane().Name(_("Canvas")));

	m_AuiManager.Update();
}

wxMenuBar * DocViewTestMainFrame::CreateMenuBar()
{
	wxMenuBar * result = new wxMenuBar;

	wxMenu * fileMenu = new wxMenu;
	fileMenu->Append(wxID_NEW, _("New\tCtrl+N"));
	fileMenu->Append(wxID_OPEN, _("Open\tCtrl+O"));
	fileMenu->AppendSeparator();
	fileMenu->Append(wxID_SAVE, _("Save\tCtrl+S"));
	fileMenu->Append(wxID_SAVEAS, _("Save as..."));
	fileMenu->AppendSeparator();
	fileMenu->Append(wxID_EXIT, _("Exit\tAlt+F4"));

	wxMenu * helpMenu = new wxMenu;
	helpMenu->Append(wxID_ABOUT, _("About..."));

	result->Append(fileMenu, _("File"));
	result->Append(helpMenu, _("Help"));

	return result;
}

void DocViewTestMainFrame::OnExit(wxCommandEvent &event)
{
	Close();
}

Our main frame class is derived from wxDocParentFrame class. wxDocParentFrame provides a default top-level frame for applications which utilize Document/View architecture. It can be used ONLY FOR SDI (Single Document Interface), not MDI (Multiple Document Interface) applications. As you can see, we pass a pointer to wxDocManager object to the constructor of our main frame. Passing of wxDocManager object to the constructor is mandatory because in other way our frame will not be able to load the documents.

Now, after we finished a GUI-related part, we have to create our Document and View classes:

DocViewTestDocument.h

#ifndef _DOC_VIEW_TEST_DOCUMENT_H
#define _DOC_VIEW_TEST_DOCUMENT_H

#include 
#include 

class DocViewTestDocument : public wxDocument
{
	DECLARE_DYNAMIC_CLASS(DocViewTestDocument)
public:
	DocViewTestDocument();
};

#endif

DocViewTestDocument.cpp

#include "DocViewTestDocument.h"

IMPLEMENT_DYNAMIC_CLASS(DocViewTestDocument, wxDocument)

DocViewTestDocument::DocViewTestDocument()
{
	wxLogTrace(wxTraceMask(), wxT("DocViewTestDocument::DocViewTestDocument"));
}

DocViewTestView.h

#ifndef _DOC_VIEW_TEST_VIEW_H
#define _DOC_VIEW_TEST_VIEW_H

#include 
#include 

class DocViewTestView : public wxView
{
	DECLARE_DYNAMIC_CLASS(DocViewTestView)
public:
	DocViewTestView();

	virtual void OnDraw(wxDC* dc);
	virtual void OnUpdate(wxView *sender, wxObject *hint = (wxObject *) NULL);
    virtual bool OnClose(bool deleteWindow = true);
};

#endif

Our DocViewTestView class overrides wxView::OnDraw, wxView::OnUpdate and wxView::OnClose methods.

The default implementation calls wxDocument::Close to close the associated document. Does not delete the view. The application may wish to do some cleaning up operations in this function, if a call to wxDocument::Close succeeded

DocViewTestView.cpp

#include "DocViewTestView.h"

IMPLEMENT_DYNAMIC_CLASS(DocViewTestView, wxView)

DocViewTestView::DocViewTestView()
{
	wxLogTrace(wxTraceMask(), wxT("DocViewTestView::DocViewTestView"));
	SetFrame(wxTheApp->GetTopWindow());
}

void DocViewTestView::OnDraw(wxDC* dc)
{
	wxLogTrace(wxTraceMask(), wxT("DocViewTestView::OnDraw"));
}

void DocViewTestView::OnUpdate(wxView *sender, wxObject *hint)
{
	wxLogTrace(wxTraceMask(), wxT("DocViewTestView::OnUpdate"));
}

bool DocViewTestView::OnClose(bool deleteWindow)
{
	wxLogTrace(wxTraceMask(), wxT("DocViewTestView::OnClose"));
	if (!GetDocument()->Close())
	{
        return false;
	}

	SetFrame(NULL);
    Activate(false);
    return true;
}

As you can see, we associate a top level window of our application with each object of DocViewTestView class. After that DocViewTestView object will receive events from this frame. In fact, we can associate not only wxFrame-derived objects but any wxWindow-derived object, e.g. wxScrolledWindow or wxTextCtrl.

Note that this “frame” is not a wxFrame at all in the generic MDI implementation which uses the notebook pages instead of the frames and this is why this method returns a wxWindow and not a wxFrame.

Now, after we created Document and View classes, we have to create a document template. The wxDocTemplate class is used to model the relationship between a document class and a view class.

DocViewTestApp.cpp

#include "DocViewTestApp.h"
#include "DocViewTestMainFrame.h"
#include "DocViewTestDocument.h"
#include "DocViewTestView.h"
...
bool DocViewTestApp::OnInit()
{
	m_DocManager = new wxDocManager;
	m_DocManager->SetMaxDocsOpen(1);

	wxDocTemplate * docTemplate = new 
		wxDocTemplate(m_DocManager, _("DocViewTest Document"), 
		wxT("*.png;*.bmp;*.tiff;*.tif;*.jpg;*.jpeg"), wxEmptyString,
		wxT("png"), wxT("DocViewTest Doc"), wxT("DocViewTest View"),
		CLASSINFO(DocViewTestDocument), CLASSINFO(DocViewTestView));
	...
}
...

As you can see here, for each wxDocTemplate object we have to specify a wxDocManager, document name (will be displayed in the file filter list of Windows file selectors), wildcard, default directory (we left this field empry by using wxEmptyString), default file extension, document type name, view type name, document and view classes.
Now we can start the application and see how it works:

Skeleton application which uses wxWidgets Document/View Framework

Skeleton application which uses wxWidgets Document/View Framework

For the first look our application does nothing. But it is only “for the first look”. If you select File -> Open menu item, file open dialog will appear and if you select a file, then the title of our main frame will be changed, if you select File -> New menu item, the title of our main frame will be changed to the name of newly created document. Also if you select File -> Save menu item, save file dialog box will appear (but in fact, you will not be able to save the document because this behavior is not specified in our skeleton application).
Also if you perform these tasks:

  • Create new document
  • Open a file
  • Save a file
  • Create new document
  • Close the application

And then will look to “Output” window of your IDE, you will see such messages:

01:54:47: DocViewTestDocument::DocViewTestDocument
01:54:47: DocViewTestView::DocViewTestView
01:54:51: DocViewTestView::OnClose
01:54:51: DocViewTestDocument::DocViewTestDocument
01:54:51: DocViewTestView::DocViewTestView
01:54:51: DocViewTestView::OnUpdate
01:55:02: DocViewTestView::OnClose
01:55:02: DocViewTestDocument::DocViewTestDocument
01:55:02: DocViewTestView::DocViewTestView
01:55:24: DocViewTestView::OnClose

Now you can get an idea about how everything works:

  • When you execute wxID_NEW command, new document is created, then a view for this document is created
  • Then you executed wxID_OPEN command, open file dialog is displayed, after you select a file wxView::OnClose method is called, then view and document are destroyed, new document is created, then a view for this document is created, wxView::OnUpdate method is called.
  • When you exit the application wxView::OnClose method is called, then view and document are destroyed.

All wxDocument-, wxView– and wxDocTemplate-derived objects are deleted automatically when wxDocManager object is destroyed (in our application we destroy it in wxApp::OnExit method).
That is all for today. In the next article I will show how to implement simple loading/saving functionality.

Download the source code for this article.

Нужна помощь в улучшении документации к библиотеке wxWidgets

wxWidgets находится в процессе работы над улучшением документации – мигрирации из текущей системы, основанной на LaTeX, в Doxygen (используя отдельный набор “интерфейсных” заголовков, вместо рабочих заголовков wxWidgets).

Разработчики wxWidgets потратили несколько месяцев на создание скриптов для автоматического преобразования документации, и уже достигли той точки, где скрипты уже не могут помочь. В Документация wxWidgets довольно обширна и файлы с документацией в новом формате требуют ручной обработки чтобы исключить ошибки, которые могли появиться в процессе автоматического преобразования.

Итак, мы нуждаемся в вашей помощи для завершения этого процесса в разумные сроки. Все подробности можно найти здесь.

Если вы заинтересованы, но вам надо информация о том, как все настроить, или если у вас есть какие-либо сомнения или вопросы, не стесняйтесь задать их здесь.

Это хорошая возможность:

  • Познакомиться с wxWidgets ближе
  • Улучшить те части документации, которые вам не очень нравились
  • Помочь сделать wxWidgets еще более конкурентоспособным инструментом разработки

Собираем IDE Code::Blocks под FreeBSD

Сегодня вашему вниманию предлагается статья Cosm’а о том, как собрать и настроить среду разработки Code::Blocks под FreeBSD.

В этой статье я попытаюсь вам объяснить как ставить Code::Blocks в FreeBSD. Code::Blocks это кросплатформенная IDE построена с помощью wxWidgets. В моем случае установка проводилась на FreeBSD-7.0-Release-i386.
Continue reading…

wxJSON 0.3.0 Released

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

This release adds support for Unicode.
Read more about the new features of wxJSON.