When you want to ask for help in programming …

then use the following template:

  • Explain details that you see as much as possible. Environment, problem, etc.
  • Explain exactly what you want – what you think should be happening.
  • Explain what is actually happening.
  • Explain why you think it should be working differently.

By walking through all these steps you may find answer by yourself. In any case this will greatly increase a chance of getting adequate answer fast.

Context menus in Sciter

Context menu is a standard UI feature and in order to support them Sciter has following mechanisms on board:

  1. custom CSS property named context-menu. It defines location of DOM element ( usually it is one of <menu class=context> ) that will appear on context menu activation.
  2. Menu behaviors and their DOM events associated with menus.
  3. Context menu activation and initialization mechanism.

Continue reading “Context menus in Sciter”

[tiscript] ‘this’ and ‘this super’ function arguments

Each function in JavaScript and TIScript gets implicit argument named this.

So when you call method of some object as foo.bar(1) then foo object is passed to the bar(param) function as a value of this argument. And the param will get value of 1.

All of us who are practicing JS, Python, Ruby, etc. know about that ‘this’ thing pretty well.

But what shall you do when you have inner function and want to access ‘this’ value of outer function? The only way in JavaScript for that is to declare other variable with distinct name and assign ‘this’ to it: var that = this;.

To cover such code patterns I’ve introduced in TIScript “super this” concept, so we have following implicit variables in any function:

  • this – standard this variable;
  • this super – standard this variable of outer function;
  • this super super – this variable of outer-outer function;
  • etc.

Here is an example that outputs “6” in standard output:

class Test {

  function this(data) { // constructor
    this.data = data;   // instance field 
  }

  function Outer(arg1) {
    // this - hidden argument, local variable 
    // arg1 - argument, local variable

    function Inner(arg2)  {
      // this - hidden argument, local variable 
      // arg2 - argument, local variable
      // arg1 - outer variable - outer argument
      // this super - outer variable - outer 'this' argument
      
      return 
        (this super).data   // 1 
        + arg1              // 2
        + arg2              // 3
    }
    return Inner;
  }
}

var test = new Test(1);

var innerFunc = test.Outer(2);

stdout.println( innerFunc(3) );

Usability of tree and paged lists

I’ve found first answer in this topic on StackExchange extremely representative.

That reminded me discussion we had when were designing the first version of Evernote application.

Initially the Evernote has UI organized as “endless tape of notes”. Here is one of sketches that I did at that time:

Challenge there was to provide UI that allows the user to find notes quickly without need of excessive scrolling.

Each note may have so called tags (a.k.a. labels) assigned. By clicking on tag (left side bar) the tape will get filter applied – only notes with such tag are shown.

By expanding the tag (“+” sign) you can see intersection of notes that have this tags and some others. For example here click on hello->world (on the left) will give you set of notes with the condition has-tag:"hello" AND has-tag:"world" (see top bar):
Note tape with filter applied

And if you type “wonderful” in the search field you will get filter has-tag:"hello" AND has-tag:"world" AND has-text:"wonderful" applied.

This will give you single note:
tape with text filter

Pretty convenient I would say.

Sciter UI, application architecture

Architecture of applications that use Sciter based UI can be visualized as this:

Typically such applications contain two distinct layers:

  • UI layer that uses Sciter window with loaded HTML/CSS and scripts (code behind UI);
  • Application logic layer, most of the time that is native code implementing logic of the application.

Ideally these two layers shall be split appart – isolated from each other as they use conceptually different code models and probably code styles.

UI layer uses event driven model: "on click here expand section there and send request to logic layer for some data".

Application logic layer (ALL) is more linear usually. It is is a collection of functions that accepts some parameters and return some data. Even if ALL uses threads code inside such threads is still linear.

UI and app-logic interaction principles:

Most of the time code execution in UI applications is initiated by the UI itself but sometimes application code may generate its own events. For the UI such events are not anyhow different from pure UI events like mouse/keyboard clicks and the like. Informational flow between UI and ALL conceptually fall into these three groups:

  1. "get-request" – synchronous calls from UI to logic layer to get some data:
  2. "post-request" – asynchronous calls with callback "when-ready" functions:
  3. "application events" – application detects some change and needs to notify UI to reflect it somehow:

To support all these scenarios application can use only two "entry points" :

  • UI-to-logic calls: event_handler::on_script_call(name,args,retval)
  • logic-to-UI calls:  sciter::host:call_function(name, args ) – calls scripting function from C/C++ code. The name here could be a path: "namespace.func".  

get-requests

To handle UI-to-logic calls the application defines sciter::event_handler and attaches its instance to the Sciter window (view). Its on_script_call method will be invoked each time when script executes code like this in scipt:

view.getSomeData(param1, param2);

that will end up in this C/C++ call:

event_handler::on_script_call(NULL,
         "getSomeData", 
         2 /*argc*/ , 
         argv[2], 
         SCITER_VALUE& retval /* return value */ );

