org.vishia.gral.base

## Class GralGraphicThread

- java.lang.Object
- - org.vishia.gral.base.GralGraphicThread

- All Implemented Interfaces:
    java.lang.Runnable

      public class GralGraphicThread
      extends java.lang.Object
      implements java.lang.Runnable

  This class is the base for implementation of graphic threading. It is implemented for SWT and Swing yet.
  The functionality and necessity of a graphic thread:
  Swing is not thread safe but it works if widgets are changed from other threads. SWT causes an exception if a widget is changed in another thread than the graphic thread. The graphic thread in SWT calls the operation system routine to dispatch events. If any event call-back method is invoked from the graphic system, it runs in the graphic thread. Therefore all other widgets can changed in this thread. For example a button is pressed, and therefore some widgets are changed in appearance (setText(), setColor()) or new widgets are created and other are deleted.
  Necessity of other threads than the graphic thread, divide of functionality in some threads:
  To get the data from the application some actions should be done which may need time or/and may wait of something for example network communication transfer. If that action are done in the graphic thread immediately, the graphic seems as frozen. It doesn't execute other activities which are need for example to resize a window, hide and focus it etc. This phenomena is known by some graphic applications. Often, firstly a pilot application works well because the actions are done in less 100 milliseconds. That's okay. But if the environment will be more and more complex and the functionality increases in real applications, the waiting time increases from 100 to ... 1 second and more, and the graphic hangs in some situations. It is bothering. Therefore long running or waiting actions should be organized in another thread. The GUI can be show any hint that some action is executing. Other actions can be done in this time, especially abort a non-response action. The GUI itself runs well.
  To organize such working, actions on the GUI should notify and inform only the other threads. The other threads executes the necessary activity. If any activity is finished, its result should be shown on the graphic. If any activity is progressed, it may be shown too, for example in steps of 300 milliseconds.
  The graphic content should be changed from some other thread. But because the graphic isn't thread safe. The graphic can't be changed in the other thread directly. The information which should be presented should be queued. That is the mechanism:
  - Version 1: An execution sequence for the graphic thread is written in a derived instance of
    - `GralGraphicTimeOrder#executeOrder(boolean)`.
    That instance should be queued calling
    - `addDispatchOrder(GralGraphicTimeOrder)`.
    With them the graphic thread is woken up because `wakeup()` is called in the 'addDispatchOrder()'-routine.
    In the graphic thread execution loop the `#queueGraphicOrders` queue is checked and all queued method are invoked. That executes the 'widget.setText(text)' or the other routines from the users programm in the `GralGraphicTimeOrder#executeOrder(boolean)`.
    After the queue is checked the `#dispatchOsEvents()` is called. In SWT it calls the operation system dispatching loop. If the underlying graphic system has its own graphic dispatching thread that thread is woken up only to present the changes in the widgets. If all graphic dispatching is done, `#graphicThreadSleep()` let this thread sleeping, its all done.
    The instance of `GralGraphicTimeOrder` will be remain in the queue. For single activities it should be queued out by itself calling its own `GralGraphicTimeOrder#removeFromList(GralGraphicThread)` method in its `GralGraphicTimeOrder#executeOrder(boolean)`-routine. Another possibility is to have instances of `GralGraphicTimeOrder` which are queued for any time. They are invoked whenever `wakeup()` is called.
  - Version 2: The order or commission can be instructed to the `setInfo(cmd, ...data)`-method of a `GralWidget`:
    - `GralMng#setInfo(org.vishia.gral.base.GralWidget widget, int cmd, int ident, Object toshow, Object data)`
    This method fills a queue of the `GralMng`:
    - `GralMng.WidgetChangeRequExecuter#guiChangeRequests`
    - `GralMng.WidgetChangeRequExecuter#executeOrder(boolean)` polls that queue.
    - `GralMng#widgetChangeRequExecuter`: The instance in the GralWidgetManager.
    The instance is a permanent member of the `#queueGraphicOrders` queue, it is executed any time when a `wakeup()` will be invoked.
    The commission for changing any widget is given in that way with a specific command and data, which is realized in the method:
    - `GralMng#setInfoGthread(org.vishia.gral.ifc.GralWidget_ifc, int, int, Object, Object)`
    That method assigns some commands to the implementation level standard invocation methods to change widget contents such as setText() or setColor(). To support this action independently of the graphic implementation two interfaces are defined:
    - `GralWidgetGthreadSet_ifc` and
    - `GralWindow_setifc`
    That interfaces defines the universal changed methods for widgets and windows.
    The second version of instructing widget changing requires less programming effort, but it supports only standard operations.
  - Version 3: All data of a widget are stored in graphic-independent fields of the derived instance of the widget. That can be done in any thread without mutex mechanisms. If there are more as one thread which changes the same widget, the last wins. That may be a non-usual case. If one thread changes a text and another thread changes a color, it may be okay. There is no necessity to make it thread-safe. But if it may be necessity, the user can wrap the access with specific synchronized methods. After any changing of content, `GralWidget.repaint(int, int)` should be invoked with a suitable delay. That queues the repaint instance
    - `GralWidget.repaintRequ` (it is private) in the queue
    - `#queueDelayedGraphicOrders`
    In that way the repaint is executed in the graphic thread and fills the graphical widgets.
  Secondary a system of delayed execution is given. All commissions to the graphic thread can be instruct with a delay. There are a queues for delayed execution and an extra time thread `#runTimer`. The starting time can be shelved if there are queued and re-instruct further time. This is necessary because some graphic appearance changing requests may be given in any thread one after another, and the graphic thread should be invoked not for any one request, but only if all requests are given. It saves thread switch activity. Especially if some data are changed and a `GralWidget.repaint()` request only applies the data to the widgets, that 'repaint()' should be invoked only if all data are given. But any data changing don't may know whether it is the last one. Therefore `GralWidget.repaint(int, int)` can be called after any data changing with shelving the repaint time. The repaint is executed not till the activity of data changing is finished.