Sciter SDK contains convenient macro wrapper/dispatcher for such on_script_call function:

  class window
    : public sciter::host<window>
    , public sciter::event_handler
  {
    HWND   _hwnd;
    ...
    
    json::value  debug(unsigned argc, const json::value* arg);      
    json::value  getSomeData(json::value param1, json::value param2);      

BEGIN_FUNCTION_MAP
  FUNCTION_V("debug", debug);  
  FUNCTION_2("getSomeData", getSomeData); 
END_FUNCTION_MAP
  }

Declaration FUNCTION_2("getSomeData", getSomeData); binds view.getSomeData() in script with native window::getSomeData call.  

Therefore functionality exposed to the UI layer by logic layer can be defined as a content of single BEGIN_FUNCTION_MAP/END_FUNCTION_MAP block.

If your application contains many modules that are connected dynamically then you can define single view.exec("path", params...) function that will do name/call dispatch using some other principles:

var newAccount = view.exec("accounts/new", initialBalance);
view.exec("accounts/delete", accountId);
view.exec("accounts/update", {customerName:"new name"} );

application events

Application can generate some events by itself. When some condition or state inside application changes it may want to notify the UI about it. To do that application code can simply call function in script namespace with needed parameters.

Let’s assume that script has following declaration:

namespace Accounts 
{
  function created( accountId, accountProps ) {
     $(#accountList).append(...);
  }
  function deleted( accountId, accountProps ) {
     $(#accountList li[accid={accountId}]).remove();
  }
}

Then the application code can fire such events by simply calling:

window* pw = ...
pw->call_function("Accounts.created", accId, accFields );
pw->call_function("Accounts.deleted", accId );

post-request

Need of post request arises when some of work need to be done inside worker threads. Some task either take too long to complete or data for them needs to be loaded from the Net or other remote sources. UI cannot be blocked for long time – it still shall be responsive. The same situation happens in Web applications when JavaScript needs to send AJAX request. In this case callback functions are used. Call to native code includes reference to script function that will be executed when the requested data is available.

Consider this UI script function that asks app-logic to create some account on a remote server:

function createAccount( accountProps ) 
  {
    function whenCreated( accountId ) // inner callback function
    { 
      $(#accountList).append(...);
    }
    view.exec("accounts/create", accountProps, whenCreated );
  }

It passes accountProps data and callback function reference to the "accounts/create" thread. This thread creates the account (presumably takes some time) and invokes whenCreated at the end.

class createAccount: worker_thread 
  {
    handle<window> ui;
    SCITER_VALUE props;
    SCITER_VALUE callback;

    void run()
    {  // the thread body
       // ... do some time consuming stuff ...

       SCITER_VALUE accountId = createAccount(props);

       // done, execute the callback in UI thread:
       ui->ui_exec([=]() {
         callback.call(accountId); 
       }); 
    }
}

Note about that ui_exec function above: the UI is single threaded by its nature – singly display device, single keyboard and mouse, etc. Worker threads shall not access the UI directly – the UI shall be updated from UI thread only. The ui_exec function does just that – executes block of code in UI thread. See C++0x: Running code in GUI thread from worker threads article about it.

Epilogue

Having just two "ports"  (out-bound UI-to-logic and in-bound logic-to-UI) is a good thing in principle. This allows to isolate effectively two different worlds – asynchronous UI and deterministic application logic world. Easily "debuggable" and manageable.

HTML, CSS and script (code behind UI) runs in most natural mode and application core is comfortable too – not tied with the UI and its event and threading model.


C++0x: Running code in GUI thread from worker threads.

One of topics in design of multi-threading GUI applications is to choose method of calling GUI code from so called worker threads – threads that do some work in background. At some point they need to report results to the GUI. But GUI is a shareable resource so some form of synchronization is required. One approach is to use some global lock/mutex and capture it each time when any thread need to access tree of GUI objects.

Another method is to enqueue update tasks to the GUI thread. GUI thread will execute them when it can. This approach does not require synchronization code to be spread across whole application. The whole system will work faster and probability of deadlocks/synchronization issues is almost zero in this case.

The only problem: for each action that you need to do in GUI thread you will need to create separate task/object for deferred execution (or to use some other mechanism like marshalling in COM).

With new features of C++0x we can accomplish this with almost zero overhead. In particular we will need lambdas.

Here is how our code of worker thread function may look like:

void worker_thread()
{
  dom::element some_el = ...; 
  string html_to_set = ...;
  int result;
  ...
  auto gui_code_block = [some_el,html_to_set,&result] () 
  { // executed in GUI thread
    if(some.children() > 10)
      some.set_html(html_to_set);
    result = 20; // report some result if needed.
  };
  gui_exec(gui_code_block); 
  ...
  if( result == 20 ) ...;
  ...
}

As you see here I am declaring inline code block that will be
executed in GUI thread while the rest of the function body will run in its own thread.

The key point here is the gui_exec() function that may look like as:

void gui_exec( std::function<void()> gui_block )
{
  event evt;
  PostMessage(hwnd, WM_NULL, WPARAM(&evt),LPARAM(&gui_block));
  evt.wait(); // suspend worker thread until GUI will execute the block.
}

It posts the message to the GUI with address of synchronization object and
address of our GUI code block (function in fact). It is simple as you see.

And the last piece – we need message handler in GUI thread that will actually execute that code block. The best place for it is inside so called “GUI message pump” – Get/DispatchMessage loop that exist in any GUI application:

typedef std::function<void(void)> gui_block;

while (GetMessage(&msg, NULL, 0, 0))
{
    if( msg.message == WM_NULL )
    {
      gui_block* pf = reinterpret_cast<gui_block*>(msg.lParam);
      event* pe = reinterpret_cast<event*>(msg.wParam);
      (*pf)();  // execute the block
      pe->signal(); // signal that we've done with it
                        // this will resume execution of worker thread.
    }
    else 
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
}

And that is it.

The only note: I am using WM_NULL message here but in reality you should use some other not that popular message for it. RegisterWindowMessage() will help to get that message number.

C++, how to change class of object in runtime.

There is a nice feature in TIScript that allows to change class of already instantiated object.
Let’s say we have two classes:

class MyWidget : Behavior { ... }
class MyWidgetReadonly : Behavior { ... }

that handle user interaction with some widget on the screen. This widget can operate in two distinct modes: normal and read-only.
These modes share the same widget state but have substantially different behavioral characteristic. So it makes sense to split these two sets of methods into two classes to avoid pollution of our code by the crowd of if(readonly) ... else ....
When needed we can switch class of the object like this:

var widget = new MyWidget();
....
if( needReadOnlyMode )
  widget.prototype = MyWidgetReadonly; // changing class of the object.
...

Pretty much all dynamic languages allow to do such things. E.g. in Python you can modify obj.__bases__.

Surprisingly you can do the same in C++ too and without any “hack”. We can use so called placement new operator to do the trick. Here is how.

Let’s define our class hierarchy as this:

class MyWidget 
{
public:
  int data;  // state variables here
  virtual void on_mouse() { printf("normal on_mouse, data=%d\n",data); }
  virtual void on_key() { printf("normal on_key\n"); }
};
class MyWidgetReadOnly: public MyWidget   
{
  // no data at all here, sic!
  virtual void on_mouse() { printf("read-only on_mouse, data=%d\n",data); }
  virtual void on_key() { printf("read-only on_key\n"); }
};

And we will switch class of our object using this helper template function:

// turn_to(A* obj) changes class of the object 
// that means it just replaces VTBL of the object by VTBL of another class.
// NOTE: these two classes has to be ABI compatible!
template <typename TO_T, typename FROM_T>
  inline void turn_to(FROM_T* p) 
  { 
    assert( sizeof(FROM_T) == sizeof(TO_T));
    ::new(p) TO_T(); // use of placement new
  }

Note: This will work if our class has default constructor that does not initialize any member variables.

Let’s try this small sample ( test.cpp ):

#include <new>
#include <assert.h>
// turn_to(A* obj) changes class of the object 
// that means it just replaces VTBL of the object by VTBL of another class.
// NOTE: these two classes has to be ABI compatible!
template <typename TO_T, typename FROM_T>
  inline void turn_to(FROM_T* p) 
  { 
    assert( sizeof(FROM_T) == sizeof(TO_T));
    ::new(p) TO_T(); // use of placement new
  }

class MyWidget 
{
public:
  int data;  // state variables here
  virtual void on_mouse() { printf("normal on_mouse, data=%d\n",data); }
  virtual void on_key() { printf("normal on_key\n"); }
};
class MyWidgetReadOnly: public MyWidget   
{
  // no data at all here, sic!
  virtual void on_mouse() { printf("read-only on_mouse, data=%d\n",data); }
  virtual void on_key() { printf("read-only on_key\n"); }
};

int main(int argc, char* argv[])
{
  MyWidget *w = new MyWidget();
  w->data = 123;
  w->on_mouse();
  turn_to<MyWidgetReadOnly>(w); // turning the instance to MyWidgetReadOnly class.
  w->on_mouse();
	return 0;
}

After compiling and running it we should see in console output like this:

normal on_mouse, data=123
read-only on_mouse, data=123

So it works – we are able to transform existing instance of some class to the instance of other class.

DISCLAIMER:

Be warned that this is a Jedi Sword feature. Use it responsibly, only if you know why you need it. And what are the consequences. Even mentioning of this approach in some software development companies (that usually are on the Dark Side) may damage your reputation.

[how-to] Add entry to Windows Explorer context “New” menu.

Pretty frequently I am creating .htm and .tis files. For example for testing purposes.
Usually such files use common template like html/head/body elements, etc.

Here is the add-html-template.reg file that adds “New HTML Document” into context menu of Windows Explorer. So to create HTML file it is enough to right-click in some folder and select “New/New HTML Document” menu item.

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\.htm\ShellNew]
"FileName"="C:\\utils\\template.htm"

Copy block of text above into, say, file named add-html-template.reg and double-click on it to run. Registry Editor will ask permission to update registry. “Ok” on that and reboot Windows (or restart Windows Explorer). Done.

Last note: path after “FileName” – it should contain real path of the template.