- - ### Nested Class Summary

    Nested Classes
    Modifier and Type | Class and Description
    --- | ---
    `static class` | `GralGraphicThread.ImplAccess` This class is used only for the implementation level of the graphic.

  - ### Field Summary

    Fields
    Modifier and Type | Field and Description
    --- | ---
    `protected boolean` | `bExit` set to true to exit in main
    `protected boolean` | `bStarted` True if the startup of the main window is done and the main window is visible.
    `protected MinMaxTime` | `checkTimes` Instance to measure execution times.
    `(package private) boolean` | `debugPrint`
    `protected long` | `graphicThreadId` The thread id of the managing thread for graphic actions.
    `private GralGraphicThread.ImplAccess` | `impl`
    `protected boolean` | `isWakedUpOnly`
    `(package private) EventTimerThread` | `orderList`
    `private java.util.concurrent.ConcurrentLinkedQueue<GralGraphicTimeOrder>` | `queueOrdersToExecute` Queue of orders to execute in the graphic thread before dispatching system events.
    `static java.lang.String` | `version` Version and history.

  - ### Constructor Summary

    Constructors
    Constructor and Description
    `GralGraphicThread()` Constructs this class as superclass.

  - ### Method Summary

    All Methods Instance Methods Concrete Methods
    Modifier and Type | Method and Description
    --- | ---
    `void` | `addDispatchOrder(GralGraphicTimeOrder order)` Adds the order to execute in the graphic dispatching thread.
    `void` | `addEvent(java.util.EventObject event)`
    `long` | `getThreadIdGui()`
    `boolean` | `isRunning()`
    `boolean` | `isStarted()`
    `boolean` | `isTerminated()`
    `EventTimerThread` | `orderList()`
    `void` | `run()` The run method of the graphic thread.
    `(package private) void` | `step()`
    `(package private) void` | `storeEvent(java.util.EventObject ev)` Stores an event in the queue, able to invoke from any thread.
    `void` | `waitForStart()`
    `void` | `wakeup()` This method should wake up the execution of the graphic thread because some actions are registered..

    - ### Methods inherited from class java.lang.Object

      `clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

- - ### Field Detail

    - #### version

          public static final java.lang.String version

      Version and history.
      - 2016-07-16 Hartmut chg: The main window will be created with same methods like all other windows.
      - 2015-01-17 Hartmut chg: Now it is an own instance able to create before the graphic is established. The graphical implementation extends the `GralGraphicThread.ImplAccess`.
      - 2012-04-20 Hartmut bugfix: If a `GralGraphicTimeOrder` throws an exception, it was started again because it was in the queue yet. The proplem occurs on build graphic. It was repeated till all graphic handles are consumed. Now the `#queueGraphicOrders` entries are deleted first, then executed. TODO use this class only for SWT, use the adequate given mechanism for AWT: java.awt.EventQueue.invokeAndWait(Runnable). use Runnable instead GralDispatchCallbackWorker.
      - 2012-03-15 Hartmut chg: Message on exception.
      - 2011-11-08 Hartmut new: Delayed orders to dispatch in the graphic thread: Some actions need some calculation time. If they are called in a fast repetition cycle, a follow up effect may occur. Therefore actions should be registered with a delayed start of execution, the start time should be able to putting off till all repetitions (for example key repetition) are done.
      - 2011-11-00 Hartmut created: as own class from Swt widget manager.
      Copyright/Copyleft: For this source the LGPL Lesser General Public License, published by the Free Software Foundation is valid. It means:
      1. You can use this source without any restriction for any desired purpose.
      2. You can redistribute copies of this source to everybody.
      3. Every user of this source, also the user of redistribute copies with or without payment, must accept this license for further using.
      4. But the LPGL is not appropriate for a whole software product, if this source is only a part of them. It means, the user must publish this part of source, but don't need to publish the whole source of the own product.
      5. You can study and modify (improve) this source for own using or for redistribution, but you have to license the modified sources likewise under this LGPL Lesser General Public License. You mustn't delete this Copyright/Copyleft inscription in this source file.
      If you are indent to use this sources without publishing its usage, you can get a second license subscribing a special contract with the author.
      See Also:
        Constant Field Values

    - #### graphicThreadId

          protected long graphicThreadId

      The thread id of the managing thread for graphic actions.

    - #### debugPrint

          boolean debugPrint

    - #### isWakedUpOnly

          protected boolean isWakedUpOnly

    - #### bStarted

          protected boolean bStarted

      True if the startup of the main window is done and the main window is visible.

    - #### bExit

          protected boolean bExit

      set to true to exit in main

    - #### checkTimes

          protected MinMaxTime checkTimes

      Instance to measure execution times.

    - #### queueOrdersToExecute

          private final java.util.concurrent.ConcurrentLinkedQueue<GralGraphicTimeOrder> queueOrdersToExecute

      Queue of orders to execute in the graphic thread before dispatching system events. Any instance will be invoked in the dispatch-loop. See `#addTimeOrder(Runnable)`. An order can be stayed in this queue for ever. It is invoked any time after the graphic thread is woken up and before the dispatching of graphic-system-event will be started. An order may be run only one time, than it should delete itself from this queue in its run-method.

    - #### orderList

          EventTimerThread orderList

    - #### impl

          private GralGraphicThread.ImplAccess impl

  - ### Constructor Detail

    - #### GralGraphicThread

          public GralGraphicThread()

      Constructs this class as superclass. The constructor of the inheriting class has some more parameter to build the primary window. Therefore the `#threadGuiDispatch`.start() to start the `run()` method of this class should be invoked only in the derived constructor after all parameter are saved to execute the overridden `#initGraphic()` method.
      Parameters:
        `name` - Name of the thread.

  - ### Method Detail

    - #### storeEvent

          void storeEvent(java.util.EventObject ev)

      Stores an event in the queue, able to invoke from any thread.
      Parameters:
        `ev` -

    - #### orderList

          public EventTimerThread orderList()

    - #### addDispatchOrder

          public void addDispatchOrder(GralGraphicTimeOrder order)

      Adds the order to execute in the graphic dispatching thread. It is the same like order.`GralGraphicTimeOrder.activate()`.
      Parameters:
        `order` -

    - #### addEvent

          public void addEvent(java.util.EventObject event)

    - #### getThreadIdGui

          public long getThreadIdGui()

    - #### wakeup

          public void wakeup()

      This method should wake up the execution of the graphic thread because some actions are registered..

    - #### waitForStart

          public void waitForStart()

    - #### isStarted

          public boolean isStarted()

    - #### isRunning

          public boolean isRunning()

    - #### isTerminated

          public boolean isTerminated()

    - #### run

          public void run()

      The run method of the graphic thread. This method is started in the constructor of the derived class of this, which implements the graphic system adapter.
      - `#initGraphic()` will be called firstly. It is overridden by the graphic system implementing class and does some things necessary for the graphic system implementing level.
      - The routine runs so long as `bExit` is not set to false. bExit may be set to false in a window close listener of the graphic system level. It means, it is set to false especially if the windows will be closed from the operation system. If the window is closed because the application is terminated by any application command the window will be closed, and the close listerer sets bReady to false then.
      - In the loop the `#queueGraphicOrders` will be executed.
      - For SWT graphic this is the dispatch loop of graphic events. They are executed in the abstract defined here `#dispatchOsEvents()` method.
      - This thread should be wait if not things are to do. The wait will be executed in the here abstract defined method `#graphicThreadSleep()`.
      Specified by:
        `run` in interface `java.lang.Runnable`
      See Also:
        `Runnable.run()`

    - #### step

          void step()