texts
stringlengths 0
1.24M
| names
stringlengths 13
33
|
---|---|
StdScrollers
DEFINITION StdScrollers;
IMPORT Dialog, Properties, Views;
CONST
horBar = 0; verBar = 1; horHide = 2; verHide = 3; width = 4; height = 5; savePos = 7; showBorder = 6;
TYPE
Prop = POINTER TO RECORD (Properties.Property)
horBar, verBar, horHide, verHide: BOOLEAN;
width, height: INTEGER;
showBorder, savePos: BOOLEAN
END;
VAR
dialog: RECORD
horizontal, vertical: RECORD
mode: INTEGER;
adapt: BOOLEAN;
size: REAL
END;
showBorder, savePos: BOOLEAN
END;
PROCEDURE AddScroller;
PROCEDURE RemoveScroller;
PROCEDURE InitDialog;
PROCEDURE Set;
PROCEDURE DialogGuard (VAR par: Dialog.Par);
PROCEDURE HeightGuard (VAR par: Dialog.Par);
PROCEDURE WidthGuard (VAR par: Dialog.Par);
PROCEDURE HorAdaptGuard (VAR par: Dialog.Par);
PROCEDURE VerAdaptGuard (VAR par: Dialog.Par);
PROCEDURE WrappedView (v: Views.View): Views.View;
PROCEDURE WrapView (v: Views.View): Views.View
END StdScrollers.
Green color denote new features for version 2.0.
Module StdScrollers provides a wrapper view which can be wrapped around any other view to provide it with a horizontal and/or vertical scrollbar. For example, a text view in a form may be wrapped in a scroller in order to allow the scrolling of text that doesn't completely fit in the text view.
CONST horBar, verBar, horHide, verHide, width, height, savePos, showBorder
Property elements of the Prop descriptor.
TYPE Prop (Properties.Property)
Properties describing the attributes of a scroller view.
horBar: BOOLEAN
Is there a horizontal scrollbar?
verBar: BOOLEAN
Is there a vertical scrollbar?
horHide: BOOLEAN horHide -> horBar
Only valid if horBar. This leaves three legal possibilities:
~horBar scrollbar is never visible
horBar & horHide scrollbar is only visible when needed (appears or disappears automatically)
horBar & ~horHide scrollbar is always visible
verHide: BOOLEAN verHide -> verBar
Only valid if verBar. This leaves three legal possibilities:
~verBar scrollbar is never visible
verBar & verHide scrollbar is only visible when needed (appears or disappears automatically)
verBar & ~verHide scrollbar is always visible
width, height: INTEGER width >= 0 & height >= 0 [units]
Size of the wrapped view.
A value of 0 means that the wrapped view automatically adapts its size to the scroller (wrapper) view. Other values are fixed sizes.
showBorder: BOOLEAN
Display a border around the wrapped view.
savePos: BOOLEAN
Save the current scroll position when the wrapper is saved to disk, and makes scrolling undoable.
VAR
dialog: RECORD
Interactor for setting the scroller properties of a singleton selection.
horizontal, vertical: RECORD
Descriptor of scrollbar behavior for both dimensions.
mode: INTEGER mode IN {0, 1, 2}
0: never a scrollbar
1: automatic scrollbar
2: always a scrollbar
adapt: BOOLEAN
adapt: set size (width or height) to 0
~adapt: retain a fixed size
size: REAL
size in cm (Dialog.metricSystem) or in inches (~Dialog.metricSystem)
showBorder, savePos: BOOLEAN
Values according to property descriptor.
PROCEDURE AddScroller
Guard: StdCmds.SingletonGuard
Wraps a scroller around the selected view.
PROCEDURE RemoveScroller
Guard: StdCmds.SingletonGuard
Removes the scroller which is selected.
PROCEDURE InitDialog
Initializes variable dialog according to the selected scroller view.
PROCEDURE Set
Applies the newly defined properties to the selected scroller view.
PROCEDURE DialogGuard (VAR par: Dialog.Par)
PROCEDURE HeightGuard (VAR par: Dialog.Par)
PROCEDURE WidthGuard (VAR par: Dialog.Par)
PROCEDURE HorAdaptGuard (VAR par: Dialog.Par)
PROCEDURE VerAdaptGuard (VAR par: Dialog.Par)
Various guards for the Std/Rsrc/Scrollers dialog box.
PROCEDURE WrappedView (v: Views.View): Views.View
Returns the wrapped view of v if v is a scroller view implemented in StdScrollers. Otherwise, returns v.
Pre
v # NIL
PROCEDURE WrapView (v: Views.View): Views.View
Returns the wrapped view of v.
| Std/Docu/Scrollers.odc |
StdStamps
DEFINITION StdStamps;
PROCEDURE Deposit;
...plus some other items used internally...
END StdStamps.
StdStamps are views which indicate (1) the date when the containing document has been saved the last time and (2) the number of document changes. Stamp views carry a sequence number and a fingerprint of the document with them. Each time the document (and therefore its fingerprint) is changed and stored, the sequence number is incremented. When determining the fingerprint of the document, whitespace is ignored, except in string literals. This behavior makes StdStamps particularily useful for program texts.
Each stamp view also keeps track of the history of the most recent changes. For up to 25 entries, the date and time, and an optional one-line comment is stored. To avoid too many entries in the history while working on a document, the most recent history entry is overwritten upon the generation of a new sequence number if the current date is the same as the date in the most recent history entry.
To avoid exceeding 25 entries the oldest uncommented entry is deleted or the oldest if they are all commented.
PROCEDURE Deposit
Deposit command for standard stamps.
...plus some other items used internally...
Clicking on the stamp view shows a history of when the document has been saved.
Ctrl-clicking on the stamp view opens a dialog box that allows to edit the comment associated with the current and previous sessions. Specifying a Comment for a new sequence number (Seq. Nr.) always adds a new entry to the history even if fingerprint and date are unchanged. Selecting an existing sequence number allows to modify the comment of a previous session. Any comment editing is made persistent only when the document is saved the next time.
| Std/Docu/Stamps.odc |
StdStdCFrames
Cross-platform realization of controls for StdCFrames intrerface
- `Update()` method is called when control contents and/or state are updated by the external source;
that's why we're calling `c.Update^` everywhere
we should check for a label/text change there for edit controls, etc.
- `Close()` is called when the control is going to die; we should free any resources there
- `SetOffset()` is called when the control is moved placed/moved; it was used to "adapt" the
original native controls
- `DblClickOk()` is called to check if doubleclick is accepted.
seems to be used only for various list boxes (listbox, selection, combo).
- `UpdateList()` is called i don't know when yet, for ListBox, ComboBox, SelectionBox, and TreeFrame.
seems to be called when we need to repopulate the internal list storage.
- `UpdateRange()` in SelectionBox seems to do this:
IF (op = Dialog.set) OR (from # TO) THEN c.Update; RETURN END;
otherwise invert the selection
- `Select()` in SelectionBox does nothing
- `GetSelection()` in SelectionBox returns [0..MAX(INTEGER)]. for ComboBox it operates on the editor.
- TreeFrame overrides `GetSize (OUT w, h: INTEGER)` for some reason.
- `.noRedraw` field means that instead of calling `Views.Update(c, Views.rebuildFrames);`
on state change, the code in `Controls` module will call `Update()` method instead.
i.e. it expects that the control will redraw itself in its updater.
the original code does lazy allocation of native controls in `Restore()`, so we can do the same.
note that ListBox can work as a combobox w/o editor when its size is small enough.
also, ComboBox displays its predefinted contents as a listbox when it is big enough.
| Std/Docu/StdCFrames.odc |
Map to the Std Subsystem
Links-Dialog Links & Targets
StdApi API for StdCmds
StdClocks analog clock views
StdCmds cmds of std menus
StdCoder ASCII coder
StdDebug minimal debugger
StdFolds fold views
StdHeaders headers / footers
StdLinks hyperlink views
StdLog standard output
StdMenuTool menu tool
StdStamps date stamp views
StdTables table controls
StdTabViews tabbed folder views
StdViewSizer set size of a view
| Std/Docu/Sys-Map.odc |
StdTables
DEFINITION StdTables;
IMPORT
Ports, Dialog, Views, Properties, Controls;
CONST
line = 0DX;
deselect = -1; select = -2; changed = -3;
layoutEditable = 0; dataEditable = 1; selectionStyle = 2;
noSelect = 0; cellSelect = 1; rowSelect = 2; colSelect = 3; crossSelect = 4;
TYPE
Table = RECORD
rows-, cols-: INTEGER;
(VAR tab: Table) SetSize (rows, cols: INTEGER), NEW;
(VAR tab: Table) SetItem (row, col: INTEGER; item: Dialog.String), NEW;
(VAR tab: Table) GetItem (row, col: INTEGER; OUT item: Dialog.String), NEW;
(VAR tab: Table) SetLabel (col: INTEGER; label: Dialog.String), NEW;
(VAR tab: Table) GetLabel (col: INTEGER; OUT label: Dialog.String), NEW;
(VAR tab: Table) HasSelection (): BOOLEAN, NEW;
(VAR tab: Table) GetSelection (OUT row, col: INTEGER), NEW;
(VAR tab: Table) Select (row, col: INTEGER), NEW;
(VAR tab: Table) Deselect, NEW;
(VAR tab: Table) SetAttr (l, t, r, b: INTEGER; style: SET; weight: INTEGER; color: Ports.Color), NEW;
(VAR tab: Table) GetAttr (row, col: INTEGER;
OUT style: SET; OUT weight: INTEGER; OUT color: Ports.Color), NEW
END;
Prop = POINTER TO RECORD (Properties.Property)
layoutEditable, dataEditable: BOOLEAN;
selectionStyle: INTEGER;
(p: Prop) IntersectWith (q: Properties.Property; OUT equal: BOOLEAN)
END;
Directory = POINTER TO ABSTRACT RECORD
(d: Directory) NewControl (p: Controls.Prop): Views.View, ABSTRACT, NEW
END;
VAR
dir-, stdDir-: Directory;
text: Dialog.String;
dlg: RECORD
layoutEditable, dataEditable: BOOLEAN;
selectionStyle: Dialog.List
END;
PROCEDURE InitDialog;
PROCEDURE Set;
PROCEDURE Guard (idx: INTEGER; VAR par: Dialog.Par);
PROCEDURE Notifier (idx, op, from, to: INTEGER);
PROCEDURE SetDir (d: Directory);
PROCEDURE DepositControl;
END StdTables.
Module StdTables implements a simple tabular control ("grid view"). To allow clients to create new table controls, a directory object is exported (StdTables.dir). As interactor, type StdTables.Table is provided.
Typical menu command:
"Insert Table" "" "StdTables.DepositControl; StdCmds.PasteView" "StdCmds.PasteViewGuard"
The property editor for the StdTables is the same as for normal controls. The fields, Link, Label, Guard and Notifier works in the same way as for other controls. In addition to the property editor, a special dialog for tables is offered, where one can choose the visual feedback of the selection in a table. Furthermore one can specify, whether the layout should be editable (column width), and whether the data in the cells should be editable.
CONST line
New line character for multiple line labels.
CONST deselect
Notifier op-code. Indicates that the cell at position row = from and column = to has been deselected.
CONST select
Notifier op-code. Indicates that the user has selected a cell at position row = from and column = to.
CONST changed
Notifier op-code. Indicates that the user has changed the contents of a cell in the table at position row = from and column = to.
CONST layoutEditable
Element of a control property's valid set. Determines, whether the layout editable property is valid.
CONST dataEditable
Element of a control property's valid set. Determines, whether the data editable property is valid.
CONST selectionStyle
Element of a control property's valid set. Determines, whether the selection style property is valid.
CONST noSelect, cellSelect, rowSelect, colSelect, crossSelect
Selection style property constants.
TYPE Table
Interactor for table controls.
rows-, cols-: INTEGER (rows >= 0) & (cols >= 0)
Number of rows and columns of the table.
PROCEDURE (VAR tab: Table) SetSize (rows, cols: INTEGER), NEW
Set size of the table.
Pre
20 (rows >= 0) & (cols >= 0)
21 ((cols > 0) OR ((cols = 0) & (rows = 0))
PROCEDURE (VAR tab: Table) SetItem (row, col: INTEGER; item: Dialog.String), NEW
Set contents of cell in row row and column col to item.
Pre
20 SetSize must have been called before
PROCEDURE (VAR tab: Table) GetItem (row, col: INTEGER; OUT item: Dialog.String), NEW
Get contents of cell in row row and column col.
Pre
20 SetSize must have been called before
PROCEDURE (VAR tab: Table) SetLabel (col: INTEGER; label: Dialog.String), NEW
Set contents of label of column col. For each occurence of the character StdTables.line in label a new line is created.
Pre
20 SetSize must have been called before
PROCEDURE (VAR tab: Table) GetLabel (col: INTEGER; OUT label: Dialog.String), NEW
Get contents of label of column col.
Pre
20 SetSize must have been called before
PROCEDURE (VAR tab: Table) HasSelection (): BOOLEAN, NEW
Returns, whether a cell in the table is currently selected.
PROCEDURE (VAR tab: Table) GetSelection (OUT row, col: INTEGER), NEW
Get coordinates (row and column) of the selected table cell.
Pre
20 SetSize must have been called before
21 tab.HasSelection()
PROCEDURE (VAR tab: Table) Select (row, col: INTEGER), NEW
Set selection in table to row row and column col.
Pre
20 SetSize must have been called before
Post
tab.HasSelection() = TRUE
PROCEDURE (VAR tab: Table) Deselect, NEW
Remove current selection in table, if any.
Pre
20 SetSize must have been called before
Post
tab.HasSelection() = FALSE
PROCEDURE (VAR tab: Table) SetAttr (l, t, r, b: INTEGER; style: SET; weight: INTEGER; color: Ports.Color), NEW
Sets the the attributes for a range of cells. style and weight affects the font for the cell and color is the color of the text in the cell. (For explanations of the parameters style and weight, see Fonts.Font.) The range is indicated by l and t being the column and row for the top left cell in the range, and r and b being the column and row of the bottom right cell in the range.
PROCEDURE (VAR tab: Table) GetAttr (row, col: INTEGER; OUT style: SET; OUT weight: INTEGER; OUT color: Ports.Color), NEW
Retrieves the current attribute values for the cell at position row, col in the table.
Pre
20 SetSize must have been called before
TYPE Prop
Table specific properties.
layoutEditable, dataEditable: BOOLEAN
Column width is editable by the user; data in table cells is editable by the user.
selectionStyle: INTEGER
Visual feedback of selections:
noSelect: no visual feedback
cellSelect: selected cell is high-lighted
rowSelect: all cells in selected row are high-lighted
colSelect: all cells in selected column are high-lighted
crossSelect: all cells in selected row and column are high-lighted
PROCEDURE (p: Prop) IntersectWith (q: Properties.Property; OUT equal: BOOLEAN)
Intersect table properties p with another property record q. Iff both are equal, equal is set to TRUE.
TYPE Directory
New controls can be created using the directory object StdTables.dir.
PROCEDURE (d: Directory) NewControl (p: Controls.Prop): Views.View, ABSTRACT, NEW
Create a new table control using properties p.
VAR dir-, stdDir-: Directory dir # NIL, stdDir # NIL, stable stdDir = d
Directory and standard directory objects for table controls.
VAR text: Dialog.String valid only during the editing of a cell
Contents of the cell currently being edited.
VAR dlg: RECORD
Interactor for table property dialog.
PROCEDURE InitDialog
Init table property dialog.
PROCEDURE Set
Set properties as selected in table property dialog.
PROCEDURE Guard (idx: INTEGER; VAR par: Dialog.Par)
Guard for table property dialog.
CASE idx OF
0: Layout Editable checkbox
1: Data Editable checkbox
2: Selection Style listbox
END
PROCEDURE Notifier (idx, op, from, to: INTEGER)
Notifier for table property dialog.
CASE idx OF
0: Layout Editable checkbox
1: Data Editable checkbox
2: Selection Style listbox
END
PROCEDURE SetDir (d: Directory)
Set directory object.
Pre
d # NIL 20
Post
stdDir' = NIL
stdDir = d
dir = d
PROCEDURE DepositControl
Deposit command for table controls.
| Std/Docu/Tables.odc |
StdTabViews
DEFINITION StdTabViews;
IMPORT Views, Dialog, StdCFrames;
CONST
noTab = -1;
TYPE
Directory = POINTER TO ABSTRACT RECORD
(d: Directory) New (): View, NEW, ABSTRACT
END;
Frame = POINTER TO ABSTRACT RECORD (StdCFrames.Frame)
(f: Frame) GetDispSize (OUT x, y, w, h: INTEGER), NEW, ABSTRACT;
(f: Frame) InDispArea (x, y: INTEGER): BOOLEAN, NEW, ABSTRACT;
(f: Frame) SetIndex (i: INTEGER), NEW
END;
FrameDirectory = POINTER TO ABSTRACT RECORD
(d: FrameDirectory) GetTabSize (VAR w, h: INTEGER), NEW, ABSTRACT;
(d: FrameDirectory) New (): Frame, NEW, ABSTRACT
END;
View = POINTER TO LIMITED RECORD (Views.View)
(tv: View) GetItem (i: INTEGER; OUT label: Dialog.String; OUT v: Views.View), NEW;
(tv: View) GetNewFrame (VAR frame: Views.Frame);
(tv: View) GetNotifier (OUT notifier: Dialog.String), NEW;
(tv: View) HandleCtrlMsg (f: Views.Frame; VAR msg: Views.CtrlMessage; VAR focus: Views.View);
(tv: View) Index (): INTEGER, NEW;
(tv: View) Neutralize;
(tv: View) NofTabs (): INTEGER, NEW;
(tv: View) Restore (f: Views.Frame; l, t, r, b: INTEGER);
(tv: View) SetIndex (i: INTEGER), NEW;
(tv: View) SetItem (i: INTEGER; label: Dialog.String; v: Views.View), NEW;
(tv: View) SetNofTabs (nofTabs: INTEGER), NEW;
(tv: View) SetNotifier (IN notifier: ARRAY OF CHAR), NEW
END;
NotifierProc = PROCEDURE (tv: View; from, to: INTEGER);
VAR
dir-: Directory;
dlg: RECORD
name, notifier: Dialog.String;
opt: INTEGER
END;
frameDir-: FrameDirectory;
frameStdDir-: FrameDirectory;
setFocus: BOOLEAN;
stdDir-: Directory;
PROCEDURE AddTab;
PROCEDURE BeginChanges (tv: View);
PROCEDURE Delete;
PROCEDURE DeleteGuard (VAR par: Dialog.Par);
PROCEDURE Deposit;
PROCEDURE EndChanges (tv: View);
PROCEDURE Focus (): View;
PROCEDURE InitDialog;
PROCEDURE LabelGuard (VAR par: Dialog.Par);
PROCEDURE LayoutModeGuard (VAR par: Dialog.Par);
PROCEDURE Left;
PROCEDURE MaskModeGuard (VAR par: Dialog.Par);
PROCEDURE ModeNotifier (op, from, to: INTEGER);
PROCEDURE NewGuard (VAR par: Dialog.Par);
PROCEDURE NotifierGuard (VAR par: Dialog.Par);
PROCEDURE Rename;
PROCEDURE RenameGuard (VAR par: Dialog.Par);
PROCEDURE Right;
PROCEDURE SetDir (d: Directory);
PROCEDURE SetFrameDir (d: FrameDirectory);
PROCEDURE SetGuard (VAR par: Dialog.Par);
PROCEDURE SetNotifier;
PROCEDURE This (v: Views.View): View;
END StdTabViews.
A StdTabViews.View displays a set of tabs to the user. Each tab consists of a label and a view. When the user clicks on the label, the associated view is displayed. Try it on the example below!
This example was created with FormViews but any Views.View can be used in the tabs.
There are two ways of creating StdTabViews: The tab can be created programmatically or it can be created using a graphical user interface. In most cases the graphical user interface is enough, and no programming is needed to create a StdTabViews.View. For more advanced use there exists a programming interface and this will be described further down.
To use the graphical user interface a StdTabViews.View needs to be dropped into a document or a form. This can be done by selecting the option Insert Tab View from the Controls menu. The new StdTabViews.View contains two tabs, called Tab1 and Tab2, and they each have an (empty) FormViews.View associated with them. A newly created tab looks like this:
The StdTabViews.View is fully functional, but a bit boring. If the StdTabViews.View is focused, each tab can be edited just like a normal form. Controls can be dropped into it and moved aound and their properties can be edited. Also this can be tried on the tab above.
To add, remove or edit the name of tabs the StdTabViews property editor needs to be started. This is done by selecting the tab and choosing "Edit->Object Properties...". The property editor looks like this:
The buttons and fields have the following meaning:
<-
Clicking on this button moves the current tab one step to the left. This can be used to changed the order of the tabs.
->
Clicking on this button moves the current tab one step to the right. This can be used to changed the order of the tabs.
Label
Displays the label of the current tab.
Rename
Sets the label of the currrent tab to the text displayed in the label field. An empty label is not allowed.
New Tab
Creats a new tab and adds it to the list. The label of the new tab is set to the text displayed in the label field. If the text field is empty no new tab can be created.
Delete
Removes the current tab from the tab view.
Notifier
Displays the name of the notifier that is associated with the tab view.
Set
Sets the notifier of the the tab view to the name displayed in the notifier field.
All tabs in Layout Mode
Sets all tabs in the Tab View in Layout Mode. Layout Mode is a container mode that allows for editing. For more information about container modes see About Container Modes futher down.
All tabs in Mask Mode
Sets all tabs in the Tab View in Mask Mode. Mask Mode is a container mode that doesn't allow selecting of contained views. This mode is used for displaying documents as dialogs. For more information about container modes see About Container Modes futher down.
About Notifiers
The notifier for StdTabViews is not the same as a notifier for normal Controls, but it works in a similar way. The signarure is different and there is just one type of notification sent. StdTabViews notifiers have the signature described by the type StdTabViews.NotifierProc.
The notifier is only called when the current tab is changed. When called, tv is the StdTabViews.View that the notification concerns, from is the tab that used to be the current tab and to is the new current tab.
When a tab is saved the index of the current tab is saved with it and when the tab is internalized the current tab is set to the index that was saved. This enables the designer of a dialog with a tab to control which tab is the current tab when the dialog is opened. It also provides a way to find a StdTabViews.View in a dialog. When the current tab is set for the first time during internalization the notifier is called with tv set to the new StdTabViews.View, from set to the constant noTab and to set to the index of the current tab saved in externalize.
This means that whenever a document with a StdTabViews.View inside is opened the notifier is called and this allows the application to bind to the StdTabViews.View if needed. This is an easy way to get to the programming interface described below.
About Container Modes
Containers can have different modes. A FormViews.View is a container and can for example be put in Layout Mode and Mask Mode. In Layout Mode it is possible to select contained views, such as Controls, and move them around. In Mask Mode, on the other hand, it is not possible to select or move around contained views.
Container modes can be changed using the Dev-menu but normally this is not needed. The normal way is to save a document in Edit or Layout Mode and then open it in the desired mode using the commands provided in StdCmds. A dialog, for example, is usually saved in Layout Mode and then opened in Mask Mode by using StdCmds.OpenAuxDialog.
The problem is that StdTabViews breaks this pattern since each tab can contain its own container with its own mode. It is needed to use the Dev-menu to put the tabs in the correct mode before saving a dialog. To use the container modes and the Dev-menu requires some knowledge about Containers. To avoid this requirement the radiobuttons "All tabs in Layout Mode" and "All tabs in Mask Mode" are provided. These buttons make it possible to set all tabs in Mask mode before saving the dialog or setting all tabs in Layout mode to edit the dialog, thus eliminating the need to use the Dev-menu.
CONST noTab
Constant used as from value to the notifier when a StdTabViews.View is internalize.
TYPE View = POINTER TO LIMITED RECORD (Views.View)
Allows the user to select different views by clicking on tabs.
PROCEDURE (tv: View) SetItem (i: INTEGER; label: Dialog.String; v: Views.View)
NEW
Adds a new tab to tv. The new tab gets label as its label and v as its view. i indicates the position of the tab among the other tabs. IF i is greater than tv.NofTabs() then then number of tabs in tv is increased, if not, the prevous tab at position i is overwritten. A deep copy of v is made before it is added to tv.
Pre
i >= 0
label # ""
v # NIL
PROCEDURE (tv: View) GetItem (i: INTEGER; OUT label: Dialog.String; OUT v: Views.View)
NEW
Retrievs the label and the view for tab i.
Pre
i >= 0
i < tv.NofTabs()
PROCEDURE (tv: View) SetNofTabs (nofTabs: INTEGER)
NEW
Makes sure that nofTabs tabs are available in tv.Note that SetItem also increases the number of tabs of the View if necessary, so SetNofTabs is strictly only necessary to decrease the number of tabs.
Pre
nofTabs >= 0
Post
tv.NofTabs() = nofTabs
PROCEDURE (tv: View) NofTabs (): INTEGER, NEW;
NEW
Retruns the number of tabs in tv.
Post
Returned value >= 0
PROCEDURE (tv: View) SetIndex (i: INTEGER)
NEW
Sets the current tab in tv, updates the view. The notifier is not called when tabs are changed by a call to SetIndex.
Pre
i >= 0
i < tv.NofTabs()
Post
tv.Index() = i
PROCEDURE (tv: View) Index (): INTEGER
NEW
Returns the index of the currently selected tab. The index is updated whenever a user clicks on a tab or whenever SetIndex is called.
Post
Returned value is >= 0 and < tv.NofTabs()
PROCEDURE (tv: View) SetNotifier (IN notifier: ARRAY OF CHAR)
NEW
Sets the notifier of tv to be notifier. notifier = "" is permitted and it is interpreted as meaning that tv has no notifer. For more information about notifiers, see the chapter About Notifiers above.
PROCEDURE (tv: View) GetNotifier (OUT notifier: Dialog.String)
NEW
Sets notifier to the value of the notifier of tv. notifer is the empty string if tv doesn't have a notifier.
TYPE Directory
ABSTRACT
Directory type for StdTabViews.View.
PROCEDURE (d: Directory) New (): View
NEW, ABSTRACT
Allocates and returns a new View.
TYPE NotifierProc = PROCEDURE (tv: View; from, to: INTEGER)
StdTabViews notification commands must have this signature. Through calls of notification procedures, an application can be notified when the selected tab of a StdTabViews.View is changed due to user interaction. The parameters have the following meaning:
tv = the StdTabViews.View where the tab was changed.
from = the selected tab before the change. Has the value noTab when the notifier is called from Internalize.
to = the new selected tab.
VAR dir-, stdDir-: Directory dir # NIL & stdDir # NIL
Directories for creating StdTabViews.Views.
PROCEDURE SetDir (d: Directory)
Set directory.
PROCEDURE Deposit
Allocate a new View using dir.New, adds two tabs to it and deposits it.
PROCEDURE This (v: Views.View): View
Traverserses view v and all its contained views (if any) and returns the first StdTabViews.View that is found. If no StdTabViews.View is found then NIL is returned.
Pre
v # NIL
PROCEDURE Focus (): View
Searches for a StdTabViews.View along the focus path. If one is found it is returned, if not NIL is returned. If more than one StdTabViews.View exists in the focus path it is undefinied which one will be returned.
PROCEDURE BeginChanges (tv: View)
Disables update of tv until a subsequent call to EndChanges. Each call to BeginChanges must be balanced by a call to EndChanges, otherwise a trap will occur (in StdTabViews.BalanceAction.Do). The calls may be nested. BeginChanges and EndChanges are provided to make it possible to do several changes to a StdTabViews.View without intermediate updates.
Pre
Number of calls to BeginChanges >= Number of calls to EndChanges, 20
PROCEDURE EndChanges (tv: View)
Enables update for tv again after a call to BeginChanges.
Pre
Number of calls to BeginChanges > Number of calls to EndChanges, 20
The following types, variables and procedures are only used internally to handle frames of StdTabViews:
TYPE Frame = POINTER TO ABSTRACT RECORD (StdCFrames.Frame)
TYPE FrameDirectory = POINTER TO ABSTRACT RECORD
VAR frameDir-, frameStdDir-: FrameDirectory
PROCEDURE SetFrameDir (d: FrameDirectory)
PROCEDURE (f: Frame) GetDispSize (OUT x, y, w, h: INTEGER), NEW, ABSTRACT
PROCEDURE (f: Frame) InDispArea (x, y: INTEGER): BOOLEAN, NEW, ABSTRACT
PROCEDURE (f: Frame) SetIndex (i: INTEGER), NEW
PROCEDURE (d: FrameDirectory) GetTabSize (VAR w, h: INTEGER), NEW, ABSTRACT
PROCEDURE (d: FrameDirectory) New (): Frame, NEW, ABSTRACT
The following types, variables and procedures are only used for the property inspector of the StdTabViews.View:
VAR dlg: RECORD
name, notifier: Dialog.String;
opt: INTEGER
END;
PROCEDURE AddTab
PROCEDURE Delete
PROCEDURE DeleteGuard (VAR par: Dialog.Par)
PROCEDURE InitDialog
PROCEDURE LabelGuard (VAR par: Dialog.Par)
PROCEDURE LayoutModeGuard (VAR par: Dialog.Par);
PROCEDURE Left
PROCEDURE MaskModeGuard (VAR par: Dialog.Par);
PROCEDURE ModeNotifier (op, from, to: INTEGER);
PROCEDURE NewGuard (VAR par: Dialog.Par)
PROCEDURE NotifierGuard (VAR par: Dialog.Par)
PROCEDURE Rename
PROCEDURE RenameGuard (VAR par: Dialog.Par)
PROCEDURE Right
PROCEDURE SetGuard (VAR par: Dialog.Par)
PROCEDURE SetNotifier
The following variable is only used internally:
VAR setFocus: BOOLEAN
| Std/Docu/TabViews.odc |
PROCEDURE Autosave (v: Views.View; IN location, fname: Files.Name);
Autosave before close is implemented using:
BeforeCloseMsg = RECORD (Sequencers.Message)
CloseHookDesc.Close sends a msg: BeforeCloseMsg via Sequencer.Notify
SeqNotifier = RECORD (Sequencers.Notifier) processes BeforeCloseMsg
PROCEDURE Autosave installs an n: SeqNotifier into a view's sequencer
So, when (any) window is about to be closed, the notification is sent to it's sequencer, and if a notifier is installed, it processes the notification and autosaves the window's view.
This infrastructure actually allows arbitrary views to be autosaved before close. | Std/Docu/Tiles.odc |
StdViewSizer
DEFINITION StdViewSizer;
IMPORT Dialog;
VAR
size: RECORD
typeName-: Dialog.String;
w, h: REAL
END;
PROCEDURE InitDialog;
PROCEDURE SetViewSize;
PROCEDURE SizeGuard (VAR par: Dialog.Par);
PROCEDURE UnitGuard (VAR par: Dialog.Par);
END StdViewSizer.
StdViewSizer is a command package allowing the user to resize views embedded in containers by specifying width and height as numbers. This is useful whenever dragging view borders with the mouse is not precise enough. The command package works on any singleton view.
For entry in a menu, the following line is recommended:
"View Size..." "" "StdViewSizer.InitDialog; StdCmds.OpenToolDialog('Std/Rsrc/ViewSizer', 'View Size')" "StdCmds.SingletonGuard"
VAR size: RECORD
Interactor for setting the view size.
typeName-: Dialog.String
Type of the current singleton view.
w: INTEGER
View width in cm or inch, depending on the value of Dialog.metricSystem.
h: INTEGER
View height in cm or inch, depending on the value of Dialog.metricSystem.
PROCEDURE InitDialog
Initialization command for size interactor.
PROCEDURE SetViewSize
Applies the interactor values in size. To set up size to the selected view, InitDialog needs to be called first.
PROCEDURE SizeGuard (VAR par: Dialog.Par)
Guard which ensures that the size interactor matches the current singleton selection. If there is no singleton selection, the guard disables.
PROCEDURE UnitGuard (VAR par: Dialog.Par)
Guard that sets par.label to "cm" or "inch" respectively, depending on the value of Dialog.metricSystem.
| Std/Docu/ViewSizer.odc |
MODULE StdApi;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20070430, mf, OpenBrowser: allowDuplicates parameter set to FALSE in call to StdDialog.Open
- 20080317, mf, OpenBrowser: allowDuplicates parameter set to TRUE in call to StdDialog.Open
- 20141027, center #19, full Unicode support for Component Pascal identifiers added
- 20150329, center #34, fixing the reuse of open documents
- 20151201, center #88, support for localizable documentation
- 20150114, center #93, Opening a Form with a Tab View
- 20161216, center #144, inconsistent docu and usage of Files.Locator error codes
- 20200120, dia, remember converter for files opened in browser mode
"
issues = "
- ...
"
**)
IMPORT
Views, Files, Dialog, Converters, Windows, Sequencers, Stores, Meta, Librarian,
Containers, StdDialog, Documents, Strings;
VAR
modeHook*: PROCEDURE(c: Containers.Controller); (* for setting nested forms to the container's mode *)
(* Auxiliary procedures *)
PROCEDURE CheckQualident (VAR str, mod, name: ARRAY OF CHAR);
VAR i, j: INTEGER; ch: CHAR;
BEGIN
i := 0;
REPEAT
ch := str[i]; mod[i] := ch; INC(i)
UNTIL (i = LEN(str)) OR (i = LEN(mod)) OR ~Strings.IsIdent(ch);
IF ch = "." THEN
mod[i - 1] := 0X; j := 0;
REPEAT
ch := str[i]; name[j] := ch; INC(i); INC(j)
UNTIL (i = LEN(str)) OR (j = LEN(name)) OR ~Strings.IsIdent(ch);
IF ch # 0X THEN mod[0] := 0X; name[0] := 0X END
ELSE mod[0] := 0X; name[0] := 0X
END
END CheckQualident;
PROCEDURE FileExists (loc: Files.Locator; IN name: ARRAY OF CHAR): BOOLEAN;
VAR fi: Files.FileInfo;
BEGIN
fi := Files.dir.FileList(loc);
WHILE (fi # NIL) & (fi.name # name) DO fi := fi.next END;
RETURN fi # NIL
END FileExists;
PROCEDURE PathToSpec (IN path: ARRAY OF CHAR; OUT loc: Files.Locator; OUT name: Files.Name;
useLang: BOOLEAN);
VAR i, j: INTEGER; ch: CHAR;
nameUpper, fn: Files.Name; langParent: Files.Locator;
BEGIN
i := 0; j := 0; loc := Files.dir.This(""); langParent := NIL;
WHILE (loc.res = 0) & (i < LEN(path) - 1) & (j < LEN(name) - 1) & (path[i] # 0X) DO
ch := path[i]; INC(i);
IF (j > 0) & ((ch = "/") OR (ch = "\")) THEN
name[j] := 0X; j := 0;
IF (loc = langParent) & (name = Dialog.defaultLanguage) THEN
langParent := NIL (* map ".../Docu/en/..." to ".../Docu/..." *)
ELSE
loc := loc.This(name)
END;
IF useLang & (langParent = NIL) THEN Strings.ToUpper(name, nameUpper);
IF nameUpper = "DOCU" THEN langParent := loc END
END
ELSE
name[j] := ch; INC(j)
END
END;
IF path[i] = 0X THEN
name[j] := 0X;
IF (loc = langParent) & (Dialog.language # "")
& (Dialog.language # Dialog.defaultLanguage) THEN (* use Dialog.language *)
loc := loc.This(Dialog.language);
fn := name;
Files.dir.GetFileName(fn, Files.docType, fn);
IF ~FileExists(loc, fn) THEN
loc := langParent
ELSE
loc.res := 0
END;
END
ELSE loc.res := 1; name := ""
END
END PathToSpec;
PROCEDURE ThisDialog (dialog: ARRAY OF CHAR; useLang: BOOLEAN): Views.View;
VAR fname, submod, sub, mod: Files.Name; canCreate: BOOLEAN; conv: Converters.Converter;
loc: Files.Locator; file: Files.File; v: Views.View; s: Stores.Store; var: Meta.Item;
BEGIN
ASSERT(dialog # "", 20);
v := NIL; file := NIL; canCreate := FALSE;
CheckQualident(dialog, submod, fname);
IF submod # "" THEN (* is qualident *)
Meta.LookupPath(dialog, var);
IF var.obj = Meta.varObj THEN (* variable exists *)
canCreate := TRUE;
Librarian.lib.SplitName(submod, sub, mod);
loc := Files.dir.This(sub);
IF loc.res = 0 THEN
Files.dir.GetFileName(fname, Files.docType, fname);
loc := loc.This("Rsrc");
IF loc.res = 0 THEN file := Files.dir.Old(loc, fname, Files.shared) END;
END
END
END;
IF (file = NIL) & ~canCreate THEN (* try file name *)
PathToSpec(dialog, loc, fname, useLang);
IF loc.res = 0 THEN
Files.dir.GetFileName(fname, Files.docType, fname);
file := Files.dir.Old(loc, fname, Files.shared)
END
END;
IF file # NIL THEN
Files.dir.GetFileName(fname, Files.docType, fname);
conv := NIL; Converters.Import(loc, fname, conv, s);
IF s # NIL THEN
v := s(Views.View)
END
ELSE Dialog.ShowParamMsg("#System:FileNotFound", dialog, "", "")
END;
RETURN v
END ThisDialog;
PROCEDURE ThisMask (param: ARRAY OF CHAR; useLang: BOOLEAN): Views.View;
VAR v: Views.View; c: Containers.Controller;
BEGIN
v := ThisDialog(param, useLang);
IF v # NIL THEN
WITH v: Containers.View DO
c := v.ThisController();
IF c # NIL THEN
c.SetOpts(c.opts - {Containers.noFocus} + {Containers.noCaret, Containers.noSelection});
IF modeHook # NIL THEN modeHook(c) END
ELSE Dialog.ShowMsg("#System:NotEditable")
END
ELSE Dialog.ShowMsg("#System:ContainerExpected")
END
END;
RETURN v
END ThisMask;
(* Interface procedures *)
PROCEDURE CloseDialog* (OUT closedView: Views.View);
CONST canClose = {Windows.neverDirty, Windows.isTool, Windows.isAux};
VAR w: Windows.Window; msg: Sequencers.CloseMsg;
BEGIN
closedView := NIL;
w := Windows.dir.First();
IF w # NIL THEN
IF w.sub THEN
closedView := w.frame.view;
Windows.dir.Close(w);
ELSIF (w.flags * canClose = {}) & w.seq.Dirty() THEN
Dialog.ShowMsg("#System:CannotCloseDirtyWindow")
ELSE
msg.sticky := FALSE; w.seq.Notify(msg);
IF ~msg.sticky THEN closedView := w.frame.view; Windows.dir.Close(w) END
END
END
END CloseDialog;
PROCEDURE OpenAux* (file, title: ARRAY OF CHAR; OUT v: Views.View);
VAR loc: Files.Locator; name: Files.Name; t: Views.Title;
BEGIN
PathToSpec(file, loc, name, FALSE);
IF loc.res = 0 THEN
loc.res := 77; v := Views.OldView(loc, name); loc.res := 0;
IF v # NIL THEN t := title$; Views.OpenAux(v, t)
ELSE Dialog.ShowParamMsg("#System:FileNotFound", file, "", "")
END
ELSE Dialog.ShowParamMsg("#System:FileNotFound", file, "", "")
END
END OpenAux;
PROCEDURE OpenAuxDialog* (file, title: ARRAY OF CHAR; OUT v: Views.View);
VAR t0: Views.Title; done: BOOLEAN;
BEGIN
Dialog.MapString(title, t0);
Windows.SelectByTitle(NIL, {Windows.isAux}, t0, done);
IF ~done THEN
v := ThisMask(file, TRUE);
IF v # NIL THEN
StdDialog.Open(v, title, NIL, "", NIL, FALSE, TRUE, TRUE, FALSE, TRUE)
END
END
END OpenAuxDialog;
(* Opening a file in 'Browser' mode is used mainly for online help files.
In that case, but also in others, it is convenient to bring an existing window to the front in case the
same file is browsed again. This behavior is the same as with opening a file as a normal window.
In order to be able to browse and edit at the same time, i.e. in two different domains, the
isAux flag is used to distinguish between both.
*)
PROCEDURE OpenBrowser* (file, title: ARRAY OF CHAR; OUT v: Views.View);
VAR loc: Files.Locator; name: Files.Name; t: Views.Title;
c: Containers.Controller; w: Windows.Window; conv: Converters.Converter;
BEGIN
PathToSpec(file, loc, name, TRUE);
IF loc.res = 0 THEN
w := Windows.GetBySpec(loc, name, Converters.list, {Windows.isAux});
IF w # NIL THEN (* bring to front; avoid re-loading the document *)
Windows.dir.Select(w, Windows.lazy);
v := w.doc.ThisView();
ELSE (* load document and open reusable aux window in Browser mode *)
loc.res := 77; v := Views.Old(Views.dontAsk, loc, name, conv); loc.res := 0;
IF v # NIL THEN
WITH v: Containers.View DO
c := v.ThisController();
IF c # NIL THEN
c.SetOpts(c.opts - {Containers.noFocus, Containers.noSelection} + {Containers.noCaret})
END
ELSE
END;
t := title$;
StdDialog.Open(v, t, loc, name, conv, FALSE, TRUE, FALSE, FALSE, FALSE)
ELSE Dialog.ShowParamMsg("#System:FileNotFound", file, "", "")
END
END
ELSE Dialog.ShowParamMsg("#System:FileNotFound", file, "", "")
END
END OpenBrowser;
PROCEDURE OpenDoc* (file: ARRAY OF CHAR; OUT v: Views.View);
VAR loc: Files.Locator; name: Files.Name; conv: Converters.Converter;
BEGIN
PathToSpec(file, loc, name, FALSE);
IF loc.res = 0 THEN
conv := NIL; v := Views.Old(Views.dontAsk, loc, name, conv);
IF loc.res = 78 THEN loc := NIL; name := "" END; (* stationery *)
IF v # NIL THEN Views.Open(v, loc, name, conv)
ELSE Dialog.ShowParamMsg("#System:FileNotFound", file, "", "")
END
ELSE Dialog.ShowParamMsg("#System:FileNotFound", file, "", "")
END
END OpenDoc;
PROCEDURE OpenCopyOf* (file: ARRAY OF CHAR; OUT v: Views.View);
VAR loc: Files.Locator; name: Files.Name; conv: Converters.Converter;
BEGIN
PathToSpec(file, loc, name, FALSE);
IF loc.res = 0 THEN
conv := NIL; v := Views.Old(Views.dontAsk, loc, name, conv);
IF loc.res = 78 THEN loc := NIL; name := "" END; (* stationary *)
IF v # NIL THEN
IF v.context # NIL THEN
v := Views.CopyOf(v.context(Documents.Context).ThisDoc(), Views.deep);
Stores.InitDomain(v)
ELSE v := Views.CopyOf(v, Views.deep)
END;
Views.Open(v, NIL, "", conv)
ELSE Dialog.ShowParamMsg("#System:FileNotFound", file, "", "")
END
ELSE Dialog.ShowParamMsg("#System:FileNotFound", file, "", "")
END
END OpenCopyOf;
PROCEDURE OpenToolDialog* (file, title: ARRAY OF CHAR; OUT v: Views.View);
VAR t0: Views.Title; done: BOOLEAN;
BEGIN
Dialog.MapString(title, t0);
Windows.SelectByTitle(NIL, {Windows.isTool}, t0, done);
IF ~done THEN
v := ThisMask(file, FALSE);
IF v # NIL THEN
StdDialog.Open(v, title, NIL, "", NIL, TRUE, FALSE, TRUE, FALSE, TRUE)
END
END
END OpenToolDialog;
END StdApi.
| Std/Mod/Api.odc |
MODULE StdCFrames;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20230116, k8, changed signature of `KeyDown()` — added `modifiers`
- 20230209, k8, added `ForceUpdate()` method, and `pressed` field
"
issues = "
- ...
"
**)
IMPORT Fonts, Ports, Views, Dates, Dialog;
CONST lineUp* = 0; lineDown* = 1; pageUp* = 2; pageDown* = 3;
TYPE
Frame* = POINTER TO ABSTRACT RECORD (Views.Frame)
disabled*, undef*, readOnly*, noRedraw*: BOOLEAN;
font*: Fonts.Font;
pressed*: BOOLEAN
END;
PushButton* = POINTER TO ABSTRACT RECORD (Frame)
label*: ARRAY 256 OF CHAR;
default*, cancel*: BOOLEAN;
Do*: PROCEDURE (f: PushButton)
END;
CheckBox* = POINTER TO ABSTRACT RECORD (Frame)
label*: ARRAY 256 OF CHAR;
Get*: PROCEDURE (f: CheckBox; OUT on: BOOLEAN);
Set*: PROCEDURE (f: CheckBox; on: BOOLEAN)
END;
RadioButton* = POINTER TO ABSTRACT RECORD (Frame)
label*: ARRAY 256 OF CHAR;
Get*: PROCEDURE (f: RadioButton; OUT on: BOOLEAN);
Set*: PROCEDURE (f: RadioButton; on: BOOLEAN)
END;
ScrollBar* = POINTER TO ABSTRACT RECORD (Frame)
Track*: PROCEDURE (f: ScrollBar; dir: INTEGER; VAR pos: INTEGER);
Get*: PROCEDURE (f: ScrollBar; OUT size, sect, pos: INTEGER);
Set*: PROCEDURE (f: ScrollBar; pos: INTEGER)
END;
Field* = POINTER TO ABSTRACT RECORD (Frame)
maxLen*: INTEGER; (* max num of characters in field (w/o 0X) *)
left*, right*, multiLine*, password*: BOOLEAN;
Get*: PROCEDURE (f: Field; OUT string: ARRAY OF CHAR);
Set*: PROCEDURE (f: Field; IN string: ARRAY OF CHAR);
Equal*: PROCEDURE (f: Field; IN s1, s2: ARRAY OF CHAR): BOOLEAN
END;
UpDownField* = POINTER TO ABSTRACT RECORD (Frame)
min*, max*, inc*: INTEGER;
Get*: PROCEDURE (f: UpDownField; OUT val: INTEGER);
Set*: PROCEDURE (f: UpDownField; val: INTEGER)
END;
DateField* = POINTER TO ABSTRACT RECORD (Frame)
Get*: PROCEDURE (f: DateField; OUT date: Dates.Date);
Set*: PROCEDURE (f: DateField; IN date: Dates.Date);
GetSel*: PROCEDURE (f: DateField; OUT sel: INTEGER);
SetSel*: PROCEDURE (f: DateField; sel: INTEGER)
END;
TimeField* = POINTER TO ABSTRACT RECORD (Frame)
Get*: PROCEDURE (f: TimeField; OUT date: Dates.Time);
Set*: PROCEDURE (f: TimeField; IN date: Dates.Time);
GetSel*: PROCEDURE (f: TimeField; OUT sel: INTEGER);
SetSel*: PROCEDURE (f: TimeField; sel: INTEGER)
END;
ColorField* = POINTER TO ABSTRACT RECORD (Frame)
Get*: PROCEDURE (f: ColorField; OUT col: INTEGER);
Set*: PROCEDURE (f: ColorField; col: INTEGER)
END;
ListBox* = POINTER TO ABSTRACT RECORD (Frame)
sorted*: BOOLEAN;
Get*: PROCEDURE (f: ListBox; OUT i: INTEGER);
Set*: PROCEDURE (f: ListBox; i: INTEGER);
GetName*: PROCEDURE (f: ListBox; i: INTEGER; VAR name: ARRAY OF CHAR)
END;
SelectionBox* = POINTER TO ABSTRACT RECORD (Frame)
sorted*: BOOLEAN;
Get*: PROCEDURE (f: SelectionBox; i: INTEGER; OUT in: BOOLEAN);
Incl*: PROCEDURE (f: SelectionBox; from, to: INTEGER);
Excl*: PROCEDURE (f: SelectionBox; from, to: INTEGER);
Set*: PROCEDURE (f: SelectionBox; from, to: INTEGER);
GetName*: PROCEDURE (f: SelectionBox; i: INTEGER; VAR name: ARRAY OF CHAR)
END;
ComboBox* = POINTER TO ABSTRACT RECORD (Frame)
sorted*: BOOLEAN;
Get*: PROCEDURE (f: ComboBox; OUT string: ARRAY OF CHAR);
Set*: PROCEDURE (f: ComboBox; IN string: ARRAY OF CHAR);
GetName*: PROCEDURE (f: ComboBox; i: INTEGER; VAR name: ARRAY OF CHAR)
END;
Caption* = POINTER TO ABSTRACT RECORD (Frame)
label*: ARRAY 256 OF CHAR;
left*, right*: BOOLEAN;
END;
Group* = POINTER TO ABSTRACT RECORD (Frame)
label*: ARRAY 256 OF CHAR
END;
TreeFrame* = POINTER TO ABSTRACT RECORD (Frame)
sorted*, haslines*, hasbuttons*, atroot*, foldericons*: BOOLEAN;
NofNodes*: PROCEDURE (f: TreeFrame): INTEGER;
Child*: PROCEDURE (f: TreeFrame; node: Dialog.TreeNode): Dialog.TreeNode;
Parent*: PROCEDURE (f: TreeFrame; node: Dialog.TreeNode): Dialog.TreeNode;
Next*: PROCEDURE (f: TreeFrame; node: Dialog.TreeNode): Dialog.TreeNode;
Select*: PROCEDURE (f: TreeFrame; node: Dialog.TreeNode);
Selected*: PROCEDURE (f: TreeFrame): Dialog.TreeNode;
SetExpansion*: PROCEDURE (f: TreeFrame; tn: Dialog.TreeNode; expanded: BOOLEAN)
END;
Directory* = POINTER TO ABSTRACT RECORD END;
VAR
setFocus*: BOOLEAN;
defaultFont*, defaultLightFont*: Fonts.Font;
dir-, stdDir-: Directory;
(** Frame **)
PROCEDURE (f: Frame) MouseDown* (x, y: INTEGER; buttons: SET), NEW, EMPTY;
PROCEDURE (f: Frame) WheelMove* (x, y: INTEGER; op, nofLines: INTEGER;
VAR done: BOOLEAN), NEW, EMPTY;
(* signature extended: added `modifiers` *)
PROCEDURE (f: Frame) KeyDown* (ch: CHAR; modifiers: SET), NEW, EMPTY;
PROCEDURE (f: Frame) Restore* (l, t, r, b: INTEGER), NEW, ABSTRACT;
PROCEDURE (f: Frame) UpdateList*, NEW, EMPTY;
PROCEDURE (f: Frame) Mark* (on, focus: BOOLEAN), NEW, EMPTY;
PROCEDURE (f: Frame) Edit* (op: INTEGER; VAR v: Views.View; VAR w, h: INTEGER;
VAR singleton, clipboard: BOOLEAN), NEW, EMPTY;
PROCEDURE (f: Frame) GetCursor* (x, y: INTEGER; modifiers: SET; VAR cursor: INTEGER), NEW, EMPTY;
(* schedule the redraw *)
PROCEDURE (f: Frame) Update*, NEW, EXTENSIBLE;
VAR l, t, r, b: INTEGER; root: Views.RootFrame;
BEGIN
(* k8: added this guard, so i can call `Update^` without annoying checks *)
IF f.view # NIL THEN
l := f.l + f.gx; t := f.t + f.gy; r := f.r + f.gx; b := f.b + f.gy;
root := Views.UltimateRootOf(f);
Views.UpdateRoot(root, l, t, r, b, Views.keepFrames)
(* Views.ValidateRoot(root) *)
END
END Update;
(* perform the immediate redraw; used in mouse tracking for buttons, etc. *)
PROCEDURE (f: Frame) ForceUpdate*, NEW, EXTENSIBLE;
VAR l, t, r, b: INTEGER; root: Views.RootFrame;
BEGIN
IF f.view # NIL THEN
l := f.l + f.gx; t := f.t + f.gy; r := f.r + f.gx; b := f.b + f.gy;
root := Views.UltimateRootOf(f);
Views.RestoreRoot(root, l, t, r, b)
END
END ForceUpdate;
PROCEDURE (f: Frame) DblClickOk* (x, y: INTEGER): BOOLEAN, NEW, EXTENSIBLE;
BEGIN
RETURN TRUE
END DblClickOk;
(* this is used internally in StdCFramesGuts to notify about closing a popup *)
PROCEDURE (f: Frame) PopupClosed* (popup: ANYPTR), NEW, EMPTY;
(** Field **)
PROCEDURE (f: Field) Idle* (), NEW, ABSTRACT;
PROCEDURE (f: Field) Select* (from, to: INTEGER), NEW, ABSTRACT;
PROCEDURE (f: Field) GetSelection* (OUT from, to: INTEGER), NEW, ABSTRACT;
PROCEDURE (f: Field) Length* (): INTEGER, NEW, ABSTRACT;
PROCEDURE (f: Field) GetCursor* (x, y: INTEGER; modifiers: SET; VAR cursor: INTEGER), EXTENSIBLE;
BEGIN
cursor := Ports.textCursor
END GetCursor;
(** UpDownField **)
PROCEDURE (f: UpDownField) Idle*, NEW, ABSTRACT;
PROCEDURE (f: UpDownField) Select* (from, to: INTEGER), NEW, ABSTRACT;
PROCEDURE (f: UpDownField) GetSelection* (OUT from, to: INTEGER), NEW, ABSTRACT;
PROCEDURE (f: UpDownField) GetCursor* (x, y: INTEGER; modifiers: SET;
VAR cursor: INTEGER), EXTENSIBLE;
BEGIN
cursor := Ports.textCursor
END GetCursor;
(** SelectionBox **)
PROCEDURE (f: SelectionBox) Select* (from, to: INTEGER), NEW, ABSTRACT;
PROCEDURE (f: SelectionBox) GetSelection* (OUT from, to: INTEGER), NEW, ABSTRACT;
PROCEDURE (f: SelectionBox) UpdateRange* (op, from, to: INTEGER), NEW, EXTENSIBLE;
BEGIN
f.Update
END UpdateRange;
(** ComboBox **)
PROCEDURE (f: ComboBox) Idle* (), NEW, ABSTRACT;
PROCEDURE (f: ComboBox) Select* (from, to: INTEGER), NEW, ABSTRACT;
PROCEDURE (f: ComboBox) GetSelection* (OUT from, to: INTEGER), NEW, ABSTRACT;
PROCEDURE (f: ComboBox) Length* (): INTEGER, NEW, ABSTRACT;
(* TreeFrame **)
PROCEDURE (f: TreeFrame) GetSize* (OUT w, h: INTEGER), NEW, ABSTRACT;
(** Directory **)
PROCEDURE (d: Directory) GetPushButtonSize* (VAR w, h: INTEGER), NEW, ABSTRACT;
PROCEDURE (d: Directory) GetCheckBoxSize* (VAR w, h: INTEGER), NEW, ABSTRACT;
PROCEDURE (d: Directory) GetRadioButtonSize* (VAR w, h: INTEGER), NEW, ABSTRACT;
PROCEDURE (d: Directory) GetScrollBarSize* (VAR w, h: INTEGER), NEW, ABSTRACT;
PROCEDURE (d: Directory) GetFieldSize* (max: INTEGER; VAR w, h: INTEGER), NEW, ABSTRACT;
PROCEDURE (d: Directory) GetUpDownFieldSize* (max: INTEGER; VAR w, h: INTEGER), NEW, ABSTRACT;
PROCEDURE (d: Directory) GetDateFieldSize* (VAR w, h: INTEGER), NEW, ABSTRACT;
PROCEDURE (d: Directory) GetTimeFieldSize* (VAR w, h: INTEGER), NEW, ABSTRACT;
PROCEDURE (d: Directory) GetColorFieldSize* (VAR w, h: INTEGER), NEW, ABSTRACT;
PROCEDURE (d: Directory) GetListBoxSize* (VAR w, h: INTEGER), NEW, ABSTRACT;
PROCEDURE (d: Directory) GetSelectionBoxSize* (VAR w, h: INTEGER), NEW, ABSTRACT;
PROCEDURE (d: Directory) GetComboBoxSize* (VAR w, h: INTEGER), NEW, ABSTRACT;
PROCEDURE (d: Directory) GetCaptionSize* (VAR w, h: INTEGER), NEW, ABSTRACT;
PROCEDURE (d: Directory) GetGroupSize* (VAR w, h: INTEGER), NEW, ABSTRACT;
PROCEDURE (d: Directory) GetTreeFrameSize* (VAR w, h: INTEGER), NEW, ABSTRACT;
PROCEDURE (d: Directory) NewPushButton* (): PushButton, NEW, ABSTRACT;
PROCEDURE (d: Directory) NewCheckBox* (): CheckBox, NEW, ABSTRACT;
PROCEDURE (d: Directory) NewRadioButton* (): RadioButton, NEW, ABSTRACT;
PROCEDURE (d: Directory) NewScrollBar* (): ScrollBar, NEW, ABSTRACT;
PROCEDURE (d: Directory) NewField* (): Field, NEW, ABSTRACT;
PROCEDURE (d: Directory) NewUpDownField* (): UpDownField, NEW, ABSTRACT;
PROCEDURE (d: Directory) NewDateField* (): DateField, NEW, ABSTRACT;
PROCEDURE (d: Directory) NewTimeField* (): TimeField, NEW, ABSTRACT;
PROCEDURE (d: Directory) NewColorField* (): ColorField, NEW, ABSTRACT;
PROCEDURE (d: Directory) NewListBox* (): ListBox, NEW, ABSTRACT;
PROCEDURE (d: Directory) NewSelectionBox* (): SelectionBox, NEW, ABSTRACT;
PROCEDURE (d: Directory) NewComboBox* (): ComboBox, NEW, ABSTRACT;
PROCEDURE (d: Directory) NewCaption* (): Caption, NEW, ABSTRACT;
PROCEDURE (d: Directory) NewGroup* (): Group, NEW, ABSTRACT;
PROCEDURE (d: Directory) NewTreeFrame* (): TreeFrame, NEW, ABSTRACT;
PROCEDURE SetDir* (d: Directory);
BEGIN
ASSERT(d # NIL, 20); dir := d;
IF stdDir = NIL THEN stdDir := d END
END SetDir;
BEGIN
setFocus := FALSE
END StdCFrames.
| Std/Mod/CFrames.odc |
MODULE StdClocks;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- YYYYMMDD, nn, ...
"
issues = "
- ...
"
**)
IMPORT
Dates, Math, Domains := Stores, Ports, Stores, Models, Views, Services, Properties,
TextModels;
CONST
minSize = 25 * Ports.point; niceSize = 42 * Ports.point;
minVersion = 0; maxVersion = 0;
TYPE
StdView = POINTER TO RECORD (Views.View)
time: Dates.Time
END;
TickAction = POINTER TO RECORD (Services.Action) END;
Msg = RECORD (Models.Message)
consumed: BOOLEAN;
time: Dates.Time
END;
VAR
clockTime: Dates.Time;
action: TickAction;
actionIsAlive: BOOLEAN;
PROCEDURE Cos (r, g: INTEGER): INTEGER;
BEGIN
RETURN SHORT(ENTIER(r * Math.Cos(2 * Math.Pi() * g / 60) + 0.5))
END Cos;
PROCEDURE Sin (r, g: INTEGER): INTEGER;
BEGIN
RETURN SHORT(ENTIER(r * Math.Sin(2 * Math.Pi() * g / 60) + 0.5))
END Sin;
PROCEDURE (a: TickAction) Do;
VAR msg: Msg; time: Dates.Time;
BEGIN
Dates.GetTime(time);
IF clockTime.second = time.second THEN
Services.DoLater(action, Services.Ticks() + Services.resolution DIV 2)
ELSE
clockTime := time;
msg.consumed := FALSE;
msg.time := time;
Views.Omnicast(msg);
IF msg.consumed THEN
Services.DoLater(action, Services.Ticks() + Services.resolution DIV 2)
ELSE
actionIsAlive := FALSE
END
END
END Do;
(* View *)
PROCEDURE DrawTick (f: Views.Frame; m, d0, d1, s, g: INTEGER; c: Ports.Color);
BEGIN
f.DrawLine(m + Sin(d0, g), m - Cos(d0, g), m + Sin(d1, g), m - Cos(d1, g), s, c)
END DrawTick;
PROCEDURE (v: StdView) Externalize (VAR wr: Stores.Writer);
BEGIN
v.Externalize^(wr);
wr.WriteVersion(maxVersion);
wr.WriteByte(9)
END Externalize;
PROCEDURE (v: StdView) Internalize (VAR rd: Stores.Reader);
VAR thisVersion: INTEGER; format: BYTE;
BEGIN
v.Internalize^(rd);
IF ~rd.cancelled THEN
rd.ReadVersion(minVersion, maxVersion, thisVersion);
IF ~rd.cancelled THEN
rd.ReadByte(format);
v.time.second := -1
END
END
END Internalize;
PROCEDURE (v: StdView) CopyFromSimpleView (source: Views.View);
BEGIN
WITH source: StdView DO
v.time.second := -1
END
END CopyFromSimpleView;
PROCEDURE (v: StdView) Restore (f: Views.Frame; l, t, r, b: INTEGER);
VAR c: Models.Context; a: TextModels.Attributes; color: Ports.Color;
time: Dates.Time;
i, m, d, u, hs, hd1, ms, md1, ss, sd0, sd1, w, h: INTEGER;
BEGIN
IF ~actionIsAlive THEN
actionIsAlive := TRUE; Services.DoLater(action, Services.now)
END;
IF v.time.second = -1 THEN Dates.GetTime(v.time) END;
c := v.context; c.GetSize(w, h);
WITH c: TextModels.Context DO a := c.Attr(); color := a.color
ELSE color := Ports.defaultColor
END;
u := f.unit;
d := h DIV u * u;
IF ~ODD(d DIV u) THEN DEC(d, u) END;
m := (h - u) DIV 2;
IF d >= niceSize - 2 * Ports.point THEN
hs := 3 * u; ms := 3 * u; ss := u;
hd1 := m * 4 DIV 6; md1 := m * 5 DIV 6; sd0 := -(m DIV 6); sd1 := m - 4 * u;
i := 0; WHILE i < 12 DO DrawTick(f, m, m * 11 DIV 12, m, u, i * 5, color); INC(i) END
ELSE
hd1 := m * 2 DIV 4; hs := u; ms := u; ss := u;
md1 := m * 3 DIV 4; sd0 := 0; sd1 := 3 * u
END;
time := v.time;
f.DrawOval(0, 0, d, d, u, color);
DrawTick(f, m, 0, m * 4 DIV 6, hs, time.hour MOD 12 * 5 + time.minute DIV 12, color);
DrawTick(f, m, 0, md1, ms, time.minute, color);
DrawTick(f, m, sd0, sd1, ss, time.second, color)
END Restore;
PROCEDURE (v: StdView) HandleModelMsg (VAR msg: Models.Message);
VAR w, h: INTEGER;
BEGIN
WITH msg: Msg DO
msg.consumed := TRUE;
IF v.time.second # msg.time.second THEN (* execute only once per view *)
Views.Update(v, Views.keepFrames);
v.time := msg.time
END
ELSE
END
END HandleModelMsg;
PROCEDURE SizePref (v: StdView; VAR p: Properties.SizePref);
BEGIN
IF (p.w > Views.undefined) & (p.h > Views.undefined) THEN
Properties.ProportionalConstraint(1, 1, p.fixedW, p.fixedH, p.w, p.h);
IF p.w < minSize THEN p.w := minSize; p.h := minSize END
ELSE
p.w := niceSize; p.h := niceSize
END
END SizePref;
PROCEDURE (v: StdView) HandlePropMsg (VAR msg: Properties.Message);
BEGIN
WITH msg: Properties.Preference DO
WITH msg: Properties.SizePref DO
SizePref(v, msg)
ELSE
END
ELSE
END
END HandlePropMsg;
(** allocation **)
PROCEDURE New* (): Views.View;
VAR v: StdView;
BEGIN
NEW(v); v.time.second := -1; RETURN v
END New;
PROCEDURE Deposit*;
BEGIN
Views.Deposit(New())
END Deposit;
BEGIN
clockTime.second := -1;
NEW(action); actionIsAlive := FALSE
CLOSE
IF actionIsAlive THEN Services.RemoveAction(action) END
END StdClocks.
| Std/Mod/Clocks.odc |
MODULE StdCmds;
(**
project = "BlackBox 2.0, diffs vs 1.7.2 are marked by green"
organizations = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Oberon microsystems, A.A. Dmitriev, I.A. Denisov"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 20141027, center #19, full Unicode support for Component Pascal identifiers added
- 20200311, Temirgaleev IE, result of Open procedures
"
issues = "
- ...
"
**)
IMPORT Kernel, Meta, Files, Converters, Printers, Printing,
Fonts, Ports, Services, Stores, Sequencers, Models, Views,
Controllers, Containers, Properties, Dialog, Documents, Windows, Strings,
StdDialog, StdApi;
CONST
illegalSizeKey = "#System:IllegalFontSize";
defaultAllocator = "TextViews.Deposit; StdCmds.Open";
(* wType, hType *)
fix = 0; page = 1; window = 2;
(* DirtyHook.Do: action *)
default* = 0; defer* = 1; save* = 2; cancel* = 3; close* = 4;
(* hints *)
expDoc = 1; (* imported view should be stored as document *)
TYPE
DirtyHook* = PROCEDURE (w: Windows.Window; OUT action: INTEGER);
ClipboardHook* = POINTER TO ABSTRACT RECORD END;
Param* = POINTER TO RECORD
dirtyHook*: ARRAY 128 OF CHAR;
clearSeqOnSave*: BOOLEAN;
proc: DirtyHook;
InitDefaults-, Init-: PROCEDURE (a: ANYPTR);
END;
OpenAction = POINTER TO RECORD (Dialog.GetAction) END;
OpenCopyAction = POINTER TO RECORD (Dialog.GetAction) END;
SaveAction = POINTER TO RECORD (Dialog.GetAction)
w: Windows.Window;
rename: BOOLEAN;
v: Views.View;
END;
SaveAsAction = POINTER TO RECORD (Dialog.GetAction)
v: Views.View;
END;
VAR
size*: RECORD
size*: INTEGER
END;
layout*: RECORD
wType*, hType*: INTEGER;
width*, height*: REAL;
doc: Documents.Document;
u: INTEGER
END;
allocator*: Dialog.String;
propEra: INTEGER; (* (propEra, props) form cache for StdProps() *)
props: Properties.StdProp; (* valid iff propEra = Props.era *)
prop: Properties.Property; (* usef for copy/paste properties *)
stdDirtyHook*: DirtyHook;
clipboardHook*: ClipboardHook;
exitHook*: PROCEDURE;
objectMenuGuard*: PROCEDURE (VAR par: Dialog.Par);
specHook: Views.GetSpecHook;
result*: INTEGER; (* 0 - last OpenXXX successful, 1 - last OpenXXX failed *)
param*: Param;
PROCEDURE (h: ClipboardHook) Register* (v: Views.View; wid, hei: INTEGER; isSingle: BOOLEAN), NEW, ABSTRACT;
PROCEDURE (h: ClipboardHook) Paste*, NEW, ABSTRACT;
(* auxiliary procedures *)
PROCEDURE SetGetSpecHook* (h: Views.GetSpecHook);
BEGIN
specHook := h
END SetGetSpecHook;
PROCEDURE StdProp (): Properties.StdProp;
BEGIN
IF propEra # Properties.era THEN
Properties.CollectStdProp(props);
propEra := Properties.era
END;
RETURN props
END StdProp;
PROCEDURE Append (VAR s: ARRAY OF CHAR; t: ARRAY OF CHAR);
VAR len, i, j: INTEGER; ch: CHAR;
BEGIN
len := LEN(s);
i := 0; WHILE s[i] # 0X DO INC(i) END;
j := 0; REPEAT ch := t[j]; s[i] := ch; INC(j); INC(i) UNTIL (ch = 0X) OR (i = len);
s[len - 1] := 0X
END Append;
(* standard commands *)
PROCEDURE OpenAuxDialog* (file, title: ARRAY OF CHAR);
VAR v: Views.View;
BEGIN
StdApi.OpenAuxDialog(file, title, v);
IF v = NIL THEN result := 1 ELSE result := 0 END
END OpenAuxDialog;
PROCEDURE OpenToolDialog* (file, title: ARRAY OF CHAR);
VAR v: Views.View;
BEGIN
StdApi.OpenToolDialog(file, title, v);
IF v = NIL THEN result := 1 ELSE result := 0 END
END OpenToolDialog;
PROCEDURE OpenDoc* (file: ARRAY OF CHAR);
VAR v: Views.View;
BEGIN
StdApi.OpenDoc(file, v);
IF v = NIL THEN result := 1 ELSE result := 0 END
END OpenDoc;
PROCEDURE OpenCopyOf* (file: ARRAY OF CHAR);
VAR v: Views.View;
BEGIN
StdApi.OpenCopyOf(file, v);
IF v = NIL THEN result := 1 ELSE result := 0 END
END OpenCopyOf;
PROCEDURE OpenAux* (file, title: ARRAY OF CHAR);
VAR v: Views.View;
BEGIN
StdApi.OpenAux(file, title, v);
IF v = NIL THEN result := 1 ELSE result := 0 END
END OpenAux;
PROCEDURE OpenBrowser* (file, title: ARRAY OF CHAR);
VAR v: Views.View;
BEGIN
StdApi.OpenBrowser(file, title, v);
IF v = NIL THEN result := 1 ELSE result := 0 END
END OpenBrowser;
PROCEDURE CloseDialog*;
(** CloseDialog will ONLY close "dialog" windows (aux, tool, neverdirty) or clean docs. It does NOT provide the user with a dialog to save a dirty document and therefore does NOT save dirty documents. It is used in form commands, so this probably was it's initial purpose. *)
VAR v: Views.View;
BEGIN
StdApi.CloseDialog(v)
END CloseDialog;
PROCEDURE SaveConvByName (IN name: Files.Name; VAR conv: Converters.Converter);
VAR i, len: INTEGER; type: Files.Type;
BEGIN
len := LEN(name$);
type := ""; conv := NIL;
i := len; WHILE (i > 0) & (name[i] # ".") DO DEC(i) END;
IF i > 0 THEN
Strings.Extract(name,i+1,len-i,type);
conv := Converters.list;
WHILE (conv # NIL) & ~( (conv.exp # "") & (conv.fileType = type) ) DO
conv := conv.next
END
END
END SaveConvByName;
PROCEDURE OpenConvByName (IN name: Files.Name; VAR conv: Converters.Converter);
VAR i, len: INTEGER; type: Files.Type;
BEGIN
len := LEN(name$);
type := "";
i := len; WHILE (i > 0) & (name[i] # ".") DO DEC(i) END;
IF i > 0 THEN
Strings.Extract(name,i+1,len-i,type);
conv := Converters.list;
WHILE (conv # NIL) & ~( (conv.imp # "") & (conv.fileType = type) ) DO
conv := conv.next
END
END;
IF (i <= 0) OR (conv = NIL) THEN
conv := Converters.list;
WHILE (conv # NIL) & ~(Converters.importAll IN conv.opts) DO
conv := conv.next
END
END
END OpenConvByName;
PROCEDURE SaveConvByType (IN type: Files.Type; VAR conv: Converters.Converter);
BEGIN
conv := Converters.list;
WHILE (conv # NIL) & ~( (conv.exp # "") & (conv.fileType = type) ) DO
conv := conv.next
END
END SaveConvByType;
PROCEDURE OpenConvByType (IN type: Files.Type; VAR conv: Converters.Converter);
BEGIN
conv := Converters.list;
WHILE (conv # NIL) & ~( (conv.imp # "") & (conv.fileType = type) ) DO
conv := conv.next
END
END OpenConvByType;
PROCEDURE ExOpen (loc: Files.Locator; name: Files.Name; conv: Converters.Converter);
(** open an existing document or view (ex HostCmds.Open) **)
VAR v: Views.View;
s: Stores.Store; w: Windows.Window;
BEGIN
(* w := Windows.GetBySpec(loc, name, conv, {}); *)
w := Windows.dir.First();
WHILE (w # NIL)
& ((w.loc = NIL) OR (w.name = "") OR (w.loc.res = 77)
OR ~Files.dir.SameFile(loc, name, w.loc, w.name)
OR (w.conv # conv)) DO
w := Windows.dir.Next(w)
END;
IF w # NIL THEN s := w.doc
ELSE
Converters.Import(loc, name, conv, s);
IF s # NIL THEN StdDialog.RecalcView(s(Views.View)) END
END;
IF s # NIL THEN
v := s(Views.View);
IF (conv # NIL) & (expDoc IN conv.opts) THEN conv := NIL END;
Views.Open(v, loc, name, conv)
ELSE
Dialog.ShowParamMsg("#System:FailedToOpen", name, "", "")
END
END ExOpen;
PROCEDURE (a: OpenAction) Do;
VAR loc: Files.Locator; name: Files.Name; conv: Converters.Converter;
BEGIN
IF ~a.cancel THEN
loc := a.loc;
name := a.name;
IF a.converterName # "" THEN
conv := Converters.list;
WHILE (conv # NIL) & (conv.imp # a.converterName) DO
conv := conv.next
END
ELSE
IF (a.type = "") OR (a.type = "*") THEN
OpenConvByName(name, conv)
ELSE
OpenConvByType(a.type$, conv)
END
END;
ExOpen(loc, name, conv);
END
END Do;
PROCEDURE OpenDialog*; (* for replace HostCmds.Open *)
(** open an existing document or view **)
VAR loc: Files.Locator; name: Files.Name; conv: Converters.Converter;
action: OpenAction;
BEGIN
loc := NIL;
name := "";
conv := NIL;
IF Dialog.platform = Dialog.windows THEN
specHook.GetIntSpec(loc, name, conv);
IF loc # NIL THEN
ExOpen(loc, name, conv);
END
ELSE
NEW(action);
action.title := "#Std:Open...";
Dialog.GetIntLocName("", loc, action);
END
END OpenDialog;
PROCEDURE (a: OpenCopyAction) Do;
VAR loc: Files.Locator; name: Files.Name; conv: Converters.Converter; v: Views.View;
BEGIN
IF ~a.cancel THEN
loc := a.loc;
name := a.name;
IF a.converterName # "" THEN
conv := Converters.list;
WHILE (conv # NIL) & (conv.imp # a.converterName) DO
conv := conv.next
END
ELSE
IF (a.type = "") OR (a.type = "*") THEN
OpenConvByName(name, conv)
ELSE
OpenConvByType(a.type$, conv)
END
END;
(* HostCmds.OpenCopyOf *)
v := Views.Old(Views.dontAsk, loc, name, conv);
IF v # NIL THEN
IF v.context # NIL THEN
v := Views.CopyOf(v.context(Documents.Context).ThisDoc(), Views.deep);
Stores.InitDomain(v)
ELSE v := Views.CopyOf(v, Views.deep)
END;
Views.Open(v, NIL, "", conv)
ELSE
Dialog.ShowParamMsg("#System:FailedToOpen", name, "", "")
END
END
END Do;
PROCEDURE OpenCopyOfDialog*; (* for replace HostCmds.OpenCopyOf *)
VAR loc: Files.Locator; name: Files.Name; conv: Converters.Converter; v: Views.View;
action: OpenCopyAction;
BEGIN
loc := NIL;
IF Dialog.platform = Dialog.windows THEN
(* HostCmds.OpenCopyOf *)
v := Views.Old(Views.ask, loc, name, conv);
IF v # NIL THEN
IF v.context # NIL THEN
v := Views.CopyOf(v.context(Documents.Context).ThisDoc(), Views.deep);
Stores.InitDomain(v)
ELSE v := Views.CopyOf(v, Views.deep)
END;
Views.Open(v, NIL, "", conv)
END
ELSE
NEW(action);
action.loc := loc;
action.title := "#Std:Open As Copy...";
Dialog.GetIntLocName("", loc, action);
END
END OpenCopyOfDialog;
PROCEDURE (a: SaveAction) Do;
VAR title: Views.Title; loc: Files.Locator; name: Files.Name; v: Views.View;
conv: Converters.Converter; len, i: INTEGER; w: Windows.Window;
rename: BOOLEAN;
BEGIN
IF ~a.cancel THEN
name := a.name;
IF (a.type # "") & (a.type # "*") THEN
Strings.Find(name, ".", 0, i);
IF i = -1 THEN
name := name + "." + a.type
END
END;
IF a.converterName # "" THEN
conv := Converters.list;
WHILE (conv # NIL) & (conv.exp # a.converterName) DO
conv := conv.next
END
END;
IF conv = NIL THEN
IF (a.type = "") OR (a.type = "*") THEN
SaveConvByName(name, conv)
ELSE
SaveConvByType(a.type$, conv)
END
END;
IF conv = NIL THEN
conv := Converters.list
END;
loc := a.loc;
w := a.w;
v := a.v;
rename := a.rename;
Dialog.ShowStatus("#System:Saving");
Converters.Export(loc, name, conv, v);
IF loc.res = 0 THEN
IF w.seq.Dirty() THEN
IF param.clearSeqOnSave THEN
(* clear sequencer *)
w.seq.BeginModification(Sequencers.notUndoable, NIL);
w.seq.EndModification(Sequencers.notUndoable, NIL);
END;
w.seq.SetDirty(FALSE)
END;
IF rename THEN
len := MIN(LEN(name$), LEN(Views.Title) - 1);
Strings.Extract(name, 0, len, title);
IF len = LEN(Views.Title) - 1 THEN
title[len - 1] := "."; title[len - 2] := "."; title[len - 3] := "."
END;
w.SetTitle(title); w.SetSpec(loc, name, conv)
END;
w.SetTitle(title); w.SetSpec(loc, name, conv);
Dialog.ShowStatus("#System:Saved")
ELSE
Dialog.ShowStatus("#System:Failed")
END;
Kernel.Cleanup
END
END Do;
PROCEDURE SaveWindow (w: Windows.Window; rename: BOOLEAN);
VAR title: Views.Title; loc: Files.Locator; name: Files.Name; v: Views.View;
conv: Converters.Converter; len: INTEGER;
action: SaveAction;
BEGIN
IF (w # NIL) & (rename OR ~(Windows.neverDirty IN w.flags)) THEN
v := w.doc.OriginalView();
loc := w.loc; name := w.name$; conv := w.conv;
IF name = "" THEN Dialog.MapString("#System:untitled", name) END;
IF (loc = NIL) OR (loc.res = 77) OR (conv # NIL) & (conv.exp = "") THEN
rename := TRUE
END;
IF (Dialog.platform = Dialog.windows) OR ~rename THEN
IF rename THEN specHook.GetExtSpec(v, loc, name, conv) END;
IF loc # NIL THEN
Dialog.ShowStatus("#System:Saving");
Converters.Export(loc, name, conv, v);
IF loc.res = 0 THEN
IF w.seq.Dirty() THEN
IF param.clearSeqOnSave THEN
(* clear sequencer *)
w.seq.BeginModification(Sequencers.notUndoable, NIL);
w.seq.EndModification(Sequencers.notUndoable, NIL);
END;
w.seq.SetDirty(FALSE)
END;
IF rename THEN
len := MIN(LEN(name$), LEN(Views.Title) - 1);
Strings.Extract(name, 0, len, title);
IF len = LEN(Views.Title) - 1 THEN
title[len - 1] := "."; title[len - 2] := "."; title[len - 3] := "."
END;
w.SetTitle(title); w.SetSpec(loc, name, conv)
END;
Dialog.ShowStatus("#System:Saved")
ELSE
Dialog.ShowStatus("#System:Failed")
END
END;
Kernel.Cleanup
ELSE
NEW(action);
IF conv # NIL THEN
action.selectConverter := conv.exp
ELSE
action.selectConverter := Converters.list.exp
END;
action.v := v;
action.w := w;
action.rename := rename;
IF rename THEN
action.title := "#Std:Save As..."
ELSE
action.title := "#Std:Save..."
END;
Dialog.GetExtLocName(name, "", loc, action);
END
END
END SaveWindow;
PROCEDURE SaveDialog*; (* to replace HostCmds.Save *)
(** save document shown in target window under old name **)
VAR w: Windows.Window;
BEGIN
w := Windows.dir.Focus(Controllers.targetPath);
IF w # NIL THEN SaveWindow(w, FALSE) END
END SaveDialog;
PROCEDURE SaveAsDialog*; (* to replace HostCmds.SaveAs *)
(** save document shown in target window under new name **)
VAR w: Windows.Window;
BEGIN
w := Windows.dir.Focus(Controllers.targetPath);
IF w # NIL THEN SaveWindow(w, TRUE) END
END SaveAsDialog;
PROCEDURE (a: SaveAsAction) Do;
VAR loc: Files.Locator; name: Files.Name; v: Views.View; conv: Converters.Converter;
i: INTEGER;
BEGIN
IF ~a.cancel THEN
name := a.name;
IF (a.type # "") & (a.type # "*") THEN
Strings.Find(name, ".", 0, i);
IF i = -1 THEN
name := name + "." + a.type
END
END;
IF a.converterName # "" THEN
conv := Converters.list;
WHILE (conv # NIL) & (conv.exp # a.converterName) DO
conv := conv.next
END
END;
IF conv = NIL THEN
IF (a.type = "") OR (a.type = "*") THEN
SaveConvByName(name, conv)
ELSE
SaveConvByType(a.type$, conv)
END
END;
IF conv = NIL THEN
conv := Converters.list
END;
loc := a.loc;
v := a.v;
Dialog.ShowStatus("#System:Saving");
Converters.Export(loc, name, conv, v);
IF loc.res = 0 THEN Dialog.ShowStatus("#System:Saved")
ELSE Dialog.ShowStatus("#System:Failed")
END;
Kernel.Cleanup
END
END Do;
PROCEDURE SaveCopyAsDialog*; (* to replace HostCmds.SaveCopyAs *)
(** save copy of document shown in target window under new name **)
VAR w: Windows.Window; loc: Files.Locator; name: Files.Name; v: Views.View;
conv: Converters.Converter;
action: SaveAsAction;
BEGIN
w := Windows.dir.Focus(Controllers.targetPath);
IF w # NIL THEN
v := w.doc.OriginalView();
loc := w.loc; name := w.name$; conv := w.conv;
IF name = "" THEN Dialog.MapString("#System:untitled", name) END;
IF Dialog.platform = Dialog.windows THEN
specHook.GetExtSpec(v, loc, name, conv);
IF loc # NIL THEN
Dialog.ShowStatus("#System:Saving");
Converters.Export(loc, name, conv, v);
IF loc.res = 0 THEN Dialog.ShowStatus("#System:Saved")
ELSE Dialog.ShowStatus("#System:Failed")
END
END;
Kernel.Cleanup
ELSE
NEW(action);
IF conv # NIL THEN
action.selectConverter := conv.exp
ELSE
action.selectConverter := Converters.list.exp
END;
action.v := v;
action.title := "#Std:Save Copy As...";
Dialog.GetExtLocName(name, "", loc, action)
END
END
END SaveCopyAsDialog;
PROCEDURE GuardedClose* (w: Windows.Window; OUT cancelled, deferred: BOOLEAN);
(* cancelled: the user cancelled closing of w process (possibly by clicking Cancel button); if closing w was part of closing a sequence of windows, the closing of the sequence is thus also cancelled deferred: the closing of w was deferred (possibly by asking the user a non-modal question *)
VAR msg: Sequencers.CloseMsg; action: INTEGER;
BEGIN
ASSERT(w # NIL, 20); cancelled := TRUE; deferred := FALSE;
IF w.sub THEN Windows.dir.Close(w)
ELSE
msg.sticky := FALSE; w.seq.Notify(msg);
IF msg.sticky THEN cancelled := TRUE; deferred := FALSE
ELSE
IF w.seq.Dirty() & ~(Windows.neverDirty IN w.flags) THEN
(* here you actually involve a dirty close dialog hook *)
IF param.proc # NIL THEN
param.proc(w, action)
ELSE
action := default
END;
ASSERT(stdDirtyHook # NIL, 38);
IF action = default THEN stdDirtyHook(w, action) END;
IF action = defer THEN cancelled := FALSE; deferred := TRUE
ELSIF action = save THEN deferred := FALSE;
SaveWindow(w, FALSE); (* if saving is canceled, document remains dirty *)
IF w.seq.Dirty() THEN cancelled := TRUE
ELSE Windows.dir.Close(w); cancelled := FALSE
END
ELSIF action = cancel THEN
cancelled := TRUE; deferred := FALSE
ELSIF action = close THEN
cancelled := FALSE; deferred := FALSE; Windows.dir.Close(w)
END
ELSE cancelled := FALSE; deferred := FALSE; Windows.dir.Close(w)
END
END;
Kernel.Cleanup
END
END GuardedClose;
PROCEDURE CloseThis* (w: Windows.Window);
VAR cancelled_, deferred_: BOOLEAN;
BEGIN GuardedClose(w, cancelled_, deferred_)
END CloseThis;
PROCEDURE CloseTopDialog*; (** close topmost window *)
VAR w: Windows.Window; cancelled_, deferred_: BOOLEAN;
BEGIN
w := Windows.dir.First();
IF w # NIL THEN GuardedClose(w, cancelled_, deferred_) END
END CloseTopDialog;
PROCEDURE Exit*;
VAR prev, w: Windows.Window; deferred, cancelled: BOOLEAN;
BEGIN
cancelled := FALSE; deferred := FALSE; prev := NIL;
REPEAT
IF prev = NIL THEN w := Windows.dir.First()
ELSE w := Windows.dir.Next(prev)
END;
IF w # NIL THEN
GuardedClose(w, cancelled, deferred);
IF w.frame # NIL (* not closed *) THEN prev := w ELSE prev := NIL END
END
UNTIL (w = NIL) OR cancelled OR deferred;
IF (Windows.dir.First() = NIL) & ~cancelled & ~deferred & (exitHook # NIL) THEN
exitHook
END
END Exit;
PROCEDURE Open*;
VAR i: INTEGER; v: Views.View;
BEGIN
i := Views.Available();
IF i > 0 THEN Views.Fetch(v); Views.OpenView(v)
ELSE Dialog.ShowMsg("#System:DepositExpected")
END
END Open;
PROCEDURE PasteView*;
VAR i: INTEGER; v: Views.View;
BEGIN
i := Views.Available();
IF i > 0 THEN
Views.Fetch(v);
Controllers.PasteView(v, Views.undefined, Views.undefined, FALSE)
ELSE Dialog.ShowMsg("#System:DepositExpected")
END
END PasteView;
(* file menu commands *)
PROCEDURE New*;
VAR res: INTEGER;
BEGIN
Dialog.Call(allocator, " ", res)
END New;
(* edit menu commands *)
PROCEDURE Undo*;
VAR w: Windows.Window;
BEGIN
w := Windows.dir.Focus(Controllers.frontPath);
IF w # NIL THEN
w.seq.Undo;
IF ~param.clearSeqOnSave THEN w.seq.SetDirty(TRUE) END
END
END Undo;
PROCEDURE Redo*;
VAR w: Windows.Window;
BEGIN
w := Windows.dir.Focus(Controllers.frontPath);
IF w # NIL THEN
w.seq.Redo;
IF ~param.clearSeqOnSave THEN w.seq.SetDirty(TRUE) END
END
END Redo;
PROCEDURE CopyProp*;
BEGIN
Properties.CollectProp(prop)
END CopyProp;
PROCEDURE PasteProp*;
BEGIN
Properties.EmitProp(NIL, prop)
END PasteProp;
PROCEDURE Clear*;
(** remove the selection of the current focus **)
VAR msg: Controllers.EditMsg;
BEGIN
msg.op := Controllers.cut; msg.view := NIL;
msg.clipboard := FALSE;
Controllers.Forward(msg)
END Clear;
PROCEDURE SelectAll*;
(** select whole content of current focus **)
VAR msg: Controllers.SelectMsg;
BEGIN
msg.set := TRUE; Controllers.Forward(msg)
END SelectAll;
PROCEDURE DeselectAll*;
(** select whole content of current focus **)
VAR msg: Controllers.SelectMsg;
BEGIN
msg.set := FALSE; Controllers.Forward(msg)
END DeselectAll;
PROCEDURE SelectDocument*;
(** select whole document **)
VAR w: Windows.Window; c: Containers.Controller;
BEGIN
w := Windows.dir.Focus(Controllers.path);
IF w # NIL THEN
c := w.doc.ThisController();
IF (c # NIL) & ~(Containers.noSelection IN c.opts) & (c.Singleton() = NIL) THEN
c.SetSingleton(w.doc.ThisView())
END
END
END SelectDocument;
PROCEDURE SelectNextView*;
VAR c: Containers.Controller; v: Views.View;
BEGIN
c := Containers.Focus();
IF (c # NIL) & ~(Containers.noSelection IN c.opts) THEN
IF c.HasSelection() THEN v := c.Singleton() ELSE v := NIL END;
IF v = NIL THEN
c.GetFirstView(Containers.any, v)
ELSE
c.GetNextView(Containers.any, v);
IF v = NIL THEN c.GetFirstView(Containers.any, v) END
END;
c.SelectAll(FALSE);
IF v # NIL THEN c.SetSingleton(v) END
ELSE Dialog.ShowMsg("#Dev:NoTargetFocusFound")
END
END SelectNextView;
(** font menu commands **)
PROCEDURE Font* (typeface: Fonts.Typeface);
(** set the selection to the given font family **)
VAR p: Properties.StdProp;
BEGIN
NEW(p); p.valid := {Properties.typeface}; p.typeface := typeface;
Properties.EmitProp(NIL, p)
END Font;
PROCEDURE DefaultFont*;
(** set the selection to the default font family **)
VAR p: Properties.StdProp;
BEGIN
NEW(p); p.valid := {Properties.typeface}; p.typeface := Fonts.default;
Properties.EmitProp(NIL, p)
END DefaultFont;
(** attributes menu commands **)
PROCEDURE Plain*;
(** reset the font attribute "weight" and all font style attributes of the selection **)
VAR p: Properties.StdProp;
BEGIN
NEW(p); p.valid := {Properties.style, Properties.weight};
p.style.val := {}; p.style.mask := {Fonts.italic, Fonts.underline, Fonts.strikeout};
p.weight := Fonts.normal;
Properties.EmitProp(NIL, p)
END Plain;
PROCEDURE Bold*;
(** change the font attribute "weight" in the selection;
if the selection has a homogeneously bold weight: toggle to normal, else force to bold **)
VAR p, p0: Properties.StdProp;
BEGIN
Properties.CollectStdProp(p0);
NEW(p); p.valid := {Properties.weight};
IF (Properties.weight IN p0.valid) & (p0.weight # Fonts.normal) THEN
p.weight := Fonts.normal
ELSE p.weight := Fonts.bold
END;
Properties.EmitProp(NIL, p)
END Bold;
PROCEDURE Italic*;
(** change the font style attribute "italic" in the selection;
if the selection is homogeneous wrt this attribute: toggle, else force to italic **)
VAR p, p0: Properties.StdProp;
BEGIN
Properties.CollectStdProp(p0);
NEW(p); p.valid := {Properties.style}; p.style.mask := {Fonts.italic};
IF (Properties.style IN p0.valid) & (Fonts.italic IN p0.style.val) THEN
p.style.val := {}
ELSE p.style.val := {Fonts.italic}
END;
Properties.EmitProp(NIL, p)
END Italic;
PROCEDURE Underline*;
(** change the font style attribute "underline" in the selection;
if the selection is homogeneous wrt this attribute: toggle, else force to underline **)
VAR p, p0: Properties.StdProp;
BEGIN
Properties.CollectStdProp(p0);
NEW(p); p.valid := {Properties.style}; p.style.mask := {Fonts.underline};
IF (Properties.style IN p0.valid) & (Fonts.underline IN p0.style.val) THEN
p.style.val := {}
ELSE p.style.val := {Fonts.underline}
END;
Properties.EmitProp(NIL, p)
END Underline;
PROCEDURE Strikeout*;
(** change the font style attribute "strikeout" in the selection,
without changing other attributes;
if the selection is homogeneous wrt this attribute: toggle,
else force to strikeout **)
VAR p, p0: Properties.StdProp;
BEGIN
Properties.CollectStdProp(p0);
NEW(p); p.valid := {Properties.style}; p.style.mask := {Fonts.strikeout};
IF (Properties.style IN p0.valid) & (Fonts.strikeout IN p0.style.val) THEN
p.style.val := {}
ELSE p.style.val := {Fonts.strikeout}
END;
Properties.EmitProp(NIL, p)
END Strikeout;
PROCEDURE Size* (size: INTEGER);
(** set the selection to the given font size **)
VAR p: Properties.StdProp;
BEGIN
NEW(p); p.valid := {Properties.size};
p.size := size * Ports.point;
Properties.EmitProp(NIL, p)
END Size;
PROCEDURE SetSize*;
VAR p: Properties.StdProp;
BEGIN
IF (0 <= size.size) & (size.size < 32768) THEN
NEW(p); p.valid := {Properties.size};
p.size := size.size * Fonts.point;
Properties.EmitProp(NIL, p)
ELSE
Dialog.ShowMsg(illegalSizeKey)
END
END SetSize;
PROCEDURE InitSizeDialog*;
VAR p: Properties.StdProp;
BEGIN
Properties.CollectStdProp(p);
IF Properties.size IN p.valid THEN size.size := p.size DIV Fonts.point END
END InitSizeDialog;
PROCEDURE Color* (color: Ports.Color);
(** set the color attributes of the selection **)
VAR p: Properties.StdProp;
BEGIN
NEW(p); p.valid := {Properties.color};
p.color.val := color;
Properties.EmitProp(NIL, p)
END Color;
PROCEDURE UpdateAll*; (* for HostCmds.Toggle *)
VAR w: Windows.Window; pw, ph: INTEGER; dirty: BOOLEAN; msg: Models.UpdateMsg;
BEGIN
w := Windows.dir.First();
WHILE w # NIL DO
IF ~w.sub THEN
dirty := w.seq.Dirty();
Models.Domaincast(w.doc.Domain(), msg);
IF ~dirty THEN w.seq.SetDirty(FALSE) END (* not perfect: "undoable dirt" ... *)
END;
HostWindows.Update(w(HostWindows.Window), Views.keepFrames);w.port.GetSize(pw, ph); (* no HostWindows *)
w.Restore(0, 0, pw, ph);
w := Windows.dir.Next(w)
END
END UpdateAll;
PROCEDURE RestoreAll*;
VAR w: Windows.Window; pw, ph: INTEGER;
BEGIN
w := Windows.dir.First();
WHILE w # NIL DO
w.port.GetSize(pw, ph);
w.Restore(0, 0, pw, ph);
w := Windows.dir.Next(w)
END
END RestoreAll;
(** document layout dialog **)
PROCEDURE SetLayout*;
VAR opts: SET; l, t, r, b, r0, b0: INTEGER; c: Containers.Controller; script: Stores.Operation;
BEGIN
c := layout.doc.ThisController();
opts := c.opts - {Documents.pageWidth..Documents.winHeight};
IF layout.wType = page THEN INCL(opts, Documents.pageWidth)
ELSIF layout.wType = window THEN INCL(opts, Documents.winWidth)
END;
IF layout.hType = page THEN INCL(opts, Documents.pageHeight)
ELSIF layout.hType = window THEN INCL(opts, Documents.winHeight)
END;
layout.doc.PollRect(l, t, r, b); r0 := r; b0 := b;
IF layout.wType = fix THEN r := l + SHORT(ENTIER(layout.width * layout.u)) END;
IF layout.hType = fix THEN b := t + SHORT(ENTIER(layout.height * layout.u)) END;
IF (opts # c.opts) OR (r # r0) OR (b # b0) THEN
Views.BeginScript(layout.doc, "#System:ChangeLayout", script);
c.SetOpts(opts);
layout.doc.SetRect(l, t, r, b);
Views.EndScript(layout.doc, script)
END
END SetLayout;
PROCEDURE InitLayoutDialog*;
(* guard: WindowGuard *)
VAR w: Windows.Window; c: Containers.Controller; l, t, r, b: INTEGER;
BEGIN
w := Windows.dir.First();
IF w # NIL THEN
layout.doc := w.doc;
c := w.doc.ThisController();
IF Documents.pageWidth IN c.opts THEN layout.wType := page
ELSIF Documents.winWidth IN c.opts THEN layout.wType := window
ELSE layout.wType := fix
END;
IF Documents.pageHeight IN c.opts THEN layout.hType := page
ELSIF Documents.winHeight IN c.opts THEN layout.hType := window
ELSE layout.hType := fix
END;
IF Dialog.metricSystem THEN layout.u := Ports.mm * 10 ELSE layout.u := Ports.inch END;
w.doc.PollRect(l, t, r, b);
layout.width := (r - l) DIV (layout.u DIV 100) / 100;
layout.height := (b - t) DIV (layout.u DIV 100) / 100
END
END InitLayoutDialog;
PROCEDURE WidthGuard* (VAR par: Dialog.Par);
BEGIN
IF layout.wType # fix THEN par.readOnly := TRUE END
END WidthGuard;
PROCEDURE HeightGuard* (VAR par: Dialog.Par);
BEGIN
IF layout.hType # fix THEN par.readOnly := TRUE END
END HeightGuard;
PROCEDURE TypeNotifier* (op_, from_, to_: INTEGER);
VAR w, h, l, t, r, b: INTEGER; d: BOOLEAN;
BEGIN
layout.doc.PollRect(l, t, r, b);
IF layout.wType = page THEN
layout.doc.PollPage(w, h, l, t, r, b, d)
ELSIF layout.wType = window THEN
layout.doc.context.GetSize(w, h); r := w - l
END;
layout.width := (r - l) DIV (layout.u DIV 100) / 100;
layout.doc.PollRect(l, t, r, b);
IF layout.hType = page THEN
layout.doc.PollPage(w, h, l, t, r, b, d)
ELSIF layout.hType = window THEN
layout.doc.context.GetSize(w, h); b := h - t
END;
layout.height := (b - t) DIV (layout.u DIV 100) / 100;
Dialog.Update(layout)
END TypeNotifier;
(** window menu command **)
PROCEDURE NewWindow*;
(** guard ModelViewGuard **)
VAR win: Windows.Window; doc: Documents.Document; v: Views.View; title: Views.Title;
seq: ANYPTR; clean: BOOLEAN;
BEGIN
win := Windows.dir.Focus(Controllers.frontPath);
IF win # NIL THEN
v := win.doc.ThisView();
IF v.Domain() # NIL THEN seq := v.Domain().GetSequencer() ELSE seq := NIL END;
clean := (seq # NIL) & ~seq(Sequencers.Sequencer).Dirty();
doc := win.doc.DocCopyOf(v);
(* Stores.InitDomain(doc, v.Domain()); *)
ASSERT(doc.Domain() = v.Domain(), 100);
win.GetTitle(title);
Windows.dir.OpenSubWindow(Windows.dir.New(), doc, win.flags, title);
IF clean THEN seq(Sequencers.Sequencer).SetDirty(FALSE) END
END
END NewWindow;
(* properties *)
PROCEDURE GetCmd (name: ARRAY OF CHAR; OUT cmd: ARRAY OF CHAR);
VAR i, j: INTEGER; ch, lch: CHAR; key: ARRAY 256 OF CHAR;
BEGIN
i := 0; ch := name[0]; key[0] := "#"; j := 1;
REPEAT
key[j] := ch; INC(j); lch := ch; INC(i); ch := name[i]
UNTIL (ch = 0X) OR (ch = ".") OR Strings.IsUpper(ch) & ~Strings.IsUpper(lch);
IF ch = "." THEN
key := "#System:" + name
ELSE
key[j] := ":"; INC(j); key[j] := 0X; j := 0;
WHILE ch # 0X DO name[j] := ch; INC(i); INC(j); ch := name[i] END;
name[j] := 0X; key := key + name
END;
Dialog.MapString(key, cmd);
IF cmd = name THEN cmd := "" END
END GetCmd;
PROCEDURE SearchCmd (call: BOOLEAN; OUT found: BOOLEAN);
VAR p: Properties.Property; std: BOOLEAN; v: Views.View;
cmd: ARRAY 256 OF CHAR; pos, res: INTEGER;
BEGIN
Controllers.SetCurrentPath(Controllers.targetPath);
v := Containers.FocusSingleton(); found := FALSE;
IF v # NIL THEN
Services.GetTypeName(v, cmd);
GetCmd(cmd, cmd);
IF cmd # "" THEN found := TRUE;
IF call THEN Dialog.Call(cmd, "", res) END
END
END;
std := FALSE;
Properties.CollectProp(p);
WHILE p # NIL DO
IF p IS Properties.StdProp THEN std := TRUE
ELSE
Services.GetTypeName(p, cmd);
GetCmd(cmd, cmd);
IF cmd # "" THEN found := TRUE;
IF call THEN Dialog.Call(cmd, "", res) END
ELSE
Services.GetTypeName(p, cmd);
Strings.Find(cmd, "Desc", LEN(cmd$)-4, pos);
IF LEN(cmd$)-4 = pos THEN
cmd[pos] := 0X; GetCmd(cmd, cmd);
IF cmd # "" THEN found := TRUE;
IF call THEN Dialog.Call(cmd, "", res) END
END
END
END
END;
p := p.next
END;
IF std & ~found THEN
Dialog.MapString("#Std:Properties.StdProp", cmd);
IF cmd # "Properties.StdProp" THEN found := TRUE;
IF call THEN Dialog.Call(cmd, "", res) END
END
END;
IF ~found THEN
Dialog.MapString("#System:ShowProp", cmd);
IF cmd # "ShowProp" THEN found := TRUE;
IF call THEN Dialog.Call(cmd, "", res) END
END
END;
Controllers.ResetCurrentPath
END SearchCmd;
PROCEDURE ShowProp*;
VAR found: BOOLEAN;
BEGIN
SearchCmd(TRUE, found)
END ShowProp;
PROCEDURE ShowPropGuard* (VAR par: Dialog.Par);
VAR found: BOOLEAN;
BEGIN
SearchCmd(FALSE, found);
IF ~found THEN par.disabled := TRUE END
END ShowPropGuard;
(* container commands *)
PROCEDURE ActFocus (): Containers.Controller;
VAR c: Containers.Controller; v: Views.View;
BEGIN
c := Containers.Focus();
IF c # NIL THEN
v := c.ThisView();
IF v IS Documents.Document THEN
v := v(Documents.Document).ThisView();
IF v IS Containers.View THEN
c := v(Containers.View).ThisController()
ELSE c := NIL
END
END
END;
RETURN c
END ActFocus;
PROCEDURE ToggleNoFocus*;
VAR c: Containers.Controller; v: Views.View;
BEGIN
c := ActFocus();
IF c # NIL THEN
v := c.ThisView();
IF ~((v IS Documents.Document) OR (Containers.noSelection IN c.opts)) THEN
IF Containers.noFocus IN c.opts THEN
c.SetOpts(c.opts - {Containers.noFocus})
ELSE
c.SetOpts(c.opts + {Containers.noFocus})
END
END
END
END ToggleNoFocus;
PROCEDURE OpenAsAuxDialog*;
(** create a new sub-window onto the focus view shown in the top window, mask mode **)
VAR win: Windows.Window; doc: Documents.Document; v, u: Views.View; title: Views.Title;
c: Containers.Controller;
BEGIN
v := Controllers.FocusView();
IF (v # NIL) & (v IS Containers.View) & ~(v IS Documents.Document) THEN
win := Windows.dir.Focus(Controllers.frontPath); ASSERT(win # NIL, 100);
doc := win.doc.DocCopyOf(v);
u := doc.ThisView();
c := u(Containers.View).ThisController();
c.SetOpts(c.opts - {Containers.noFocus} + {Containers.noCaret, Containers.noSelection});
IF v # win.doc.ThisView() THEN
c := doc.ThisController();
c.SetOpts(c.opts - {Documents.pageWidth, Documents.pageHeight}
+ {Documents.winWidth, Documents.winHeight})
END;
(* Stores.InitDomain(doc, v.Domain()); already done in DocCopyOf *)
win.GetTitle(title);
Windows.dir.OpenSubWindow(Windows.dir.New(), doc, {Windows.isAux, Windows.neverDirty, Windows.noResize, Windows.noHScroll, Windows.noVScroll}, title)
ELSE Dialog.Beep
END
END OpenAsAuxDialog;
PROCEDURE OpenAsToolDialog*;
(** create a new sub-window onto the focus view shown in the top window, mask mode **)
VAR win: Windows.Window; doc: Documents.Document; v, u: Views.View; title: Views.Title;
c: Containers.Controller;
BEGIN
v := Controllers.FocusView();
IF (v # NIL) & (v IS Containers.View) & ~(v IS Documents.Document) THEN
win := Windows.dir.Focus(Controllers.frontPath); ASSERT(win # NIL, 100);
doc := win.doc.DocCopyOf(v);
u := doc.ThisView();
c := u(Containers.View).ThisController();
c.SetOpts(c.opts - {Containers.noFocus} + {Containers.noCaret, Containers.noSelection});
IF v # win.doc.ThisView() THEN
c := doc.ThisController();
c.SetOpts(c.opts - {Documents.pageWidth, Documents.pageHeight}
+ {Documents.winWidth, Documents.winHeight})
END;
(* Stores.InitDomain(doc, v.Domain()); already done in DocCopyOf *)
win.GetTitle(title);
Windows.dir.OpenSubWindow(Windows.dir.New(), doc, {Windows.isTool, Windows.neverDirty, Windows.noResize, Windows.noHScroll, Windows.noVScroll}, title)
ELSE Dialog.Beep
END
END OpenAsToolDialog;
PROCEDURE RecalcFocusSize*;
VAR c: Containers.Controller; v: Views.View; bounds: Properties.BoundsPref;
BEGIN
c := Containers.Focus();
IF c # NIL THEN
v := c.ThisView();
bounds.w := Views.undefined; bounds.h := Views.undefined;
Views.HandlePropMsg(v, bounds);
v.context.SetSize(bounds.w, bounds.h)
END
END RecalcFocusSize;
PROCEDURE RecalcAllSizes*;
VAR w: Windows.Window;
BEGIN
w := Windows.dir.First();
WHILE w # NIL DO
StdDialog.RecalcView(w.doc.ThisView());
w := Windows.dir.Next(w)
END
END RecalcAllSizes;
PROCEDURE SetMode(opts: SET);
VAR
c: Containers.Controller; v: Views.View;
gm: Containers.GetOpts; sm: Containers.SetOpts;
w: Windows.Window;
BEGIN
c := Containers.Focus();
gm.valid := {};
IF (c # NIL) & (c.Singleton() # NIL) THEN
v := c.Singleton();
Views.HandlePropMsg(v, gm);
END;
IF gm.valid = {} THEN
w := Windows.dir.Focus(Controllers.path);
IF (w # NIL) & (w.doc.ThisView() IS Containers.View) THEN v := w.doc.ThisView() ELSE v := NIL END
END;
IF v # NIL THEN
sm.valid := {Containers.noSelection, Containers.noFocus, Containers.noCaret};
sm.opts := opts;
Views.HandlePropMsg(v, sm);
END;
END SetMode;
PROCEDURE GetMode(OUT found: BOOLEAN; OUT opts: SET);
VAR c: Containers.Controller; gm: Containers.GetOpts; w: Windows.Window;
BEGIN
c := Containers.Focus();
gm.valid := {};
IF (c # NIL) & (c.Singleton() # NIL) THEN
Views.HandlePropMsg(c.Singleton(), gm);
END;
IF gm.valid = {} THEN
w := Windows.dir.Focus(Controllers.path);
IF (w # NIL) & (w.doc.ThisView() IS Containers.View) THEN
Views.HandlePropMsg(w.doc.ThisView(), gm);
END
END;
found := gm.valid # {};
opts := gm.opts
END GetMode;
PROCEDURE SetMaskMode*;
(* Guard: SetMaskGuard *)
BEGIN
SetMode({Containers.noSelection, Containers.noCaret})
END SetMaskMode;
PROCEDURE SetEditMode*;
(* Guard: SetEditGuard *)
BEGIN
SetMode({})
END SetEditMode;
PROCEDURE SetLayoutMode*;
(* Guard: SetLayoutGuard *)
BEGIN
SetMode({Containers.noFocus})
END SetLayoutMode;
PROCEDURE SetBrowserMode*;
(* Guard: SetBrowserGuard *)
BEGIN
SetMode({Containers.noCaret})
END SetBrowserMode;
PROCEDURE PasteObject*;
BEGIN
Dialog.ShowMsg("PasteObject not implemented yet");
END PasteObject;
PROCEDURE PasteToWindow*;
BEGIN
Dialog.ShowMsg("PasteToWindow not implemented yet");
END PasteToWindow;
(* standard guards *)
PROCEDURE ToggleNoFocusGuard* (VAR par: Dialog.Par);
VAR c: Containers.Controller; v: Views.View;
BEGIN
c := ActFocus();
IF c # NIL THEN
v := c.ThisView();
IF ~((v IS Documents.Document) OR (Containers.noSelection IN c.opts)) THEN
IF Containers.noFocus IN c.opts THEN par.label := "#System:AllowFocus"
ELSE par.label := "#System:PreventFocus"
END
ELSE par.disabled := TRUE
END
ELSE par.disabled := TRUE
END
END ToggleNoFocusGuard;
PROCEDURE ReadOnlyGuard* (VAR par: Dialog.Par);
BEGIN
par.readOnly := TRUE
END ReadOnlyGuard;
PROCEDURE WindowGuard* (VAR par: Dialog.Par);
VAR w: Windows.Window;
BEGIN
w := Windows.dir.First();
IF w = NIL THEN par.disabled := TRUE END
END WindowGuard;
PROCEDURE ModelViewGuard* (VAR par: Dialog.Par);
VAR w: Windows.Window;
BEGIN
w := Windows.dir.Focus(Controllers.frontPath);
par.disabled := (w = NIL) OR (w.doc.ThisView().ThisModel() = NIL)
END ModelViewGuard;
PROCEDURE SetMaskModeGuard* (VAR par: Dialog.Par);
CONST mode = {Containers.noSelection, Containers.noFocus, Containers.noCaret};
VAR opts: SET; found: BOOLEAN;
BEGIN
GetMode(found, opts);
IF found THEN
par.checked := opts * mode = {Containers.noSelection, Containers.noCaret}
ELSE
par.disabled := TRUE
END
END SetMaskModeGuard;
PROCEDURE SetEditModeGuard* (VAR par: Dialog.Par);
CONST mode = {Containers.noSelection, Containers.noFocus, Containers.noCaret};
VAR opts: SET; found: BOOLEAN;
BEGIN
GetMode(found, opts);
IF found THEN
par.checked := opts * mode = {}
ELSE
par.disabled := TRUE
END
END SetEditModeGuard;
PROCEDURE SetLayoutModeGuard* (VAR par: Dialog.Par);
CONST mode = {Containers.noSelection, Containers.noFocus, Containers.noCaret};
VAR opts: SET; found: BOOLEAN;
BEGIN
GetMode(found, opts);
IF found THEN
par.checked := opts * mode = {Containers.noFocus}
ELSE
par.disabled := TRUE
END
END SetLayoutModeGuard;
PROCEDURE SetBrowserModeGuard* (VAR par: Dialog.Par);
CONST mode = {Containers.noSelection, Containers.noFocus, Containers.noCaret};
VAR opts: SET; found: BOOLEAN;
BEGIN
GetMode(found, opts);
IF found THEN
par.checked := opts * mode = {Containers.noCaret}
ELSE
par.disabled := TRUE
END
END SetBrowserModeGuard;
PROCEDURE SelectionGuard* (VAR par: Dialog.Par);
VAR ops: Controllers.PollOpsMsg;
BEGIN
Controllers.PollOps(ops);
IF ops.valid * {Controllers.cut, Controllers.copy} = {} THEN par.disabled := TRUE END
END SelectionGuard;
PROCEDURE SingletonGuard* (VAR par: Dialog.Par);
VAR ops: Controllers.PollOpsMsg;
BEGIN
Controllers.PollOps(ops);
IF ops.singleton = NIL THEN par.disabled := TRUE END
END SingletonGuard;
PROCEDURE SelectAllGuard* (VAR par: Dialog.Par);
VAR ops: Controllers.PollOpsMsg;
BEGIN
Controllers.PollOps(ops);
IF ~ops.selectable THEN par.disabled := TRUE END
END SelectAllGuard;
PROCEDURE CaretGuard* (VAR par: Dialog.Par);
VAR ops: Controllers.PollOpsMsg;
BEGIN
Controllers.PollOps(ops);
IF ops.valid * {Controllers.pasteChar .. Controllers.paste} = {} THEN par.disabled := TRUE END
END CaretGuard;
PROCEDURE PasteCharGuard* (VAR par: Dialog.Par);
VAR ops: Controllers.PollOpsMsg;
BEGIN
Controllers.PollOps(ops);
IF ~(Controllers.pasteChar IN ops.valid) THEN par.disabled := TRUE END
END PasteCharGuard;
PROCEDURE PasteLCharGuard* (VAR par: Dialog.Par);
VAR ops: Controllers.PollOpsMsg;
BEGIN
Controllers.PollOps(ops);
IF ~(Controllers.pasteChar IN ops.valid) THEN par.disabled := TRUE END
END PasteLCharGuard;
PROCEDURE PasteViewGuard* (VAR par: Dialog.Par);
VAR ops: Controllers.PollOpsMsg;
BEGIN
Controllers.PollOps(ops);
IF ~(Controllers.paste IN ops.valid) THEN par.disabled := TRUE END
END PasteViewGuard;
PROCEDURE ContainerGuard* (VAR par: Dialog.Par);
BEGIN
IF Containers.Focus() = NIL THEN par.disabled := TRUE END
END ContainerGuard;
PROCEDURE UndoGuard* (VAR par: Dialog.Par);
VAR f: Windows.Window; opName: Stores.OpName;
BEGIN
Dialog.MapString("#System:Undo", par.label);
f := Windows.dir.Focus(Controllers.frontPath);
IF (f # NIL) & f.seq.CanUndo() THEN
f.seq.GetUndoName(opName);
Dialog.MapString(opName, opName);
Append(par.label, " ");
Append(par.label, opName)
ELSE
par.disabled := TRUE
END
END UndoGuard;
PROCEDURE RedoGuard* (VAR par: Dialog.Par);
VAR f: Windows.Window; opName: Stores.OpName;
BEGIN
Dialog.MapString("#System:Redo", par.label);
f := Windows.dir.Focus(Controllers.frontPath);
IF (f # NIL) & f.seq.CanRedo() THEN
f.seq.GetRedoName(opName);
Dialog.MapString(opName, opName);
Append(par.label, " ");
Append(par.label, opName)
ELSE
par.disabled := TRUE
END
END RedoGuard;
PROCEDURE PlainGuard* (VAR par: Dialog.Par);
VAR props: Properties.StdProp;
BEGIN
props := StdProp();
IF props.known * {Properties.style, Properties.weight} # {} THEN
par.checked := (Properties.style IN props.valid)
& (props.style.val = {}) & ({Fonts.italic, Fonts.underline, Fonts.strikeout} - props.style.mask = {})
& (Properties.weight IN props.valid) & (props.weight = Fonts.normal)
ELSE
par.disabled := TRUE
END
END PlainGuard;
PROCEDURE BoldGuard* (VAR par: Dialog.Par);
VAR props: Properties.StdProp;
BEGIN
props := StdProp();
IF Properties.weight IN props.known THEN
par.checked := (Properties.weight IN props.valid) & (props.weight = Fonts.bold)
ELSE
par.disabled := TRUE
END
END BoldGuard;
PROCEDURE ItalicGuard* (VAR par: Dialog.Par);
VAR props: Properties.StdProp;
BEGIN
props := StdProp();
IF Properties.style IN props.known THEN
par.checked := (Properties.style IN props.valid) & (Fonts.italic IN props.style.val)
ELSE
par.disabled := TRUE
END
END ItalicGuard;
PROCEDURE UnderlineGuard* (VAR par: Dialog.Par);
VAR props: Properties.StdProp;
BEGIN
props := StdProp();
IF Properties.style IN props.known THEN
par.checked := (Properties.style IN props.valid) & (Fonts.underline IN props.style.val)
ELSE
par.disabled := TRUE
END
END UnderlineGuard;
PROCEDURE StrikeoutGuard* (VAR par: Dialog.Par);
VAR props: Properties.StdProp;
BEGIN
props := StdProp();
IF Properties.style IN props.known THEN
par.checked := (Properties.style IN props.valid) & (Fonts.strikeout IN props.style.val)
ELSE
par.disabled := TRUE
END
END StrikeoutGuard;
PROCEDURE SizeGuard* (size: INTEGER; VAR par: Dialog.Par);
VAR props: Properties.StdProp;
BEGIN
props := StdProp();
IF Properties.size IN props.known THEN
par.checked := (Properties.size IN props.valid) & (size = props.size DIV Ports.point)
ELSE
par.disabled := TRUE
END
END SizeGuard;
PROCEDURE ColorGuard* (color: INTEGER; VAR par: Dialog.Par);
VAR props: Properties.StdProp;
BEGIN
props := StdProp();
IF Properties.color IN props.known THEN
par.checked := (Properties.color IN props.valid) & (color = props.color.val)
ELSE
par.disabled := TRUE
END
END ColorGuard;
PROCEDURE DefaultFontGuard* (VAR par: Dialog.Par);
VAR props: Properties.StdProp;
BEGIN
props := StdProp();
IF Properties.typeface IN props.known THEN
par.checked := (Properties.typeface IN props.valid) & (props.typeface = Fonts.default)
ELSE
par.disabled := TRUE
END
END DefaultFontGuard;
PROCEDURE TypefaceGuard* (VAR par: Dialog.Par);
VAR props: Properties.StdProp;
BEGIN
props := StdProp();
IF ~(Properties.typeface IN props.known) THEN par.disabled := TRUE END
END TypefaceGuard;
PROCEDURE SaveGuard* (VAR par: Dialog.Par);
VAR w: Windows.Window;
BEGIN
w := Windows.dir.Focus(Controllers.targetPath);
IF (w = NIL) OR (Windows.neverDirty IN w.flags) OR ~w.seq.Dirty() THEN
par.disabled := TRUE
END
END SaveGuard;
(* printing *)
PROCEDURE PrintGuard* (VAR par: Dialog.Par);
VAR w: Windows.Window;
BEGIN
w := Windows.dir.Focus(Controllers.targetPath);
IF (w = NIL) OR (Printers.dir = NIL) OR ~Printers.dir.Available() THEN
par.disabled := TRUE
END
END PrintGuard;
PROCEDURE PrinterGuard* (VAR par: Dialog.Par);
BEGIN
IF ~Printers.dir.Available() THEN par.disabled := TRUE END
END PrinterGuard;
PROCEDURE HasSel (w: Windows.Window): BOOLEAN;
VAR ops: Controllers.PollOpsMsg;
BEGIN
ops.type := ""; ops.singleton := NIL; ops.selectable := FALSE; ops.valid := {};
w.ForwardCtrlMsg(ops);
RETURN ops.singleton # NIL
END HasSel;
PROCEDURE PrintSel (w: Windows.Window; from_, to_, copies_: INTEGER);
VAR wt, title: Views.Title; i: INTEGER; edit: Controllers.EditMsg;
BEGIN
edit.op := Controllers.copy; edit.view := NIL;
edit.clipboard := FALSE; w.ForwardCtrlMsg(edit);
ASSERT(edit.view # NIL, 100);
w.GetTitle(wt); title := "[";
i := 1; WHILE (wt[i - 1] # 0X) & (i < LEN(title)) DO title[i] := wt[i - 1]; INC(i) END;
IF i >= LEN(title) - 1 THEN i := LEN(title) - 2 END;
title[i] := "]"; title[i + 1] := 0X;
Printing.PrintView(edit.view, (*edit.w, edit.h,*) Printing.NewDefaultPar(title))
END PrintSel;
PROCEDURE PrintDoc (w: Windows.Window; from, to, copies: INTEGER);
VAR pw, ph, l, t, r, b: INTEGER; decorate: BOOLEAN;
page: Printing.PageInfo; header, footer: Printing.Banner;
BEGIN
w.doc.PollPage(pw, ph, l, t, r, b, decorate);
page.first := 1; page.from := from; page.to := to; page.alternate := FALSE;
w.GetTitle(page.title);
IF decorate THEN
header.gap := 5 * Ports.mm; header.right := "&d&;&p";
ELSE
header.gap := 0; header.right := "";
END;
footer.gap := 0; footer.right := "";
Printing.PrintView(w.doc, Printing.NewPar(page, header, footer, copies));
END PrintDoc;
PROCEDURE PrintThis (w: Windows.Window; from, to, copies: INTEGER; sel: BOOLEAN);
BEGIN
IF copies > 0 THEN
IF sel THEN
PrintSel(w, from, to, copies)
ELSE
PrintDoc(w, from, to, copies)
END
END
END PrintThis;
PROCEDURE Print*;
(** print the front window's document **)
VAR win: Windows.Window;
from, to, copies: INTEGER; selection: BOOLEAN;
BEGIN
IF Printers.dir.Available() THEN
win := Windows.dir.Focus(Controllers.targetPath);
IF win # NIL THEN
WHILE win.sub DO win := win.link END;
selection := FALSE;
StdDialog.PrintDialog(HasSel(win), from, to, copies, selection);
PrintThis(win, from, to, copies, selection)
END;
Kernel.Cleanup
END
END Print;
(* clipboard *)
PROCEDURE Cut*;
(** move the focus document's selection into the clipboard **)
VAR msg: Controllers.EditMsg;
BEGIN
msg.op := Controllers.cut;
msg.clipboard := TRUE;
msg.view := NIL; msg.w := Views.undefined; msg.h := Views.undefined;
Controllers.Forward(msg);
IF msg.view # NIL THEN
clipboardHook.Register(msg.view, msg.w, msg.h, msg.isSingle)
END
END Cut;
PROCEDURE Copy*;
(** move a copy of the focus document's selection into the clipboard **)
VAR msg: Controllers.EditMsg;
BEGIN
msg.op := Controllers.copy;
msg.clipboard := TRUE;
msg.view := NIL; msg.w := Views.undefined; msg.h := Views.undefined;
Controllers.Forward(msg);
IF msg.view # NIL THEN
clipboardHook.Register(msg.view, msg.w, msg.h, msg.isSingle)
END
END Copy;
PROCEDURE Paste*;
BEGIN
IF clipboardHook # NIL THEN clipboardHook.Paste END;
END Paste;
PROCEDURE ObjectMenu*;
(* this procedure should no be ever called, see MdiMenus *)
BEGIN
HALT(127)
END ObjectMenu;
PROCEDURE ObjectMenuGuard* (VAR par: Dialog.Par);
BEGIN
IF objectMenuGuard # NIL THEN
objectMenuGuard(par)
ELSE
par.disabled := TRUE
END
END ObjectMenuGuard;
PROCEDURE CutGuard* (VAR par: Dialog.Par);
VAR ops: Controllers.PollOpsMsg;
BEGIN
Controllers.PollOps(ops);
IF ~(Controllers.cut IN ops.valid) THEN par.disabled := TRUE END
END CutGuard;
PROCEDURE CopyGuard* (VAR par: Dialog.Par);
VAR ops: Controllers.PollOpsMsg;
BEGIN
Controllers.PollOps(ops);
IF ~(Controllers.copy IN ops.valid) THEN par.disabled := TRUE END
END CopyGuard;
PROCEDURE PasteGuard* (VAR par: Dialog.Par);
VAR ops: Controllers.PollOpsMsg;
BEGIN
Controllers.PollOps(ops);
IF ~(Controllers.paste IN ops.valid)
(* OR ~HostClipboard.ConvertibleTo(ops.pasteType) TODO *)
THEN par.disabled := TRUE END
END PasteGuard;
PROCEDURE CutGuardHidden* (VAR par: Dialog.Par);
VAR ops: Controllers.PollOpsMsg;
BEGIN
par.label := '-' (* StdMenus.hidden*);
Controllers.PollOps(ops);
IF ~(Controllers.cut IN ops.valid) THEN par.disabled := TRUE END
END CutGuardHidden;
PROCEDURE CopyGuardHidden* (VAR par: Dialog.Par);
VAR ops: Controllers.PollOpsMsg;
BEGIN
par.label := '-' (* StdMenus.hidden*);
Controllers.PollOps(ops);
IF ~(Controllers.copy IN ops.valid) THEN par.disabled := TRUE END
END CopyGuardHidden;
PROCEDURE PasteGuardHidden* (VAR par: Dialog.Par);
VAR ops: Controllers.PollOpsMsg;
BEGIN
par.label := '-' (* StdMenus.hidden*);
Controllers.PollOps(ops);
IF ~(Controllers.paste IN ops.valid)
(* OR ~HostClipboard.ConvertibleTo(ops.pasteType) TODO *)
THEN par.disabled := TRUE END
END PasteGuardHidden;
(* standard notifiers *)
PROCEDURE DefaultOnDoubleClick* (op, from, to_: INTEGER);
VAR msg: Controllers.EditMsg; c: Containers.Controller;
BEGIN
IF (op = Dialog.pressed) & (from = 1) THEN
Controllers.SetCurrentPath(Controllers.frontPath);
c := Containers.Focus();
Controllers.ResetCurrentPath;
IF {Containers.noSelection, Containers.noCaret} - c.opts = {} THEN
msg.op := Controllers.pasteChar;
msg.char := 0DX; msg.modifiers := {};
Controllers.ForwardVia(Controllers.frontPath, msg)
END
END
END DefaultOnDoubleClick;
PROCEDURE ParamInit (par: ANYPTR);
VAR val: RECORD (Meta.Value) hook: DirtyHook END; it: Meta.Item; ok: BOOLEAN;
BEGIN
WITH par: Param DO
par.proc := NIL;
Meta.LookupPath(par.dirtyHook, it);
IF it.Valid() THEN
it.GetVal(val, ok);
IF ok THEN par.proc := val.hook END
END
END
END ParamInit;
PROCEDURE ParamInitDefaults (par: ANYPTR);
BEGIN
WITH par: Param DO
par.dirtyHook := "";
par.proc := NIL;
par.clearSeqOnSave := FALSE;
par.Init := ParamInit; par.InitDefaults := ParamInitDefaults
END
END ParamInitDefaults;
PROCEDURE Init;
BEGIN
allocator := defaultAllocator;
propEra := -1;
NEW(param); ParamInitDefaults(param)
END Init;
BEGIN
Init
END StdCmds.
Closing windows and exiting BlackBox
technical note by Anton Dmitriev
StdCmds.CloseTopDialog
StdCmds.GuardedClose(w...)
w.seq.Notify(msg:Sequencers.CloseMsg)
StdTiles.SeqNotifier.Notify(msg)
StdTiles.CloseNestedWindows(w)
∀u∈w: StdCmds.GuardedClose(u)
IF ~msg.sticky THEN
DirtyHook(w, action) (* presents a modal or non-modal dirty close confirmation *)
CASE action OF default | cancel | save | close | defer
END
END
Kernel.Cleanup
File->Close => StdCmds.CloseTopDialog
Window ⨂ =>
LinBackends.DeleteHandler.Do
StdWindows.guardedCloseHook -> StdCmds.CloseThis
StdCmds.GuardedClose
So, for this to work,
1) the tyler window's sequencer has to be given a notifier. This is done in StdTiles.New.
2) StdWindows.guardedCloseHook has to be set. This is done in LinInit
File->Exit => StdCmds.Exit
The main event loop for dialog (event-driven) applications is now in Dialog.Loop. It's started in Lin(Win)Init with Dialog.Start, which is given two procedures: one to let the platform process an event, another to validate views.
The loop ends when there's no windows AND exit without windows has been enabled thru Dialog.RequestExit(Dialog.exitWithoutWindows). Windowless applications should enable the loop to operate without windows by Dialog.RequestExit(~Dialog.exitWithouWindows): this way they can sit in the background and wait for a timer event or another platform event, and, if/when necessary, open new windows. Dialog.RequestExit can be done at any time.
Another application kind is batch applications (or command-line applications). They do not use the Dialog.Loop (thru Dialog.Start) at all, which is clear in LinIntInit, for example.
To enable legacy MDI applications to exit, StdCmds provides VAR exitHook, which is called at the end of StdCmds.Exit in case all windows were successfully closed. Applications using the new event loop do not need to provide this hook.
StdCmds.Exit
close all windows
exitHook -> MdiMenus.AllowExit
MdiMenus.exit := TRUE
WinMenus.Loop
WHILE WinApi.GetMessage() # 0 DO
IF exit THEN Exit
WinApi.SendMessage(WinWindows.main, WM_CLOSE)
WinMenus.ApplWinHandler
CASE WM_CLOSE:
WinMenus.Quit
IF ~WinMenus.exit THEN
StdCmds.Exit
END
WinApi.DefWndProc
sends WM_QUIT to WinWindows.main
END
END
END;
(* WinApi.GetMessage() = 0 AFTER WM_QUIT *)
Kernel.Quit
File->Exit => StdCmds.Exit
Click Main ⨂ => sends WM_CLOSE to WinWindows.mainWin (see above) => StdCmds.Exit
MDI ⨂ =>
WinWindows.DocWinHandler
CASE WM_CLOSE
WinApi.SendMessage(WinWindows.main, WM_COMMAND iClose)
WinMenus.ApplWinHandler
CASE WM_COMMAND
WinMenus.MenuCommand
CASE iClose
StdCmds.CloseTopDialog
| Std/Mod/Cmds.odc |
MODULE StdCoder;
(**
project = "BlackBox 2.0"
organization = "www.oberon.ch, blackbox.oberon.org"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 20160321, center #110, use mapped strings for labels in all forms
- 20161010, center #133, bug fix in Encoding/Decoding Unicode filenames and paths
- 20161216, center #144, inconsistent docu and usage of Files.Locator error codes
- 20170225, center #148, StdCoder to support file names with spaces
- 20190211, center #196, StdCoder to support both "\" & "/" in file paths
"
issues = "
- ...
"
**)
IMPORT
Kernel, Files, Converters, Stores, Views, Controllers, Dialog, Documents, Windows,
TextModels, TextViews, TextControllers, TextMappers, Utf,
StdCmds;
CONST
N = 16384;
LineLength = 74;
OldVersion = 0; ThisVersion = 1;
Tag = "StdCoder.Decode"; (* first letter of Tag must not to appear within Tag again *)
Separator = "/";
Separator2 = "\";
View = 1; File = 2; List = 3;
TYPE
FileList = POINTER TO RECORD
next: FileList;
file: Files.File;
type: Files.Type;
name: Dialog.String
END;
ParList* = RECORD
list*: Dialog.Selection;
storeAs*: Dialog.String;
files: FileList
END;
VAR
par*: ParList;
askOption*: BOOLEAN;
code: ARRAY 64 OF CHAR;
revCode: ARRAY 256 OF BYTE;
table: ARRAY N OF BYTE;
stdDocuType: Files.Type;
PROCEDURE NofSelections(IN list: Dialog.Selection): INTEGER;
VAR i, n: INTEGER;
BEGIN
i := 0; n := 0;
WHILE i # list.len DO
IF list.In(i) THEN INC(n) END;
INC(i)
END;
RETURN n
END NofSelections;
PROCEDURE ShowError(n: INTEGER; par: ARRAY OF CHAR);
BEGIN
Dialog.Beep;
CASE n OF
1: Dialog.ShowParamMsg("#Std:bad characters", par, "", "")
| 2: Dialog.ShowParamMsg("#Std:checksum error", par, "", "")
| 3: Dialog.ShowParamMsg("#Std:incompatible version", par, "", "")
| 4: Dialog.ShowParamMsg("#Std:filing error", par, "", "")
| 5: Dialog.ShowParamMsg("#Std:directory ^0 not found", par, "", "")
| 6: Dialog.ShowParamMsg("#Std:file ^0 not found", par, "", "")
| 7: Dialog.ShowParamMsg("#Std:illegal path", par, "", "")
| 8: Dialog.ShowParamMsg("#Std:no tag", par, "", "")
| 9: Dialog.ShowParamMsg("#Std:disk write protected", par, "", "")
| 10: Dialog.ShowParamMsg("#Std:io error", par, "", "")
END
END ShowError;
PROCEDURE ShowSizeMsg(x: INTEGER);
VAR i, j: INTEGER; ch: CHAR; s: ARRAY 20 OF CHAR;
BEGIN
ASSERT(x >= 0, 20);
i := 0;
REPEAT s[i] := CHR(ORD("0") + x MOD 10); INC(i); x := x DIV 10 UNTIL x = 0;
s[i] := 0X;
DEC(i); j := 0;
WHILE j < i DO ch := s[j]; s[j] := s[i]; s[i] := ch; INC(j); DEC(i) END;
Dialog.ShowParamStatus("#Std:^0 characters coded", s, "", "")
END ShowSizeMsg;
PROCEDURE Write(dest: TextModels.Writer; x: INTEGER; VAR n: INTEGER);
BEGIN
dest.WriteChar(code[x]); INC(n);
IF n = LineLength THEN dest.WriteChar(0DX); dest.WriteChar(" "); n := 0 END
END Write;
PROCEDURE WriteHeader(dest: TextModels.Writer; VAR n: INTEGER;
name: ARRAY OF CHAR; type: BYTE
);
VAR byte, bit, i, res: INTEGER; ch: CHAR; tag: ARRAY 16 OF CHAR; utf8: Kernel.Utf8Name;
BEGIN
tag := Tag; i := 0; ch := tag[0];
WHILE ch # 0X DO dest.WriteChar(ch); INC(n); INC(i); ch := tag[i] END;
dest.WriteChar(" "); INC(n);
bit := 0; byte := 0; i := 0;
Utf.StringToUtf8(name, utf8, res); ASSERT(res = 0);
REPEAT
ch := utf8[i]; INC(byte, ASH(ORD(ch), bit)); INC(bit, 8);
WHILE bit >= 6 DO Write(dest, byte MOD 64, n); byte := byte DIV 64; DEC(bit, 6) END;
INC(i)
UNTIL ch = 0X;
IF bit # 0 THEN Write(dest, byte, n) END;
Write(dest, ThisVersion, n); Write(dest, type, n)
END WriteHeader;
PROCEDURE WriteFileType(dest: TextModels.Writer; VAR n: INTEGER; t: Files.Type);
VAR byte, bit, i: INTEGER; ch: CHAR;
BEGIN
IF t = Files.docType THEN t := stdDocuType END;
bit := 0; byte := 0; i := 0; dest.WriteChar(" ");
REPEAT
ch := t[i]; INC(byte, ASH(ORD(ch), bit)); INC(bit, 8);
WHILE bit >= 6 DO Write(dest, byte MOD 64, n); byte := byte DIV 64; DEC(bit, 6) END;
INC(i)
UNTIL ch = 0X;
IF bit # 0 THEN Write(dest, byte, n) END
END WriteFileType;
PROCEDURE WriteFile(dest: TextModels.Writer; VAR n: INTEGER; f: Files.File);
VAR hash, byte, bit, i, j, sum, len: INTEGER; src: Files.Reader; b: BYTE;
BEGIN
len := f.Length(); j := len; i := 6;
WHILE i # 0 DO Write(dest, j MOD 64, n); j := j DIV 64; DEC(i) END;
i := 0;
REPEAT table[i] := 0; INC(i) UNTIL i = N;
hash := 0; bit := 0; byte := 0; sum := 0; src := f.NewReader(NIL);
WHILE len # 0 DO
src.ReadByte(b); DEC(len);
sum := (sum + b MOD 256) MOD (16 * 1024);
IF table[hash] = b THEN INC(bit) (* 0 bit for correct prediction *)
ELSE (* Incorrect prediction -> 1'xxxx'xxxx bits *)
table[hash] := b; INC(byte, ASH(1, bit)); INC(bit);
INC(byte, ASH(b MOD 256, bit)); INC(bit, 8)
END;
WHILE bit >= 6 DO Write(dest, byte MOD 64, n); byte := byte DIV 64; DEC(bit, 6) END;
hash := (16 * hash + b MOD 256) MOD N
END;
IF bit # 0 THEN Write(dest, byte, n) END;
i := 6;
WHILE i # 0 DO Write(dest, sum MOD 64, n); sum := sum DIV 64; DEC(i) END;
IF n # 0 THEN dest.WriteChar(0DX); n := 0 END
END WriteFile;
PROCEDURE Read(src: TextModels.Reader; VAR x: INTEGER; VAR res: INTEGER);
VAR ch: CHAR;
BEGIN
IF res = 0 THEN
REPEAT src.ReadChar(ch); x := revCode[ORD(ch)] UNTIL (x >= 0) OR src.eot;
IF src.eot THEN res := 1 END
END;
IF res # 0 THEN x := 0 END
END Read;
PROCEDURE Utf8ToString(IN in: ARRAY OF SHORTCHAR; OUT out: ARRAY OF CHAR);
VAR res: INTEGER;
BEGIN
Utf.Utf8ToString(in, out, res);
ASSERT(res IN {0, 2}) (* for backward compatibility: res = 2 allows non-encoded strings as well *)
END Utf8ToString;
PROCEDURE ReadHeader(src: TextModels.Reader; VAR res: INTEGER;
VAR name: ARRAY OF CHAR; VAR type: BYTE
);
VAR x, bit, i, j: INTEGER; ch: CHAR; tag: ARRAY 16 OF CHAR; utf8: Kernel.Utf8Name;
BEGIN
tag := Tag; i := 0; name := "";
WHILE ~src.eot & (tag[i] # 0X) DO
src.ReadChar(ch);
IF ch = tag[i] THEN INC(i) ELSIF ch = tag[0] THEN i := 1 ELSE i := 0 END
END;
IF ~src.eot THEN
res := 0; i := 0; bit := 0; x := 0;
REPEAT
WHILE (res = 0) & (bit < 8) DO Read(src, j, res); INC(x, ASH(j, bit)); INC(bit, 6) END;
IF res = 0 THEN
ch := CHR(x MOD 256); x := x DIV 256; DEC(bit, 8); utf8[i] := SHORT(ch); INC(i)
END
UNTIL (res # 0) OR (ch = 0X);
Read(src, j, res);
IF res = 0 THEN
Utf8ToString(utf8, name);
IF (j = ThisVersion) OR (j = OldVersion) THEN
Read(src, j, res); type := SHORT(SHORT(j))
ELSE res := 3
END
END
ELSE res := 8
END
END ReadHeader;
PROCEDURE ReadFileType(src: TextModels.Reader; VAR res: INTEGER; VAR ftype: Files.Type);
VAR x, bit, i, j: INTEGER; ch: CHAR;
BEGIN
res := 0; i := 0; bit := 0; x := 0;
REPEAT
WHILE (res = 0) & (bit < 8) DO Read(src, j, res); INC(x, ASH(j, bit)); INC(bit, 6) END;
IF res = 0 THEN ch := CHR(x MOD 256); x := x DIV 256; DEC(bit, 8); ftype[i] := ch; INC(i) END
UNTIL (res # 0) OR (ch = 0X);
IF ftype = stdDocuType THEN ftype := Files.docType END
END ReadFileType;
PROCEDURE ReadFile(src: TextModels.Reader; VAR res: INTEGER; f: Files.File);
VAR hash, x, bit, i, j, len, sum, s: INTEGER; byte: BYTE; dest: Files.Writer;
BEGIN
res := 0; i := 0; len := 0;
REPEAT Read(src, x, res); len := len + ASH(x, 6 * i); INC(i) UNTIL (res # 0) OR (i = 6);
i := 0;
REPEAT table[i] := 0; INC(i) UNTIL i = N;
bit := 0; hash := 0; sum := 0; dest := f.NewWriter(NIL);
WHILE (res = 0) & (len # 0) DO
IF bit = 0 THEN Read(src, x, res); bit := 6 END;
IF ODD(x) THEN (* Incorrect prediction -> 1'xxxx'xxxx *)
x := x DIV 2; DEC(bit);
WHILE (res = 0) & (bit < 8) DO Read(src, j, res); INC(x, ASH(j, bit)); INC(bit, 6) END;
i := x MOD 256;
IF i > MAX(BYTE) THEN i := i - 256 END;
byte := SHORT(SHORT(i)); x := x DIV 256; DEC(bit, 8);
table[hash] := byte
ELSE byte := table[hash]; x := x DIV 2; DEC(bit) (* correct prediction *)
END;
hash := (16 * hash + byte MOD 256) MOD N;
dest.WriteByte(byte); sum := (sum + byte MOD 256) MOD (16 * 1024); DEC(len)
END;
IF res = 0 THEN
i := 0; s := 0;
REPEAT Read(src, x, res); s := s + ASH(x, 6 * i); INC(i) UNTIL (res # 0) OR (i = 6);
IF (res = 0) & (s # sum) THEN res := 2 END
END
END ReadFile;
PROCEDURE ShowText (t: TextModels.Model);
VAR l: INTEGER; v: Views.View; wr: TextMappers.Formatter; conv: Converters.Converter;
BEGIN
l := t.Length();
wr.ConnectTo(t); wr.SetPos(l); wr.WriteString(" --- end of encoding ---");
ShowSizeMsg(l);
v := TextViews.dir.New(t);
conv := Converters.list;
WHILE (conv # NIL) & (conv.imp # "StdTextConv.ImportText") DO conv := conv.next END;
Views.Open(v, NIL, "", conv);
Views.SetDirty(v)
END ShowText;
PROCEDURE EncodedView*(v: Views.View): TextModels.Model;
VAR n: INTEGER; f: Files.File; wrs: Stores.Writer; t: TextModels.Model; wr: TextModels.Writer;
BEGIN
f := Files.dir.Temp(); wrs.ConnectTo(f); Views.WriteView(wrs, v);
t := TextModels.dir.New(); wr := t.NewWriter(NIL);
n := 0; WriteHeader(wr, n, "", View); WriteFileType(wr, n, f.type); WriteFile(wr, n, f);
RETURN t
END EncodedView;
PROCEDURE EncodeDocument*;
VAR v: Views.View; w: Windows.Window;
BEGIN
w := Windows.dir.First();
IF w # NIL THEN
v := w.doc.OriginalView();
IF (v.context # NIL) & (v.context IS Documents.Context) THEN
v := v.context(Documents.Context).ThisDoc()
END;
IF v # NIL THEN ShowText(EncodedView(v)) END
END
END EncodeDocument;
PROCEDURE EncodeFocus*;
VAR v: Views.View;
BEGIN
v := Controllers.FocusView();
IF v # NIL THEN ShowText(EncodedView(v)) END
END EncodeFocus;
PROCEDURE EncodeSelection*;
VAR beg, end: INTEGER; t: TextModels.Model; c: TextControllers.Controller;
BEGIN
c := TextControllers.Focus();
IF (c # NIL) & c.HasSelection() THEN
c.GetSelection(beg, end);
t := TextModels.CloneOf(c.text); t.InsertCopy(0, c.text, beg, end);
ShowText(EncodedView(TextViews.dir.New(t)))
END
END EncodeSelection;
PROCEDURE EncodeFile*;
VAR n: INTEGER; loc: Files.Locator; name: Files.Name; f: Files.File;
t: TextModels.Model; wr: TextModels.Writer;
BEGIN
Dialog.GetIntSpec("", loc, name);
IF loc # NIL THEN
f := Files.dir.Old(loc, name, TRUE);
IF f # NIL THEN
t := TextModels.dir.New(); wr := t.NewWriter(NIL);
n := 0; WriteHeader(wr, n, name, File); WriteFileType(wr, n, f.type); WriteFile(wr, n, f);
ShowText(t)
END
END
END EncodeFile;
PROCEDURE GetFile(VAR path: ARRAY OF CHAR; VAR loc: Files.Locator; VAR name: Files.Name);
VAR i, j: INTEGER; ch: CHAR;
BEGIN
i := 0; ch := path[0]; loc := Files.dir.This(""); name := "";
WHILE (ch # 0X) & (loc.res = 0) DO
j := 0;
WHILE (ch # 0X) & (ch # Separator) & (ch # Separator2) DO name[j] := ch; INC(j); INC(i); ch := path[i] END;
name[j] := 0X;
IF (ch = Separator) OR (ch = Separator2) THEN loc := loc.This(name); INC(i); ch := path[i] END;
END;
IF loc.res # 0 THEN loc := NIL END;
path[i] := 0X
END GetFile;
PROCEDURE ReadPath(rd: TextModels.Reader; VAR path: ARRAY OF CHAR; VAR len: INTEGER);
VAR i, l: INTEGER; ch: CHAR; quote: CHAR;
BEGIN
i := 0; l := LEN(path) - 1;
REPEAT rd.ReadChar(ch) UNTIL rd.eot OR (ch > " ");
IF (ch = "'") OR (ch = '"') THEN quote := ch; rd.ReadChar(ch) ELSE quote := 0X END;
WHILE ~rd.eot & (i < l) & ((quote = 0X) & (ch > " ") OR (quote # 0X) & (ch # quote) & (ch >= " ")) DO
path[i] := ch; INC(i); rd.ReadChar(ch)
END;
path[i] := 0X; len := i
END ReadPath;
PROCEDURE WriteString(w: Files.Writer; IN str: ARRAY OF CHAR; len: INTEGER);
VAR i, res: INTEGER; utf8: Kernel.Utf8Name;
BEGIN
Utf.StringToUtf8(str, utf8, res); ASSERT(res = 0); len:= LEN(utf8$) + 1;
i := 0;
WHILE i < len DO
IF ORD(utf8[i]) > MAX(BYTE) THEN w.WriteByte(SHORT(SHORT(ORD(utf8[i]) - 256)))
ELSE w.WriteByte(SHORT(ORD(utf8[i])))
END;
INC(i)
END
END WriteString;
PROCEDURE EncodeFileList*;
TYPE
FileList = POINTER TO RECORD
next: FileList;
f: Files.File
END;
VAR
beg, end, i, j, n: INTEGER; err: BOOLEAN;
files, last: FileList;
list, f: Files.File; w: Files.Writer; loc: Files.Locator;
rd: TextModels.Reader; wr: TextModels.Writer; t: TextModels.Model;
c: TextControllers.Controller;
name: Files.Name; path, next: ARRAY 2048 OF CHAR;
BEGIN
c := TextControllers.Focus();
IF (c # NIL) & c.HasSelection() THEN c.GetSelection(beg, end);
rd := c.text.NewReader(NIL); rd.SetPos(beg); err := FALSE;
list := Files.dir.Temp(); w := list.NewWriter(NIL); files := NIL; last := NIL;
ReadPath(rd, path, i);
WHILE (path # "") & (rd.Pos() - i < end) & ~err DO
GetFile(path, loc, name);
IF loc # NIL THEN
f := Files.dir.Old(loc, name, TRUE); err := f = NIL;
IF ~err THEN
IF last = NIL THEN NEW(last); files := last ELSE NEW(last.next); last := last.next END;
last.f := f;
ReadPath(rd, next, j);
IF (next = "=>") & (rd.Pos() - j < end) THEN
ReadPath(rd, next, j);
IF next # "" THEN WriteString(w, next, j + 1); ReadPath(rd, next, j)
ELSE err := TRUE
END
ELSE WriteString(w, path, i + 1)
END;
path := next; i := j
END
ELSE err := TRUE
END
END;
IF ~err & (files # NIL) THEN
t := TextModels.dir.New(); wr := t.NewWriter(NIL);
n := 0; WriteHeader(wr, n, "", List);
WriteFileType(wr, n, list.type); WriteFile(wr, n, list);
WHILE files # NIL DO
WriteFileType(wr, n, files.f.type); WriteFile(wr, n, files.f); files := files.next
END;
ShowText(t)
ELSIF err THEN
IF path = "" THEN ShowError(7, path)
ELSIF loc # NIL THEN ShowError(6, path)
ELSE ShowError(5, path)
END
END
END
END EncodeFileList;
PROCEDURE DecodeView(rd: TextModels.Reader; name: Files.Name);
VAR res: INTEGER; f: Files.File; ftype: Files.Type; rds: Stores.Reader; v: Views.View;
BEGIN
ReadFileType(rd, res, ftype);
IF res = 0 THEN
f := Files.dir.Temp(); ReadFile(rd, res, f);
IF res = 0 THEN
rds.ConnectTo(f); Views.ReadView(rds, v); Views.Open(v, NIL, name, NIL);
Views.SetDirty(v)
ELSE ShowError(res, "")
END
ELSE ShowError(res, "")
END
END DecodeView;
PROCEDURE DecodeFile(rd: TextModels.Reader; name: Files.Name);
VAR res: INTEGER; ftype: Files.Type; loc: Files.Locator; f: Files.File;
BEGIN
ReadFileType(rd, res, ftype);
IF res = 0 THEN
Dialog.GetExtSpec(name, ftype, loc, name);
IF loc # NIL THEN
f := Files.dir.New(loc, askOption);
IF f # NIL THEN
ReadFile(rd, res, f);
IF res = 0 THEN
f.Register(name, ftype, askOption, res);
IF res # 0 THEN ShowError(4, "") END
ELSE ShowError(res, "")
END
ELSIF loc.res = 4 THEN ShowError(9, "")
ELSIF loc.res = 5 THEN ShowError(10, "")
END
END
ELSE ShowError(res, "")
END
END DecodeFile;
PROCEDURE DecodeFileList (rd: TextModels.Reader; VAR files: FileList; VAR len, res: INTEGER);
VAR i, n: INTEGER; b: BYTE; p: FileList;
ftype: Files.Type; f: Files.File; frd: Files.Reader; utf8: Kernel.Utf8Name;
BEGIN
ReadFileType(rd, res, ftype);
IF res = 0 THEN
f := Files.dir.Temp(); ReadFile(rd, res, f);
IF res = 0 THEN
files := NIL; p := NIL; n := 0;
frd := f.NewReader(NIL); frd.ReadByte(b);
WHILE ~frd.eof & (res = 0) DO
INC(n); i := 0;
WHILE ~frd.eof & (b # 0) DO
utf8[i] := SHORT(CHR(b MOD 256)); INC(i); frd.ReadByte(b)
END;
utf8[i] := 0X;
(*
IF (i > 4) & (utf8[i - 4] = ".") & (CAP(utf8[i - 3]) = "O")
& (CAP(utf8[i - 2]) = "D") & (CAP(utf8[i - 1]) = "C")
THEN utf8[i - 4] := 0X
ELSE utf8[i] := 0X
END;
*)
IF ~frd.eof THEN
IF p = NIL THEN NEW(p); files := p ELSE NEW(p.next); p := p.next END;
Utf8ToString(utf8, p.name);
frd.ReadByte(b)
ELSE res := 1
END
END;
p := files; len := n;
WHILE (res = 0) & (p # NIL) DO
ReadFileType(rd, res, p.type);
IF res = 0 THEN p.file := Files.dir.Temp(); ReadFile(rd, res, p.file) END;
p := p.next
END
END
END
END DecodeFileList;
PROCEDURE OpenDialog(files: FileList; len: INTEGER);
VAR i: INTEGER; p: FileList;
BEGIN
par.files := files; par.list.SetLen(len);
p := files; i := 0;
WHILE p # NIL DO par.list.SetItem(i, p.name); INC(i); p := p.next END;
par.storeAs := "";
Dialog.Update(par); Dialog.UpdateList(par.list);
StdCmds.OpenAuxDialog("Std/Rsrc/Coder", "#Std:DecodeDialog")
END OpenDialog;
PROCEDURE CloseDialog*;
BEGIN
par.files := NIL; par.list.SetLen(0); par.storeAs := "";
Dialog.UpdateList(par.list); Dialog.Update(par)
END CloseDialog;
PROCEDURE Select*(op, from, to: INTEGER);
VAR p: FileList; i: INTEGER;
BEGIN
IF (op = Dialog.included) OR (op = Dialog.excluded) OR (op = Dialog.set) THEN
IF NofSelections(par.list) = 1 THEN
i := 0; p := par.files;
WHILE ~par.list.In(i) DO INC(i); p := p.next END;
par.storeAs := p.name
ELSE par.storeAs := ""
END;
Dialog.Update(par)
END
END Select;
PROCEDURE CopyFile(from: Files.File; loc: Files.Locator; name: Files.Name; type: Files.Type);
CONST BufSize = 4096;
VAR res, k, l: INTEGER; f: Files.File; r: Files.Reader; w: Files.Writer;
buf: ARRAY BufSize OF BYTE;
BEGIN
f := Files.dir.New(loc, askOption);
IF f # NIL THEN
r := from.NewReader(NIL); w := f.NewWriter(NIL); l := from.Length();
WHILE l # 0 DO
IF l <= BufSize THEN k := l ELSE k := BufSize END;
r.ReadBytes(buf, 0, k); w.WriteBytes(buf, 0, k);
l := l - k
END;
f.Register(name, type, askOption, res);
IF res # 0 THEN ShowError(4, "") END
ELSIF loc.res = 4 THEN ShowError(9, "")
ELSIF loc.res = 5 THEN ShowError(10, "")
END
END CopyFile;
PROCEDURE StoreSelection*;
VAR i, n: INTEGER; p: FileList; loc: Files.Locator; name: Files.Name;
BEGIN
n := NofSelections(par.list);
IF n > 1 THEN
i := 0; p := par.files;
WHILE n # 0 DO
WHILE ~par.list.In(i) DO INC(i); p := p.next END;
GetFile(p.name, loc, name); CopyFile(p.file, loc, name, p.type);
DEC(n); INC(i); p := p.next
END
ELSIF (n = 1) & (par.storeAs # "") THEN
i := 0; p := par.files;
WHILE ~par.list.In(i) DO INC(i); p := p.next END;
GetFile(par.storeAs, loc, name); CopyFile(p.file, loc, name, p.type)
END
END StoreSelection;
PROCEDURE StoreSelectionGuard*(VAR p: Dialog.Par);
VAR n: INTEGER;
BEGIN
n := NofSelections(par.list);
p.disabled := (n = 0) OR ((n = 1) & (par.storeAs = ""))
END StoreSelectionGuard;
PROCEDURE StoreSingle*;
VAR i: INTEGER; p: FileList; loc: Files.Locator; name: Files.Name;
BEGIN
IF NofSelections(par.list) = 1 THEN
i := 0; p := par.files;
WHILE ~par.list.In(i) DO INC(i); p := p.next END;
GetFile(p.name, loc, name);
Dialog.GetExtSpec(name, p.type, loc, name);
IF loc # NIL THEN CopyFile(p.file, loc, name, p.type) END
END
END StoreSingle;
PROCEDURE StoreSingleGuard*(VAR p: Dialog.Par);
BEGIN
p.disabled := NofSelections(par.list) # 1
END StoreSingleGuard;
PROCEDURE StoreAllFiles(files: FileList);
VAR loc: Files.Locator; name: Files.Name;
BEGIN
WHILE files # NIL DO
GetFile(files.name, loc, name); CopyFile(files.file, loc, name, files.type); files := files.next
END
END StoreAllFiles;
PROCEDURE StoreAll*;
BEGIN
StoreAllFiles(par.files)
END StoreAll;
PROCEDURE DecodeAllFromText*(text: TextModels.Model; beg: INTEGER; ask: BOOLEAN);
VAR res, i: INTEGER; type: BYTE; name: Files.Name; rd: TextModels.Reader; files: FileList;
BEGIN
CloseDialog;
rd := text.NewReader(NIL); rd.SetPos(beg);
ReadHeader(rd, res, name, type);
(*
i := 0;
WHILE name[i] # 0X DO INC(i) END;
IF (i > 4) & (name[i - 4] = ".") & (CAP(name[i - 3]) = "O")
& (CAP(name[i - 2]) = "D") & (CAP(name[i - 1]) = "C")
THEN name[i - 4] := 0X
END;
*)
IF res = 0 THEN
IF type = View THEN DecodeView(rd, name)
ELSIF type = File THEN DecodeFile(rd, name)
ELSIF type = List THEN
DecodeFileList(rd, files, i, res);
IF res = 0 THEN
IF ask THEN OpenDialog(files, i) ELSE StoreAllFiles(files) END
ELSE ShowError(res, "")
END
ELSE ShowError(3, "")
END
ELSE ShowError(res, "")
END
END DecodeAllFromText;
PROCEDURE Decode*;
VAR beg, end: INTEGER; c: TextControllers.Controller;
BEGIN
CloseDialog;
c := TextControllers.Focus();
IF c # NIL THEN
IF c.HasSelection() THEN c.GetSelection(beg, end) ELSE beg := 0 END;
DecodeAllFromText(c.text, beg, TRUE)
END
END Decode;
PROCEDURE ListFiles(rd: TextModels.Reader; VAR wr: TextMappers.Formatter);
VAR i, n, res: INTEGER; b: BYTE;
ftype: Files.Type; f: Files.File; frd: Files.Reader; path: Dialog.String; utf8: Kernel.Utf8Name;
BEGIN
ReadFileType(rd, res, ftype);
IF res = 0 THEN
f := Files.dir.Temp(); ReadFile(rd, res, f);
IF res = 0 THEN
n := 0;
frd := f.NewReader(NIL); frd.ReadByte(b);
WHILE ~frd.eof & (res = 0) DO
INC(n); i := 0;
WHILE ~frd.eof & (b # 0) DO
utf8[i] := SHORT(CHR(b MOD 256)); INC(i); frd.ReadByte(b)
END;
utf8[i] := 0X;
(*
IF (i > 4) & (utf8[i - 4] = ".") & (CAP(utf8[i - 3]) = "O")
& (CAP(utf8[i - 2]) = "D") & (CAP(utf8[i - 1]) = "C")
THEN utf8[i - 4] := 0X
ELSE utf8[i] := 0X
END;
*)
IF ~frd.eof THEN Utf8ToString(utf8, path); wr.WriteString(path); wr.WriteLn; frd.ReadByte(b)
ELSE res := 1
END
END
ELSE ShowError(res, "")
END
ELSE ShowError(res, "")
END
END ListFiles;
PROCEDURE ListSingleton(type, name: ARRAY OF CHAR; VAR wr: TextMappers.Formatter);
BEGIN
wr.WriteString(type);
IF name # "" THEN wr.WriteString(": '"); wr.WriteString(name); wr.WriteChar("'") END;
wr.WriteLn
END ListSingleton;
PROCEDURE EncodedInText*(text: TextModels.Model; beg: INTEGER): TextModels.Model;
VAR res, i: INTEGER; type: BYTE; name: Files.Name;
rd: TextModels.Reader; report: TextModels.Model; wr: TextMappers.Formatter;
BEGIN
report := TextModels.dir.New(); wr.ConnectTo(report);
rd := text.NewReader(NIL); rd.SetPos(beg);
ReadHeader(rd, res, name, type);
(*
i := 0;
WHILE name[i] # 0X DO INC(i) END;
IF (i > 4) & (name[i - 4] = ".") & (CAP(name[i - 3]) = "O")
& (CAP(name[i - 2]) = "D") & (CAP(name[i - 1]) = "C")
THEN name[i - 4] := 0X
END;
*)
IF res = 0 THEN
IF type = View THEN ListSingleton("View", name, wr)
ELSIF type = File THEN ListSingleton("File", name, wr)
ELSIF type = List THEN ListFiles(rd, wr)
ELSE ShowError(3, "")
END
ELSE ShowError(res, "")
END;
RETURN report
END EncodedInText;
PROCEDURE ListEncodedMaterial*;
VAR beg, end: INTEGER; c: TextControllers.Controller;
BEGIN
c := TextControllers.Focus();
IF c # NIL THEN
IF c.HasSelection() THEN c.GetSelection(beg, end) ELSE beg := 0 END;
Views.OpenView(TextViews.dir.New(EncodedInText(c.text, beg)))
END
END ListEncodedMaterial;
PROCEDURE InitCodes;
VAR i: BYTE; j: INTEGER;
BEGIN
j := 0;
WHILE j # 256 DO revCode[j] := -1; INC(j) END;
code[0] := "."; revCode[ORD(".")] := 0; code[1] := ","; revCode[ORD(",")] := 1;
i := 2; j := ORD("0");
WHILE j <= ORD("9") DO code[i] := CHR(j); revCode[j] := i; INC(i); INC(j) END;
j := ORD("A");
WHILE j <= ORD("Z") DO code[i] := CHR(j); revCode[j] := i; INC(i); INC(j) END;
j := ORD("a");
WHILE j <= ORD("z") DO code[i] := CHR(j); revCode[j] := i; INC(i); INC(j) END;
ASSERT(i = 64, 60)
END InitCodes;
BEGIN
InitCodes;
askOption := TRUE;
stdDocuType[0] := 3X; stdDocuType[1] := 3X; stdDocuType[2] := 3X; stdDocuType[3] := 0X
END StdCoder.
| Std/Mod/Coder.odc |
MODULE StdConfig;
(**
project = "BlackBox 2.0"
organization = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Oberon microsystems, A. Dmitriev, I. Denisov"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- YYYYMMDD, nn, ...
"
issues = "
- ...
"
**)
IMPORT Kernel, Converters, Dialog, Documents, Views, Ports, Containers, Windows,
StdMenus, StdMenuTool, StdTiles, StdGrids, StdWindows, StdDocuments;
PROCEDURE Router (IN title: ARRAY OF CHAR);
VAR
trapTitle: ARRAY 64 OF CHAR;
PROCEDURE EndsWith (IN str, patt: ARRAY OF CHAR): BOOLEAN;
VAR k, i: INTEGER; res: BOOLEAN;
BEGIN
i := LEN(patt$); k := LEN(str$);
IF k >= i THEN
REPEAT DEC(i); DEC(k); res := str[k] = patt[i] UNTIL ~res OR (i = 0)
ELSE res := FALSE
END;
RETURN res
END EndsWith;
PROCEDURE StartsWith (IN str, patt: ARRAY OF CHAR): BOOLEAN;
VAR i, k: INTEGER; res: BOOLEAN;
BEGIN
i := LEN(patt$); k := LEN(str$);
IF k >= i THEN
k := 0;
REPEAT res := patt[k] = str[k]; INC(k) UNTIL ~res OR (k = i)
ELSE res := FALSE
END;
RETURN res
END StartsWith;
BEGIN
IF title = ">>>" THEN
(* rout sub windows by current target track *)
IF StdTiles.targetTrack = "User" THEN
StdTiles.SetTarget("Aux")
ELSIF (StdTiles.targetTrack = "Aux") OR (StdTiles.targetTrack = "System") THEN
StdTiles.SetTarget("User")
ELSE
StdTiles.SetTarget("")
END
ELSE
(* rout new windows by title *)
Dialog.MapString("#Dev:Trap", trapTitle);
IF (title = "Variables") OR (title = trapTitle) OR (title = "Heap Object")
OR EndsWith(title, " interface)") OR StartsWith(title, "<") THEN
StdTiles.SetTarget("Aux")
ELSIF (title = "#Dev:Log") OR (title = "Log") THEN
StdTiles.SetTarget("System")
ELSE
StdTiles.SetTarget("User")
END;
END
END Router;
PROCEDURE CanDrop (v_: StdGrids.View; ind_: INTEGER): BOOLEAN;
(* Forbids dropping new views into v; needed by the root and unnamed dividers *)
BEGIN
RETURN FALSE
END CanDrop;
PROCEDURE SetupWorkspace;
VAR
right: StdGrids.View; root: StdGrids.View; (* root divider *)
w: StdWindows.Window; doc: Documents.Document; mainLine, u: Views.View;
system, user, aux: StdGrids.View; bd: StdWindows.BackendDirectory;
c: Containers.Controller; tmsg: StdGrids.TrackPropMsg;
screenWidth, screenHeight: INTEGER;
BEGIN
root := StdGrids.NewDivider(StdGrids.horizontal);
root.canDrop := CanDrop;
system := StdGrids.NewStack();
user := StdGrids.NewStack();
aux := StdGrids.NewStack();
tmsg.name := 'System'; Views.HandlePropMsg(system, tmsg);
tmsg.name := 'Root'; Views.HandlePropMsg(root, tmsg);
tmsg.name := 'User'; Views.HandlePropMsg(user, tmsg);
tmsg.name := 'Aux'; Views.HandlePropMsg(aux, tmsg);
right := StdGrids.NewDivider(StdGrids.horizontal); right.canDrop := CanDrop;
StdGrids.AppendDivTile(right, user, 180 * Ports.mm, 0);
StdGrids.AppendDivTile(right, aux, 0, 0);
StdGrids.AppendDivTile(root, system, 90 * Ports.mm, 0);
StdGrids.AppendDivTile(root, right, 0, 0);
bd := StdWindows.backendDir;
StdWindows.SetBackendDir(StdWindows.stdBackendDir);
w := StdWindows.stdDir.New()(StdWindows.Window); ASSERT(w.port # NIL);
IF bd # StdWindows.backendDir THEN StdWindows.SetBackendDir(bd) END;
Windows.dir.GetBounds(screenWidth, screenHeight);
Windows.dir.l := screenWidth DIV 10;
Windows.dir.t := screenHeight DIV 10;
Windows.dir.r := screenWidth - screenWidth DIV 10;
Windows.dir.b := screenHeight - screenHeight DIV 10;
doc := Documents.dir.New(root, Views.undefined, Views.undefined);
c := doc.ThisController();
c.SetOpts(c.opts - {Documents.pageWidth..Documents.winHeight} +
{Documents.winHeight, Documents.winWidth}
);
Windows.dir.Open(w, doc, {Windows.isAux, Windows.neverDirty,
Windows.noVScroll, Windows.noHScroll}, Dialog.appName$, NIL, "", NIL
);
WITH doc: StdDocuments.Document DO
mainLine := StdMenus.NewMainLine();
StdDocuments.InsertBar(doc, StdDocuments.top, mainLine, NIL, TRUE, NIL);
StdMenus.DepositStatusBar;
Views.Fetch(u);
IF u # NIL THEN
StdDocuments.InsertBar(doc, StdDocuments.bottom, u, NIL, FALSE, NIL)
END
ELSE HALT(61)
END;
StdTiles.BindCloseNotifier(w);
END SetupWorkspace;
(*
PROCEDURE SecondHead;
VAR root, stack, ref: StdGrids.View; (* root divider *) n: INTEGER;
BEGIN
StdWindows.ext.GetNumHeads(n);
IF n > 1 THEN
root := StdGrids.NewDivider(StdGrids.horizontal);
root.canDrop := CanDrop;
ref := StdGrids.NewDivider(StdGrids.vertical);
ref.canDrop := CanDrop;
stack := StdGrids.NewStack();
stack.canDrop := CanDrop;
StdGrids.AppendDivTile(root, stack, 0, 5000);
StdGrids.AppendDivTile(root, ref, 0, 10000);
StdWindows.ext.ToHead(wb, 2);
StdWindows.ext.Maximize(wb)
END
END SecondHead;
*)
PROCEDURE Setup*;
VAR res: INTEGER; par: ARRAY 16 OF CHAR;
BEGIN
StdWindows.Init;
StdDocuments.Install;
Converters.Register(
"StdDocuments.ImportDocument", "StdDocuments.ExportDocument", "", "odc", {});
StdMenus.Install;
StdMenuTool.UpdateAllMenus;
StdWindows.border := 0;
StdTiles.On;
SetupWorkspace;
StdTiles.SetWindowsRouter(Router);
Converters.Register("StdTextConv.ImportUtf8", "StdTextConv.ExportUtf8", "TextViews.View", "utf8", {Converters.importAll});
Converters.Register("StdTextConv.ImportText", "StdTextConv.ExportText", "TextViews.View", "txt", {});
Converters.Register("StdTextConv.ImportUnicode", "StdTextConv.ExportUnicode", "TextViews.View", "utf", {});
Converters.Register("StdTextConv.ImportDosText", "", "TextViews.View", "txt", {});
Converters.Register("StdTextConv.ImportHex", "", "TextViews.View", "dat", {Converters.importAll});
Converters.Register("StdTextConv.ImportUtf8", "StdTextConv.ExportUtf8", "TextViews.View", "xml", {});
Converters.Register("StdTextConv.ImportUtf8", "StdTextConv.ExportUtf8", "TextViews.View", "html", {});
Converters.Register("DevBrowser.ImportSymFile", "", "TextViews.View", "osf", {});
Converters.Register("DevBrowser.ImportCodeFile", "", "TextViews.View", "ocf", {});
Converters.Register("WinBitmaps.ImportBitmap", "WinBitmaps.ExportBitmap", "WinBitmaps.StdView", "bmp", {});
Converters.Register("", "XhtmlExporter.ExportText", "TextViews.View", "html", {});
Converters.Register("StdRasters.Import", "", "StdRasters.View", "png", {});
Dialog.Call("StdLog.Open", "", res);
Dialog.Call("StdFilesBrowser.SetupPlaces", "", res);
Dialog.GetPar("DEBUG", par, res);
Kernel.debug := res = 0;
END Setup;
END StdConfig.
| Std/Mod/Config.odc |
MODULE StdDebug;
(**
project = "BlackBox 2.0, new module"
organizations = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20070123, bh, WriteString, ShowArray, & ShowVar changed (Unicode support)
- 20141027, center #19, full Unicode support for Component Pascal identifiers added
- 20150929, center #72, speeding up the dump of large data structures by avoiding fold.Flip
- 20170215, center #139, localization support for error messages
- 20181207, center #195, support for long identifiers in trap handlers
"
issues = "
- ...
"
**)
IMPORT SYSTEM, Kernel,
Utf, Strings, Fonts, Services, Ports, Views, Properties, Dialog, Containers, StdFolds,
TextModels, TextMappers, TextViews, TextRulers, Librarian;
CONST
refViewSize = 9 * Ports.point;
heap = 1; source = 2; module = 3; modules = 4; (* RefView types *)
TYPE
ArrayPtr = POINTER TO RECORD
last, t, first: INTEGER; (* gc header *)
len: ARRAY 16 OF INTEGER (* dynamic array length table *)
END;
RefView = POINTER TO RefViewDesc;
RefViewDesc = RECORD
type: SHORTINT;
command: SHORTINT;
back: RefView;
adr: INTEGER;
desc: Kernel.Type;
ptr: ArrayPtr;
name: Kernel.Utf8Name
END;
Action = POINTER TO RECORD (Services.Action)
text: TextModels.Model
END;
Cluster = POINTER TO RECORD [untagged] (* must correspond to Kernel.Cluster *)
size: INTEGER;
next: Cluster
END;
FoldContext = RECORD
prevText: TextModels.Model;
prevPos: INTEGER
END;
VAR
out: TextMappers.Formatter;
PROCEDURE NewRuler (): TextRulers.Ruler;
CONST mm = Ports.mm;
VAR r: TextRulers.Ruler;
BEGIN
r := TextRulers.dir.New(NIL);
TextRulers.SetRight(r, 140 * mm);
TextRulers.AddTab(r, 4 * mm); TextRulers.AddTab(r, 34 * mm); TextRulers.AddTab(r, 80 * mm);
RETURN r
END NewRuler;
PROCEDURE OpenViewer (t: TextModels.Model; title: Views.Title; ruler:TextRulers.Ruler);
VAR v: TextViews.View; c: Containers.Controller;
BEGIN
Dialog.MapString(title, title);
v := TextViews.dir.New(t);
v.SetDefaults(ruler, TextViews.dir.defAttr);
c := v.ThisController();
IF c # NIL THEN
c.SetOpts(c.opts - {Containers.noFocus, Containers.noSelection} + {Containers.noCaret})
END;
Views.OpenAux(v, title)
END OpenViewer;
PROCEDURE OpenFold (OUT fc: FoldContext);
BEGIN
fc.prevText := out.rider.Base();
fc.prevPos := out.Pos();
out.ConnectTo(TextModels.dir.New())
END OpenFold;
PROCEDURE CloseFold (IN fc: FoldContext; collapsed: BOOLEAN; IN hidden: ARRAY OF CHAR);
VAR fold: StdFolds.Fold; t: TextModels.Model; w: TextMappers.Formatter; hiddenx: ARRAY 32 OF CHAR;
BEGIN
Dialog.MapString(hidden, hiddenx);
(* avoid expensive fold.Flip operation *)
IF collapsed THEN
fold := StdFolds.dir.New(StdFolds.collapsed, "", out.rider.Base());
out.ConnectTo(fc.prevText);
out.WriteView(fold);
out.WriteString(hiddenx)
ELSE
t := TextModels.dir.New();
w.ConnectTo(t); w.WriteString(hiddenx);
fold := StdFolds.dir.New(StdFolds.expanded, "", t);
t := out.rider.Base();
out.ConnectTo(fc.prevText);
out.WriteView(fold);
fc.prevText.Insert(out.Pos(), t, 0, t.Length());
out.SetPos(out.rider.Base().Length())
END;
fold := StdFolds.dir.New(collapsed, "", NIL);
out.WriteView(fold)
END CloseFold;
PROCEDURE WriteHex (n: INTEGER);
BEGIN
out.WriteIntForm(n, TextMappers.hexadecimal, 9, "0", TextMappers.showBase)
END WriteHex;
PROCEDURE WriteString (adr, len, base: INTEGER; zterm, unicode: BOOLEAN);
CONST beg = 0; char = 1; code = 2;
VAR ch: CHAR; sc: SHORTCHAR; val, mode: INTEGER; str: ARRAY 16 OF CHAR;
BEGIN
mode := beg;
IF base = 2 THEN SYSTEM.GET(adr, ch); val := ORD(ch) ELSE SYSTEM.GET(adr, sc); val := ORD(sc) END;
IF zterm & (val = 0) THEN out.WriteString('""')
ELSE
REPEAT
IF (val >= ORD(" ")) & (val < 7FH) OR (val > 0A0H) & (val < 100H) OR unicode & (val >= 100H) THEN
IF mode # char THEN
IF mode = code THEN out.WriteString(", ") END;
out.WriteChar(22X); mode := char
END;
out.WriteChar(CHR(val))
ELSE
IF mode = char THEN out.WriteChar(22X) END;
IF mode # beg THEN out.WriteString(", ") END;
mode := code; Strings.IntToStringForm(val, Strings.hexadecimal, 1, "0", FALSE, str);
IF str[0] > "9" THEN out.WriteChar("0") END;
out.WriteString(str); out.WriteChar("X")
END;
INC(adr, base); DEC(len);
IF base = 2 THEN SYSTEM.GET(adr, ch); val := ORD(ch) ELSE SYSTEM.GET(adr, sc); val := ORD(sc) END
UNTIL (len = 0) OR zterm & (val = 0)
END;
IF mode = char THEN out.WriteChar(22X) END
END WriteString;
PROCEDURE OutString (IN s: ARRAY OF CHAR);
VAR str: Dialog.String;
BEGIN
Dialog.MapString(s, str);
out.WriteString(str)
END OutString;
(* ------------------- variable display ------------------- *)
PROCEDURE FormOf (t: Kernel.Type): SHORTCHAR;
BEGIN
IF SYSTEM.VAL(INTEGER, t) DIV 256 = 0 THEN
RETURN SHORT(CHR(SYSTEM.VAL(INTEGER, t)))
ELSE
RETURN SHORT(CHR(16 + t.id MOD 4))
END
END FormOf;
PROCEDURE LenOf (t: Kernel.Type; ptr: ArrayPtr): INTEGER;
BEGIN
IF t.size # 0 THEN RETURN t.size
ELSIF ptr # NIL THEN RETURN ptr.len[t.id DIV 16 MOD 16 - 1]
ELSE RETURN 0
END
END LenOf;
PROCEDURE SizeOf (t: Kernel.Type; ptr: ArrayPtr): INTEGER;
BEGIN
CASE FormOf(t) OF
| 0BX: RETURN 0
| 1X, 2X, 4X: RETURN 1
| 3X, 5X: RETURN 2
| 8X, 0AX: RETURN 8
| 11X: RETURN t.size
| 12X: RETURN LenOf(t, ptr) * SizeOf(t.base[0], ptr)
ELSE RETURN 4
END
END SizeOf;
PROCEDURE WriteName (t: Kernel.Type; ptr: ArrayPtr);
VAR modName, name: Kernel.Name; f: SHORTCHAR;
BEGIN
f := FormOf(t);
CASE f OF
| 0X: OutString("#Dev:Unknown")
| 1X: out.WriteString("BOOLEAN")
| 2X: out.WriteString("SHORTCHAR")
| 3X: out.WriteString("CHAR")
| 4X: out.WriteString("BYTE")
| 5X: out.WriteString("SHORTINT")
| 6X: out.WriteString("INTEGER")
| 7X: out.WriteString("SHORTREAL")
| 8X: out.WriteString("REAL")
| 9X: out.WriteString("SET")
| 0AX: out.WriteString("LONGINT")
| 0BX: out.WriteString("ANYREC")
| 0CX: out.WriteString("ANYPTR")
| 0DX: out.WriteString("POINTER")
| 0EX: out.WriteString("PROCEDURE")
| 0FX: out.WriteString("STRING")
| 10X..13X:
Kernel.GetTypeName(t, name);
IF name = "!" THEN
IF f = 11X THEN out.WriteString("RECORD")
ELSIF f = 12X THEN out.WriteString("ARRAY")
ELSE OutString("#Dev:Unknown")
END
ELSIF (t.id DIV 256 # 0) & (t.mod.refcnt >= 0) THEN
Kernel.GetModName(t.mod, modName); out.WriteString(modName); out.WriteChar("."); out.WriteString(name)
ELSIF f = 11X THEN
Kernel.GetModName(t.mod, modName); out.WriteString(modName); out.WriteString(".RECORD")
ELSIF f = 12X THEN
out.WriteString("ARRAY "); out.WriteInt(LenOf(t, ptr)); t := t.base[0];
WHILE (FormOf(t) = 12X) & ((t.id DIV 256 = 0) OR (t.mod.refcnt < 0)) DO
out.WriteString(", "); out.WriteInt(LenOf(t, ptr)); t := t.base[0]
END;
out.WriteString(" OF "); WriteName(t, ptr)
ELSIF f = 13X THEN
out.WriteString("POINTER")
ELSE
out.WriteString("PROCEDURE")
END
| 20X: out.WriteString("COM.IUnknown")
| 21X: out.WriteString("COM.GUID")
| 22X: out.WriteString("COM.RESULT")
ELSE OutString("#Dev:UnknownFormat"); out.WriteInt(ORD(f))
END
END WriteName;
PROCEDURE WriteGuid (a: INTEGER);
PROCEDURE Hex (a: INTEGER);
VAR x: SHORTCHAR;
BEGIN
SYSTEM.GET(a, x);
out.WriteIntForm(ORD(x), TextMappers.hexadecimal, 2, "0", FALSE)
END Hex;
BEGIN
out.WriteChar("{");
Hex(a + 3); Hex(a + 2); Hex(a + 1); Hex(a);
out.WriteChar("-");
Hex(a + 5); Hex(a + 4);
out.WriteChar("-");
Hex(a + 7); Hex(a + 6);
out.WriteChar("-");
Hex(a + 8);
Hex(a + 9);
out.WriteChar("-");
Hex(a + 10);
Hex(a + 11);
Hex(a + 12);
Hex(a + 13);
Hex(a + 14);
Hex(a + 15);
out.WriteChar("}")
END WriteGuid;
PROCEDURE^ ShowVar (ad, ind: INTEGER; f, c: SHORTCHAR; desc: Kernel.Type; ptr: ArrayPtr;
back: RefView; VAR name, sel: Kernel.Name);
PROCEDURE ShowRecord (a, ind: INTEGER; desc: Kernel.Type; back: RefView; VAR sel: Kernel.Name);
VAR dir: Kernel.Directory; obj: Kernel.Object; name: Kernel.Name; i, j, n: INTEGER; base: Kernel.Type;
fc: FoldContext;
BEGIN
WriteName(desc, NIL); out.WriteTab;
IF desc.mod.refcnt >= 0 THEN
OpenFold(fc);
n := desc.id DIV 16 MOD 16; j := 0;
WHILE j <= n DO
base := desc.base[j];
IF base # NIL THEN
dir := base.fields; i := 0;
WHILE i < dir.num DO
obj := SYSTEM.VAL(Kernel.Object, SYSTEM.ADR(dir.obj[i]));
Kernel.GetObjName(base.mod, obj, name);
ShowVar(a + obj.offs, ind, FormOf(obj.struct), 1X, obj.struct, NIL, back, name, sel);
INC(i)
END
END;
INC(j)
END;
out.WriteString(" ");
CloseFold(fc, (ind > 1) OR (sel # ""), "#Dev:Fields")
ELSE
OutString("#Dev:Unloaded")
END
END ShowRecord;
PROCEDURE ShowArray (a, ind: INTEGER; desc: Kernel.Type; ptr: ArrayPtr; back: RefView; VAR sel: Kernel.Name);
VAR f: SHORTCHAR; i, n, m, size, len: INTEGER; name: Kernel.Name; eltyp, t: Kernel.Type;
vi: SHORTINT; vs: BYTE; str: Dialog.String; high: BOOLEAN;
fc: FoldContext;
BEGIN
WriteName(desc, ptr); out.WriteTab;
len := LenOf(desc, ptr); eltyp := desc.base[0]; f := FormOf(eltyp); size := SizeOf(eltyp, ptr);
IF (f = 2X) OR (f = 3X) THEN (* string *)
n := 0; m := len; high := FALSE;
IF f = 2X THEN
REPEAT SYSTEM.GET(a + n, vs); INC(n) UNTIL (n = 32) OR (n = len) OR (vs = 0);
REPEAT DEC(m); SYSTEM.GET(a + m, vs) UNTIL (m = 0) OR (vs # 0)
ELSE
REPEAT
SYSTEM.GET(a + n * 2, vi); INC(n);
IF vi DIV 256 # 0 THEN high := TRUE END
UNTIL (n = len) OR (vi = 0);
n := MIN(n, 32);
REPEAT DEC(m); SYSTEM.GET(a + m * 2, vi) UNTIL (m = 0) OR (vi # 0)
END;
WriteString(a, n, size, TRUE, TRUE);
INC(m, 2);
IF m > len THEN m := len END;
IF high OR (m > n) THEN
out.WriteString(" ");
OpenFold(fc);
out.WriteLn;
IF high & (n = 32) THEN
WriteString(a, m, size, TRUE, TRUE);
out.WriteLn; out.WriteLn
END;
WriteString(a, m, size, FALSE, FALSE);
IF m < len THEN out.WriteString(", ..., 0X") END;
out.WriteString(" ");
CloseFold(fc, TRUE, "...")
END
ELSE
t := eltyp;
WHILE FormOf(t) = 12X DO t := t.base[0] END;
IF FormOf(t) # 0X THEN
OpenFold(fc);
i := 0;
WHILE i < len DO
Strings.IntToString(i, str);
name := "[" + SHORT(str$) + "]";
ShowVar(a, ind, f, 1X, eltyp, ptr, back, name, sel);
INC(i); INC(a, size)
END;
out.WriteString(" ");
CloseFold(fc, StdFolds.collapsed, "#Dev:Elements")
END
END
END ShowArray;
PROCEDURE ShowProcVar (a: INTEGER);
VAR vli, n, ref: INTEGER; m: Kernel.Module; modName, name: Kernel.Name; res: INTEGER; nn: Kernel.Utf8Name;
BEGIN
SYSTEM.GET(a, vli);
Kernel.SearchProcVar(vli, m, vli);
IF m = NIL THEN
IF vli = 0 THEN out.WriteString("NIL")
ELSE WriteHex(vli)
END
ELSE
IF m.refcnt >= 0 THEN
Kernel.GetModName(m, modName); out.WriteString(modName); ref := m.refs;
REPEAT Kernel.GetRefProc(ref, n, nn) UNTIL (n = 0) OR (vli < n);
IF vli < n THEN out.WriteChar("."); Utf.Utf8ToString(nn, name, res); out.WriteString(name) END
ELSE
OutString("#Dev:ProcInUnloadedMod");
Kernel.GetModName(m, modName); out.WriteString(modName); out.WriteString(" !!!")
END
END
END ShowProcVar;
PROCEDURE ShowPointer (a: INTEGER; f: SHORTCHAR; desc: Kernel.Type; back: RefView; VAR sel: Kernel.Name);
VAR adr, x: INTEGER; ptr: ArrayPtr; c: Cluster; btyp: Kernel.Type;
BEGIN
SYSTEM.GET(a, adr);
IF f = 13X THEN btyp := desc.base[0] ELSE btyp := NIL END;
IF adr = 0 THEN out.WriteString("NIL")
ELSIF f = 20X THEN
out.WriteChar("["); WriteHex(adr); out.WriteChar("]");
out.WriteChar(" "); c := SYSTEM.VAL(Cluster, Kernel.Root());
WHILE (c # NIL) & ((adr < SYSTEM.VAL(INTEGER, c)) OR (adr >= SYSTEM.VAL(INTEGER, c) + c.size)) DO c := c.next END;
IF c # NIL THEN
ptr := SYSTEM.VAL(ArrayPtr, adr)
END
ELSE
IF (f = 13X) OR (f = 0CX) THEN x := adr - 4 ELSE x := adr END;
IF ((adr < -4) OR (adr >= 65536)) & Kernel.IsReadable(x, adr + 16) THEN
out.WriteChar("["); WriteHex(adr); out.WriteChar("]");
IF (f = 13X) OR (f = 0CX) THEN
out.WriteChar(" "); c := SYSTEM.VAL(Cluster, Kernel.Root());
WHILE (c # NIL) & ((adr < SYSTEM.VAL(INTEGER, c)) OR (adr >= SYSTEM.VAL(INTEGER, c) + c.size)) DO
c := c.next
END;
IF c # NIL THEN
ptr := SYSTEM.VAL(ArrayPtr, adr);
IF (f = 13X) & (FormOf(btyp) = 12X) THEN (* array *)
adr := SYSTEM.ADR(ptr.len[btyp.id DIV 16 MOD 16])
END
ELSE OutString("#Dev:IllegalPointer")
END
END
ELSE OutString("#Dev:IllegalAddress"); WriteHex(adr)
END
END
END ShowPointer;
PROCEDURE ShowSelector (ref: RefView);
VAR b: RefView; n: SHORTINT; a, a0: TextModels.Attributes; res: INTEGER; nn: Kernel.Name;
BEGIN
b := ref.back; n := 1;
IF b # NIL THEN
WHILE (b.name = ref.name) & (b.back # NIL) DO INC(n); b := b.back END;
ShowSelector(b);
IF n > 1 THEN out.WriteChar("(") END;
out.WriteChar(".")
END;
Utf.Utf8ToString(ref.name, nn, res); out.WriteString(nn);
IF ref.type = heap THEN out.WriteChar("^") END;
IF n > 1 THEN
out.WriteChar(")");
a0 := out.rider.attr; a := TextModels.NewOffset(a0, 2 * Ports.point);
out.rider.SetAttr(a);
out.WriteInt(n); out.rider.SetAttr(a0)
END
END ShowSelector;
PROCEDURE ShowVar (ad, ind: INTEGER; f, c: SHORTCHAR; desc: Kernel.Type; ptr: ArrayPtr; back: RefView;
VAR name, sel: Kernel.Name);
VAR i, j, vli, a: INTEGER; tsel: Kernel.Name; a0: TextModels.Attributes;
vc: SHORTCHAR; vsi: BYTE; vi: SHORTINT; vr: SHORTREAL; vlr: REAL; vs: SET;
BEGIN
out.WriteLn; out.WriteTab; i := 0;
WHILE i < ind DO out.WriteString(" "); INC(i) END;
a := ad; i := 0; j := 0;
IF sel # "" THEN
WHILE sel[i] # 0X DO tsel[i] := sel[i]; INC(i) END;
IF (tsel[i-1] # ":") & (name[0] # "[") THEN tsel[i] := "."; INC(i) END
END;
WHILE name[j] # 0X DO tsel[i] := name[j]; INC(i); INC(j) END;
tsel[i] := 0X;
a0 := out.rider.attr;
IF c = 3X THEN (* varpar *)
SYSTEM.GET(ad, a);
out.rider.SetAttr(TextModels.NewStyle(a0, {Fonts.italic}))
END;
IF name[0] # "[" THEN out.WriteChar(".") END;
out.WriteString(name);
out.rider.SetAttr(a0); out.WriteTab;
IF (c = 3X) & (a >= 0) & (a < 65536) THEN
out.WriteTab; out.WriteString("NIL VARPAR")
ELSIF f = 11X THEN
Kernel.GetTypeName(desc, name);
IF (c = 3X) & (name[0] # "!") THEN SYSTEM.GET(ad + 4, desc) END; (* dynamic type *)
ShowRecord(a, ind + 1, desc, back, tsel)
ELSIF (c = 3X) & (f = 0BX) THEN (* VAR anyrecord *)
SYSTEM.GET(ad + 4, desc);
ShowRecord(a, ind + 1, desc, back, tsel)
ELSIF f = 12X THEN
IF (desc.size = 0) & (ptr = NIL) THEN SYSTEM.GET(ad, a) END; (* dyn array val par *)
IF ptr = NIL THEN ptr := SYSTEM.VAL(ArrayPtr, ad - 8) END;
ShowArray(a, ind + 1, desc, ptr, back, tsel)
ELSE
IF desc = NIL THEN desc := SYSTEM.VAL(Kernel.Type, ORD(f)) END;
WriteName(desc, NIL); out.WriteTab;
CASE f OF
| 0X: (* SYSTEM.GET(a, vli); WriteHex(vli) *)
| 1X: SYSTEM.GET(a, vc);
IF vc = 0X THEN out.WriteString("FALSE")
ELSIF vc = 1X THEN out.WriteString("TRUE")
ELSE OutString("#Dev:Undefined"); out.WriteInt(ORD(vc))
END
| 2X: WriteString(a, 1, 1, FALSE, FALSE)
| 3X: WriteString(a, 1, 2, FALSE, TRUE);
SYSTEM.GET(a, vi);
IF vi DIV 256 # 0 THEN out.WriteString(" "); WriteString(a, 1, 2, FALSE, FALSE) END
| 4X: SYSTEM.GET(a, vsi); out.WriteInt(vsi)
| 5X: SYSTEM.GET(a, vi); out.WriteInt(vi)
| 6X: SYSTEM.GET(a, vli); out.WriteInt(vli)
| 7X: SYSTEM.GET(a, vr); out.WriteReal(vr)
| 8X: SYSTEM.GET(a, vlr); out.WriteReal(vlr)
| 9X: SYSTEM.GET(a, vs); out.WriteSet(vs)
| 0AX: SYSTEM.GET(a, vli); SYSTEM.GET(a + 4, i);
IF (vli >= 0) & (i = 0) OR (vli < 0) & (i = -1) THEN out.WriteInt(vli)
ELSE out.WriteIntForm(i, TextMappers.hexadecimal, 8, "0", TextMappers.hideBase); WriteHex(vli)
END
| 0CX, 0DX, 13X, 20X: ShowPointer(a, f, desc, back, tsel)
| 0EX, 10X: ShowProcVar(a)
| 0FX: WriteString(a, 256, 1, TRUE, FALSE)
| 21X: WriteGuid(a)
| 22X: SYSTEM.GET(a, vli); WriteHex(vli)
ELSE
END
END
END ShowVar;
PROCEDURE ShowStack;
VAR ref, end, i, j, x, a, b, c: INTEGER; m, f: SHORTCHAR; mod: Kernel.Module; modName, name, sel: Kernel.Name;
d: Kernel.Type; res: INTEGER; nn: Kernel.Utf8Name;
BEGIN
a := Kernel.pc; b := Kernel.fp; c := 100;
REPEAT
mod := Kernel.modList;
WHILE (mod # NIL) & ((a < mod.code) OR (a >= mod.code + mod.csize)) DO mod := mod.next END;
IF mod # NIL THEN
DEC(a, mod.code);
IF mod.refcnt >= 0 THEN
Kernel.GetModName(mod, modName); out.WriteChar(" "); out.WriteString(modName); ref := mod.refs;
REPEAT Kernel.GetRefProc(ref, end, nn) UNTIL (end = 0) OR (a < end);
IF a < end THEN
Utf.Utf8ToString(nn, name, res); out.WriteChar("."); out.WriteString(name);
sel := mod.name$; i := 0;
WHILE sel[i] # 0X DO INC(i) END;
sel[i] := "."; INC(i); j := 0;
WHILE name[j] # 0X DO sel[i] := name[j]; INC(i); INC(j) END;
sel[i] := ":"; sel[i+1] := 0X;
out.WriteString(" ["); WriteHex(a);
out.WriteString("] ");
i := Kernel.SourcePos(mod, 0);
IF name # "$$" THEN
Kernel.GetRefVar(ref, m, f, d, x, nn); Utf.Utf8ToString(nn, name, res);
WHILE m # 0X DO
IF name[0] # "@" THEN ShowVar(b + x, 0, f, m, d, NIL, NIL, name, sel) END;
Kernel.GetRefVar(ref, m, f, d, x, nn); Utf.Utf8ToString(nn, name, res)
END
END;
out.WriteLn
ELSE out.WriteString(".???"); out.WriteLn
END
ELSE
Kernel.GetModName(mod, modName); out.WriteChar("("); out.WriteString(modName);
out.WriteString(") (pc="); WriteHex(a);
out.WriteString(", fp="); WriteHex(b); out.WriteChar(")");
out.WriteLn
END
ELSE
out.WriteString("<system> (pc="); WriteHex(a);
out.WriteString(", fp="); WriteHex(b); out.WriteChar(")");
out.WriteLn
END;
IF (b >= Kernel.fp) & (b < Kernel.stack) THEN
SYSTEM.GET(b+4, a); (* stacked pc *)
SYSTEM.GET(b, b); (* dynamic link *)
DEC(a); DEC(c)
ELSE c := 0
END
UNTIL c = 0
END ShowStack;
PROCEDURE (a: Action) Do; (* delayed trap window open *)
BEGIN
Kernel.SetTrapGuard(TRUE);
OpenViewer(a.text, "#Dev:Trap", NewRuler());
Kernel.SetTrapGuard(FALSE);
END Do;
PROCEDURE GetTrapMsg(OUT msg: ARRAY OF CHAR);
VAR ref, end, a, res: INTEGER; mod: Kernel.Module; nn: Kernel.Utf8Name;
name, head, tail: Kernel.Name; errstr: ARRAY 12 OF CHAR;
key: ARRAY Kernel.nameLen * 3 + LEN(errstr) OF CHAR;
BEGIN
a := Kernel.pc; mod := Kernel.modList; msg := "";
WHILE (mod # NIL) & ((a < mod.code) OR (a >= mod.code + mod.csize)) DO mod := mod.next END;
IF mod # NIL THEN
DEC(a, mod.code); ref := mod.refs;
REPEAT Kernel.GetRefProc(ref, end, nn) UNTIL (end = 0) OR (a < end);
Utf.Utf8ToString(nn, name, res);
IF a < end THEN
Kernel.GetModName(mod, head);
Librarian.lib.SplitName(head, head, tail);
Strings.IntToString(Kernel.err, errstr);
key := tail + "." + name + "." + errstr;
Dialog.MapString("#" + head + ":" + key, msg);
IF msg = key THEN msg := "" END
END
END
END GetTrapMsg;
PROCEDURE OutAdr (adr: INTEGER);
BEGIN
out.WriteString(" ("); OutString("#System:adr"); out.WriteString(" = "); WriteHex(adr); out.WriteChar(")")
END OutAdr;
PROCEDURE Trap;
VAR a0: TextModels.Attributes; action: Action; msg: ARRAY 512 OF CHAR;
BEGIN
out.ConnectTo(TextModels.dir.New());
a0 := out.rider.attr;
out.rider.SetAttr(TextModels.NewWeight(a0, Fonts.bold));
IF Kernel.err = 129 THEN OutString("#System:invalid WITH")
ELSIF Kernel.err = 130 THEN OutString("#System:invalid CASE")
ELSIF Kernel.err = 131 THEN OutString("#System:function without RETURN")
ELSIF Kernel.err = 132 THEN OutString("#System:type guard")
ELSIF Kernel.err = 133 THEN OutString("#System:implied type guard")
ELSIF Kernel.err = 134 THEN OutString("#System:value out of range")
ELSIF Kernel.err = 135 THEN OutString("#System:index out of range")
ELSIF Kernel.err = 136 THEN OutString("#System:string too long")
ELSIF Kernel.err = 137 THEN OutString("#System:stack overflow")
ELSIF Kernel.err = 138 THEN OutString("#System:integer overflow")
ELSIF Kernel.err = 139 THEN OutString("#System:division by zero")
ELSIF Kernel.err = 140 THEN OutString("#System:infinite real result")
ELSIF Kernel.err = 141 THEN OutString("#System:real underflow")
ELSIF Kernel.err = 142 THEN OutString("#System:real overflow")
ELSIF Kernel.err = 143 THEN
OutString("#System:undefined real result"); out.WriteString(" (");
out.WriteIntForm(Kernel.val MOD 10000H, TextMappers.hexadecimal, 4, "0", TextMappers.hideBase); out.WriteString(", ");
out.WriteIntForm(Kernel.val DIV 10000H, TextMappers.hexadecimal, 3, "0", TextMappers.hideBase); out.WriteChar(")")
ELSIF Kernel.err = 144 THEN OutString("#System:not a number")
ELSIF Kernel.err = 200 THEN OutString("#System:keyboard interrupt")
ELSIF Kernel.err = 201 THEN
OutString("#System:NIL dereference")
ELSIF Kernel.err = 202 THEN
OutString("#System:illegal instruction"); out.WriteString(": ");
out.WriteIntForm(Kernel.val, TextMappers.hexadecimal, 5, "0", TextMappers.showBase)
ELSIF Kernel.err = 203 THEN
IF (Kernel.val >= -4) & (Kernel.val < 65536) THEN OutString("#System:NIL dereference (read)")
ELSE OutString("#System:illegal memory read"); OutAdr(Kernel.val)
END
ELSIF Kernel.err = 204 THEN
IF (Kernel.val >= -4) & (Kernel.val < 65536) THEN OutString("#System:NIL dereference (write)")
ELSE OutString("#System:illegal memory write"); OutAdr(Kernel.val)
END
ELSIF Kernel.err = 205 THEN
IF (Kernel.val >= -4) & (Kernel.val < 65536) THEN OutString("#System:NIL procedure call")
ELSE OutString("#System:illegal execution"); OutAdr(Kernel.val)
END
ELSIF Kernel.err = 257 THEN OutString("#System:out of memory")
ELSIF Kernel.err = 10001H THEN OutString("#System:bus error")
ELSIF Kernel.err = 10002H THEN OutString("#System:address error")
ELSIF Kernel.err = 10007H THEN OutString("#System:fpu error")
ELSIF Kernel.err < 0 THEN
OutString("#System:Exception"); out.WriteChar(" ");
out.WriteIntForm(-Kernel.err, TextMappers.hexadecimal, 3, "0", TextMappers.showBase)
ELSE
OutString("#System:TRAP"); out.WriteChar(" "); out.WriteInt(Kernel.err);
IF Kernel.err = 126 THEN out.WriteString(" ("); OutString("#System:not yet implemented"); out.WriteChar(")")
ELSIF Kernel.err = 125 THEN out.WriteString(" ("); OutString("#System:call of obsolete procedure"); out.WriteChar(")")
ELSIF Kernel.err >= 100 THEN out.WriteString(" ("); OutString("#System:invariant violated"); out.WriteChar(")")
ELSIF Kernel.err >= 60 THEN out.WriteString(" ("); OutString("#System:postcondition violated"); out.WriteChar(")")
ELSIF Kernel.err >= 20 THEN out.WriteString(" ("); OutString("#System:precondition violated"); out.WriteChar(")")
END
END;
GetTrapMsg(msg);
IF msg # "" THEN out.WriteLn; out.WriteString(msg) END;
out.WriteLn; out.rider.SetAttr(a0);
out.WriteLn; ShowStack;
NEW(action); action.text := out.rider.Base();
Services.DoLater(action, Services.now);
out.ConnectTo(NIL)
END Trap;
BEGIN
Kernel.InstallTrapViewer(Trap);
END StdDebug.
| Std/Mod/Debug.odc |
MODULE StdDialog;
(**
project = "BlackBox 2.0, changes from 1.7.2 marked by green"
organization = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Oberon microsystems, Anton Dmitriev, Ivan Denisov"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 20070212, mf, minor cleanup
- 20150329, center #34, fixing the reuse of open documents
- 20161216, center #144, inconsistent docu and usage of Files.Locator error codes
- 20191107, AD, introduced a hook to modify the Open behavior as part of the Tyler project
"
issues = "
- ...
"
**)
IMPORT
Meta, Strings, Files, Stores, Models, Sequencers, Views,
Log, Ports, Fonts, Librarian, StdRegistry, TextModels, TextViews, Controllers, Printers,
Containers, Dialog, Properties, Documents, Converters, Windows;
TYPE
Item* = POINTER TO EXTENSIBLE RECORD
next*: Item;
item-, string-, filter-: POINTER TO ARRAY OF CHAR;
shortcut-: ARRAY 8 OF CHAR;
privateFilter-, failed, trapped: BOOLEAN; (* filter call failed, caused a trap *)
res: INTEGER (* result code of failed filter *)
END;
FilterProcVal = RECORD (Meta.Value)
p: Dialog.GuardProc
END;
FilterProcPVal = RECORD (Meta.Value)
p: PROCEDURE(n: INTEGER; VAR p: Dialog.Par)
END;
ViewHook* = POINTER TO ABSTRACT RECORD (Views.ViewHook) END;
StdViewHook = POINTER TO RECORD (ViewHook) END;
PrintHook* = POINTER TO ABSTRACT RECORD END;
(* page setup *)
Preview = POINTER TO RECORD (Views.View) END;
UpdateMsg = RECORD (Views.Message) END;
VAR
curItem-: Item; (** IN parameter for item filters **)
platformPrefOk*, platformInitPrefDialog*,
RecalcMainWindow*: PROCEDURE; (* called after preferences have been changed *)
prefs*: RECORD
statusbar*, colorTheme*, windowBackground*,
defaultColor*: INTEGER;
thickCaret*: BOOLEAN;
caretPeriod*: INTEGER;
scaleFactor*: INTEGER;
beep*: BOOLEAN;
language*: Dialog.Combo;
END;
prefFName, prefDName: Fonts.Typeface;
prefFSize, prefDSize, prefDWght: INTEGER;
prefDStyle: SET;
(* page setup *)
setup*: RECORD
decorate*: BOOLEAN;
landscape*: BOOLEAN;
left*, right*, top*, bottom*: REAL;
w*, h*: INTEGER;
hs, vs: REAL
END;
viewHook: ViewHook;
stdViewHook: StdViewHook;
printHook: PrintHook;
PROCEDURE GetSubLoc* (mod: ARRAY OF CHAR; cat: Files.Name;
OUT loc: Files.Locator; OUT name: Files.Name);
BEGIN
Librarian.lib.GetSpec(mod, cat, loc, name)
END GetSubLoc;
PROCEDURE AddItem* (i: Item; item, string, filter, shortcut: ARRAY OF CHAR);
VAR j: INTEGER; ch: CHAR;
BEGIN
ASSERT(i # NIL, 20);
NEW(i.item, LEN(item$) + 1);
NEW(i.string, LEN(string$) + 1);
NEW(i.filter, LEN(filter$) + 1);
ASSERT((i.item # NIL) & (i.string # NIL) & (i.filter # NIL), 100);
i.item^ := item$;
i.string^ := string$;
i.filter^ := filter$;
i.shortcut := shortcut$;
j := 0; ch := filter[0]; WHILE (ch # ".") & (ch # 0X) DO INC(j); ch := filter[j] END;
i.privateFilter := (j > 0) & (ch = 0X);
i.failed := FALSE; i.trapped := FALSE
END AddItem;
PROCEDURE ClearGuards* (i: Item);
BEGIN
i.failed := FALSE; i.trapped := FALSE
END ClearGuards;
PROCEDURE GetGuardProc (name: ARRAY OF CHAR; VAR i: Meta.Item;
VAR par: BOOLEAN; VAR n: INTEGER);
VAR j, k: INTEGER; num: ARRAY 32 OF CHAR;
BEGIN
j := 0;
WHILE (name[j] # 0X) & (name[j] # "(") DO INC(j) END;
IF name[j] = "(" THEN
name[j] := 0X; INC(j); k := 0;
WHILE (name[j] # 0X) & (name[j] # ")") DO
num[k] := name[j]; INC(j); INC(k)
END;
IF (name[j] = ")") & (name[j+1] = 0X) THEN
num[k] := 0X; Strings.StringToInt(num, n, k);
IF k = 0 THEN Meta.LookupPath(name, i); par := TRUE
ELSE Meta.Lookup("", i)
END
ELSE Meta.Lookup("", i)
END
ELSE
Meta.LookupPath(name, i); par := FALSE
END
END GetGuardProc;
PROCEDURE CheckFilter* (i: Item; VAR failed, ok: BOOLEAN; VAR par: Dialog.Par);
VAR x: Meta.Item; v: FilterProcVal; vp: FilterProcPVal; p: BOOLEAN; n: INTEGER;
BEGIN
IF ~i.failed THEN
curItem := i;
par.disabled := FALSE; par.checked := FALSE; par.label := i.item$;
par.undef := FALSE; par.readOnly := FALSE;
i.failed := TRUE; i.trapped := TRUE;
GetGuardProc(i.filter^, x, p, n);
IF (x.obj = Meta.procObj) OR (x.obj = Meta.varObj) & (x.typ = Meta.procTyp) THEN
IF p THEN
x.GetVal(vp, ok);
IF ok THEN vp.p(n, par) END
ELSE
x.GetVal(v, ok);
IF ok THEN v.p(par) END
END
ELSE ok := FALSE
END;
IF ok THEN i.res := 0 ELSE i.res := 1 END;
i.trapped := FALSE; i.failed := ~ok
END;
failed := i.failed
END CheckFilter;
PROCEDURE HandleItem* (i: Item);
VAR res: INTEGER;
BEGIN
IF ~i.failed THEN
Views.ClearQueue; res := 0;
Dialog.Call(i.string^, " ", res)
ELSIF (i # NIL) & i.failed THEN
IF i.trapped THEN
Dialog.ShowParamMsg("#System:ItemFilterTrapped", i.string^, i.filter^, "")
ELSE
Dialog.ShowParamMsg("#System:ItemFilterNotFound", i.string^, i.filter^, "")
END
END
END HandleItem;
PROCEDURE RecalcView* (v: Views.View);
(* recalc size of all subviews of v, then v itself *)
VAR m: Models.Model; v1: Views.View; c: Containers.Controller;
minW, maxW, minH, maxH, w, h, w0, h0: INTEGER;
BEGIN
IF v IS Containers.View THEN
c := v(Containers.View).ThisController();
IF c # NIL THEN
v1 := NIL; c.GetFirstView(Containers.any, v1);
WHILE v1 # NIL DO
RecalcView(v1);
c.GetNextView(Containers.any, v1)
END
END
END;
IF v.context # NIL THEN
m := v.context.ThisModel();
IF (m # NIL) & (m IS Containers.Model) THEN
m(Containers.Model).GetEmbeddingLimits(minW, maxW, minH, maxH);
v.context.GetSize(w0, h0); w := w0; h := h0;
Properties.PreferredSize(v, minW, maxW, minH, maxH, w, h, w, h);
IF (w # w0) OR (h # h0) THEN v.context.SetSize(w, h) END
END
END
END RecalcView;
PROCEDURE Open* (v: Views.View; title: ARRAY OF CHAR;
loc: Files.Locator; name: Files.Name; conv: Converters.Converter;
asTool, asAux, noResize, allowDuplicates, neverDirty: BOOLEAN);
BEGIN
viewHook.Open(v, title, loc, name, conv,
asTool, asAux, noResize, allowDuplicates, neverDirty)
END Open;
(* ViewHook *)
PROCEDURE (h: StdViewHook) Open (v: Views.View; title: ARRAY OF CHAR;
loc: Files.Locator; name: Files.Name; conv: Converters.Converter;
asTool, asAux, noResize, allowDuplicates, neverDirty: BOOLEAN);
VAR t: Views.Title; flags, opts: SET; done: BOOLEAN; d: Documents.Document;
len: INTEGER; win: Windows.Window; c: Containers.Controller; seq: ANYPTR;
BEGIN
IF conv = NIL THEN conv := Converters.list END; (* use document converter *)
ASSERT(v # NIL, 20);
flags := {}; done := FALSE;
IF noResize THEN
flags := flags + {Windows.noResize, Windows.noHScroll, Windows.noVScroll}
END;
IF asTool THEN INCL(flags, Windows.isTool) END;
IF asAux THEN INCL(flags, Windows.isAux) END;
IF neverDirty THEN INCL(flags, Windows.neverDirty) END;
len := MIN(LEN(title$), LEN(Views.Title) - 1);
Strings.Extract(title, 0, len, t);
IF len = LEN(Views.Title) - 1 THEN
t[len - 1] := "."; t[len - 2] := "."; t[len - 3] := "."
END;
IF ~allowDuplicates THEN
Windows.SelectBySpec(loc, name, conv, flags, done);
IF ~done & (title # "") & (loc = NIL) & (name = "") THEN
Windows.SelectByTitle(v, flags, t, done)
END
ELSE
INCL(flags, Windows.allowDuplicates)
END;
IF ~done THEN
IF v IS Documents.Document THEN
IF v.context # NIL THEN
d := Documents.dir.New(
Views.CopyOf(v(Documents.Document).ThisView(), Views.shallow),
Views.undefined, Views.undefined)
ELSE
d := v(Documents.Document)
END;
ASSERT(d.context = NIL, 22);
v := d.ThisView(); ASSERT(v # NIL, 23)
ELSIF v.context # NIL THEN
ASSERT(v.context IS Documents.Context, 24);
d := v.context(Documents.Context).ThisDoc();
IF d.context # NIL THEN
d := Documents.dir.New(Views.CopyOf(v, Views.shallow), Views.undefined, Views.undefined)
END;
ASSERT(d.context = NIL, 25)
(*IF d.Domain() = NIL THEN Stores.InitDomain(d, v.Domain()) END (for views opened via Views.Old *)
ELSE
d := Documents.dir.New(v, Views.undefined, Views.undefined)
END;
IF asTool OR asAux THEN
c := d.ThisController();
c.SetOpts(c.opts + {Containers.noSelection})
END;
ASSERT(d.Domain() = v.Domain(), 100);
ASSERT(d.Domain() # NIL, 101);
seq := d.Domain().GetSequencer();
IF neverDirty & (seq # NIL) THEN
ASSERT(seq IS Sequencers.Sequencer, 26);
seq(Sequencers.Sequencer).SetDirty(FALSE)
END;
IF neverDirty THEN
(* change "fit to page" to "fit to window" in secondary windows *)
c := d.ThisController(); opts := c.opts;
IF Documents.pageWidth IN opts THEN
opts := opts - {Documents.pageWidth} + {Documents.winWidth}
END;
IF Documents.pageHeight IN opts THEN
opts := opts - {Documents.pageHeight} + {Documents.winHeight}
END;
c.SetOpts(opts)
END;
win := Windows.dir.New();
IF seq # NIL THEN
Windows.dir.OpenSubWindow(win, d, flags, t)
ELSE
Windows.dir.Open(win, d, flags, t, loc, name, conv)
END
END
END Open;
PROCEDURE (h: ViewHook) OldView* (loc: Files.Locator; VAR name: Files.Name;
VAR conv: Converters.Converter): Views.View;
VAR w: Windows.Window; s: Stores.Store; c: Converters.Converter;
BEGIN
ASSERT(loc # NIL, 20); ASSERT(name # "", 21);
Files.dir.GetFileName(name, Files.docType, name); s := NIL;
c := conv;
IF c = NIL THEN c := Converters.list END; (* use document converter *)
w := Windows.GetBySpec(loc, name, c, {});
IF w # NIL THEN s := w.doc.ThisView() END;
IF s = NIL THEN
Converters.Import(loc, name, conv, s);
IF s # NIL THEN RecalcView(s(Views.View)) END
END;
IF s # NIL THEN RETURN s(Views.View) ELSE RETURN NIL END
END OldView;
PROCEDURE (h: ViewHook) RegisterView* (v: Views.View;
loc: Files.Locator; name: Files.Name; conv: Converters.Converter);
BEGIN
ASSERT(v # NIL, 20); ASSERT(loc # NIL, 21); ASSERT(name # "", 22);
Files.dir.GetFileName(name, Files.docType, name);
Converters.Export(loc, name, conv, v)
END RegisterView;
PROCEDURE InitLanguage;
VAR loc: Files.Locator; li: Files.LocInfo; lang: Dialog.Language; n: INTEGER;
BEGIN
prefs.language.SetItem(0, Dialog.defaultLanguage);
n := 1;
loc := Files.dir.This("System/Rsrc/");
li := Files.dir.LocList(loc);
WHILE li # NIL DO
IF LEN(li.name$) = 2 THEN
Strings.ToLower(li.name, lang);
prefs.language.SetItem(n, lang);
INC(n);
END;
li := li.next;
END;
prefs.language.SetLen(n);
prefs.language.item := Dialog.language$;
IF prefs.language.item = '' THEN
prefs.language.item := Dialog.defaultLanguage$
END;
END InitLanguage;
PROCEDURE PrefOk*;
VAR res: INTEGER;
BEGIN
IF prefs.statusbar = 1 THEN
Dialog.showsStatus := TRUE; Dialog.memInStatus := FALSE
ELSIF prefs.statusbar = 2 THEN
Dialog.showsStatus := TRUE; Dialog.memInStatus := TRUE
ELSE
Dialog.showsStatus := FALSE
END;
Dialog.Call("StdCmds.UpdateAll", "", res);
Dialog.Call("StdCmds.RecalcAllSizes", "", res);
Dialog.Call("TextCmds.UpdateDefaultAttr", "", res);
StdRegistry.WriteBool("noStatus", ~Dialog.showsStatus);
StdRegistry.WriteBool("memStatus", Dialog.memInStatus);
Dialog.thickCaret := prefs.thickCaret;
Dialog.caretPeriod := prefs.caretPeriod;
IF prefs.scaleFactor < 50 THEN
prefs.scaleFactor := 50;
Dialog.UpdateInt(prefs.scaleFactor);
END;
IF prefs.scaleFactor > 200 THEN
prefs.scaleFactor := 200;
Dialog.UpdateInt(prefs.scaleFactor);
END;
Dialog.scaleFactor := prefs.scaleFactor;
Dialog.colorTheme := prefs.colorTheme;
Dialog.defaultColor := prefs.defaultColor;
Ports.background := prefs.windowBackground;
Dialog.Call("StdTiles.UpdateUIColors", "", res);
StdRegistry.WriteInt("colorTheme", Dialog.colorTheme);
StdRegistry.WriteInt("defaultColor", Dialog.defaultColor);
StdRegistry.WriteInt("windowBackground", Ports.background );
Dialog.beep := prefs.beep;
StdRegistry.WriteBool("thickCaret", Dialog.thickCaret);
StdRegistry.WriteInt("caretPeriod", Dialog.caretPeriod);
StdRegistry.WriteInt("scaleFactor", Dialog.scaleFactor);
StdRegistry.WriteBool("beep", Dialog.beep);
IF platformPrefOk # NIL THEN
platformPrefOk
END;
Dialog.SetLanguage(prefs.language.item$, Dialog.persistent);
IF RecalcMainWindow # NIL THEN RecalcMainWindow() END;
END PrefOk;
PROCEDURE PrefsNotifier* (op, from, to: INTEGER);
VAR msg: UpdateMsg; t: INTEGER;
BEGIN
IF op = Dialog.changed THEN
IF prefs.caretPeriod < 50 THEN
prefs.caretPeriod := 50;
Dialog.UpdateInt(prefs.caretPeriod)
END;
IF prefs.caretPeriod > 10000 THEN
prefs.caretPeriod := 10000;
Dialog.UpdateInt(prefs.caretPeriod)
END;
(*
IF prefs.scaleFactor < 10 THEN
prefs.scaleFactor := 10;
Dialog.UpdateInt(prefs.scaleFactor)
END;
IF prefs.scaleFactor > 500 THEN
prefs.scaleFactor := 500;
Dialog.UpdateInt(prefs.scaleFactor)
END
*)
END
END PrefsNotifier;
PROCEDURE InitPrefDialog;
BEGIN
IF ~Dialog.showsStatus THEN
prefs.statusbar := 0
ELSIF Dialog.memInStatus THEN
prefs.statusbar := 2
ELSE
prefs.statusbar := 1
END;
prefs.thickCaret := Dialog.thickCaret;
prefs.caretPeriod := Dialog.caretPeriod;
prefs.scaleFactor := Dialog.scaleFactor;
prefs.colorTheme := Dialog.colorTheme;
prefs.defaultColor := Dialog.defaultColor;
prefs.windowBackground := Ports.background;
prefs.beep := Dialog.beep;
Dialog.GetDefaultFont(prefFName, prefFSize);
Dialog.GetDialogFont(prefDName, prefDSize, prefDStyle, prefDWght);
InitLanguage;
IF platformInitPrefDialog # NIL THEN
platformInitPrefDialog
END
END InitPrefDialog;
PROCEDURE OpenPrefDialog*;
VAR m, mPlatform: TextModels.Model; v: Views.View; c: Containers.Controller;
BEGIN
InitPrefDialog;
IF Dialog.language # Dialog.defaultLanguage THEN
v := Views.OldView(Files.dir.This("Std/Rsrc/"+Dialog.language), "Preferences.odc")
END;
IF v = NIL THEN
v := Views.OldView(Files.dir.This("Std/Rsrc"), "Preferences.odc")
END;
IF v # NIL THEN
WITH v: TextViews.View DO
m := v.ThisModel()
ELSE END
END;
IF (m # NIL) & (Dialog.platform = Dialog.windows) THEN
IF Dialog.language # Dialog.defaultLanguage THEN
v := Views.OldView(
Files.dir.This("Win/Rsrc/"+Dialog.language), "Preferences.odc")
END;
IF v = NIL THEN
v := Views.OldView(Files.dir.This("Win/Rsrc"), "Preferences.odc")
END;
WITH v: TextViews.View DO
mPlatform := v.ThisModel();
ELSE END;
IF (mPlatform # NIL) THEN
m.Insert(m.Length(), mPlatform, 0, mPlatform.Length())
END
END;
IF m # NIL THEN
v := TextViews.dir.New(m);
WITH v: Containers.View DO
c := v.ThisController();
IF c # NIL THEN
c.SetOpts(c.opts - {Containers.noFocus} + {Containers.noCaret, Containers.noSelection});
Open(v, "#Std:Preferences", NIL, "", NIL,
FALSE, TRUE, FALSE, FALSE, TRUE)
(* asTool, asAux, noResize, allowDuplicates, neverDirty *)
(* for some reason, asUax = TRUE => (wheel) scrolling enabled!,
~asAux => scrolling disabled! эта работа пока не завершена *)
END
END
ELSE
Log.String("can not find Preferences form neither Std nor Win subsystem"); Log.Ln;
END
END OpenPrefDialog;
(* printer dialogs *)
PROCEDURE SetPrintHook* (hook: PrintHook);
BEGIN
printHook := hook
END SetPrintHook;
PROCEDURE (hook: PrintHook) GetPage* (p: Printers.Printer; VAR w, h: INTEGER), NEW, ABSTRACT;
PROCEDURE (hook: PrintHook) PrintSetup*, NEW, ABSTRACT;
PROCEDURE (hook: PrintHook) PrintDialog* (
hasSelection: BOOLEAN; VAR from, to, copies: INTEGER; VAR selection: BOOLEAN
), NEW, ABSTRACT;
(* page setup previewer view *)
PROCEDURE (v: Preview) Restore (f: Views.Frame; l, t, r, b: INTEGER);
CONST scale = 16; rmm = Ports.mm DIV scale; size = 460 * rmm;
VAR u, w, h, x, y, uu: INTEGER;
BEGIN
u := f.unit;
IF Dialog.metricSystem THEN uu := 10 * rmm ELSE uu := Ports.inch DIV scale END;
w := setup.w DIV scale;
h := setup.h DIV scale;
x := (size - w) DIV 2;
y := (size - h) DIV 2;
l := SHORT(ENTIER(setup.left * uu));
t := SHORT(ENTIER(setup.top * uu));
r := SHORT(ENTIER(setup.right * uu));
b := SHORT(ENTIER(setup.bottom * uu));
f.DrawRect(x, y, x + w, y + h, Ports.fill, Ports.background);
f.DrawRect(x - u, y - u, x + w + u, y + h + u, 0, Ports.defaultColor);
IF setup.decorate THEN
IF t < 14 * rmm THEN t := 14 * rmm END;
f.DrawRect(x + l, y + 10 * rmm, x + l + 20 * rmm, y + 10 * rmm + u, Ports.fill, Ports.defaultColor);
f.DrawRect(x + w - r - 8 * rmm, y + 10 * rmm, x + w - r, y + 10 * rmm + u, Ports.fill, Ports.defaultColor)
END;
IF (w - r > l) & (h - b > t) THEN
f.DrawRect(x + l, y + t, x + w - r, y + h - b, 0, Ports.defaultColor)
END
END Restore;
PROCEDURE (v: Preview) HandleViewMsg (f: Views.Frame; VAR msg: Views.Message);
BEGIN
WITH msg: UpdateMsg DO
Views.Update(v, Views.keepFrames)
ELSE
END
END HandleViewMsg;
PROCEDURE Deposit*;
VAR v: Preview;
BEGIN
NEW(v); Views.Deposit(v)
END Deposit;
(* page setup dialog *)
PROCEDURE SetupNotify* (op, from, to: INTEGER);
VAR msg: UpdateMsg; t: INTEGER;
BEGIN
IF op = Dialog.changed THEN
IF setup.landscape # (setup.w > setup.h) THEN
t := setup.w; setup.w := setup.h; setup.h := t
END;
Views.Omnicast(msg);
Dialog.Update(setup)
END
END SetupNotify;
PROCEDURE PageSetupOk*;
VAR win: Windows.Window; w, h, l, t, r, b, uu, res_: INTEGER;
BEGIN
win := Windows.dir.Focus(Controllers.targetPath);
IF win # NIL THEN
IF Dialog.metricSystem THEN
uu := 10 * Ports.mm
ELSE
uu := Ports.inch
END;
w := setup.w; h := setup.h;
l := SHORT(ENTIER(setup.left * uu));
t := SHORT(ENTIER(setup.top * uu));
r := w - SHORT(ENTIER(setup.right * uu));
b := h - SHORT(ENTIER(setup.bottom * uu));
IF (0 <= l) & (l < r) & (r <= w) & (0 <= t) & (t < b) & (b <= h) THEN
win.doc.SetPage(w, h, l, t, r, b, setup.decorate);
Dialog.Call("StdCmds.CloseDialog", "", res_)
ELSE
Dialog.Beep
END
END
END PageSetupOk;
PROCEDURE InitPageSetup;
VAR win: Windows.Window; w, h, pw, ph, l, t, r, b, uu: INTEGER; p: Printers.Printer;
BEGIN
win := Windows.dir.Focus(Controllers.targetPath);
IF win # NIL THEN
IF Dialog.metricSystem THEN
uu := Ports.mm DIV 10
ELSE
uu := Ports.inch DIV 100
END;
win.doc.PollPage(w, h, l, t, r, b, setup.decorate);
p := Printers.dir.Current();
IF p # NIL THEN
printHook.GetPage(p, pw, ph);
IF (pw > ph) = (w > h) THEN
w := pw; h := ph
ELSE
w := ph; h := pw
END
END;
r := w - r; b := h - b;
setup.left := l DIV uu / 100;
setup.right := r DIV uu / 100;
setup.top := t DIV uu / 100;
setup.bottom := b DIV uu / 100;
setup.w := w; setup.h := h;
setup.hs := setup.right + setup.left;
setup.vs := setup.bottom + setup.top;
setup.landscape := w > h
END
END InitPageSetup;
PROCEDURE OpenPageSetup*;
VAR res_: INTEGER;
BEGIN
IF printHook # NIL THEN
InitPageSetup;
Dialog.Call("StdCmds.OpenToolDialog('Std/Rsrc/PageSetup', '#System:PageSetup')", "", res_)
END
END OpenPageSetup;
PROCEDURE PrintSetup*;
BEGIN
IF printHook # NIL THEN printHook.PrintSetup END
END PrintSetup;
PROCEDURE PrintDialog* (hasSelection: BOOLEAN; VAR from, to, copies: INTEGER; VAR selection: BOOLEAN);
BEGIN
IF printHook # NIL THEN
printHook.PrintDialog(hasSelection, from, to, copies, selection)
END
END PrintDialog;
(* Std Dialogs *)
PROCEDURE DefaultFontDialog*;
VAR tf: Fonts.Typeface; size, color, w: INTEGER; style: SET; set: BOOLEAN;
title: Dialog.String;
BEGIN
tf := prefFName;
size := prefFSize;
w := Fonts.normal;
style := {};
Dialog.MapString("#Std:Default font", title);
Dialog.GetFont(TRUE, tf, size, color, w, style, set, title);
IF set THEN
prefFName := tf; prefFSize := size;
Dialog.SetDefaultFont(prefFName, prefFSize);
END
END DefaultFontDialog;
PROCEDURE DialogsFontDialog*;
VAR tf: Fonts.Typeface; size, color, w: INTEGER;
style: SET; set: BOOLEAN; title: Dialog.String;
BEGIN
tf := prefDName;
size := prefDSize;
w := prefDWght;
style := prefDStyle;
Dialog.MapString("#Std:Dialog font", title);
Dialog.GetFont(TRUE, tf, size, color, w, style, set, title);
IF set THEN
prefDName := tf; prefDSize := size;
prefDStyle := style; prefDWght := w;
Dialog.SetDialogFont(prefDName, prefDSize, prefDStyle, prefDWght);
END
END DialogsFontDialog;
PROCEDURE ColorDialog*;
VAR set: BOOLEAN; p: Properties.StdProp; color: Ports.Color;
BEGIN
Properties.CollectStdProp(p);
IF ~(Properties.color IN p.known) THEN p.color.val := Ports.black END;
Dialog.GetColor(p.color.val, color, set);
IF set THEN
p.valid := {Properties.color};
p.color.val := color;
Properties.EmitProp(NIL, p)
END
END ColorDialog;
PROCEDURE FontDialog*;
(** open font dialog and set selection to choosen attributes **)
VAR set: BOOLEAN; p, p0: Properties.StdProp; title: Dialog.String;
BEGIN
Properties.CollectStdProp(p0);
IF (p0 # NIL) & (Properties.typeface IN p0.known) THEN
NEW(p);
p.typeface := p0.typeface$;
p.size := p0.size;
p.color.val := p0.color.val;
p.weight := p0.weight;
p.style := p0.style;
Dialog.MapString("#Std:Font", title);
Dialog.GetFont(TRUE, p.typeface, p.size, p.color.val, p.weight, p.style.val, set, title);
IF set THEN
p.valid := {Properties.typeface, Properties.style, Properties.weight, Properties.size, Properties.color};
p.style.mask := {Fonts.italic, Fonts.underline, Fonts.strikeout};
Properties.EmitProp(NIL, p)
END
END
END FontDialog;
PROCEDURE TypefaceDialog*;
(** open font dialog and set selection to choosen typeface **)
VAR set: BOOLEAN; p, p0: Properties.StdProp; title: Dialog.String;
BEGIN
Properties.CollectStdProp(p0);
IF (p0 # NIL) & (Properties.typeface IN p0.known) THEN
NEW(p);
p.typeface := p0.typeface$;
p.size := p0.size;
p.weight := p0.weight;
p.style := p0.style;
Dialog.MapString("#Std:Typeface", title);
Dialog.GetFont(FALSE, p.typeface, p.size, p.color.val, p.weight, p.style.val, set, title);
IF set THEN
p.valid := {Properties.typeface};
Properties.EmitProp(NIL, p)
END
END
END TypefaceDialog;
PROCEDURE SetViewHook* (hook: ViewHook);
BEGIN
IF hook = NIL THEN hook := stdViewHook END;
viewHook := hook; Views.SetViewHook(hook)
END SetViewHook;
PROCEDURE Init;
VAR b: BOOLEAN; p, res: INTEGER;
BEGIN
NEW(stdViewHook);
Views.SetViewHook(stdViewHook); viewHook := stdViewHook;
StdRegistry.ReadBool("noStatus", b, res);
Dialog.showsStatus := (res # 0) OR ~b;
StdRegistry.ReadBool("memStatus", b, res);
Dialog.memInStatus := (res = 0) & b;
StdRegistry.ReadBool("thickCaret", b, res);
IF res = 0 THEN Dialog.thickCaret := b END;
StdRegistry.ReadInt("caretPeriod", p, res);
IF (res = 0) & (p > 0) & (p <= 10000) THEN Dialog.caretPeriod := p END;
StdRegistry.ReadInt("colorTheme", p, res);
IF res = 0 THEN Dialog.colorTheme := p END;
StdRegistry.ReadInt("defaultColor", p, res);
IF res = 0 THEN Dialog.defaultColor := p END;
StdRegistry.ReadInt("windowBackground", p, res);
IF res = 0 THEN Ports.background := p END;
StdRegistry.ReadBool("beep", b, res);
IF res = 0 THEN Dialog.beep := b END;
END Init;
BEGIN
Init
END StdDialog.
| Std/Mod/Dialog.odc |
MODULE StdDocuments;
(**
project = "BlackBox 2.0, new module"
organization = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Contributors, Anton Dmitriev, Ivan Denisov, Ketmar Dark"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 20070326, bh, SetPage corrected
- 20070327, bh, SetOrientation calls added
- 20191201, AD, Document.GetBackground now returns Views.transparent
- 20230520, k8, scrollbar fixes
- 20240521, dia, prevent fall in DoRecalc
"
issues = "
- ...
"
**)
IMPORT
Files, Ports, Printers, Documents, Services, Windows,
Stores, Models, Views, Controllers, Properties,
Printing, Containers, StdScrollbars;
CONST
(** Controller.opts **)
pageWidth = Documents.pageWidth; pageHeight = Documents.pageHeight;
winWidth = Documents.winWidth; winHeight = Documents.winHeight;
forceRecalc = TRUE; (* for PROCEDURE DoRecalc *)
mm = Ports.mm;
defB = 8 * Ports.point; (* defB also used by HostWindows in DefBorders *)
scrollUnit = 16 * Ports.point;
resizingKey = "#System:Resizing";
pageSetupKey = "#System:PageSetup";
docTag = 6F4F4443H; docVersion = 0; modelVersion = 0;
minVersion = 0; maxModelVersion = 0;
maxDocVersion = 0; maxCtrlVersion = 0;
(* Constants for Document.frame.flags that indicate it ∈ to front or target path *)
front* = 20; target* = 21;
left* = TRUE; right* = ~left; (** Constants for Param.sbSide *)
center* = -1; (* possible value for l, t in PROCEDURE InsertOverlaid *)
(* Context.align *)
noalign* = 0; top* = 1; bottom* = 2;
(* OverlayProposal.op *)
show* = 0; hide* = 1; poll* = 2; pollFrame* = 3;
TYPE
Context* = POINTER TO ABSTRACT RECORD (Documents.Context)
l*, t*, w*, h*, (** bounding box, w = 0 => not restored (not Views.InstallFrame'd) *)
level*: INTEGER; (** z-ordering, passed into Views.InstallFrame *)
view*: Views.View;
END;
StdContext = POINTER TO EXTENSIBLE RECORD (Context)
next: StdContext;
model: StdModel;
align: INTEGER;
overlaid: BOOLEAN;
(* modal: BOOLEAN; *)
owner: Views.View; (* optional owner of an overlaid view, will receive msgs *)
par: ANYPTR;
END;
(* merge these types? *)
SBContext = POINTER TO RECORD (StdContext) END;
(* this type is for the sake of Consider'ing a StdScrollbars.Proposal *)
Directory* = POINTER TO ABSTRACT RECORD (Documents.Directory) END;
Model* = POINTER TO ABSTRACT RECORD (Containers.Model)
(** responsible for allocating and positioning auxiliary views *)
view: Views.View;
l, t, r, b: INTEGER; (* possibly r, b >= Views.infinite *) (* the box occupied by .view *)
(* l, t: constant (= defB) *)
(* r-l, b-t: invalid in some cases, use PollRect *)
doc-: Document; (* one-to-one relationship *)
(* parameters to .Recalc: *)
ocw-, och-, (* last obtained original's context w, h,*)
unit-: INTEGER; (* frame unit, (backup unit size, for situations when Recalc is requested while it's frame is not provided (i.e. when .Recalc is called from PollRect) *)
opts-: SET; (* and original's controllers opts *)
END;
Document* = POINTER TO RECORD (Documents.Document)
model: Model; (* one-to-one relationship *)
original: Document; (* original # NIL => d IS copy of original *)
pw, ph, pl, pt, pr, pb: INTEGER; (* invalid if original # NIL, use PollPage *)
decorate: BOOLEAN;
x, y: INTEGER; (* scroll state *)
clipper: RootContext; (* clipping box for doc's view in this ACTUAL (not original) document. This clipping box is different from the view's box obtained thru PollRect, 'cause in case of winWidth, winHeight options, the view's box depends on the ORIGINAL doc's context, not the ACTUAL doc's context. At the time, .clipper.view = NIL *)
prevW, prevH: INTEGER;
(* clipper: Clipper; (* clipping box for doc's view in this ACTUAL (not original) document. This clipping box is different from the view's box obtained thru PollRect, 'cause in case of winWidth, winHeight options, the view's box depends on the ORIGINAL doc's context, not the ACTUAL doc's context *) *)
END;
Clipper = POINTER TO RECORD (Views.View) END;
(** Wrapper that sets up clipping rect for root view *)
ClipperCtx = POINTER TO RECORD (Context)
model: Model
END;
RootContext = POINTER TO RECORD (Context)
model: Model
END;
SetRectOp = POINTER TO RECORD (Stores.Operation)
model: Model;
w, h: INTEGER
END;
SetPageOp = POINTER TO RECORD (Stores.Operation)
d: Document;
pw, ph, pl, pt, pr, pb: INTEGER;
decorate: BOOLEAN
END;
ReplaceViewOp = POINTER TO RECORD (Stores.Operation)
model: Model;
new: Views.View
END;
UpdateMsg = RECORD (Views.Message)
doc: Document
END;
Param* = POINTER TO RECORD
sbSide*: BOOLEAN; (** left = TRUE; right = FALSE *)
sbThickness*: Pixels; (** scrollbar thickness, in pixels *)
debug*: BOOLEAN;
InitDefaults-, Init-: PROCEDURE (par: ANYPTR)
END;
OverlayProposal* = RECORD (Models.Proposal)
op*,
x*, y*: INTEGER;
owner*, (* optional owner for .view, will receive some related msgs *)
view*: Views.View; (* view to be shown if .op = show *)
frame*: Views.Frame; (* valid iff .op = pollFrame; IN: .owner's frame OUT: overlay's frame *)
END;
UCs = INTEGER;
Pixels = INTEGER;
PollOptsMsg* = RECORD (Views.Message)
opts*: SET
END;
PanWindowPref* = RECORD (Properties.Preference) (* relocate? cf. TylerMenus, LinWindows*)
atLocation*: BOOLEAN;
x*, y*: INTEGER;
panWindow*: BOOLEAN (* callee => caller *)
END;
StdModel = POINTER TO RECORD (Model)
param: Param;
sbV, sbH: StdContext;
sbVv, sbHv: StdScrollbars.Scrollbar;
showV, showH: BOOLEAN;
aux: StdContext; (* linked list of aux views *)
END;
Controller = POINTER TO RECORD (Containers.Controller)
doc: Document;
model: StdModel;
overlaid: StdContext;
END;
StdDirectory = POINTER TO RECORD (Directory) END;
ResetBarAction = POINTER TO RECORD (Services.Action) END;
PollPointerMsg = RECORD (Views.Message)
x, y: INTEGER
END;
(** Used to poll current pointer position *)
RemoveOverlayMsg* = RECORD (Views.Message) END;
(** Informs the overlaid owner view of the fact the overlay is removed *)
Backdrop = POINTER TO RECORD (Views.View)
view: Views.View;
END;
BackdropContext = POINTER TO RECORD (Models.Context)
backdrop: Backdrop
END;
VAR
dir-, stdDir-: Directory;
param*: Param;
resetBar: ResetBarAction;
bar: StdContext;
par-: ANYPTR; (* optional parameter of currently activated pane *)
PROCEDURE (c: Context) Normalize* (): BOOLEAN; BEGIN RETURN TRUE END Normalize;
PROCEDURE (c: Context) GetSize* (OUT w, h: INTEGER), EXTENSIBLE;
BEGIN w := c.w; h := c.h
END GetSize;
(* Clipper *)
PROCEDURE (c: ClipperCtx) ThisModel (): Models.Model; BEGIN RETURN c.model END ThisModel;
PROCEDURE (c: ClipperCtx) ThisDoc (): Document; BEGIN RETURN c.model.doc END ThisDoc;
PROCEDURE (v: Clipper) Restore (f: Views.Frame; l, t, r, b: INTEGER);
VAR c: Models.Context; m: Model;
BEGIN
c := v.context;
WITH c: ClipperCtx DO
m := c.model;
Views.InstallFrame(f, m.view, m.l + m.doc.x, m.t + m.doc.y, 0, TRUE)
ELSE HALT(20)
END
END Restore;
PROCEDURE (v: Clipper) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View);
BEGIN
focus := v.context(ClipperCtx).model.view
END HandleCtrlMsg;
PROCEDURE (v: Clipper) HandlePropMsg (VAR msg: Properties.Message);
BEGIN
Views.HandlePropMsg(v.context(ClipperCtx).model.view, msg)
END HandlePropMsg;
(* Model *)
PROCEDURE (lo: Model) First* (): Context, NEW, ABSTRACT;
(** First aux view context for doc *)
PROCEDURE (lo: Model) Next* (c: Context): Context, NEW, ABSTRACT;
(** Linked list of contexts for aux views *)
PROCEDURE (m: Model) Recalc- (clipper: Context), NEW, ABSTRACT;
(** Recalculate aux views boxes for m. m.ocw, .och, .unit, .opts are parameters to Recalc, their valid values are guaranteed by the caller. clipper is the clipping rectangle for document's view: it may exclude the space occupied by tiled auxiliary views and is the box in which the view is placed. The view's rect (cf. PollRect, SetRect) is a rect inside clipper *)
PROCEDURE (m: Model) Internalize2- (VAR rd: Stores.Reader), NEW, EMPTY;
PROCEDURE (m: Model) Externalize2- (VAR wr: Stores.Writer), NEW, EMPTY;
PROCEDURE (m: Model) CopyFrom2- (source: Stores.Store), NEW, EMPTY;
PROCEDURE (m: Model) Internalize- (VAR rd: Stores.Reader);
VAR c: RootContext; thisVersion: INTEGER; l, t, r, b: INTEGER;
BEGIN
m.Internalize^(rd);
IF rd.cancelled THEN RETURN END;
rd.ReadVersion(minVersion, maxModelVersion, thisVersion);
IF rd.cancelled THEN RETURN END;
Views.ReadView(rd, m.view);
rd.ReadInt(l); rd.ReadInt(t); rd.ReadInt(r); rd.ReadInt(b);
m.l := defB; m.t := defB; m.r := defB + r - l; m.b := defB + b - t;
NEW(c); c.model := m; m.view.InitContext(c);
m.Internalize2(rd)
END Internalize;
PROCEDURE (m: Model) Externalize- (VAR wr: Stores.Writer);
BEGIN
ASSERT(m.doc.original = NIL, 100);
m.Externalize^(wr);
wr.WriteVersion(maxModelVersion);
Views.WriteView(wr, m.view);
wr.WriteInt(m.l); wr.WriteInt(m.t); wr.WriteInt(m.r); wr.WriteInt(m.b);
m.Externalize2(wr)
END Externalize;
PROCEDURE (m: Model) CopyFrom- (source: Stores.Store);
VAR c: RootContext;
BEGIN
WITH source: Model DO
m.view := Stores.CopyOf(source.view)(Views.View);
m.l := source.l; m.t := source.t; m.r := source.r; m.b := source.b;
NEW(c); c.model := m; m.view.InitContext(c);
m.CopyFrom2(source)
END
END CopyFrom;
PROCEDURE (m: Model) InitFrom- (source: Containers.Model);
VAR c: RootContext;
BEGIN
WITH source: Model DO
m.view := Stores.CopyOf(source.view)(Views.View);
m.l := source.l; m.t := source.t; m.r := source.r; m.b := source.b;
NEW(c); c.model := m; m.view.InitContext(c)
END
END InitFrom;
PROCEDURE (m: Model) GetEmbeddingLimits* (OUT minW, maxW, minH, maxH: INTEGER);
BEGIN
minW := 5 * mm; minH := 5 * mm;
maxW := MAX(INTEGER) DIV 2; maxH := MAX(INTEGER) DIV 2
END GetEmbeddingLimits;
PROCEDURE (m: Model) ReplaceView* (old, new: Views.View);
VAR con: Models.Context; op: ReplaceViewOp;
BEGIN
ASSERT(old # NIL, 20); con := old.context;
ASSERT(con # NIL, 21); ASSERT(con.ThisModel() = m, 22);
ASSERT(new # NIL, 23);
ASSERT((new.context = NIL) OR (new.context = con), 24);
IF new # old THEN
IF new.context = NIL THEN new.InitContext(con) END;
Stores.Join(m, new);
NEW(op); op.model := m; op.new := new;
Models.Do(m, "#System:ReplaceView", op)
END
END ReplaceView;
PROCEDURE (c: StdContext) ThisModel (): Model;
BEGIN RETURN c.model
END ThisModel;
PROCEDURE (c: StdContext) ThisDoc (): Document;
BEGIN RETURN c.model.doc
END ThisDoc;
(* StdModel *)
(* shouldn't First and .Next be replaced with Containers.Controller.GetFirst, .GetNext? *)
PROCEDURE (m: StdModel) First (): StdContext;
VAR res: StdContext;
BEGIN
res := m.aux;
IF res = NIL THEN res := m.doc.ThisController()(Controller).overlaid END;
RETURN res
END First;
PROCEDURE (m: StdModel) Next (c: Context): StdContext;
VAR ctx, overlaid, res: StdContext; ctrl: Containers.Controller;
BEGIN
ctrl := m.doc.ThisController();
WITH ctrl: Controller DO
overlaid := ctrl.overlaid;
ctx := m.aux; WHILE (ctx # NIL) & (ctx # overlaid) DO ctx := ctx.next END;
IF ctx = overlaid THEN overlaid := NIL END
(* Post: overlaid ∉ m.aux *)
ELSE HALT(21)
END;
IF (c = overlaid) & (overlaid # NIL) THEN (* nothing *)
ELSE
WITH c: StdContext DO res := c.next; IF res = NIL THEN res := overlaid END
ELSE HALT(20)
END
END;
RETURN res
END Next;
PROCEDURE SBLeft (wid, hei, thickness: UCs; validV, validH: BOOLEAN; clipper: Context; v, h: StdContext);
VAR a: UCs; (** scrollbar on the left *)
BEGIN
v.l := 0; v.t := 0; clipper.t := 0; h.l := 0;
IF validV THEN a := MIN(wid, thickness) ELSE a := 0 END; v.w := a;
clipper.w := wid - a; clipper.l := a;
IF validH THEN a := MIN(hei, thickness) ELSE a := 0 END; h.h := a;
h.t := hei - a; clipper.h := hei - a;
v.h := hei - a;
h.w := wid;
END SBLeft;
PROCEDURE SBRight (wid, hei, thickness: UCs; validV, validH: BOOLEAN; clipper: Context; v, h: StdContext);
VAR a: UCs; (** scrollbar on the right *)
BEGIN
clipper.l := 0; clipper.t := 0; v.t := 0; h.l := 0;
IF validV THEN a := MIN(wid, thickness) ELSE a := 0 END; v.w := a;
v.l := wid - a; clipper.w := wid - a;
IF validH THEN a := MIN(hei, thickness) ELSE a := 0 END; h.h := a;
h.t := hei - a; clipper.h := hei - a;
v.h := hei;
h.w := wid - v.w;
END SBRight;
PROCEDURE PreferredSize (v: Views.View; m: StdModel; OUT w, h: INTEGER);
VAR bounds: Properties.BoundsPref; wl, wh, hl, hh: INTEGER;
BEGIN
bounds.w := Views.undefined; bounds.h := Views.undefined;
Views.HandlePropMsg(v, bounds);
IF (bounds.w > Views.undefined) & (bounds.h > Views.undefined) THEN
w := bounds.w; h := bounds.h
ELSE
m.GetEmbeddingLimits(wl, wh, hl, hh);
w := Views.undefined; h := Views.undefined;
Properties.PreferredSize(v, wl, wh, hl, hh, 50 * Ports.mm, 50 * Ports.mm, w, h)
END
END PreferredSize;
PROCEDURE (m: StdModel) Recalc (clipper: Context);
VAR _, thickness, aw, ah, l, t, r, b: UCs; c: StdContext;
BEGIN
IF m.doc.context = NIL THEN (* window initialization branch *)
m.doc.PollRect(l, t, r, b); clipper.l := 0; clipper.t := 0; clipper.w := r; clipper.h := b
ELSE m.doc.context.GetSize(aw, ah);
IF m.unit = 0 THEN thickness := 0
ELSE thickness := m.param.sbThickness * (Ports.point - Ports.point MOD m.unit)
END;
IF (aw = 0) OR (ah = 0) THEN
ELSIF m.param.sbSide = left THEN
SBLeft(aw, ah, thickness, m.showV, m.showH, clipper, m.sbV, m.sbH)
ELSE
SBRight(aw, ah, thickness, m.showV, m.showH, clipper, m.sbV, m.sbH)
END
END;
(* At this point, the scrollbars and clipper have been set *)
c := m.aux;
WHILE c # NIL DO
IF (c.align = top) OR (c.align = bottom) THEN
PreferredSize(c.view, m, _, c.h);
c.l := clipper.l; c.w := clipper.w;
IF c.align = top THEN c.t := clipper.t; INC(clipper.t, c.h); DEC(clipper.h, c.h)
ELSE DEC(clipper.h, c.h); c.t := clipper.t + clipper.h
END
END;
c := c.next
END;
(* At this point, all aligned auxiliary views have been set *)
(* The .overlaid view is set when handling OverlayProposal -> DoInsertOverlaid *)
END Recalc;
PROCEDURE GetSection (f: Views.Frame; focus, vertical: BOOLEAN; VAR size, sect, pos: INTEGER; VAR valid: BOOLEAN);
VAR msg: Controllers.PollSectionMsg;
BEGIN (* portable *)
msg.focus := focus; msg.vertical := vertical;
msg.wholeSize := 1;
msg.partSize := 0; msg.partPos := 0;
msg.valid := FALSE; msg.done := FALSE;
Views.ForwardCtrlMsg(f, msg);
IF msg.done THEN
size := msg.wholeSize; sect := msg.partSize; pos := msg.partPos;
IF size < 0 THEN size := 0 END;
IF sect < 0 THEN sect := 0 ELSIF sect > size THEN sect := size END;
IF pos > size - sect THEN pos := size - sect END;
IF pos < 0 THEN pos := 0 END
ELSE size := 1; sect := 0; pos := 0
END;
valid := msg.valid
END GetSection;
PROCEDURE UpdateScrollbar (f: Views.Frame; m: StdModel; vertical, focus: BOOLEAN; OUT show, upd: BOOLEAN);
VAR size, sect, pos: INTEGER; sb: StdScrollbars.Scrollbar;
BEGIN
IF vertical THEN sb := m.sbVv ELSE sb := m.sbHv END;
GetSection(f, focus, vertical, size, sect, pos, show);
IF show THEN (* ? *) IF size = 0 THEN size := 1 END
ELSIF ~focus THEN GetSection(f, FALSE, vertical, size, sect, pos, show)
END;
upd := FALSE;
IF show THEN
IF sb.wholeSize # size THEN sb.wholeSize := size; upd := TRUE END;
IF sb.partSize # sect THEN sb.partSize := sect; upd := TRUE END;
IF sb.partPos # pos THEN sb.partPos := pos; upd := TRUE END
END
END UpdateScrollbar;
PROCEDURE ^ Recalc* (d: Document; unit: INTEGER);
PROCEDURE (m: Model) UpdateScrollbars- (f: Views.Frame; opts: SET), NEW, EMPTY;
PROCEDURE (m: StdModel) UpdateScrollbars (f: Views.Frame; opts: SET);
VAR recalc, updV, updH, showV, showH: BOOLEAN; flags: SET;
BEGIN
WITH f: Views.RootFrame DO flags := f.flags ELSE flags := {} END;
showV := ~(Windows.noVScroll IN flags); showH := ~(Windows.noHScroll IN flags);
IF showV THEN
UpdateScrollbar(f, m, StdScrollbars.vertical, FALSE, showV, updV)
END;
IF showH THEN
UpdateScrollbar(f, m, ~StdScrollbars.vertical, FALSE, showH, updH)
END;
recalc := (m.showV # showV) OR (m.showH # showH);
m.showV := showV; m.showH := showH;
IF recalc THEN
Recalc(m.doc, f.unit)
ELSE
IF updV THEN Views.Update(m.sbVv, Views.keepFrames) END;
IF updH THEN Views.Update(m.sbHv, Views.keepFrames) END
END
END UpdateScrollbars;
PROCEDURE UpdateScrollbars* (f: Views.Frame);
VAR recalc, updV, updH, showV, showH: BOOLEAN; opts: SET; d: Views.View; m: Model;
BEGIN ASSERT(f # NIL, 20);
(* if Controllers.modify IN opts THEN scrollbars should show doc's proper scroll state rather than it'f focus view's scroll state *)
IF f.view # NIL THEN
d := f.view;
WITH d: Document DO
d.model.UpdateScrollbars(f, d.ThisController().opts)
ELSE
HALT(21)
END
END
END UpdateScrollbars;
(* operations *)
PROCEDURE (op: SetRectOp) Do;
VAR m: Model; w, h: INTEGER; upd: UpdateMsg;
BEGIN
m := op.model;
w := m.r - m.l; h := m.b - m.t;
m.r := m.l + op.w; m.b := m.t + op.h;
op.w := w; op.h := h;
IF m.doc.context # NIL THEN
upd.doc := m.doc;
Views.Domaincast(m.doc.Domain(), upd)
END
END Do;
PROCEDURE (op: SetPageOp) Do;
VAR d: Document; pw, ph, pl, pt, pr, pb: INTEGER; decorate: BOOLEAN; upd: UpdateMsg;
BEGIN
d := op.d;
pw := d.pw; ph := d.ph; pl := d.pl; pt := d.pt; pr := d.pr; pb := d.pb;
decorate := d.decorate;
d.pw := op.pw; d.ph := op.ph; d.pl := op.pl; d.pt := op.pt; d.pr := op.pr; d.pb := op.pb;
d.decorate := op.decorate;
op.pw := pw; op.ph := ph; op.pl := pl; op.pt := pt; op.pr := pr; op.pb := pb;
op.decorate := decorate;
IF d.context # NIL THEN
upd.doc := d;
Views.Domaincast(d.Domain(), upd)
END
END Do;
PROCEDURE (op: ReplaceViewOp) Do;
VAR new: Views.View; upd: UpdateMsg;
BEGIN
new := op.new; op.new := op.model.view; op.model.view := new;
upd.doc := op.model.doc;
IF upd.doc.context # NIL THEN
Views.Domaincast(upd.doc.Domain(), upd)
END
END Do;
(* support for Document paging *)
PROCEDURE HasFocus (v: Views.View; f: Views.Frame): BOOLEAN;
VAR focus: Views.View; dummy: Controllers.PollFocusMsg;
BEGIN
focus := NIL; dummy.focus := NIL;
v.HandleCtrlMsg(f, dummy, focus);
RETURN focus # NIL
END HasFocus;
PROCEDURE ScrollDoc (v: Document; x, y: INTEGER);
VAR xShift, yShift: INTEGER;
BEGIN
IF (x # v.x) OR (y # v.y) THEN
xShift := x - v.x; yShift := y - v.y;
v.x := x; v.y := y;
Views.Scroll(v, xShift, yShift)
END
END ScrollDoc;
PROCEDURE GetOtherSBSize (v: Document; vert: BOOLEAN): UCs;
VAR
res, w, h: UCs;
m: StdModel;
BEGIN ASSERT(v # NIL, 20);
res := 0;
IF v.model IS StdModel THEN
m := v.model(StdModel);
IF vert & m.showH THEN ASSERT(m.sbHv # NIL, 100);
m.sbHv.context.GetSize(w, h);
res := MAX(0, h)
ELSIF ~vert & m.showV THEN ASSERT(m.sbVv # NIL, 101);
m.sbVv.context.GetSize(w, h);
res := MAX(0, w)
END
END;
RETURN res
END GetOtherSBSize;
PROCEDURE CalcScrollParams (d: Document; unit: UCs; vert: BOOLEAN; OUT p, ps, vs, sz: INTEGER);
VAR w, h, l, t, r, b, sbsize: UCs;
BEGIN ASSERT(d # NIL, 20);
d.PollRect(l, t, r, b);
d.context.GetSize(w, h);
IF vert THEN
p := -d.y;
ps := h;
vs := b + t;
sz := b - t
ELSE
p := -d.x;
ps := w;
vs := r + l;
sz := r - l
END;
sbsize := GetOtherSBSize(d, vert);
INC(vs, sbsize);
INC(sz, sbsize)
END CalcScrollParams;
PROCEDURE PollSection (v: Document; f: Views.Frame; VAR msg: Controllers.PollSectionMsg);
VAR mv: Views.View; g: Views.Frame;
p, vs, ps, ws, sz: INTEGER;
c: Containers.Controller;
BEGIN
IF Windows.isTool IN f(Views.RootFrame).flags THEN
(* novelty: docs open in tool windows show scrollers in case doc's proper view won't fit in the size allowed for it, and DO NOT show scrollers for embedded views *)
ELSE
mv := v.model.view;
g := Views.ThisFrame(f, mv);
c := v.ThisController();
IF c.Singleton() # NIL THEN g := NIL END;
IF g # NIL THEN Views.ForwardCtrlMsg(g, msg) END;
IF (g = NIL) OR ~msg.done & (~msg.focus OR ~HasFocus(mv, g)) THEN
CalcScrollParams(v, f.unit, msg.vertical, p, ps, vs, sz);
IF ps > vs THEN ps := vs END;
ws := vs - ps; (* normalized scroll state *)
IF p > ws THEN
(* Scroll position normalization: PollSection is called by scrollbar update mechanism; if the document discovers itself in a new size (after window resize), it tries to 'normalize' it's scroll position, as much as possible - i.e. return itself to 0,0 if it had beed scrolled off 0,0 before *)
p := ws;
IF msg.vertical THEN
ScrollDoc(v, v.x, -p)
ELSE
ScrollDoc(v, -p, v.y)
END
END;
msg.wholeSize := vs;
msg.partSize := ps;
msg.partPos := p;
msg.valid := ws > Ports.point
END;
END;
msg.done := TRUE
END PollSection;
PROCEDURE Scroll (v: Document; f: Views.Frame; VAR msg: Controllers.ScrollMsg);
VAR mv: Views.View; g: Views.Frame; vs, ps, ws, p, sz: INTEGER;
c: Containers.Controller; was: BOOLEAN;
BEGIN
mv := v.model.view;
g := Views.ThisFrame(f, mv);
c := v.ThisController();
IF c.Singleton() # NIL THEN g := NIL END;
IF g # NIL THEN
was := msg.focus;
IF Windows.isTool IN f(Views.RootFrame).flags THEN msg.focus := TRUE END;
Views.ForwardCtrlMsg(g, msg);
msg.focus := was
END;
IF (g = NIL) OR ~msg.done OR ~msg.focus OR ~HasFocus(mv, g) THEN
CalcScrollParams(v, f.unit, msg.vertical, p, ps, vs, sz);
IF sz - ps > f.dot * 2 THEN
(* adimetrius: follwing are weird calculations that i don't understand... *)
ws := vs - ps;
CASE msg.op OF
Controllers.decLine: p := MAX(0, p - scrollUnit)
| Controllers.incLine: p := MIN(ws, p + scrollUnit)
| Controllers.decPage: p := MAX(0, p - ps + scrollUnit)
| Controllers.incPage: p := MIN(ws, p + ps - scrollUnit)
| Controllers.gotoPos: p := MAX(0, MIN(ws, msg.pos))
ELSE
END;
IF msg.vertical THEN ScrollDoc(v, v.x, -p)
ELSE ScrollDoc(v, -p, v.y)
END
END;
msg.done := TRUE
END;
(* msg.done := TRUE *)
END Scroll;
PROCEDURE Page (d: Document; f: Views.Frame;
VAR msg: Controllers.PageMsg);
VAR g: Views.Frame;
BEGIN
g := Views.ThisFrame(f, d.model.view);
IF g # NIL THEN Views.ForwardCtrlMsg(g, msg) END
END Page;
(* Document *)
PROCEDURE (d: Document) Internalize2- (VAR rd: Stores.Reader);
VAR thisVersion: INTEGER; c: Containers.Controller; opts: SET;
BEGIN
d.Internalize2^(rd);
IF rd.cancelled THEN RETURN END;
rd.ReadVersion(minVersion, maxDocVersion, thisVersion);
IF rd.cancelled THEN RETURN END;
rd.ReadInt(d.pw); rd.ReadInt(d.ph);
rd.ReadInt(d.pl); rd.ReadInt(d.pt); rd.ReadInt(d.pr); rd.ReadInt(d.pb);
rd.ReadBool(d.decorate);
NEW(d.clipper);
(* change infinite height to "fit to window" *)
c := d.ThisController();
IF (c # NIL) & (d.model.b >= 29000 * mm) & (c.opts * {winHeight, pageHeight} = {}) THEN
opts := { winHeight }
ELSE opts := {}
END;
c.SetOpts(c.opts + opts - {Containers.noSelection});
d.x := 0; d.y := 0;
Stores.InitDomain(d);
Recalc(d, 0)
END Internalize2;
PROCEDURE (d: Document) Externalize2- (VAR wr: Stores.Writer);
BEGIN
ASSERT(d.original = NIL, 100);
d.Externalize2^(wr);
wr.WriteVersion(maxDocVersion);
wr.WriteInt(d.pw); wr.WriteInt(d.ph);
wr.WriteInt(d.pl); wr.WriteInt(d.pt); wr.WriteInt(d.pr); wr.WriteInt(d.pb);
wr.WriteBool(d.decorate)
END Externalize2;
PROCEDURE (d: Document) CopyFromModelView2- (source: Views.View; model: Models.Model);
BEGIN
WITH source: Document DO
d.pw := source.pw; d.ph := source.ph;
d.pl := source.pl; d.pt := source.pt; d.pr := source.pr; d.pb := source.pb;
d.decorate := source.decorate;
NEW(d.clipper)
END
END CopyFromModelView2;
PROCEDURE (d: Document) AcceptableModel- (m: Containers.Model): BOOLEAN;
BEGIN
RETURN m IS Model
END AcceptableModel;
PROCEDURE (d: Document) InitModel2- (m: Containers.Model);
BEGIN
ASSERT((d.model = NIL) OR (d.model = m), 20);
ASSERT(m IS Model, 23);
WITH m: Model DO d.model := m; m.doc := d END
END InitModel2;
PROCEDURE DoRecalc (d: Document; unit: INTEGER; force: BOOLEAN);
(** Check if recalc is necessary and, if so, perform it *)
VAR w_, h_, ww, wh, pw, ph, l, t, r, b, w, h: INTEGER; opts: SET; org: Documents.Document;
c: Containers.Controller; m: Model; decorate_: BOOLEAN;
curCL, curCT, curCW, curCH: INTEGER;
uu: INTEGER;
BEGIN
org := d.original; IF org = NIL THEN org := d END;
IF org.context # NIL THEN org.context.GetSize(w, h) ELSE w := 0; h := 0 END;
c := org.ThisController();
IF c = NIL THEN opts := {}
ELSE opts := c.opts * { pageWidth, pageHeight, winWidth, winHeight }
END;
m := d.model;
IF force OR (m.ocw # w) OR (m.och # h) OR (opts # m.opts) OR (unit # 0) & (unit # m.unit) THEN
IF unit # 0 THEN m.unit := unit END; m.ocw := w; m.och := h; m.opts := opts;
m.Recalc(d.clipper);
curCL := d.clipper.l; curCT := d.clipper.t;
curCW := d.clipper.w; curCH := d.clipper.h;
(* adapted from PollRect *)
WITH org: Document DO pw := org.pr - org.pl; ph := org.pb - org.pt;
w := org.model.r - org.model.l; h := org.model.b - org.model.t
ELSE org.PollPage(w_, h_, l, t, r, b, decorate_); pw := r - l; ph := b - t;
org.PollRect(l, t, r, b); w := r - l; h := b - t
END;
l := d.model.l; t := d.model.t;
IF d.context = NIL THEN ww := 0; wh := 0
ELSIF d.context IS Documents.PrinterContext THEN ww := pw; wh := ph
ELSE
INC(l, curCL); INC(t, curCT);
ww := curCW - 2 * d.model.l; wh := curCH - 2 * d.model.t (* doc border *)
END;
IF pageWidth IN m.opts THEN r := l + pw
ELSIF winWidth IN m.opts THEN
IF ww > 0 THEN r := l + ww ELSE r := d.model.r END
ELSE r := l + w
END;
IF pageHeight IN m.opts THEN b := t + ph
ELSIF winHeight IN m.opts THEN
IF wh > 0 THEN b := t + wh ELSE b := d.model.b END
ELSE b := t + h
END;
IF r <= l THEN r := l + 1 END;
IF b <= t THEN b := t + 1 END;
m.l := l - curCL; m.t := t - curCT; m.r := r - curCL; m.b := b - curCT;
Views.Update(d, Views.keepFrames);
END
END DoRecalc;
PROCEDURE Recalc* (d: Document; unit: INTEGER);
BEGIN DoRecalc(d, unit, forceRecalc)
END Recalc;
PROCEDURE (d: Document) PollRect* (OUT l, t, r, b: INTEGER);
BEGIN
DoRecalc(d, 0, ~forceRecalc);
l := (* d.clipper.l + *) d.model.l; t := (* d.clipper.t + *) d.model.t;
r := (* d.clipper.l + *) d.model.r; b := (* d.clipper.t + *) d.model.b
END PollRect;
PROCEDURE (d: Document) PollPage* (OUT w, h, l, t, r, b: INTEGER; OUT decorate: BOOLEAN);
VAR doc: Document;
BEGIN
IF d.original = NIL THEN doc := d ELSE doc := d.original END;
w := doc.pw; h := doc.ph;
l := doc.pl; t := doc.pt; r := doc.pr; b := doc.pb;
decorate := doc.decorate
END PollPage;
PROCEDURE (d: Document) DocCopyOf* (v: Views.View): Documents.Document;
VAR c0, c1: Containers.Controller; u: Views.View;
new: Documents.Document; w, h: INTEGER;
BEGIN
ASSERT(v # NIL, 20);
ASSERT(~(v IS Document), 21);
ASSERT(d.Domain() = v.Domain(), 22);
ASSERT(d.Domain() # NIL, 23);
Views.BeginModification(3, v);
u := Views.CopyOf(v, Views.shallow);
v.context.GetSize(w, h);
new := dir.New(u, w, h);
WITH new: Document DO
IF d.original # NIL THEN
new.original := d.original
ELSE
new.original := d
END
END;
c0 := d.ThisController();
c1 := new.ThisController();
c1.SetOpts(c0.opts);
Views.EndModification(3, v);
RETURN new
END DocCopyOf;
PROCEDURE (d: Document) Restore* (f: Views.Frame; l, t, r, b: INTEGER);
VAR
c: Containers.Controller; m: Model; con: Models.Context; s: Views.View; ctx: Context;
dw, dh: INTEGER;
BEGIN
m := d.model; con := d.context;
(* k8: we need to recalc if document size was changed. fixes bug with scrollbars in subwindows. *)
d.context.GetSize(dw, dh);
IF (m.unit = 0) OR (d.prevW # dw) OR (d.prevH # dh) THEN
DoRecalc(d, f.unit, forceRecalc)
END;
d.prevW := dw; d.prevH := dh;
WITH con: Documents.PrinterContext DO
IF con.param.page.alternate & ~ODD(con.param.page.first + Printing.Current()) THEN
Views.InstallFrame(f, m.view, con.pw - con.r, con.t, 0, FALSE)
ELSE
Views.InstallFrame(f, m.view, con.l, con.t, 0, FALSE)
END
ELSE
c := d.ThisController(); s := c.Singleton();
IF param.debug THEN
f.DrawRect(d.clipper.l, d.clipper.t, d.clipper.l + d.clipper.w, d.clipper.t + d.clipper.h, 0, Ports.red);
END;
d.GetRect(f, m.view, l, t, r, b);
Views.InstallFrame(f, m.view, l, t, 0, s = NIL);
ctx := d.model.First();
WHILE ctx # NIL DO
Views.InstallFrame(f, ctx.view, ctx.l, ctx.t, 0, FALSE);
ctx := m.Next(ctx)
END;
END
END Restore;
PROCEDURE (d: Document) GetRect* (f_: Views.Frame; view: Views.View; OUT l, t, r, b: INTEGER);
VAR c: Models.Context;
BEGIN
ASSERT(view # NIL, 20); c := view.context; ASSERT(c # NIL, 21);
IF view = d.model.view THEN
d.PollRect(l, t, r, b);
INC(l, d.clipper.l); INC(t, d.clipper.t);
INC(r, d.clipper.l); INC(b, d.clipper.t);
INC(l, d.x); INC(t, d.y); INC(r, d.x); INC(b, d.y)
ELSE HALT(126)
END
END GetRect;
PROCEDURE (d: Document) SetView* (view: Views.View; w, h: INTEGER);
CONST
wA4 = 210 * mm; hA4 = 296 * mm; (* A4 default paper size *)
lm = 20 * mm; tm = 20 * mm; rm = 20 * mm; bm = 20 * mm;
VAR m: Model; c: RootContext; prt: Printers.Printer;
ctrl: Containers.Controller; opts: SET; rp: Properties.ResizePref;
u, minW, maxW, minH, maxH, defW, defH, dw, dh, pw, ph,
pageW, pageH, paperW, paperH, leftM, topM, rightM, botM: INTEGER;
l, t, r, b: INTEGER; port: Ports.Port;
BEGIN
ASSERT(view # NIL, 20); ASSERT(~(view IS Document), 21);
ASSERT(d.original = NIL, 100);
m := d.model;
NEW(c); c.model := m; view.InitContext(c);
ASSERT(view.context = c, 60 (* make sure view accepted c *) );
IF d.context # NIL THEN Stores.Join(d, view) END;
IF Printers.dir # NIL THEN prt := Printers.dir.Current() ELSE prt := NIL END;
IF prt # NIL THEN
prt.SetOrientation(FALSE);
port := prt.ThisPort(); prt.GetRect(l, t, r, b);
port.GetSize(pw, ph); u := port.unit;
paperW := r - l; paperH := b - t;
pageW := paperW - lm - rm; pageH := paperH - tm - bm;
leftM := lm; topM := tm; rightM := rm; botM := bm;
IF pageW > pw * u THEN pageW := pw * u END;
IF pageH > ph * u THEN pageH := ph * u END;
IF leftM + l < 0 THEN dw := -(leftM + l)
ELSIF paperW - rightM + l > pw * u THEN dw := pw * u - (paperW - rightM + l)
ELSE dw := 0
END;
IF topM + t < 0 THEN dh := -(topM + t)
ELSIF paperH - botM + t > ph * u THEN dh := ph * u - (paperH - botM + t)
ELSE dh := 0
END;
INC(leftM, dw); INC(topM, dh); INC(rightM, dw); INC(botM, dh)
ELSE
paperW := wA4; paperH := hA4;
pageW := paperW - lm - rm; pageH := paperH - tm - bm;
leftM := lm; topM := tm; rightM := rm; botM := bm
END;
m.GetEmbeddingLimits(minW, maxW, minH, maxH);
defW := MAX(minW, pageW - m.l - defB);
defH := MAX(minH, pageH - m.t - defB);
Properties.PreferredSize(view, minW, maxW, minH, maxH, defW, defH, w, h);
opts := {}; rp.fixed := FALSE;
rp.horFitToPage := FALSE;
rp.verFitToPage := FALSE;
rp.horFitToWin := FALSE;
rp.verFitToWin := FALSE;
Views.HandlePropMsg(view, rp);
IF rp.horFitToPage THEN INCL(opts, pageWidth)
ELSIF rp.horFitToWin THEN INCL(opts, winWidth)
END;
IF rp.verFitToPage THEN INCL(opts, pageHeight)
ELSIF rp.verFitToWin THEN INCL(opts, winHeight)
END;
Views.BeginModification(Views.notUndoable, d);
m.view := view; d.x := 0; d.y := 0;
ctrl := d.ThisController();
ctrl.SetOpts(ctrl.opts - {pageWidth..winHeight});
d.SetPage(paperW, paperH, leftM, topM, paperW - rightM, paperH - botM, Documents.plain);
ASSERT(w > 0, 100); ASSERT(h > 0, 101);
d.SetRect(m.l, m.t, m.l + w, m.t + h);
ctrl.SetOpts(ctrl.opts + opts);
Views.EndModification(Views.notUndoable, d);
Stores.Join(d, view);
Views.Update(d, Views.rebuildFrames) (* Recalc? *)
END SetView;
PROCEDURE (d: Document) ThisView* (): Views.View;
BEGIN
RETURN d.model.view
END ThisView;
PROCEDURE (d: Document) OriginalView* (): Views.View;
BEGIN
IF d.original = NIL THEN RETURN d.model.view
ELSE RETURN d.original.model.view
END
END OriginalView;
PROCEDURE (d: Document) SetRect* (l, t, r, b: INTEGER);
VAR m: Model; op: SetRectOp; c: Containers.Controller; w, h: INTEGER;
BEGIN
ASSERT(l < r, 22); ASSERT(t < b, 25);
m := d.model;
IF (m.l # l) OR (m.t # t) THEN
m.r := l + m.r - m.l; m.l := l;
m.b := t + m.b - m.t; m.t := t
END;
IF d.original # NIL THEN m := d.original.model END;
c := d.ThisController(); w := r - l; h := b - t;
IF (pageWidth IN c.opts) OR (winWidth IN c.opts) THEN w := m.r - m.l END;
IF (pageHeight IN c.opts) OR (winHeight IN c.opts) THEN h := m.b - m.t END;
IF (w # m.r - m.l) OR (h # m.b - m.t) THEN
NEW(op); op.model := m; op.w:= w; op.h := h;
Views.Do(d, resizingKey, op)
END
END SetRect;
PROCEDURE (d: Document) SetPage* (pw, ph, pl, pt, pr, pb: INTEGER; decorate: BOOLEAN);
VAR op: SetPageOp; doc: Document;
BEGIN
IF d.original = NIL THEN doc := d ELSE doc := d.original END;
IF (doc.pw # pw) OR (doc.ph # ph) OR (doc.decorate # decorate)
OR (doc.pl # pl) OR (doc.pt # pt) OR (doc.pr # pr) OR (doc.pb # pb) THEN
ASSERT(0 <= pw, 20);
ASSERT(0 <= ph, 22);
ASSERT(0 <= pl, 24); ASSERT(pl < pr, 25); ASSERT(pr <= pw, 26);
ASSERT(0 <= pt, 27); ASSERT(pt < pb, 28); ASSERT(pb <= ph, 29);
NEW(op);
op.d := doc;
op.pw := pw; op.ph := ph; op.pl := pl; op.pt := pt; op.pr := pr; op.pb := pb;
op.decorate := decorate;
Views.Do(doc, pageSetupKey, op)
END
END SetPage;
PROCEDURE (d: Document) HandleViewMsg2- (f: Views.Frame; VAR msg: Views.Message);
BEGIN
WITH msg: UpdateMsg DO
IF (msg.doc = d) OR (msg.doc = d.original) THEN
DoRecalc(d, 0, ~forceRecalc)
END
| msg: PollOptsMsg DO
WITH f: Views.RootFrame DO
msg.opts := f.flags
ELSE END
ELSE
END
END HandleViewMsg2;
PROCEDURE (d: Document) HandleCtrlMsg2- (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View);
VAR
smsg: Controllers.ScrollMsg;
g: Views.Frame;
m: StdModel;
dw, dh, w, h: UCs;
sendScroll: BOOLEAN;
BEGIN
WITH f: Views.RootFrame DO
WITH msg: Controllers.PollSectionMsg DO
PollSection(d, f, msg); focus := NIL
| msg: Controllers.ScrollMsg DO
Scroll(d, f, msg); focus := NIL
| msg: Controllers.PageMsg DO
Page(d, f, msg); focus := NIL
| msg: Controllers.WheelMsg DO
d.context.GetSize(dw, dh);
IF d.model IS StdModel THEN
m := d.model(StdModel);
smsg.focus := FALSE; smsg.op := msg.op;
smsg.pos := 0; smsg.done := FALSE; sendScroll := FALSE;
IF m.showV & (m.sbVv # NIL) & (msg.y >= 0) & (msg.y < dh) THEN
m.sbVv.context.GetSize(w, h);
IF (m.param.sbSide = left) & (msg.x >= 0) & (msg.x < w) OR
(m.param.sbSide = ~left) & (msg.x >= dw - w) & (msg.x < dw)
THEN
smsg.vertical := TRUE;
sendScroll := TRUE
END
END;
IF ~sendScroll & m.showH & (m.sbHv # NIL) THEN
m.sbHv.context.GetSize(w, h);
IF (msg.x >= 0) & (msg.x < dw) & (msg.y >= dh - h) & (msg.y < dh) THEN
smsg.vertical := FALSE;
sendScroll := TRUE
END
END;
IF sendScroll THEN
g := Views.ThisFrame(f, d.model.view);
IF g # NIL THEN Views.ForwardCtrlMsg(g, smsg) END;
msg.done := TRUE; focus := NIL;
IF ~smsg.done THEN Scroll(d, f, smsg) END
END
END
ELSE END
END
END HandleCtrlMsg2;
(* RootContext *)
PROCEDURE ^ ConsiderOverlayProposal (c: Context; model: StdModel; VAR p: OverlayProposal);
PROCEDURE (c: RootContext) Consider (VAR p: Models.Proposal);
VAR m: Model;
BEGIN
WITH p: OverlayProposal DO
m := c.model;
WITH m: StdModel DO ConsiderOverlayProposal(c, m, p) ELSE END
ELSE
END
END Consider;
PROCEDURE (c: RootContext) ThisModel (): Models.Model;
BEGIN
RETURN c.model
END ThisModel;
PROCEDURE (c: RootContext) GetSize (OUT w, h: INTEGER);
VAR m: Model; dc: Models.Context; l, t, r, b: INTEGER;
BEGIN
m := c.model;
m.doc.PollRect(l, t, r, b); w := r - l; h := b - t;
dc := m.doc.context;
IF dc # NIL THEN
WITH dc: Documents.PrinterContext DO
w := MIN(w, dc.r - dc.l); h := MIN(h, dc.b - dc.t)
ELSE
END
END;
ASSERT(w > 0, 60); ASSERT(h > 0, 61)
END GetSize;
PROCEDURE (c: RootContext) SetSize (w, h: INTEGER);
VAR m: Model; d: Document; minW, maxW, minH, maxH, defW, defH: INTEGER;
BEGIN
m := c.model; d := m.doc; ASSERT(d # NIL, 20);
m.GetEmbeddingLimits(minW, maxW, minH, maxH);
defW := m.r - m.l; defH := m.b - m.t;
Properties.PreferredSize(m.view, minW, maxW, minH, maxH, defW, defH, w, h);
d.SetRect(m.l, m.t, m.l + w, m.t + h)
END SetSize;
PROCEDURE (c: RootContext) ThisDoc* (): Document;
BEGIN
RETURN c.model.doc
END ThisDoc;
PROCEDURE (c: RootContext) MakeVisible (l, t, r, b: INTEGER);
VAR x, y, w, h, dw, dh, ml, mt, mr, mb: INTEGER; d: Document;
BEGIN
d := c.model.doc(Document);
WITH d: Document DO
d.context.GetSize(w, h);
x := -d.x; y := -d.y;
d.PollRect(ml, mt, mr, mb);
dw := mr + ml - w; dh := mb + mt - h;
IF dw > 0 THEN
IF r > x + w - 2 * ml THEN x := r - w + 2 * ml END;
IF l < x THEN x := l END;
IF x < 0 THEN x := 0 ELSIF x > dw THEN x := dw END
END;
IF dh > 0 THEN
IF b > y + h - 2 * mt THEN y := b - h + 2 * mt END;
IF t < y THEN y := t END;
IF y < 0 THEN y := 0 ELSIF y > dh THEN y := dh END
END;
ScrollDoc(d, -x, -y)
END
END MakeVisible;
(* Controller *)
PROCEDURE (ctrl: Controller) RestoreMarks2 (f: Views.Frame; l, t, r, b: INTEGER);
VAR d: Documents.Document;
BEGIN
IF param.debug THEN
d := ctrl.doc;
d.PollRect(l, t, r, b); f.DrawRect(l, t, r, b, 0, Ports.green);
d.GetRect(f, d.ThisView(), l, t, r, b); f.DrawRect(l, t, r, b, 0, Ports.blue);
END;
END RestoreMarks2;
PROCEDURE (c: Controller) HandleViewMsg (f: Views.Frame; VAR msg: Views.Message);
VAR g: Views.Frame;
BEGIN
WITH msg: RemoveOverlayMsg DO
(* ASSERT(c.overlaid # NIL, 20); removed in producion version *)
IF c.overlaid # NIL THEN
g := Views.ThisFrame(f, c.overlaid.view);
IF g # NIL THEN Views.RemoveFrame(f, g) END
END;
ELSE
c.HandleViewMsg^(f, msg)
END
END HandleViewMsg;
PROCEDURE (c: Controller) Internalize2 (VAR rd: Stores.Reader);
VAR v: INTEGER;
BEGIN
rd.ReadVersion(minVersion, maxCtrlVersion, v)
END Internalize2;
PROCEDURE (c: Controller) Externalize2 (VAR wr: Stores.Writer);
BEGIN
wr.WriteVersion(maxCtrlVersion)
END Externalize2;
PROCEDURE (c: Controller) InitView2 (v: Views.View);
VAR m: Models.Model;
BEGIN
IF v # NIL THEN
WITH v: Document DO c.doc := v; m := c.doc.ThisModel();
ASSERT(m # NIL, 21);
WITH m: StdModel DO c.model := m ELSE HALT(22) END
ELSE HALT(20)
END
ELSE c.doc := NIL; c.model := NIL
END
END InitView2;
PROCEDURE (c: Controller) GetContextType (OUT type: Stores.TypeName);
END GetContextType;
PROCEDURE (c: Controller) GetValidOps (OUT valid: SET);
BEGIN
IF c.Singleton() # NIL THEN
valid := {Controllers.copy}
END
END GetValidOps;
PROCEDURE (c: Controller) NativeModel (m: Models.Model): BOOLEAN;
BEGIN
RETURN m IS StdModel
END NativeModel;
PROCEDURE (c: Controller) NativeView (v: Views.View): BOOLEAN;
BEGIN
RETURN v IS Document
END NativeView;
PROCEDURE (c: Controller) NativeCursorAt (f: Views.Frame; x, y: INTEGER): INTEGER;
BEGIN
RETURN Ports.arrowCursor
END NativeCursorAt;
PROCEDURE (c: Controller) PollNativeProp (selection: BOOLEAN; VAR p: Properties.Property; VAR truncated: BOOLEAN);
END PollNativeProp;
PROCEDURE (c: Controller) SetNativeProp (selection: BOOLEAN; p, old: Properties.Property);
END SetNativeProp;
PROCEDURE (c: Controller) GetFirstView (selection: BOOLEAN; OUT v: Views.View);
BEGIN
IF selection THEN v := c.Singleton() ELSE v := c.doc.ThisView() END
END GetFirstView;
PROCEDURE (c: Controller) GetNextView (selection: BOOLEAN; VAR v: Views.View);
(** Skip 'modal' views that are out of focus *)
VAR next: StdContext; ctx: Models.Context;
BEGIN
v := NIL
(*
IF selection THEN
v := NIL
ELSIF v = c.doc.ThisView() (* clipper *) THEN
next := c.model.aux
ELSE
ctx := v.context; ASSERT(ctx # NIL, 20);
WITH ctx: StdContext DO
ASSERT(ctx.ThisDoc() = c.doc, 21); next := ctx.next
ELSE HALT(22) END
END;
IF next # NIL THEN
v := next.view;
IF next.modal & (c.ThisFocus() # v) THEN c.GetNextView(selection, v) END
ELSE v := NIL
END
*)
END GetNextView;
PROCEDURE (c: Controller) GetPrevView (selection: BOOLEAN; VAR v: Views.View);
VAR this: Models.Context; aux: StdContext;
BEGIN
v := NIL
(*
ASSERT(v # NIL, 20);
aux := c.model.aux;
IF selection THEN v := NIL
ELSIF v = c.doc.ThisView() (* clipper*) THEN v := NIL
ELSIF aux = NIL THEN HALT(21 (* v ∈ ctrl.doc *))
ELSIF v = aux.view THEN v := c.doc.ThisView() (* clipper *)
ELSE
this := v.context; ASSERT(this # NIL, 22);
WITH this: StdContext DO ASSERT(this.model = c.model, 23);
WHILE (aux # NIL) & (this # aux.next) DO aux := aux.next END;
ASSERT(aux # NIL(*=>this = aux.next*), 24 (* v ∈ ctrl.doc *));
v := aux.view
ELSE HALT(25)
END
END
*)
END GetPrevView;
PROCEDURE (c: Controller) TrackMarks (f: Views.Frame; x, y: INTEGER; units, extend, add: BOOLEAN);
BEGIN
c.Neutralize
END TrackMarks;
PROCEDURE (c: Controller) Resize (view: Views.View; l, t, r, b: INTEGER);
VAR d: Document; l0, t0, r0_, b0_: INTEGER;
BEGIN
d := c.doc;
ASSERT(view = d.ThisView(), 20);
d.PollRect(l0, t0, r0_, b0_);
d.SetRect(l0, t0, l0 + r - l, t0 + b - t)
END Resize;
PROCEDURE (c: Controller) DeleteSelection;
END DeleteSelection;
PROCEDURE (c: Controller) MoveLocalSelection (f, dest: Views.Frame; x, y: INTEGER; dx, dy: INTEGER);
VAR l, t, r, b: INTEGER; view: Views.View;
BEGIN
IF f = dest THEN
view := c.doc.ThisView(); c.doc.PollRect(l, t, r, b);
DEC(dx, x); DEC(dy, y);
INC(l, dx); INC(t, dy); INC(r, dx); INC(b, dy);
c.Resize(view, l, t, r, b);
IF c.Singleton() = NIL THEN c.SetSingleton(view) END
END
END MoveLocalSelection;
PROCEDURE (c: Controller) SelectionCopy (): StdModel;
BEGIN
RETURN NIL
END SelectionCopy;
PROCEDURE (c: Controller) NativePaste (m: Models.Model; f: Views.Frame);
VAR l, t, r, b: INTEGER;
BEGIN
WITH m: StdModel DO
c.model.ReplaceView(c.doc.ThisView(), m.doc.ThisView());
m.doc.PollRect(l, t, r, b);
c.doc.SetRect(l, t, r, b)
END
END NativePaste;
PROCEDURE (c: Controller) PasteView (f: Views.Frame; v: Views.View; w, h: INTEGER);
VAR m: StdModel; l, t, r, b, minW, maxW, minH, maxH, defW, defH: INTEGER;
BEGIN
m := c.model;
m.GetEmbeddingLimits(minW, maxW, minH, maxH);
c.doc.PollRect(l, t, r, b);
defW := r - l; defH := b - t;
Properties.PreferredSize(v, minW, maxW, minH, maxH, defW, defH, w, h);
m.ReplaceView(c.doc.ThisView(), v);
c.doc.SetRect(l, t, l + w, t + h)
END PasteView;
PROCEDURE (c: Controller) Drop (src, dst: Views.Frame; sx, sy, x, y, w, h, rx, ry: INTEGER; v: Views.View; isSingle: BOOLEAN);
VAR m: StdModel; l, t, r, b, minW, maxW, minH, maxH, defW, defH: INTEGER;
BEGIN
m := c.model;
m.GetEmbeddingLimits(minW, maxW, minH, maxH);
c.doc.PollRect(l, t, r, b);
defW := r - l; defH := b - t;
Properties.PreferredSize(v, minW, maxW, minH, maxH, defW, defH, w, h);
m.ReplaceView(c.doc.ThisView(), v);
c.doc.SetRect(l, t, l + w, t + h)
END Drop;
(* selection *)
PROCEDURE (c: Controller) Selectable (): BOOLEAN;
BEGIN
RETURN TRUE
END Selectable;
PROCEDURE (c: Controller) SelectAll (select: BOOLEAN);
BEGIN
IF ~select & (c.Singleton() # NIL) THEN
c.SetSingleton(NIL)
ELSIF select & (c.Singleton() = NIL) THEN
c.SetSingleton(c.doc.ThisView())
END
END SelectAll;
PROCEDURE (c: Controller) InSelection (f: Views.Frame; x, y: INTEGER): BOOLEAN;
BEGIN
RETURN c.Singleton() # NIL
END InSelection;
(* caret *)
PROCEDURE (c: Controller) HasCaret (): BOOLEAN;
BEGIN
RETURN FALSE
END HasCaret;
PROCEDURE (c: Controller) MarkCaret (f: Views.Frame; show: BOOLEAN);
END MarkCaret;
PROCEDURE (c: Controller) CanDrop (f: Views.Frame; x, y: INTEGER): BOOLEAN;
BEGIN
RETURN FALSE
END CanDrop;
(* handlers *)
PROCEDURE GetFocusPrefAt (v: Views.View; host, frame: Views.Frame; x, y: INTEGER; OUT hot, set: BOOLEAN);
VAR p: Properties.FocusPref;
BEGIN
p.atLocation := TRUE; p.x := x + host.gx - frame.gx; p.y := y + host.gy - frame.gy;
p.hotFocus := FALSE; p.setFocus := FALSE;
Views.HandlePropMsg(v, p);
ASSERT(~(p.setFocus & p.hotFocus), 20);
hot := p.hotFocus; set := ~hot & p.setFocus
END GetFocusPrefAt;
PROCEDURE IsMasked (v: Views.View): BOOLEAN;
(** Returns TRUE if v is a container view in mask mode, FALSE otherwise *)
VAR res: BOOLEAN; c: Containers.Controller;
BEGIN
WITH v: Containers.View DO c := v.ThisController();
IF c # NIL THEN res := Containers.mask * c.opts = Containers.mask END
ELSE
END;
RETURN res
END IsMasked;
PROCEDURE RemoveOverlaid (c: Controller);
VAR msg: RemoveOverlayMsg;
BEGIN
IF (c.overlaid # NIL) & (c.overlaid.owner # NIL) THEN
Views.Broadcast(c.overlaid.owner, msg)
END;
Views.Broadcast(c.doc, msg); (* Received by each frame of c.doc so that overlaid frame can be removed - this is done to avoid rebuilding the whole frame tree *)
c.overlaid := NIL
END RemoveOverlaid;
PROCEDURE LeafAt (f: Views.Frame; x, y: INTEGER): Views.View;
VAR g: Views.Frame;
BEGIN
REPEAT
g := f; f := Views.FrameAt(f, x, y);
IF f # NIL THEN DEC(x, f.gx - g.gx); DEC(y, f.gy - g.gy) END
UNTIL f = NIL;
RETURN g.view
END LeafAt;
PROCEDURE IsAux (ctrl: Controller; ctx: StdContext): BOOLEAN;
VAR c: StdContext;
BEGIN
ASSERT(ctx # NIL, 20);
c := ctrl.model.aux;
WHILE (c # NIL) & (c # ctx) DO c := c.next END;
RETURN c = ctx
END IsAux;
PROCEDURE (c: Controller) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View);
CONST ESC = 1BX;
VAR l, t, r, b: INTEGER; g: Views.Frame; dont, aux, hot, _: BOOLEAN; ctx: Models.Context;
br, new: StdContext; top: Views.View; ct: Containers.Controller;
BEGIN
aux := FALSE;
WITH msg: Controllers.CursorMessage DO
IF c.Singleton() = NIL THEN
(* move the copypasted black text somewhere in this branch? *)
g := Views.FrameAt(f, msg.x, msg.y);
IF g # NIL THEN
WITH msg: Controllers.TrackMsg DO
ctx := g.view.context;
WITH ctx: StdContext DO
aux := TRUE;
IF ctx.overlaid THEN new := ctx; focus := g.view
ELSIF (c.overlaid # NIL) & (c.overlaid.owner # NIL) & (LeafAt(f, msg.x, msg.y) = c.overlaid.owner) THEN
new := c.overlaid
END
ELSE
IF (c.overlaid # NIL) & (c.overlaid.owner # NIL) THEN
IF (LeafAt(f, msg.x, msg.y) = c.overlaid.owner) THEN new := c.overlaid END;
END
END;
IF new # c.overlaid THEN (* Mark-Unmark*)
IF c.overlaid # NIL THEN RemoveOverlaid(c) END;
c.overlaid := new; Recalc(c.doc, 0);
END;
IF focus = NIL THEN
GetFocusPrefAt(g.view, f, g, msg.x, msg.y, hot, _);
IF hot OR IsMasked(g.view) THEN focus := g.view END
END;
IF focus # NIL THEN
ctx := focus.context;
WITH ctx: StdContext DO br := ctx ELSE END
END
ELSE IF g.view.context IS StdContext THEN focus := g.view END
END
END
END;
| msg: Controllers.EditMsg DO
IF (msg.op = Controllers.pasteChar) & (msg.char = ESC) & (c.overlaid # NIL) THEN
RemoveOverlaid(c);
Recalc(c.doc, 0)
ELSIF c.overlaid # NIL THEN focus := c.overlaid.view; br := focus.context(StdContext)
END
(* | msg: PollOutermostMsg DO msg.model := c.model; aux := TRUE *)
ELSE
END;
IF br # NIL THEN
ASSERT(bar = NIL, 100); (* should never be nested *)
bar := br; par := bar.par;
Services.DoLater(resetBar, Services.immediately)
ELSIF ~aux & (focus = NIL) THEN
dont := FALSE;
IF ~(Containers.noFocus IN c.opts) THEN
WITH msg: Controllers.TickMsg DO
g := Views.UltimateRootOf(f); top := g.view;
WITH top: Document DO
ct := top.ThisController();
WITH ct: Controller DO dont := (ct.overlaid # NIL) & ~IsAux(ct, ct.overlaid);
IF dont THEN g := Views.ThisFrame(g, ct.overlaid.view);
(* let overlaid rcv the tick *)
IF g # NIL THEN Views.ForwardCtrlMsg(g, msg) END
(* maybe also send a MarkMsg to front window with focus = FALSE, on = FALSE to let texts display proper caret? that's more appropriate when the overlaid is inserted, though *)
END
ELSE
END
ELSE
END;
IF ~dont & (c.Singleton() = NIL) THEN c.SetFocus(c.doc.ThisView())
END
| msg: Controllers.CursorMessage DO
IF c.Singleton() = NIL THEN (* delegate to focus, even if not directly hit *)
focus := c.ThisFocus();
c.doc.GetRect(f, focus, l, t, r, b); (* except for resize in lower right corner *)
IF (c.opts * {pageWidth..winHeight} # {})
OR (msg.x < r) OR (msg.y < b)(l <= msg.x) & (msg.x < r) & (t <= msg.y) & (msg.y < b) THEN
RETURN
END
END
ELSE
END
END;
IF ~dont THEN c.HandleCtrlMsg^(f, msg, focus) END
END
END HandleCtrlMsg;
PROCEDURE (ctrl: Controller) HandlePropMsg (VAR msg: Properties.Message);
VAR c: StdContext;
BEGIN
ctrl.HandlePropMsg^(msg);
WITH msg: PanWindowPref DO
IF msg.atLocation THEN
c := ctrl.model.First();
WHILE (c # NIL) & ~((c.l <= msg.x)
& (msg.x - c.l < c.w) & (c.t <= msg.y) & (msg.y - c.t < c.h)) DO
c := ctrl.model.Next(c)
END;
IF c # NIL THEN
DEC(msg.x, c.l); DEC(msg.y, c.t);
Views.HandlePropMsg(c.view, msg)
END
END
ELSE
END
END HandlePropMsg;
PROCEDURE (c: Controller) ThisFocus (): Views.View;
BEGIN
IF c.Singleton() = NIL THEN c.SetFocus(c.doc.ThisView()) END;
RETURN c.ThisFocus^()
END ThisFocus;
PROCEDURE (c: Controller) PasteChar (ch: CHAR);
END PasteChar;
PROCEDURE (c: Controller) ControlChar (f: Views.Frame; ch: CHAR);
END ControlChar;
PROCEDURE (c: Controller) ArrowChar (f: Views.Frame; ch: CHAR; units, select: BOOLEAN);
END ArrowChar;
PROCEDURE (c: Controller) CopyLocalSelection (src, dst: Views.Frame; sx, sy, dx, dy: INTEGER);
END CopyLocalSelection;
(* Directory *)
PROCEDURE (d: Directory) NewModel* (): Model, NEW, ABSTRACT;
PROCEDURE (d: Directory) NewController* (): Containers.Controller, NEW, ABSTRACT;
PROCEDURE (d: Directory) New* (view: Views.View; w, h: INTEGER): Document;
VAR doc: Document; m: Model; c: Containers.Controller;
BEGIN
ASSERT(view # NIL, 20); ASSERT(~(view IS Document), 21);
m := dir.NewModel();
NEW(doc); doc.InitModel(m);
c := dir.NewController();
doc.SetController(c);
NEW(doc.clipper);
doc.SetRect(defB, defB, defB + 1, defB + 1); (* set top-left point *)
doc.SetView(view, w, h); (* joins store graphs of doc and view *)
Stores.InitDomain(doc); (* domains of new documents are bound *)
RETURN doc
END New;
(* StdDirectory *)
PROCEDURE NewScrollbar (isVertical: BOOLEAN; m: StdModel; OUT sb: StdScrollbars.Scrollbar; OUT ctx: StdContext);
VAR c: SBContext;
BEGIN
sb := StdScrollbars.sbDir.New();
sb.isVertical := isVertical;
sb.wholeSize := 0;
NEW(c); ctx := c; c.view := sb; c.model := m; sb.InitContext(c); Stores.Join(sb, m)
END NewScrollbar;
PROCEDURE InitModel (m: StdModel);
BEGIN
m.showV := FALSE; m.showH := FALSE; m.param := param;
NewScrollbar(StdScrollbars.vertical, m, m.sbVv, m.sbV);
NewScrollbar(~StdScrollbars.vertical, m, m.sbHv, m.sbH);
m.aux := m.sbV; m.sbV.next := m.sbH
END InitModel;
PROCEDURE (d: StdDirectory) NewModel (): StdModel;
VAR m: StdModel;
BEGIN
NEW(m); InitModel(m); RETURN m
END NewModel;
PROCEDURE (d: StdDirectory) NewController (): Controller;
VAR res: Controller;
BEGIN NEW(res); RETURN res
END NewController;
PROCEDURE (m: StdModel) Internalize2 (VAR rd: Stores.Reader);
VAR ver: INTEGER; v: Views.View; new, last: StdContext;
BEGIN
rd.ReadVersion(modelVersion, modelVersion, ver);
IF ~rd.cancelled THEN
InitModel(m);
REPEAT Views.ReadView(rd, v);
IF v # NIL THEN
NEW(new);
IF last # NIL THEN last.next := new ELSE m.aux := new END; last := new;
new.view := v; rd.ReadInt(new.align); rd.ReadBool(new.overlaid);
new.model := m;
v.InitContext(new)
END
UNTIL v = NIL
END
END Internalize2;
PROCEDURE (m: StdModel) Externalize2 (VAR wr: Stores.Writer);
VAR c: StdContext;
BEGIN
wr.WriteVersion(modelVersion);
c := m.aux; WHILE c # NIL DO
IF (c # m.sbV) & (c # m.sbH) THEN
Views.WriteView(wr, c.view); wr.WriteInt(c.align); wr.WriteBool(c.overlaid)
END;
c := c.next
END;
wr.WriteStore(NIL)
END Externalize2;
PROCEDURE (m: StdModel) CopyFrom2 (source: Stores.Store);
BEGIN
InitModel(m)
END CopyFrom2;
(* Bars *)
PROCEDURE Next (c: StdContext; align: INTEGER): StdContext;
BEGIN ASSERT(c # NIL, 20);
REPEAT c := c.next UNTIL (c = NIL) OR (c.align = align); RETURN c
END Next;
PROCEDURE InsertBar* (d: Document; align: INTEGER; view, above: Views.View; overlaid: BOOLEAN; par: ANYPTR);
(** Insert view as a bar at the top (align = top) or bottom (align = bottom) of d just above above., including it in the overlaid focus path if overlaid is set. par is an arbitrary parameter that will be assigned to global variable par before view's HandleCtrlMsg is called.
ATTN! view will only receive Controller.TrackMsg if it is 'hot focus' (cf. Properties.FocusPref) or if it is a Containers.View with controller in mask mode.
For example, a regular t: TextViews.View may be inserted as a bar; a link may be in the text calling some command C; when C is activated, it may check TylerLayouts.par for the par that was passed to InsertBar.
Pre:
d # NIL 20
view # NIL 21
view.context = NIL 22
d.ThisModel() IS StdModel 23
above # NIL
above ∈ m 24 25 26 27
(align = top) OR (align = bottom) OR (align = noalign) 28
(view.Domain() = NIL) OR (d.Domain() = view.Domain()) 29
*)
VAR next, c, new: StdContext; mm: Containers.Model; m: StdModel; ac: Models.Context;
BEGIN
ASSERT(d # NIL, 20); ASSERT(view # NIL, 21); ASSERT(view.context = NIL, 22);
ASSERT((align = top) OR (align = bottom) OR (align = noalign), 28);
mm := d.ThisModel(); WITH mm: StdModel DO m := mm ELSE HALT(23) END;
IF above # NIL THEN ac := above.context; ASSERT(ac # NIL, 24);
WITH ac: StdContext DO ASSERT(ac.model = m, 25) ELSE HALT(26) END
END;
ASSERT((view.Domain() = NIL) OR (d.Domain() = view.Domain()), 29);
NEW(new); new.view := view; new.align := align; new.model := m; new.overlaid := overlaid;
new.par := par;
view.InitContext(new); Stores.Join(d, view);
next := m.aux;
REPEAT c := next; next := Next(c, align)
UNTIL (c = NIL) OR (next = NIL) OR (next.view = above);
IF c # NIL THEN ASSERT((next # NIL) OR (above = NIL), 27 (* above ∈ m *));
new.next := c.next; c.next := new
ELSE m.aux := new
END;
Recalc(d, 0)
END InsertBar;
PROCEDURE DoInsertOverlaid (m: StdModel; v, owner: Views.View; l, t, w, h: INTEGER; par: ANYPTR);
VAR c: Models.Context; ctrl: Controller; ctx: StdContext;
BEGIN
ctrl := m.doc.ThisController()(Controller);
IF ctrl.overlaid # NIL THEN (* remove a temporal overlaid - the one not among aux views *)
ctx := ctrl.model.aux;
WHILE (ctx # NIL) & (ctx # ctrl.overlaid) DO ctx := ctx.next END;
IF ctx = NIL THEN RemoveOverlaid(ctrl) END
END;IF (ctrl.overlaid # NIL) & ~IsAux(ctrl, ctrl.overlaid) THEN
(* remove a temporal overlaid - the one not among aux views *)
RemoveOverlaid(ctrl)
END;
c := v.context;
IF c = NIL THEN
NEW(ctx); ctx.view := v; ctx.model := m; ctx.l := 0; ctx.t := 0; ctx.owner := owner;
Stores.Join(v, m); v.InitContext(ctx);
ctrl.overlaid := ctx
ELSE
WITH c: StdContext DO
ASSERT(c.model = m, 21);
ctrl.overlaid := c; ctx := c
ELSE HALT(22)
END
END;
IF (w = Views.undefined) OR (h = Views.undefined) THEN
PreferredSize(v, m, ctx.w, ctx.h)
ELSE
ctx.w := w; ctx.h := h
END;
IF (l = center) OR (t = center) THEN
m.doc.context.GetSize(w, h);
IF l = center THEN l := (w - ctrl.overlaid.w) DIV 2 END;
IF t = center THEN t := (h - ctrl.overlaid.h) DIV 2 END
END;
ctrl.overlaid.l := l;
ctrl.overlaid.t := t;
ctrl.overlaid.overlaid := TRUE;
ctrl.overlaid.par := par
END DoInsertOverlaid;
PROCEDURE InsertOverlaid* (v, owner: Views.View; d: Document; l, t, w, h: INTEGER; par: ANYPTR);
BEGIN DoInsertOverlaid(d.ThisModel()(StdModel), v, owner, l, t, w, h, par); Recalc(d, 0)
END InsertOverlaid;
(* Contexts *)
PROCEDURE ConsiderOverlayProposal (c: Context; model: StdModel; VAR p: OverlayProposal);
VAR upd: BOOLEAN; ctrl: Controller; f: Views.Frame;
BEGIN
upd := FALSE; ctrl := model.doc.ThisController()(Controller);
IF p.op = show THEN
upd := TRUE; ASSERT(p.view # NIL, 20);
DoInsertOverlaid(model, p.view, p.owner, p.x + c.l, p.y + c.t, Views.undefined, Views.undefined, NIL)
ELSIF p.op = hide THEN upd := TRUE; RemoveOverlaid(ctrl)
ELSIF p.op = poll THEN
IF ctrl.overlaid = NIL THEN p.view := NIL ELSE p.view := ctrl.overlaid.view END
ELSIF p.op = pollFrame THEN ASSERT(p.frame # NIL, 21);
ASSERT(ctrl.overlaid # NIL, 22); ASSERT(ctrl.overlaid.owner # NIL, 23);
ASSERT(p.frame.view = ctrl.overlaid.owner, 24);
f := p.frame; REPEAT f := Views.HostOf(f) UNTIL (f = NIL) OR (f.view = model.doc);
IF f # NIL THEN p.frame := Views.ThisFrame(f, ctrl.overlaid.view)
ELSE p.frame := NIL
END
ELSE HALT(26)
END;
IF upd THEN Recalc(model.doc, 0) END
END ConsiderOverlayProposal;
PROCEDURE (c: StdContext) Consider (VAR p: Models.Proposal), EXTENSIBLE;
BEGIN
WITH p: OverlayProposal DO ConsiderOverlayProposal(c, c.model, p)
ELSE
END
END Consider;
PROCEDURE (c: SBContext) Consider (VAR p: Models.Proposal);
VAR msg: Controllers.ScrollMsg; host: Views.Frame;
BEGIN
WITH p: StdScrollbars.Proposal DO
IF (p.sb = c.view) & (p.frame # NIL) & (p.frame.view = p.sb) THEN
host := Views.HostOf(p.frame);
ASSERT((host # NIL) & (host.view = c.ThisDoc()));
msg.pos := p.sb.partPos;
msg.focus := FALSE;
msg.vertical := p.sb.isVertical;
msg.op := p.op;
msg.done := FALSE;
Views.ForwardCtrlMsg(host, msg)
END
ELSE
END
END Consider;
(* Backdrop *)
PROCEDURE (v: Backdrop) Restore (f: Views.Frame; l, t, w, h: INTEGER);
BEGIN
v.context.GetSize(w, h);
f.DrawRect(0, 0, w, h, 0, 128);
Views.InstallFrame(f, v.view, 2 * Ports.mm, 2 * Ports.mm, 0, TRUE)
END Restore;
PROCEDURE (v: Backdrop) GetBackground (VAR col: Ports.Color);
VAR c: Models.Context;
BEGIN
v.view.GetBackground(col);
IF col = Views.transparent THEN
c := v.context;
WITH c: StdContext DO c.model.doc.GetBackground(col) ELSE END;
IF col = Views.transparent THEN col := Ports.background END
END
END GetBackground;
PROCEDURE AddBackground* (v: Views.View): Views.View;
VAR bk: Backdrop; c: BackdropContext;
BEGIN
NEW(bk); bk.view := v; NEW(c);
c.backdrop := bk; v.InitContext(c); Stores.Join(v, bk);
RETURN bk
END AddBackground;
PROCEDURE (v: Backdrop) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View);
BEGIN focus := v.view
END HandleCtrlMsg;
PROCEDURE (v: Backdrop) HandlePropMsg (VAR msg: Properties.Message);
BEGIN
Views.HandlePropMsg(v.view, msg);
WITH msg: Properties.BoundsPref DO
INC(msg.w, 4 * Ports.mm); INC(msg.h, 4 * Ports.mm)
| msg: Properties.SizePref DO
INC(msg.w, 4 * Ports.mm); INC(msg.h, 4 * Ports.mm)
ELSE
END
END HandlePropMsg;
PROCEDURE (c: BackdropContext) GetSize (OUT w, h: INTEGER);
BEGIN
ASSERT(c.backdrop # NIL, 20);
c.backdrop.context.GetSize(w, h);
DEC(w, 4 * Ports.mm); DEC(h, 4 * Ports.mm)
END GetSize;
PROCEDURE (c: BackdropContext) Normalize (): BOOLEAN; BEGIN RETURN TRUE END Normalize;
PROCEDURE (c: BackdropContext) ThisModel (): Models.Model; BEGIN RETURN NIL END ThisModel;
(* Commands *)
PROCEDURE CloseThisBar (bar: StdContext);
VAR m: StdModel; c: StdContext; ctrl: Controller;
BEGIN
ASSERT(bar # NIL, 20);
ASSERT(bar.view # NIL, 21);
ASSERT(bar.view.context = bar, 22);
m := bar.model;
ctrl := m.doc.ThisController()(Controller);
IF bar = ctrl.overlaid THEN ctrl.overlaid := NIL
ELSIF m.aux = bar THEN m.aux := bar.next
ELSE c := m.aux;
WHILE (c # NIL) & (c.next # bar) DO c := c.next END; ASSERT(c # NIL, 23);
c.next := bar.next; bar.next := NIL
END;
Recalc(m.doc, 0);
IF bar.view = ctrl.ThisFocus() THEN ctrl.SetFocus(m.doc.ThisView()) END
END CloseThisBar;
PROCEDURE CloseBar*;
(** Close the currently activated bar, if any *)
BEGIN IF bar # NIL THEN CloseThisBar(bar) END
END CloseBar;
PROCEDURE RemoveFrontBar* (d: Document);
(** Remove the front bar from d, if any*)
VAR f: Views.View;
BEGIN
ASSERT(d # NIL, 20); f := d.ThisController().ThisFocus();
IF (f # NIL) & (f.context IS StdContext) THEN CloseThisBar(f.context(StdContext)) END
END RemoveFrontBar;
(* Conversion between Documents.Document and StdDocuments.Document *)
PROCEDURE ImportDocument* (f: Files.File; OUT s: Stores.Store);
VAR rd: Stores.Reader; tag, version: INTEGER; res: Views.View;
l, t, r, b: INTEGER;
BEGIN
ASSERT(f # NIL, 20);
rd.ConnectTo(f);
rd.ReadInt(tag);
IF tag = docTag THEN
rd.ReadInt(version);
ASSERT(version = docVersion, 100);
rd.ReadStore(s);
(* k8: if we want to open loaded document later, it must be StdDocument.Document.
otherwise StdWindows will make the copy of the document view, violating the
(unwritten) rule that OldView result should be the same view that the window
will show. not all loaded documents will be opened, but let's trade
some resources for keeping the contract unchanged. *)
WITH s: Document DO
res := s.ThisView();
s.PollRect(l, t, r, b);
| s: Documents.Document DO
res := Documents.DuplicateAs(s, dir).ThisView();
ELSE
END;
s := res
END
END ImportDocument;
PROCEDURE ExportDocument* (s: Stores.Store; f: Files.File);
VAR
w: Stores.Writer; v: Views.View; name: ARRAY 64 OF CHAR;
std, d: Documents.Document;
BEGIN
ASSERT(s # NIL, 20);
ASSERT(s IS Views.View, 21);
ASSERT(f # NIL, 22);
v := s(Views.View);
IF (v.context # NIL) & (v.context IS Documents.Context) THEN
d := v.context(Context).ThisDoc()
END;
IF d # NIL THEN
Services.GetTypeName(d, name);
IF name = "Documents.StdDocument" THEN std := d
ELSE std := Documents.DuplicateAs(d, Documents.stdDir)
END
ELSE
IF v.context # NIL THEN v := Views.CopyOf(v, Views.shallow) END;
std := Documents.stdDir.New(v, Views.undefined, Views.undefined)
END;
w.ConnectTo(f);
w.WriteInt(docTag); w.WriteInt(docVersion);
w.WriteStore(std)
END ExportDocument;
PROCEDURE SetDir* (d: Directory);
BEGIN
ASSERT(d # NIL, 20);
dir := d;
IF stdDir = NIL THEN stdDir := d END;
Documents.SetDir(d) (* relay *)
END SetDir;
(* Actions *)
PROCEDURE (a: ResetBarAction) Do; BEGIN bar := NIL; par := NIL END Do;
PROCEDURE InitParam (p: ANYPTR);
BEGIN
WITH p: Param DO
END
END InitParam;
PROCEDURE InitDefaults (p: ANYPTR);
BEGIN
WITH p: Param DO
p.debug := FALSE;
p.sbSide := right;
p.sbThickness := 10;
p.InitDefaults := InitDefaults;
p.Init := InitParam;
END
END InitDefaults;
PROCEDURE Install*;
VAR d: StdDirectory;
BEGIN
NEW(d); SetDir(d);
NEW(param);
InitDefaults(param);
NEW(resetBar)
END Install;
PROCEDURE Uninstall*;
VAR d: StdDirectory;
BEGIN
Documents.SetDir(Documents.stdDir)
END Uninstall;
END StdDocuments.
Modal focus
A view may be inserted in a document model as a modal focus view. Such views are only displayed when they are in focus; as soon as they become out of focus, they are undisplayed (but not removed from the model)
doc.ThisController().ThisFocus() = v <=> v is visible in doc
A view is inserted as a modal focus view by InsertModal. To put such a view v into focus (and therefore make it visible):
doc.ThisController().SetFocus(v)
Implementation:
A context has .modal flag.
Controller.GetNextView() skips modal focus views that are out of focus. This means that such views do not participate in doc's behavior.
doc.Restore() uses Controller.GetNextView() to iterate thru a doc's auxiliary views, including modal focus views, therefore allowing Controller to filter out modal focus views that are out of focus.
Whenever an interaction results in doc's focus view changing, Controller.SetFocus is called. This procedure is terminal in Containers; I found no way of how the extender would be informed of a focus change. Such informing is necessary, because when a modal focus view is moved out of focus, it's frame needs to be removed (on all doc's frames for that matter). Therefore, I had to export FocusMsg from Containers, and respond to it in doc.HandleViewMsg2.
Another opportunity would be to go over all modal focus views in doc.Restore, and remove all their frames, if any. The drawback of this would be that the Document view has to be made aware of modal focus flags; whereas now it isn't - it relies completely on the Controller filtering those views out. But on the positive side, you won't have to export Containers.FocusMsg.
| Std/Mod/Documents.odc |
MODULE StdFilesBrowser;
(**
project = "BlackBox 2.0"
organization = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Ivan Denisov, Ketmar Dark (k8)"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 20220531, dia, add cross-platform file browser
- 20230105, k8, added "parent dir" place; use right align for current path control, better keyboard navigation
- 20230106, k8, going to parent dir now correctly places the cursor; fixed "Open" button guard
- 20230106, k8, pressing alphanum now jumps to the next list item started with that char
- 20230107, k8, added M-Down to open converter popup, and (limited) keyboard navigation for it
- 20230108, k8, added proper guard for "save" button in save file dialog, and for directory selection browser
"
issues = "
- ...
"
**)
IMPORT
Files, Stores, Models, Sequencers, Views, Fonts,
Dialog, Properties, Converters, Ports, Controllers, Controls,
Librarian, StdDialog, StdScrollers;
CONST
(* for standard files browser *)
undefined = -2; back = -1;
location = 1; open = 2; save = 3;
itemHeight = 5 * Ports.mm;
closedConvList = 6 * Ports.mm;
expandedConvList = 25 * Ports.mm;
(* char codes *)
CtrlPageUp = 10X;
CtrlPageDown = 11X;
PageUp = 12X;
PageDown = 13X;
HomeKey = 14X;
EndKey = 15X;
CtrlHome = 16X;
CtrlEnd = 017X;
LeftArrow = 1CX;
RightArrow = 1DX;
UpArrow = 1EX;
DownArrow = 1FX;
Enter = 0DX;
Esc = 1BX;
Backspace = 08X;
Tab = 09X;
DeleteKey = 07H;
TYPE
DialogStdGetHook = POINTER TO RECORD (Dialog.StdGetHook) END;
(* for standard files browser *)
Context = POINTER TO RECORD (Models.Context)
base: FilesBrowser;
view: Views.View;
l, t, r, b: INTEGER;
wrapped: BOOLEAN
END;
FilesBrowser = POINTER TO RECORD (Views.View)
action: Dialog.GetAction;
font: Fonts.Font;
files, places, converters, confirmAddButton,
confirmButton, cancelButton, addButton,
pathField, nameField, fNameField: Context;
focusView: Views.View;
margin, convertersHeight: INTEGER;
type: BYTE;
convList: Converters.Converter;
converter: Converters.Converter;
focusLocInfoNum, focusFileInfoNum: INTEGER;
activeAddFolder: BOOLEAN;
initTypes: POINTER TO ARRAY OF Files.Type;
(* k8:HACK! for some reason, "go up" with `MakeVisible()` doesn't work; force it in repaint with this autoresetflag *)
forceMakeCurrFVisible: BOOLEAN
END;
PlaceActionProc = PROCEDURE (v: FilesBrowserPlaces);
Place = POINTER TO RECORD
name, path: ARRAY 256 OF CHAR;
specialAction: PlaceActionProc;
next: Place
END;
FilesBrowserPlaces = POINTER TO RECORD (Views.View)
base: FilesBrowser
END;
FilesBrowserTable = POINTER TO RECORD (Views.View)
base: FilesBrowser
END;
FilesBrowserConverters = POINTER TO RECORD (Views.View)
base: FilesBrowser
END;
CloseNotifier = POINTER TO RECORD (Sequencers.Notifier) END;
Param* = POINTER TO RECORD
bgCursorUpDir*,
bgCursorDir*,
bgCursorFile*,
bgActivePlace*,
bgActiveConverter* : Ports.Color;
upDirStr*: ARRAY 8 OF CHAR;
upper*: Files.Name;
InitDefaults-: PROCEDURE (a: ANYPTR)
END;
VAR
browser-: FilesBrowser;
showHidden*, preventCleanup: BOOLEAN;
name*, fName*, path-: Files.Name;
place*: Place;
param*: Param;
lastLoc: Files.Locator;
PROCEDURE UpdatePath;
BEGIN
Dialog.GetLocPath(browser.action.loc, path);
Dialog.UpdateString(path)
END UpdatePath;
PROCEDURE IsHidden (item: ANYPTR): BOOLEAN;
VAR hidden: BOOLEAN; name: Files.Name; i: INTEGER;
BEGIN
hidden := TRUE;
IF browser # NIL THEN
WITH item: Files.LocInfo DO
name := item.name;
hidden := ~showHidden & (name[0] = ".")
| item: Files.FileInfo DO
name := item.name;
hidden := ~showHidden & (name[0] = ".");
IF ~hidden THEN
IF (browser.converter # NIL) THEN
hidden := (item.type = "") OR (browser.converter.fileType # item.type)
ELSE
IF (browser.initTypes # NIL) & (browser.initTypes[0] # "*") THEN
hidden := TRUE;
IF (item.type # "") THEN
FOR i := 0 TO LEN(browser.initTypes) - 1 DO
IF item.type = browser.initTypes[i] THEN
hidden := FALSE
END
END
END
END
END
END
ELSE END
END;
RETURN hidden
END IsHidden;
PROCEDURE CountLocs (nav: FilesBrowser): INTEGER;
VAR
locInfo: Files.LocInfo;
locs: INTEGER;
BEGIN
locs := 0;
locInfo := Files.dir.LocList(nav.action.loc);
WHILE locInfo # NIL DO
IF ~IsHidden(locInfo) THEN INC(locs) END;
locInfo := locInfo.next
END;
RETURN locs
END CountLocs;
PROCEDURE CountLocsFiles (nav: FilesBrowser; OUT locs, files: INTEGER);
VAR locInfo: Files.LocInfo; fileInfo: Files.FileInfo;
BEGIN
locs := 0;
locInfo := Files.dir.LocList(nav.action.loc);
WHILE locInfo # NIL DO
IF ~IsHidden(locInfo) THEN
INC(locs)
END;
locInfo := locInfo.next
END;
files := 0;
fileInfo := Files.dir.FileList(nav.action.loc);
WHILE fileInfo # NIL DO
IF ~IsHidden(fileInfo) THEN
INC(files)
END;
fileInfo := fileInfo.next
END
END CountLocsFiles;
PROCEDURE LookupNextDirForChar (nav: FilesBrowser; ch: CHAR; fidx: INTEGER): INTEGER;
VAR
info: Files.LocInfo;
res, idx: INTEGER;
BEGIN
res := -1; ch := CAP(ch); idx := 0;
info := Files.dir.LocList(nav.action.loc);
WHILE (res < 0) & (info # NIL) DO
IF ~IsHidden(info) THEN
IF (idx > fidx) & (CAP(info.name[0]) = ch) THEN res := idx END;
INC(idx)
END;
info := info.next
END;
RETURN res
END LookupNextDirForChar;
PROCEDURE LookupNextFileForChar (nav: FilesBrowser; ch: CHAR; fidx: INTEGER): INTEGER;
VAR
info: Files.FileInfo;
res, idx: INTEGER;
BEGIN
res := -1; ch := CAP(ch); idx := 0;
info := Files.dir.FileList(nav.action.loc);
WHILE (res < 0) & (info # NIL) DO
IF ~IsHidden(info) THEN
IF (idx > fidx) & (CAP(info.name[0]) = ch) THEN res := idx END;
INC(idx)
END;
info := info.next
END;
RETURN res
END LookupNextFileForChar;
(* return `FALSE` if not found *)
PROCEDURE LookupNextItemForChar (nav: FilesBrowser; ch: CHAR; OUT loc, file: INTEGER): BOOLEAN;
VAR
idx: INTEGER;
isdir: BOOLEAN;
BEGIN
idx := -1; isdir := FALSE;
IF (nav.focusLocInfoNum # undefined) OR
((nav.focusLocInfoNum = undefined) & (nav.focusFileInfoNum = undefined))
THEN
(* look into dirs *)
idx := LookupNextDirForChar(nav, ch, nav.focusLocInfoNum);
isdir := TRUE
END;
(* look into files *)
IF idx < 0 THEN idx := LookupNextFileForChar(nav, ch, nav.focusFileInfoNum); isdir := FALSE END;
(* and again *)
IF idx < 0 THEN idx := LookupNextDirForChar(nav, ch, -1); isdir := TRUE END;
IF idx < 0 THEN idx := LookupNextFileForChar(nav, ch, -1); isdir := FALSE END;
(* setup results *)
IF idx >= 0 THEN
IF isdir THEN loc := idx; file := undefined ELSE loc := undefined; file := idx END
END;
RETURN (idx >= 0)
END LookupNextItemForChar;
PROCEDURE GetLastDirName (v: FilesBrowser; OUT ldname: ARRAY OF CHAR);
VAR
path: ARRAY 1024 OF CHAR;
i, dp: INTEGER;
BEGIN
ASSERT(v # NIL);
Dialog.GetLocPath(v.action.loc, path);
i := LEN(path$);
(* k8: didn't i told ya that we need platform-independent path manipulation API?! *)
IF Dialog.platform = Dialog.windows THEN
IF (i = 1) & ((path[0] = '/') OR (path[0] = '\')) THEN
ldname := ""
ELSIF (i = 3) & (path[1] = ':') & ((path[2] = '/') OR (path[2] = '\')) THEN
ldname := ""
ELSE
WHILE (i > 0) & ((path[i-1] # '/') & (path[i] # '\') ) DO DEC(i) END;
INC(i);
dp := 0;
WHILE path[i] # 0X DO
ldname[dp] := path[i];
INC(i); INC(dp)
END;
ldname[dp] := 0X
END
ELSE
IF (i = 1) & (path[0] = '/') THEN
ldname := ""
ELSE
WHILE (i > 0) & (path[i-1] # '/') DO DEC(i) END;
dp := 0;
WHILE path[i] # 0X DO
ldname[dp] := path[i];
INC(i); INC(dp)
END;
ldname[dp] := 0X
END
END
END GetLastDirName;
PROCEDURE SelectDirInFiles (v: FilesBrowser; IN dname: ARRAY OF CHAR);
VAR
n, y: INTEGER;
locInfo: Files.LocInfo;
path: ARRAY 1024 OF CHAR;
BEGIN
ASSERT(v # NIL);
IF dname[0] # 0X THEN
Dialog.GetLocPath(v.action.loc, path);
locInfo := Files.dir.LocList(v.action.loc);
n := 0; y := itemHeight * 2;
WHILE (locInfo # NIL) & (locInfo.name # dname) DO
IF ~IsHidden(locInfo) THEN
INC(y, itemHeight);
INC(n)
END;
locInfo := locInfo.next
END;
IF locInfo # NIL THEN
v.focusFileInfoNum := undefined;
v.focusLocInfoNum := n
ELSE
v.focusFileInfoNum := undefined;
v.focusLocInfoNum := undefined
END;
v.forceMakeCurrFVisible := TRUE;
Views.Update(v.files.view, Views.rebuildFrames(*keepFrames*));
v.focusView := browser.files.view
ELSE
v.focusFileInfoNum := undefined;
v.focusLocInfoNum := 0;
Views.Update(v.files.view, Views.rebuildFrames)
END
END SelectDirInFiles;
PROCEDURE GoOneDirUp (v: FilesBrowser);
VAR
i: INTEGER;
path: ARRAY 1024 OF CHAR;
dname: ARRAY 256 OF CHAR;
BEGIN
ASSERT(v # NIL);
Dialog.GetLocPath(v.action.loc, path);
IF param.upper # path THEN
GetLastDirName(v, dname);
i := LEN(path$);
WHILE (i > 0) & ((path[i] # "/") & (path[i] # "\") ) DO DEC(i) END;
IF (i = 0) & ((path[0] = "/") OR (path[0] = "\")) THEN
path[1] := 0X; i := 1
ELSE
path[i] := 0X
END;
IF i > 0 THEN
v.action.loc := v.action.loc.This(path);
UpdatePath;
(*Views.Update(v.files.view, Views.rebuildFrames)*)
SelectDirInFiles(v, dname)
END
END
END GoOneDirUp;
PROCEDURE (c: Context) ThisModel (): Models.Model;
BEGIN RETURN NIL
END ThisModel;
PROCEDURE (c: Context) GetSize (OUT w, h: INTEGER);
BEGIN
IF c.wrapped THEN
w := c.r - c.l;
h := 300 * Ports.mm
ELSE
w := c.r - c.l;
h := c.b - c.t
END
END GetSize;
PROCEDURE (c: Context) Consider (VAR p: Models.Proposal);
BEGIN
c.base.context.Consider(p)
END Consider;
PROCEDURE (c: Context) Normalize (): BOOLEAN;
BEGIN
RETURN c.base.context.Normalize()
END Normalize;
PROCEDURE NewContext (v: Views.View; base: FilesBrowser): Context;
VAR c: Context;
BEGIN
ASSERT(v # NIL, 21);
NEW(c); c.view := v; c.base := base;
c.wrapped := FALSE;
v.InitContext(c); Stores.Join(v, base);
RETURN c
END NewContext;
(* get spec dialogs *)
PROCEDURE BrowserConfirm*;
VAR action: Dialog.GetAction;
BEGIN
IF (browser # NIL)
& ~((browser.type = open) &
(browser.focusFileInfoNum = undefined)) THEN
IF browser.type = location THEN
IF name # "" THEN
browser.action.loc := browser.action.loc.This(name)
END;
browser.action.name := ""
ELSE
browser.action.name := name$
END;
IF browser.converter # NIL THEN
IF browser.type = save THEN
browser.action.converterName := browser.converter.exp
ELSIF browser.type = open THEN
browser.action.converterName := browser.converter.imp
END;
browser.action.type := browser.converter.fileType$
ELSE
browser.action.converterName := "";
browser.action.type := ""
END;
browser.action.cancel := FALSE;
lastLoc := browser.action.loc;
action := browser.action;
browser := NIL;
action.Do;
END
END BrowserConfirm;
PROCEDURE BrowserConfirmGuard* (VAR par: Dialog.Par);
BEGIN
IF browser # NIL THEN
par.disabled := FALSE;
CASE browser.type OF
| open:
par.disabled := (browser.focusFileInfoNum = undefined)
| save:
par.disabled := (name$ = "")
| location:
par.disabled := (browser.focusLocInfoNum < 0)
ELSE END
END
END BrowserConfirmGuard;
PROCEDURE BrowserCancel*;
BEGIN
IF browser # NIL THEN
browser.action.cancel := TRUE;
browser.action.Do;
browser := NIL
END
END BrowserCancel;
PROCEDURE BrowserNewFolderDialog*;
BEGIN
IF browser # NIL THEN
fName := "";
browser.activeAddFolder := TRUE;
browser.focusView := browser.fNameField.view
END
END BrowserNewFolderDialog;
PROCEDURE CloseAddFolder;
BEGIN
IF browser # NIL THEN
fName := "";
browser.focusView := browser.files.view;
browser.activeAddFolder := FALSE;
Views.Update(browser, Views.rebuildFrames)
END
END CloseAddFolder;
PROCEDURE BrowserCreateFolderGuard* (VAR par: Dialog.Par);
VAR
locInfo: Files.LocInfo;
BEGIN
IF browser # NIL THEN
par.disabled := (fName$ = "");
(* check if folder already exists *)
IF ~par.disabled THEN
locInfo := Files.dir.LocList(browser.action.loc);
WHILE (locInfo # NIL) & (locInfo.name # fName) DO locInfo := locInfo.next END;
par.disabled := (locInfo # NIL)
END
END
END BrowserCreateFolderGuard;
PROCEDURE BrowserCreateFolder*;
VAR file: Files.File; res, n, y: INTEGER; loc: Files.Locator; locInfo: Files.LocInfo;
BEGIN
IF (browser # NIL) & (fName$ # "") THEN
(* check if folder already exists *)
locInfo := Files.dir.LocList(browser.action.loc);
WHILE (locInfo # NIL) & (locInfo.name # fName) DO
locInfo := locInfo.next
END;
IF locInfo = NIL THEN
(* create new folder by making temp file *)
loc := browser.action.loc.This(fName);
IF loc.res = 0 THEN
file := Files.dir.New(loc, Files.dontAsk);
IF loc.res = 0 THEN
file.Register('.temp', '', Files.dontAsk, res);
Files.dir.Delete(loc, ".temp")
ELSE
Dialog.ShowMsg("error")
END
ELSE
Dialog.ShowMsg("error")
END
END;
(* select folder *)
locInfo := Files.dir.LocList(browser.action.loc);
n := 0; y := itemHeight * 2;
WHILE (locInfo # NIL) & (locInfo.name # fName) DO
IF ~IsHidden(locInfo) THEN
INC(y, itemHeight);
INC(n)
END;
locInfo := locInfo.next
END;
IF locInfo # NIL THEN
browser.focusFileInfoNum := undefined;
browser.focusLocInfoNum := n
END;
Views.Update(browser, Views.rebuildFrames);
StdScrollers.WrappedView(browser.files.view).context.MakeVisible(0, y, 0, y + itemHeight);
browser.focusView := browser.files.view;
browser.activeAddFolder := FALSE
END
END BrowserCreateFolder;
PROCEDURE PreventCleanup*;
BEGIN
preventCleanup := TRUE
END PreventCleanup;
PROCEDURE (c: CloseNotifier) Notify (VAR msg: Sequencers.Message);
BEGIN
IF ~preventCleanup THEN
browser := NIL
END
END Notify;
PROCEDURE GetFirstLocInfo (): Files.LocInfo;
VAR locInfo: Files.LocInfo;
BEGIN
IF ~showHidden THEN
locInfo := Files.dir.LocList(browser.action.loc);
WHILE (locInfo # NIL) & IsHidden(locInfo) DO
locInfo := locInfo.next
END
ELSE
locInfo := Files.dir.LocList(browser.action.loc)
END;
RETURN locInfo
END GetFirstLocInfo;
PROCEDURE GetFirstFileInfo (): Files.FileInfo;
VAR fileInfo: Files.FileInfo;
BEGIN
IF ~showHidden THEN
fileInfo := Files.dir.FileList(browser.action.loc);
WHILE (fileInfo # NIL) & IsHidden(fileInfo) DO
fileInfo := fileInfo.next
END
ELSE
fileInfo := Files.dir.FileList(browser.action.loc)
END;
RETURN fileInfo
END GetFirstFileInfo;
PROCEDURE (v: FilesBrowser) IsConvOpen (): BOOLEAN, NEW;
BEGIN
RETURN (v.convertersHeight # closedConvList)
END IsConvOpen;
PROCEDURE (v: FilesBrowser) ConvOpen, NEW;
BEGIN
IF ~v.IsConvOpen() & (v.convList.next # NIL) THEN
v.forceMakeCurrFVisible := TRUE;
v.convertersHeight := expandedConvList;
v.focusView := v.converters.view;
Views.Update(v, Views.rebuildFrames)
END
END ConvOpen;
PROCEDURE (v: FilesBrowser) ConvClose, NEW;
BEGIN
IF v.IsConvOpen() THEN
v.forceMakeCurrFVisible := TRUE;
v.convertersHeight := closedConvList;
v.focusView := v.files.view;
Views.Update(v, Views.rebuildFrames)
(*StdScrollers.WrappedView(v.files.view).context.MakeVisible(0, 0, 1, 1)*)
END
END ConvClose;
PROCEDURE (v: FilesBrowser) IsGoodConv (cc: Converters.Converter): BOOLEAN, NEW;
VAR
res: BOOLEAN;
BEGIN
res := FALSE;
IF cc # NIL THEN
IF (v.type = open) & (cc.imp # "") THEN res := TRUE
ELSIF (v.type = save) & (cc.exp # "") THEN res := TRUE
END
END;
RETURN res
END IsGoodConv;
(* HACK! *)
PROCEDURE (v: FilesBrowser) ConvResetFileCursor, NEW;
VAR
locs: INTEGER;
BEGIN
IF v.focusFileInfoNum # undefined THEN
v.focusFileInfoNum := undefined;
locs := CountLocs(v);
IF locs > 0 THEN v.focusLocInfoNum := locs - 1
ELSE v.focusLocInfoNum := undefined
END
END;
v.forceMakeCurrFVisible := TRUE
END ConvResetFileCursor;
PROCEDURE RecalcLayout (v: FilesBrowser; w, h: INTEGER);
VAR
sep, leftTitlesWidth, w1, w2, nameShift: INTEGER;
nameStr, locatorStr: Dialog.String;
c: Context;
BEGIN
Dialog.MapString("#Std:Name:", nameStr);
w1 := v.font.StringWidth(nameStr);
Dialog.MapString("#Std:Locator:", locatorStr);
w2 := v.font.StringWidth(locatorStr);
leftTitlesWidth := MAX(w1, w2) + v.margin * 2;
sep := w DIV 3;
(* name input field *)
IF v.nameField # NIL THEN
c := v.nameField;
c.l := v.margin + leftTitlesWidth;
c.t := v.margin;
c.r := w - v.margin;
c.b := v.margin + 7 * Ports.mm;
nameShift := 7 * Ports.mm + v.margin
END;
IF v.fNameField # NIL THEN
IF v.activeAddFolder THEN
(* path and "add folder" button *)
c := v.pathField;
c.l := v.margin + leftTitlesWidth;
c.t := v.margin + nameShift;
c.r := w - 70 * Ports.mm - v.margin * 3;
c.b := v.margin + nameShift + 7 * Ports.mm;
c := v.fNameField;
c.l := w - 70 * Ports.mm - 2 * v.margin;
c.t := v.margin + nameShift;
c.r := w - 20 * Ports.mm - 2 * v.margin;
c.b := v.margin + nameShift + 7 * Ports.mm;
c := v.confirmAddButton;
c.l := w - 20 * Ports.mm - v.margin;
c.t := v.margin + nameShift;
c.r := w - v.margin;
c.b := v.margin + nameShift + 7 * Ports.mm
ELSE
(* path only *)
c := v.pathField;
c.l := v.margin + leftTitlesWidth;
c.t := v.margin + nameShift;
c.r := w - 30 * Ports.mm - v.margin * 2;
c.b := v.margin + nameShift + 7 * Ports.mm;
c := v.addButton;
c.l := w - 30 * Ports.mm - v.margin;
c.t := v.margin + nameShift;
c.r := w - v.margin;
c.b := v.margin + nameShift + 7 * Ports.mm
END;
nameShift := nameShift + 7 * Ports.mm + v.margin
ELSE
(* path only *)
c := v.pathField;
c.l := v.margin + leftTitlesWidth;
c.t := v.margin;
c.r := w - v.margin;
c.b := v.margin + 7 * Ports.mm;
nameShift := v.margin + 7 * Ports.mm
END;
c := v.places;
c.l := v.margin;
c.t := v.margin + nameShift;
c.r := sep - v.margin;
c.b := h - v.margin - 10 * Ports.mm;
IF v.converters # NIL THEN
c := v.files;
c.l := sep + v.margin;
c.t := v.margin + nameShift;
c.r := w - v.margin;
c.b := h - v.margin - 10 * Ports.mm - (v.convertersHeight + v.margin);
c := v.converters;
c.l := sep + v.margin;
c.t := h - v.margin - 10 * Ports.mm - (v.convertersHeight);
c.r := w - v.margin;
c.b := h - v.margin - 10 * Ports.mm
ELSE
c := v.files;
c.l := sep + v.margin;
c.t := v.margin + nameShift;
c.r := w - v.margin;
c.b := h - v.margin - 10 * Ports.mm
END;
c := v.confirmButton;
c.l := w - v.margin - 74 * Ports.mm;
c.t := h - v.margin - 8 * Ports.mm;
c.r := w - v.margin - 38 * Ports.mm;
c.b := h - v.margin;
c := v.cancelButton;
c.l := w - v.margin - 36 * Ports.mm;
c.t := h - v.margin - 8 * Ports.mm;
c.r := w - v.margin;
c.b := h - v.margin
END RecalcLayout;
PROCEDURE (v: FilesBrowser) Restore (f: Views.Frame; l_, t_, r_, b_: INTEGER);
VAR
c: Context; conv: Converters.Converter;
d, w, h, asc, dsc, w_, locs, files: INTEGER;
nameStr, locatorStr: Dialog.String; removeFrame: Views.Frame;
BEGIN
IF browser = NIL THEN RETURN END;
v.context.GetSize(w, h);
f.DrawRect(0, 0, w, h, Ports.fill, Ports.dialogBackground);
RecalcLayout(v, w, h);
browser.font.GetBounds(asc, dsc, w_);
(* draw name input field *)
IF v.nameField # NIL THEN
c := v.nameField;
Views.InstallFrame(f, c.view, c.l, c.t, 0, TRUE);
Dialog.MapString("#Std:Name:", nameStr);
f.DrawString(v.margin+Ports.mm, c.t+(c.b-c.t) DIV 2 + asc DIV 2 - Ports.mm DIV 2,
Ports.black, nameStr, browser.font)
END;
(* draw locator label *)
c := v.pathField;
Views.InstallFrame(f, c.view, c.l, c.t, 0, TRUE);
Dialog.MapString("#Std:Locator:", locatorStr);
f.DrawString(v.margin + Ports.mm, c.t+(c.b-c.t) DIV 2 + asc DIV 2 - Ports.mm DIV 2, Ports.black, locatorStr, browser.font);
(* draw places *)
c := v.places;
Views.InstallFrame(f, c.view, c.l, c.t, 0, TRUE);
c := v.files;
(* calculate size of files list, possible to optimize *)
c.view.context.GetSize(w_, h);
StdScrollers.WrappedView(c.view).context.GetSize(w, h);
CountLocsFiles(v, locs, files);
IF v.type = location THEN
h := (locs + 2) * itemHeight
ELSE
h := (locs + files + 2) * itemHeight
END;
StdScrollers.WrappedView(c.view).context.SetSize(w_, h);
Views.InstallFrame(f, c.view, c.l, c.t, 0, TRUE);
(* draw file types *)
IF v.converters # NIL THEN
c := v.converters;
c.view.context.GetSize(w_, h);
StdScrollers.WrappedView(c.view).context.GetSize(w, h);
IF ~v.IsConvOpen() THEN
h := closedConvList
ELSE
h := itemHeight * 2;
conv := v.convList;
WHILE conv # NIL DO
IF v.IsGoodConv(conv) THEN INC(h, itemHeight) END;
conv := conv.next
END
END;
StdScrollers.WrappedView(c.view).context.SetSize(w_, h);
Views.InstallFrame(f, c.view, c.l, c.t, 0, TRUE)
END;
(* draw buttons *)
c := v.confirmButton;
Views.InstallFrame(f, c.view, c.l, c.t, 0, TRUE);
c := v.cancelButton;
Views.InstallFrame(f, c.view, c.l, c.t, 0, TRUE);
(* add new direcrory button *)
IF v.activeAddFolder THEN
IF v.addButton # NIL THEN
removeFrame := Views.ThisFrame(f, v.addButton.view);
IF removeFrame # NIL THEN Views.RemoveFrame(f, removeFrame) END
END;
IF v.fNameField # NIL THEN
c := v.fNameField;
Views.InstallFrame(f, c.view, c.l, c.t, 0, TRUE)
END;
IF v.confirmAddButton # NIL THEN
c := v.confirmAddButton;
Views.InstallFrame(f, c.view, c.l, c.t, 0, TRUE)
END
ELSE
IF v.fNameField # NIL THEN
removeFrame := Views.ThisFrame(f, v.fNameField.view);
IF removeFrame # NIL THEN Views.RemoveFrame(f, removeFrame) END
END;
IF v.confirmAddButton # NIL THEN
removeFrame := Views.ThisFrame(f, v.confirmAddButton.view);
IF removeFrame # NIL THEN Views.RemoveFrame(f, removeFrame) END
END;
IF v.addButton # NIL THEN
c := v.addButton;
Views.InstallFrame(f, c.view, c.l, c.t, 0, TRUE)
END
END;
(* draw frame around the subviews *)
d := f.dot;
IF v.places # NIL THEN
c := v.places;
IF (c.t - d < c.b + d) & (c.l - d < c.r + d) THEN
IF v.focusView = c.view THEN
f.DrawRect(c.l - d, c.t - d, c.r + d, c.b + d, 2 * f.dot, Ports.black)
ELSE
f.DrawRect(c.l - d, c.t - d, c.r + d, c.b + d, f.dot, Ports.black)
END
END
END;
IF v.files # NIL THEN
c := v.files;
IF (c.t - d < c.b + d) & (c.l - d < c.r + d) THEN
IF v.focusView = c.view THEN
f.DrawRect(c.l - d, c.t - d, c.r + d, c.b + d, 2 * f.dot, Ports.black)
ELSE
f.DrawRect(c.l - d, c.t - d, c.r + d, c.b + d, f.dot, Ports.black)
END
END
END;
IF v.converters # NIL THEN
c := v.converters;
IF (c.t - d < c.b + d) & (c.l - d < c.r + d) THEN
IF v.focusView = c.view THEN
f.DrawRect(c.l - d, c.t - d, c.r + d, c.b + d, 2 * f.dot, Ports.black)
ELSE
f.DrawRect(c.l - d, c.t - d, c.r + d, c.b + d, f.dot, Ports.black)
END
END
END
END Restore;
PROCEDURE (v: FilesBrowser) HandleCtrlMsg (f: Views.Frame;
VAR msg: Controllers.Message; VAR focus: Views.View);
VAR
g: Views.Frame;
res_: INTEGER;
eaten: BOOLEAN;
(* foward edit msgs to focused view *)
PROCEDURE PassMessage;
BEGIN
IF v.focusView # NIL THEN
IF (v.addButton # NIL) & (v.focusView = v.addButton.view) THEN focus := v.files.view
ELSE focus := v.focusView
END
END
END PassMessage;
(* k8: sorry for this mess! *)
PROCEDURE DoTabNext;
BEGIN
IF v.focusView = NIL THEN
eaten := TRUE;
IF v.nameField # NIL THEN v.focusView := v.nameField.view
ELSE v.focusView := v.files.view
END
ELSIF (v.nameField # NIL) & (v.focusView = v.nameField.view) THEN
eaten := TRUE;
IF v.addButton # NIL THEN v.focusView := v.addButton.view
ELSE v.focusView := v.files.view
END
ELSIF (v.addButton # NIL) & (v.focusView = v.addButton.view) THEN
eaten := TRUE;
v.focusView := v.files.view
ELSIF (v.fNameField # NIL) & (v.focusView = v.fNameField.view) THEN
eaten := TRUE;
IF v.confirmAddButton # NIL THEN
v.focusView := v.confirmAddButton.view
END
ELSIF (v.confirmAddButton # NIL) & (v.focusView = v.confirmAddButton.view) THEN
eaten := TRUE;
IF v.fNameField # NIL THEN
v.focusView := v.fNameField.view
END
ELSIF v.focusView = v.files.view THEN
IF v.nameField # NIL THEN v.focusView := v.nameField.view; eaten := TRUE END
END
END DoTabNext;
(* k8: sorry for this mess! *)
PROCEDURE DoTabPrev;
BEGIN
IF v.focusView = NIL THEN
eaten := TRUE;
IF v.nameField # NIL THEN v.focusView := v.nameField.view
ELSE v.focusView := v.files.view
END
ELSIF (v.nameField # NIL) & (v.focusView = v.nameField.view) THEN
eaten := TRUE;
v.focusView := v.files.view
ELSIF (v.addButton # NIL) & (v.focusView = v.addButton.view) THEN
eaten := TRUE;
IF v.nameField # NIL THEN v.focusView := v.nameField.view
ELSE v.focusView := v.files.view
END
ELSIF (v.fNameField # NIL) & (v.focusView = v.fNameField.view) THEN
eaten := TRUE;
IF v.confirmAddButton # NIL THEN
v.focusView := v.confirmAddButton.view
END
ELSIF (v.confirmAddButton # NIL) & (v.focusView = v.confirmAddButton.view) THEN
eaten := TRUE;
IF v.fNameField # NIL THEN
v.focusView := v.fNameField.view
END
ELSIF v.focusView = v.files.view THEN
IF v.nameField # NIL THEN v.focusView := v.nameField.view; eaten := TRUE END
END
END DoTabPrev;
BEGIN
WITH msg: Controllers.TrackMsg DO
g := Views.FrameAt(f, msg.x, msg.y);
IF g # NIL THEN
focus := g.view;
v.focusView := g.view
END
| msg: Controllers.CursorMessage DO
g := Views.FrameAt(f, msg.x, msg.y);
IF g # NIL THEN focus := g.view END
| msg: Controllers.EditMsg DO
eaten := FALSE;
IF (msg.op = Controllers.pasteChar) & (msg.char = Tab) &
(msg.modifiers*{Controllers.extend,Controllers.modify,Controllers.pick} # {}) THEN
DoTabPrev
ELSIF (msg.op = Controllers.pasteChar) & (msg.modifiers = {}) THEN
CASE msg.char OF
| Enter:
IF (v.nameField # NIL) & (v.focusView = v.nameField.view) THEN
eaten := TRUE;
PreventCleanup;
Dialog.Call("StdCmds.CloseTopDialog", "", res_);
BrowserConfirm
ELSIF (v.fNameField # NIL) & (v.focusView = v.fNameField.view) THEN
eaten := TRUE;
BrowserCreateFolder
END
| Esc:
IF (v.fNameField # NIL) & (v.focusView = v.fNameField.view) THEN
eaten := TRUE;
CloseAddFolder
ELSIF ~v.IsConvOpen() THEN
eaten := TRUE;
BrowserCancel;
Dialog.Call("StdCmds.CloseTopDialog", "", res_)
END
| Tab:
DoTabNext
ELSE END
END;
IF eaten THEN
Views.Update(v, Views.rebuildFrames(*keepFrames*))
ELSE
PassMessage
END
| msg: Controllers.Message DO
IF (v.nameField # NIL) & (v.focusView = v.nameField.view) THEN
focus := v.focusView
END
ELSE END
END HandleCtrlMsg;
(* places table *)
PROCEDURE (v: FilesBrowserPlaces) Restore (f: Views.Frame; l_, t_, r_, b_: INTEGER);
VAR x, y: INTEGER; str, path: Dialog.String; p: Place;
BEGIN
v.context.GetSize(x, y);
f.DrawRect(0, 0, x, y, Ports.fill, Ports.white);
Dialog.GetLocPath(browser.action.loc, path);
x := 5 * Ports.mm; y := 7 * Ports.mm;
p := place;
WHILE p # NIL DO
Dialog.MapString("#Std:" + p.name, str);
IF path = p.path THEN
f.DrawRect(
x - Ports.mm,
y - 4 * Ports.mm,
x + browser.font.StringWidth(str) + Ports.mm,
y + Ports.mm,
Ports.fill, param.bgActivePlace)
END;
f.DrawString(x, y, Ports.black, str, v.base.font);
y := y + 7 * Ports.mm;
p := p.next
END
END Restore;
PROCEDURE (v: FilesBrowserPlaces) HandleCtrlMsg (f_: Views.Frame;
VAR msg: Controllers.Message; VAR focus: Views.View);
VAR pos: INTEGER; p: Place;
BEGIN
WITH msg: Controllers.TrackMsg DO
pos := Ports.mm * 7;
p := place;
WHILE (p # NIL) & (msg.y > pos) DO
pos := pos + Ports.mm * 7;
p := p.next
END;
IF p # NIL THEN
IF p.specialAction # NIL THEN p.specialAction(v)
ELSE
v.base.action.loc := Files.dir.This(p.path);
v.base.focusLocInfoNum := back;
v.base.focusFileInfoNum := undefined;
UpdatePath;
StdScrollers.WrappedView(v.base.files.view).context.MakeVisible(0, 0, 1, 1);
Views.Update(v.base.files.view, Views.rebuildFrames(*keepFrames*))
END
END
ELSE END
END HandleCtrlMsg;
(* converters table *)
PROCEDURE (v: FilesBrowserConverters) Restore (f: Views.Frame; l_, t_, r_, b_: INTEGER);
VAR x, y, n, i: INTEGER; str: Dialog.String; conv: Converters.Converter;
PROCEDURE MapConv (IN cmd: ARRAY OF CHAR; VAR name: ARRAY OF CHAR);
VAR i: INTEGER; sub, str: Dialog.String;
BEGIN
str := cmd$; i := 0;
WHILE str[i] >= "0" DO INC(i) END;
str[i] := 0X;
Librarian.lib.SplitName(str, sub, str);
Dialog.MapString("#"+sub+":"+cmd, name)
END MapConv;
BEGIN
v.context.GetSize(x, y);
IF ~v.base.IsConvOpen() THEN
IF v.base.convList.next # NIL THEN
f.DrawRect(0, 0, x, y, Ports.fill, Ports.white)
ELSE
f.DrawRect(0, 0, x, y, Ports.fill, Ports.grey12)
END;
x := 3 * Ports.mm; y := 4 * Ports.mm + Ports.mm DIV 2;
IF v.base.converter # NIL THEN
IF v.base.type = open THEN
MapConv(v.base.converter.imp, str)
ELSIF browser.type = save THEN
MapConv(v.base.converter.exp, str)
END;
f.DrawString(x, y, Ports.black, str+" (*."+v.base.converter.fileType+")", v.base.font)
ELSIF (v.base.initTypes = NIL) OR (v.base.initTypes[0] = "*") THEN
Dialog.MapString("#System:AllFiles", str);
f.DrawString(x, y, Ports.black, str + " (*.*)", v.base.font)
ELSE
Dialog.MapString("#System:AllSupportedFiles", str);
str := str + " (";
FOR i := 0 TO LEN(v.base.initTypes) - 1 DO
str := str + "*." + v.base.initTypes[i] + ","
END;
str[LEN(str$)-1] := 0X; (* remove last comma *)
str := str + ")";
f.DrawString(x, y, Ports.black, str, v.base.font)
END
ELSE
f.DrawRect(0, 0, x, y, Ports.fill, Ports.white);
x := 3 * Ports.mm; y := 5 * Ports.mm;
conv := v.base.convList;
n := 0;
WHILE conv # NIL DO
str := "";
IF v.base.type = open THEN
MapConv(conv.imp, str)
ELSIF v.base.type = save THEN
MapConv(conv.exp, str)
END;
IF str # "" THEN
IF conv = v.base.converter THEN
f.DrawRect(
x - Ports.mm,
y - 4*Ports.mm,
x + 16*Ports.mm + v.base.font.StringWidth(str) + 14*f.dot + 2*Ports.mm,
y + Ports.mm,
Ports.fill, param.bgActiveConverter)
END;
f.DrawString(x, y, Ports.black, str + " (*." + conv.fileType + ")", v.base.font);
INC(y, itemHeight)
END;
conv := conv.next;
INC(n)
END;
IF (n > 1) & (v.base.type = open) THEN
IF v.base.converter = NIL THEN
f.DrawRect(
x - Ports.mm,
y - 4*Ports.mm,
x + 16*Ports.mm + v.base.font.StringWidth(str) + 14*f.dot + 2*Ports.mm,
y + Ports.mm,
Ports.fill, param.bgActiveConverter)
END;
IF (v.base.initTypes = NIL) OR (v.base.initTypes[0] = "*") THEN
Dialog.MapString("#System:AllFiles", str);
f.DrawString(x, y, Ports.black, str + " (*.*)", v.base.font)
ELSE
Dialog.MapString("#System:AllSupportedFiles", str);
str := str + " (";
FOR i := 0 TO LEN(v.base.initTypes) - 1 DO
str := str + "*." + v.base.initTypes[i] + ","
END;
str[LEN(str$)-1] := 0X; (* remove last comma *)
str := str + ")";
f.DrawString(x, y, Ports.black, str, v.base.font)
END
END
END
END Restore;
PROCEDURE (v: FilesBrowserConverters) HandleCtrlMsg (f_: Views.Frame;
VAR msg: Controllers.Message; VAR focus: Views.View);
VAR
okconv: Converters.Converter;
forceSet: BOOLEAN;
PROCEDURE MakeCurrConvVisible;
VAR
conv: Converters.Converter;
y: INTEGER;
done: BOOLEAN;
BEGIN
done := FALSE;
y := 5 * Ports.mm;
conv := v.base.convList;
WHILE ~done & (conv # NIL) DO
IF conv = v.base.converter THEN done := TRUE
ELSE
IF v.base.IsGoodConv(conv) THEN INC(y, itemHeight) END;
conv := conv.next
END
END;
IF (conv = NIL) & (v.base.type = open) THEN done := TRUE END;
IF done THEN
DEC(y, itemHeight - Ports.mm);
v.context.MakeVisible(0, y, 1, y+itemHeight-1)
END
END MakeCurrConvVisible;
PROCEDURE DoMouseSelect (y: INTEGER);
VAR
conv: Converters.Converter;
h: INTEGER;
BEGIN
conv := v.base.convList;
h := itemHeight;
WHILE (conv # NIL) & (h < y) DO
conv := conv.next;
IF v.base.IsGoodConv(conv) THEN INC(h, itemHeight) END
END;
IF (conv # NIL) OR (v.base.type = open) THEN
v.base.converter := conv;
IF conv # NIL THEN v.base.action.type := conv.fileType$ END;
v.base.ConvClose
END
END DoMouseSelect;
PROCEDURE GoUp;
VAR
conv: Converters.Converter;
BEGIN
conv := v.base.convList;
WHILE (conv # NIL) & (conv # v.base.converter) DO
IF v.base.IsGoodConv(conv) THEN okconv := conv END;
conv := conv.next
END
END GoUp;
PROCEDURE GoDown;
VAR
conv: Converters.Converter;
BEGIN
conv := v.base.converter;
WHILE (okconv = NIL) & (conv # NIL) & (conv.next # NIL) DO
conv := conv.next;
IF v.base.IsGoodConv(conv) THEN okconv := conv END
END;
IF (okconv = NIL) & (v.base.type = open) THEN forceSet := TRUE END
END GoDown;
PROCEDURE GoHome;
VAR
conv: Converters.Converter;
BEGIN
conv := v.base.convList;
WHILE (okconv = NIL) & (conv # NIL) DO
IF v.base.IsGoodConv(conv) THEN okconv := conv END;
conv := conv.next
END;
IF (okconv # NIL) & (okconv = v.base.converter) THEN okconv := NIL END
END GoHome;
PROCEDURE GoEnd;
VAR
conv: Converters.Converter;
BEGIN
IF v.base.type = open THEN
okconv := NIL; forceSet := (v.base.converter # NIL)
ELSE
conv := v.base.convList;
WHILE (conv # NIL) DO
IF v.base.IsGoodConv(conv) THEN okconv := conv END;
conv := conv.next
END;
IF (okconv # NIL) & (okconv = v.base.converter) THEN okconv := NIL END
END
END GoEnd;
BEGIN
WITH msg: Controllers.ScrollMsg DO v.base.ConvOpen
| msg: Controllers.TrackMsg DO
IF ~v.base.IsConvOpen() THEN
v.base.ConvOpen
ELSE
DoMouseSelect(msg.y)
END
| msg: Controllers.EditMsg DO
okconv := NIL; forceSet := FALSE;
IF (msg.op = Controllers.pasteChar) & (msg.modifiers = {}) THEN
CASE msg.char OF
| Enter, Esc: v.base.ConvClose
| UpArrow: GoUp
| DownArrow: GoDown
| HomeKey: GoHome
| EndKey: GoEnd
ELSE END;
IF forceSet OR ((okconv # NIL) & (okconv # v.base.converter)) THEN
v.base.converter := okconv;
IF okconv # NIL THEN v.base.action.type := okconv.fileType$ END;
MakeCurrConvVisible;
v.base.ConvResetFileCursor;
Views.Update(v.base, Views.rebuildFrames)
END
END
ELSE END
END HandleCtrlMsg;
(* files table *)
PROCEDURE (v: FilesBrowserTable) Restore (f: Views.Frame; l_, t_, r, b_: INTEGER);
VAR
locInfo: Files.LocInfo;
fileInfo: Files.FileInfo;
x, y, n: INTEGER;
visy: INTEGER;
BEGIN
visy := -1024;
x := Ports.mm * 5;
y := itemHeight;
IF -1 = v.base.focusLocInfoNum THEN
visy := y;
f.DrawRect(
x - Ports.mm, y - 4 * Ports.mm,
r - Ports.mm * 2, y + Ports.mm,
Ports.fill, param.bgCursorUpDir)
END;
f.DrawString(x, y, Ports.black, param.upDirStr, v.base.font);
INC(y, itemHeight);
(* draw dirs *)
locInfo := Files.dir.LocList(v.base.action.loc);
n := 0;
WHILE locInfo # NIL DO
IF ~IsHidden(locInfo) THEN
IF n = v.base.focusLocInfoNum THEN
(* selected dir background *)
visy := y;
f.DrawRect(
x - Ports.mm,
y - 4 * Ports.mm,
r - Ports.mm * 2,
y + Ports.mm,
Ports.fill, param.bgCursorDir)
END;
(* folder icon *)
f.DrawRect(x, y - 12 * f.dot, x + 12 * f.dot, y - 9 * f.dot, Ports.fill, Ports.grey50);
f.DrawRect(x, y - 9 * f.dot, x + 14 * f.dot, y + 2 * f.dot, Ports.fill, Ports.grey75);
(* folder name *)
f.DrawString(x + 16 * f.dot, y, Ports.black, locInfo.name, v.base.font);
INC(y, itemHeight);
INC(n)
END;
locInfo := locInfo.next
END;
(* draw files *)
IF v.base.type # location THEN
fileInfo := Files.dir.FileList(v.base.action.loc);
n := 0;
WHILE fileInfo # NIL DO
IF ~IsHidden(fileInfo) THEN
IF n = v.base.focusFileInfoNum THEN
(* selected file background *)
visy := y;
f.DrawRect(
x - Ports.mm, y - 4 * Ports.mm,
r - Ports.mm * 2, y + Ports.mm,
Ports.fill, param.bgCursorFile)
END;
f.DrawString(x, y, Ports.black, fileInfo.name, v.base.font);
INC(y, itemHeight);
INC(n)
END;
fileInfo := fileInfo.next
END
END;
(* k8: i'm not sure if it is legal to do this here, but meh... it seems to work *)
IF v.base.forceMakeCurrFVisible THEN
v.base.forceMakeCurrFVisible := FALSE;
IF visy >= 0 THEN
v.context.MakeVisible(0, visy - 4 * Ports.mm, 1, visy + itemHeight)
END
END
END Restore;
PROCEDURE (v: FilesBrowserTable) HandleCtrlMsg (f_: Views.Frame;
VAR msg: Controllers.Message; VAR focus: Views.View);
VAR
locInfo: Files.LocInfo; fileInfo: Files.FileInfo; tmp: Files.Name;
y, n, locs, files: INTEGER;
w, h: INTEGER;
PROCEDURE OpenItem (msgy: INTEGER);
VAR
res_: INTEGER;
BEGIN
IF v.base.type # save THEN
name := ""
END;
IF msgy < itemHeight THEN
GoOneDirUp(v.base)
ELSE
y := itemHeight * 2;
locInfo := GetFirstLocInfo();
WHILE (locInfo # NIL) & (y < msgy) DO
IF ~IsHidden(locInfo) THEN
INC(y, itemHeight)
END;
locInfo := locInfo.next
END;
IF locInfo # NIL THEN
IF (v.base.type IN {save, open})
OR (Files.dir.LocList(v.base.action.loc.This(locInfo.name)) # NIL) THEN
v.base.focusLocInfoNum := back;
v.base.focusFileInfoNum := undefined;
v.base.action.loc := v.base.action.loc.This(locInfo.name);
UpdatePath
END
ELSIF v.base.type # location THEN
(* open file *)
n := 0; tmp := ""; DEC(y, itemHeight);
fileInfo := GetFirstFileInfo();
WHILE (fileInfo # NIL) & (y < msgy) DO
IF ~IsHidden(fileInfo) THEN
INC(y, itemHeight);
INC(n);
tmp := fileInfo.name
END;
fileInfo := fileInfo.next
END;
IF n # 0 THEN
IF (v.base.type = open) OR (tmp # "") THEN
name := tmp;
PreventCleanup;
Dialog.Call("StdCmds.CloseTopDialog", "", res_);
BrowserConfirm
END
END
END
END
END OpenItem;
PROCEDURE MakeItemVisible;
BEGIN
IF v.base.focusLocInfoNum < 0 THEN
IF v.base.focusFileInfoNum < 0 THEN
v.context.MakeVisible(0, 0, 1, 1)
ELSE
v.context.MakeVisible(
0, (locs + (v.base.focusFileInfoNum+1))*itemHeight,
1, (locs + (v.base.focusFileInfoNum+2))*itemHeight+itemHeight DIV 2)
END
ELSE
v.context.MakeVisible(
0, (v.base.focusLocInfoNum+1)*itemHeight,
1, (v.base.focusLocInfoNum+2)*itemHeight + itemHeight DIV 2)
END
END MakeItemVisible;
PROCEDURE CursorMoved;
BEGIN
UpdatePath;
Views.Update(v.base.files.view, Views.rebuildFrames(*keepFrames*));
MakeItemVisible
END CursorMoved;
PROCEDURE MoveUpDown (delta: INTEGER);
BEGIN
CountLocsFiles(v.base, locs, files);
WHILE delta # 0 DO
IF delta < 0 THEN
IF v.base.focusFileInfoNum > 0 THEN
DEC(v.base.focusFileInfoNum)
ELSE
v.base.focusFileInfoNum := undefined;
IF v.base.focusLocInfoNum = undefined THEN
IF locs = 0 THEN
v.base.focusLocInfoNum := back
ELSE
v.base.focusLocInfoNum := locs - 1
END
ELSIF v.base.focusLocInfoNum > back THEN
DEC(v.base.focusLocInfoNum)
END
END;
INC(delta)
ELSE
IF (v.base.focusFileInfoNum = undefined) & (v.base.focusLocInfoNum < locs-1) THEN
INC(v.base.focusLocInfoNum)
ELSIF (v.base.type # location) & (files > 0) THEN
v.base.focusLocInfoNum := undefined;
IF v.base.focusFileInfoNum < files THEN
IF v.base.focusFileInfoNum = undefined THEN
v.base.focusFileInfoNum := 0
ELSE
IF v.base.focusFileInfoNum < files - 1 THEN
INC(v.base.focusFileInfoNum)
END
END
END
END;
DEC(delta)
END
END;
CursorMoved
END MoveUpDown;
PROCEDURE MoveHome;
BEGIN
CountLocsFiles(v.base, locs, files);
IF v.base.focusFileInfoNum > 0 THEN
v.base.focusFileInfoNum := 0
ELSIF v.base.focusFileInfoNum = 0 THEN
IF locs > 0 THEN
v.base.focusFileInfoNum := undefined;
v.base.focusLocInfoNum := 0
END
ELSIF v.base.focusLocInfoNum > 0 THEN
v.base.focusFileInfoNum := undefined;
v.base.focusLocInfoNum := 0
ELSIF v.base.focusLocInfoNum = 0 THEN
IF files > 0 THEN
v.base.focusFileInfoNum := 0;
v.base.focusLocInfoNum := undefined
END
END;
CursorMoved
END MoveHome;
PROCEDURE MoveEnd;
BEGIN
CountLocsFiles(v.base, locs, files);
IF (files > 0) & (v.base.focusFileInfoNum # undefined) &(v.base.focusFileInfoNum < files-1) THEN
v.base.focusFileInfoNum := files-1
ELSIF (files > 0) & (v.base.focusFileInfoNum = files-1) THEN
IF locs > 0 THEN
v.base.focusFileInfoNum := undefined;
v.base.focusLocInfoNum := locs-1
END
ELSIF (locs > 0) & (v.base.focusLocInfoNum # undefined) & (v.base.focusLocInfoNum < locs-1) THEN
v.base.focusFileInfoNum := undefined;
v.base.focusLocInfoNum := locs-1
ELSIF (locs > 0) & (v.base.focusLocInfoNum = locs-1) THEN
IF files > 0 THEN
v.base.focusFileInfoNum := files-1;
v.base.focusLocInfoNum := undefined
END
END;
CursorMoved
END MoveEnd;
PROCEDURE MovePageUp;
BEGIN
v.base.files.view.context.GetSize(w, h);
MoveUpDown(-(h DIV itemHeight))
END MovePageUp;
PROCEDURE MovePageDown;
BEGIN
v.base.files.view.context.GetSize(w, h);
MoveUpDown(h DIV itemHeight)
END MovePageDown;
PROCEDURE GoToPrjDir;
VAR
locs: INTEGER;
path: ARRAY 1024 OF CHAR;
BEGIN
Dialog.GetLocPath(Files.dir.This(""), path);
v.base.action.loc := v.base.action.loc.This(path);
locs := CountLocs(v.base);
v.base.focusFileInfoNum := undefined;
IF locs > 0 THEN
v.base.focusLocInfoNum := 0
ELSE
v.base.focusLocInfoNum := undefined
END;
v.base.forceMakeCurrFVisible := TRUE;
UpdatePath;
Views.Update(v.base, Views.rebuildFrames)
END GoToPrjDir;
PROCEDURE DoAcceptDirDown (): BOOLEAN;
VAR
res: BOOLEAN;
BEGIN
res := FALSE;
IF v.base.focusLocInfoNum = back THEN
res := TRUE;
GoOneDirUp(v.base)
ELSIF v.base.focusLocInfoNum # undefined THEN
res := TRUE;
locInfo := GetFirstLocInfo();
n := 0;
WHILE (locInfo # NIL) & (n < v.base.focusLocInfoNum) DO
IF ~IsHidden(locInfo) THEN INC(n) END;
locInfo := locInfo.next
END;
IF locInfo # NIL THEN
IF (v.base.type IN {save, open})
OR (Files.dir.LocList(v.base.action.loc.This(locInfo.name)) # NIL)
THEN
v.base.focusLocInfoNum := back;
v.base.focusFileInfoNum := undefined;
v.base.action.loc := v.base.action.loc.This(locInfo.name);
UpdatePath;
Views.Update(v.base.files.view, Views.rebuildFrames(*keepFrames*));
v.context.MakeVisible(0, 0, 1, 1)
END
END
END;
RETURN res
END DoAcceptDirDown;
PROCEDURE DoAccept;
VAR
n: INTEGER;
res_: INTEGER;
BEGIN
IF ~DoAcceptDirDown() & (v.base.focusFileInfoNum # undefined) THEN
fileInfo := GetFirstFileInfo();
n := 0;
WHILE (fileInfo # NIL) & (n <= v.base.focusFileInfoNum) DO
IF ~IsHidden(fileInfo) THEN
INC(n);
name := fileInfo.name$
END;
fileInfo := fileInfo.next
END;
IF name # "" THEN
PreventCleanup;
Dialog.Call("StdCmds.CloseTopDialog", "", res_);
BrowserConfirm
END
END
END DoAccept;
PROCEDURE LookupNext (ch: CHAR);
VAR
l, f: INTEGER;
BEGIN
IF LookupNextItemForChar(v.base, ch, l, f) THEN
v.base.focusLocInfoNum := l;
v.base.focusFileInfoNum := f;
CountLocsFiles(v.base, locs, files); (* requred for `MakeItemVisible()` *)
CursorMoved
END
END LookupNext;
BEGIN
WITH msg: Controllers.ScrollMsg DO
v.base.ConvClose
| msg: Controllers.TrackMsg DO
IF Controllers.doubleClick IN msg.modifiers THEN
OpenItem(msg.y);
IF browser # NIL THEN
UpdatePath;
Views.Update(v.base.files.view, Views.rebuildFrames(*keepFrames*));
v.context.MakeVisible(0, 0, 1, 1)
END
ELSE
IF msg.y < itemHeight THEN
v.base.focusLocInfoNum := back;
v.base.focusFileInfoNum := undefined
ELSE
(* search focus folder name *)
locInfo := GetFirstLocInfo();
y := itemHeight * 2 + Ports.mm;
n := 0;
WHILE (locInfo # NIL) & (y < msg.y) DO
IF ~IsHidden(locInfo) THEN
INC(y, itemHeight);
INC(n)
END;
locInfo := locInfo.next
END;
IF locInfo # NIL THEN
IF v.base.type = location THEN (* store folder name to use later *)
name := locInfo.name$
END;
v.base.focusFileInfoNum := undefined;
v.base.focusLocInfoNum := n
ELSIF v.base.type # location THEN
v.base.focusLocInfoNum := undefined;
(* search focus file name *)
fileInfo := GetFirstFileInfo();
n := 0; tmp := "";
DEC(y, itemHeight);
WHILE (fileInfo # NIL) & (y < msg.y) DO
IF ~IsHidden(fileInfo) THEN
INC(y, itemHeight);
INC(n);
tmp := fileInfo.name
END;
fileInfo := fileInfo.next
END;
IF n = 0 THEN
v.base.focusFileInfoNum := undefined
ELSE
name := tmp;
v.base.focusFileInfoNum := n - 1
END
END
END;
Views.Update(v.base.files.view, Views.rebuildFrames(*keepFrames*))
END;
v.base.ConvClose
| msg: Controllers.EditMsg DO
IF msg.op = Controllers.pasteChar THEN
(*
shift 24 extend 1 Shift key
ctrl 25 modify 2 Ctrl key
alt 28 pick 4 Alt key
*)
IF Controllers.pick IN msg.modifiers THEN (* Alt *)
IF msg.char = DownArrow THEN v.base.ConvOpen END
ELSIF msg.modifiers*{0,1,2,3,4,5,6,7} = {} THEN
CASE msg.char OF
| CtrlPageUp: GoOneDirUp(v.base)
| CtrlPageDown: IF DoAcceptDirDown() THEN END (* sorry! *)
| CtrlHome: GoToPrjDir()
| PageUp: MovePageUp
| PageDown: MovePageDown
| HomeKey: MoveHome
| EndKey: MoveEnd
| UpArrow: MoveUpDown(-1)
| DownArrow: MoveUpDown(1)
| Backspace: GoOneDirUp(v.base)
| Enter: IF msg.modifiers = {} THEN DoAccept END
ELSE (* process letters and digits *)
IF msg.modifiers = {} THEN
IF (msg.char >= 020X) & (msg.char <= 07EX) THEN
LookupNext(msg.char)
END
END
END
END
END
ELSE END
END HandleCtrlMsg;
PROCEDURE (v: FilesBrowser) HandlePropMsg (VAR msg: Properties.Message);
BEGIN
WITH msg: Properties.SizePref DO
IF (msg.w = Views.undefined) OR (msg.h = Views.undefined) THEN
msg.w := 200 * Ports.mm; msg.h := 100 * Ports.mm
END
| msg: Properties.FocusPref DO
msg.setFocus := TRUE
ELSE
END
END HandlePropMsg;
PROCEDURE (v: FilesBrowser) ConsiderFocusRequestBy (view: Views.View);
BEGIN
IF view = v.places.view THEN
v.focusView := v.places.view
ELSIF view = v.files.view THEN
v.focusView := v.files.view
ELSE
HALT(20)
END
END ConsiderFocusRequestBy;
PROCEDURE (v: FilesBrowserTable) CopyFromSimpleView- (source: Views.View);
BEGIN
WITH source: FilesBrowserTable DO
v.base := source.base;
v.base.focusLocInfoNum := source.base.focusLocInfoNum
END
END CopyFromSimpleView;
PROCEDURE (v: FilesBrowserPlaces) CopyFromSimpleView- (source: Views.View);
BEGIN
WITH source: FilesBrowserPlaces DO
v.base := source.base
END
END CopyFromSimpleView;
PROCEDURE (v: FilesBrowserConverters) CopyFromSimpleView- (source: Views.View);
BEGIN
WITH source: FilesBrowserConverters DO
v.base := source.base
END
END CopyFromSimpleView;
(* common code to create various browsers *)
PROCEDURE CreateBrowserFormCommon (navtype: BYTE; action: Dialog.GetAction; IN svstr, dlgstr: Dialog.String);
VAR
nav: FilesBrowser;
w1: FilesBrowserPlaces; w2: FilesBrowserTable; w3: FilesBrowserConverters;
context2: Context; title: Dialog.String;
tf: Fonts.Typeface; size, weight, pos, pos2, n: INTEGER; style: SET;
p: Controls.Prop; cNotif: CloseNotifier; conv, conv2: Converters.Converter;
type: ARRAY 16 OF CHAR;
locs, files: INTEGER;
BEGIN
NEW(nav);
preventCleanup := FALSE;
nav.type := navtype;
nav.margin := 2 * Ports.mm;
nav.action := action;
nav.action.cancel := TRUE;
(* build converters list; this is not required for directory browser *)
IF navtype # location THEN
IF action.type # "" THEN
n := 0; pos := 0;
WHILE action.type[pos] # 0X DO
IF action.type[pos] = "," THEN INC(n) END;
INC(pos)
END;
NEW(nav.initTypes, n+1);
pos := -1; n := 0;
REPEAT
INC(pos);
pos2 := 0;
WHILE (action.type[pos] # 0X) & (action.type[pos] # ",") DO
type[pos2] := action.type[pos]; INC(pos); INC(pos2)
END;
type[pos2] := 0X;
nav.initTypes[n] := type$;
INC(n)
UNTIL action.type[pos] = 0X
END;
IF action.converterName # "" THEN
conv := Converters.list;
WHILE (conv # NIL) & (conv.imp # action.converterName) DO
conv := conv.next
END
END;
IF conv # NIL THEN
NEW(nav.convList);
nav.convList^ := conv^;
nav.convList.next := NIL;
nav.converter := nav.convList
ELSE
IF action.type = "" THEN
nav.convList := Converters.list;
IF action.selectConverter # "" THEN
conv := Converters.list;
WHILE (conv # NIL) & (conv.imp # action.selectConverter) DO
conv := conv.next
END
END;
IF conv # NIL THEN
nav.converter := conv
ELSE
nav.converter := Converters.list
END
ELSIF action.type = "*" THEN
nav.convList := Converters.list;
nav.converter := NIL
ELSE
pos := -1;
REPEAT
INC(pos);
pos2 := 0;
WHILE (action.type[pos] # 0X) & (action.type[pos] # ",") DO
type[pos2] := action.type[pos]; INC(pos); INC(pos2)
END;
type[pos2] := 0X;
conv := Converters.list;
WHILE (conv # NIL) & ~((conv.imp # "") & (conv.fileType = type)) DO
conv := conv.next
END;
IF conv # NIL THEN
IF nav.convList = NIL THEN
NEW(nav.convList);
nav.convList^ := conv^;
nav.converter := nav.convList;
nav.convList.next := NIL
ELSE
conv2 := nav.convList;
WHILE conv2.next # NIL DO conv2 := conv2.next END;
NEW(conv2.next);
conv2.next^ := conv^;
conv2.next.next := NIL
END
END
UNTIL action.type[pos] = 0X;
IF nav.convList = NIL THEN
nav.convList := Converters.list
END
END
END
END;
nav.focusLocInfoNum := undefined;
nav.focusFileInfoNum := undefined;
Dialog.GetDialogFont(tf, size, style, weight);
nav.font := Fonts.dir.This(tf, size, style, weight);
(* places *)
NEW(w1);
w1.base := nav;
nav.places := NewContext(w1, nav);
(* file/dir list *)
NEW(w2);
w2.base := nav;
context2 := NewContext(w2, nav);
context2.wrapped := TRUE;
nav.files := NewContext(StdScrollers.WrapView(w2), nav);
(* converters are not required for directory browser *)
IF navtype # location THEN
NEW(w3);
w3.base := nav;
context2 := NewContext(w3, nav);
context2.wrapped := TRUE;
nav.converters := NewContext(StdScrollers.WrapView(w3), nav);
nav.convertersHeight := closedConvList
END;
(*k8: assign it here to activate the guard early *)
fName := "";
IF navtype = save THEN
(* file name entry field *)
name := action.name$
END;
browser := nav;
(* "accept" button *)
NEW(p);
p.link := "StdFilesBrowser.PreventCleanup; StdCmds.CloseTopDialog; StdFilesBrowser.BrowserConfirm";
p.label := svstr$; (*"#Std:OpenFile";*)
p.guard := "StdFilesBrowser.BrowserConfirmGuard"; p.notifier := "";
p.level := 0;
p.opt[0] := FALSE; p.opt[1] := FALSE; p.opt[2] := FALSE;
p.opt[3] := FALSE; p.opt[4] := FALSE;
nav.confirmButton := NewContext(Controls.dir.NewPushButton(p), nav);
(* "cancel" button *)
NEW(p);
p.link := "StdFilesBrowser.BrowserCancel; StdCmds.CloseTopDialog";
p.label := "#Std:Cancel";
p.guard := ""; p.notifier := "";
p.level := 0;
p.opt[0] := FALSE; p.opt[1] := FALSE; p.opt[2] := FALSE;
p.opt[3] := FALSE; p.opt[4] := FALSE;
nav.cancelButton := NewContext(Controls.dir.NewPushButton(p), nav);
IF (navtype = save) OR (navtype = location) THEN
(* "new directory" button *)
NEW(p);
p.link := "StdFilesBrowser.BrowserNewFolderDialog";
p.label := "#Std:Add folder";
p.guard := ""; p.notifier := "";
p.level := 0;
p.opt[0] := FALSE; p.opt[1] := FALSE; p.opt[2] := FALSE;
p.opt[3] := FALSE; p.opt[4] := FALSE;
nav.addButton := NewContext(Controls.dir.NewPushButton(p), nav);
(* "confirm new directory" button *)
NEW(p);
p.link := "StdFilesBrowser.BrowserCreateFolder";
p.label := "#Std:Confirm";
p.guard := "StdFilesBrowser.BrowserCreateFolderGuard"; p.notifier := "";
p.level := 0;
p.opt[0] := FALSE; p.opt[1] := FALSE; p.opt[2] := FALSE;
p.opt[3] := FALSE; p.opt[4] := FALSE;
nav.confirmAddButton := NewContext(Controls.dir.NewPushButton(p), nav);
(* directory name entry field *)
NEW(p);
p.link := "StdFilesBrowser.fName";
p.label := "";
p.guard := ""; p.notifier := "";
p.level := 0;
p.opt[0] := TRUE; p.opt[1] := FALSE; p.opt[2] := FALSE;
p.opt[3] := FALSE; p.opt[4] := FALSE;
nav.fNameField := NewContext(Controls.dir.NewField(p), nav)
END;
IF navtype = save THEN
(* file name entry field *)
(*name := action.name$;*)
NEW(p);
p.link := "StdFilesBrowser.name";
p.label := "";
p.guard := ""; p.notifier := "";
p.level := 0;
p.opt[0] := TRUE; p.opt[1] := FALSE; p.opt[2] := FALSE;
p.opt[3] := FALSE; p.opt[4] := FALSE;
nav.nameField := NewContext(Controls.dir.NewField(p), nav)
END;
IF action.loc = NIL THEN
IF lastLoc # NIL THEN
action.loc := lastLoc
ELSE
Dialog.GetLocPath(Files.dir.This(""), path);
action.loc := Files.dir.This(path)
END
END;
Dialog.GetLocPath(action.loc, path);
NEW(p);
p.link := "StdFilesBrowser.path";
p.label := "";
p.guard := ""; p.notifier := "";
p.level := 0;
p.opt[0] := TRUE; p.opt[1] := FALSE; p.opt[2] := FALSE;
p.opt[3] := FALSE; p.opt[4] := FALSE;
nav.pathField := NewContext(Controls.dir.NewField(p), nav);
CountLocsFiles(nav, locs, files);
IF locs > 0 THEN nav.focusLocInfoNum := 0
ELSIF files > 0 THEN nav.focusFileInfoNum := 0
END;
IF navtype = save THEN
nav.focusView := nav.nameField.view
ELSE
nav.focusView := nav.files.view
END;
IF action.title = "" THEN
Dialog.MapString(dlgstr$, title)
ELSE
Dialog.MapString(action.title, title)
END;
StdDialog.Open(nav, title, NIL, "", NIL, TRUE, FALSE, FALSE, FALSE, TRUE);
(* asTool, asAux, noResize, allowDuplicates, neverDirty *)
NEW(cNotif);
nav.Domain().GetSequencer()(Sequencers.Sequencer).InstallNotifier(cNotif)
END CreateBrowserFormCommon;
(* select a directory *)
PROCEDURE (hook: DialogStdGetHook) GetLoc (action: Dialog.GetAction);
BEGIN
IF browser = NIL THEN
CreateBrowserFormCommon(location, action, "#Std:Choose folder", "#Std:Choose folder")
END
END GetLoc;
(* open existing file *)
PROCEDURE (hook: DialogStdGetHook) GetIntLocName (action: Dialog.GetAction);
BEGIN
IF browser = NIL THEN
CreateBrowserFormCommon(open, action, "#Std:OpenFile", "#Std:Open...")
END
END GetIntLocName;
(* save file with a new name *)
PROCEDURE (hook: DialogStdGetHook) GetExtLocName (action: Dialog.GetAction);
BEGIN
IF browser = NIL THEN
CreateBrowserFormCommon(save, action, "#Std:Save", "#Std:Save...")
END
END GetExtLocName;
PROCEDURE ActPlaceGoUp (v: FilesBrowserPlaces);
BEGIN
GoOneDirUp(v.base)
END ActPlaceGoUp;
PROCEDURE FindPlace (IN name: Dialog.String): Place;
VAR
c: Place;
BEGIN
c := place;
WHILE (c # NIL) & (c.name$ # name$) DO c := c.next END;
RETURN c
END FindPlace;
(* add new place, or replace the existing one *)
PROCEDURE AddPlaceIntr (IN name, path: Dialog.String; act: PlaceActionProc);
VAR
c: Place;
BEGIN
ASSERT(LEN(name$) > 0);
c := FindPlace(name);
IF c = NIL THEN
c := place;
IF c = NIL THEN
NEW(c);
place := c
ELSE
WHILE c.next # NIL DO c := c.next END;
NEW(c.next);
c := c.next
END
END;
c.name := name$;
c.path := path$;
c.specialAction := act
END AddPlaceIntr;
PROCEDURE AddPlace* (IN name, path: Dialog.String);
BEGIN
AddPlaceIntr(name, path, NIL)
END AddPlace;
PROCEDURE SetupPlaces*;
VAR path, pathName: Dialog.String; res_: INTEGER;
BEGIN
Dialog.MapString("#Std:Parent folder", pathName);
AddPlaceIntr(pathName, "..", ActPlaceGoUp);
Dialog.GetLocPath(Files.dir.This(""), path);
Dialog.MapString("#Std:Project folder", pathName);
AddPlace(pathName, path);
IF Dialog.platform = Dialog.windows THEN
Dialog.GetPar("USERPROFILE", path, res_)
ELSE (*ELSIF Dialog.platform = Dialog.linux THEN*)
Dialog.GetPar("HOME", path, res_)
END;
Dialog.MapString("#Std:Home folder", pathName);
AddPlace(pathName, path)
(* this paramiter allow to limit upper directory user can browse
StdFilesBrowser.upper := path$;
*)
END SetupPlaces;
PROCEDURE ParamDefaults (p: ANYPTR);
BEGIN
WITH p: Param DO
p.bgCursorUpDir := Ports.RGBColor(220,210,235);
p.bgCursorDir := Ports.RGBColor(220,210,235);
p.bgCursorFile := Ports.RGBColor(220,210,235);
p.bgActivePlace := Ports.RGBColor(220,210,235);
p.bgActiveConverter := Ports.RGBColor(220,210,235);
p.upDirStr := "<..>";
p.upper := "";
p.InitDefaults := ParamDefaults;
END
END ParamDefaults;
PROCEDURE Init;
VAR dh: DialogStdGetHook;
BEGIN
NEW(dh); Dialog.SetStdGetHook(dh);
browser := NIL;
name := "";
showHidden := FALSE;
NEW(param); ParamDefaults(param);
END Init;
PROCEDURE ResetupAfterUnload*;
BEGIN
Init;
place := NIL;
SetupPlaces
END ResetupAfterUnload;
BEGIN
Init
END StdFilesBrowser.
StdFilesBrowser.ResetupAfterUnload
| Std/Mod/FilesBrowser.odc |
MODULE StdFolds;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20150327, center #32, remove fonts dependencies
- 20150616, center #61, Unicode support for fold labels
- 20160330, center #110, dialog improved
- 20160324, center #111, code cleanups
"
issues = "
- ...
"
**)
IMPORT
Ports, Stores, Containers, Models, Views, Controllers, Fonts,
Properties,Controls,
TextModels, TextViews, TextControllers, TextSetters,
Dialog, Services;
CONST
expanded* = FALSE; collapsed* = TRUE;
minVersion = 0; currentVersion = 1;
collapseFoldKey = "#Std:Collapse Fold";
expandFoldKey = "#Std:Expand Fold";
zoomInKey = "#Std:Zoom In";
zoomOutKey = "#Std:Zoom Out";
expandFoldsKey = "#Std:Expand Folds";
collapseFoldsKey = "#Std:Collapse Folds";
insertFoldKey = "#Std:Insert Fold";
setLabelKey = "#Std:Set Label";
TYPE
Label* = ARRAY 32 OF CHAR;
Fold* = POINTER TO RECORD (Views.View)
leftSide-: BOOLEAN;
collapsed-: BOOLEAN;
label-: Label; (* valid iff leftSide *)
hidden: TextModels.Model (* valid iff leftSide; NIL if no hidden text *)
END;
Directory* = POINTER TO ABSTRACT RECORD END;
StdDirectory = POINTER TO RECORD (Directory) END;
FlipOp = POINTER TO RECORD (Stores.Operation)
text: TextModels.Model; (* containing text *)
leftpos, rightpos: INTEGER (* position of left and right Fold *)
END;
SetLabelOp = POINTER TO RECORD (Stores.Operation)
text: TextModels.Model; (* containing text *)
pos: INTEGER; (* position of fold in text *)
oldlabel: Label
END;
Action = POINTER TO RECORD (Services.Action) END;
VAR
dir-, stdDir-: Directory;
foldData*: RECORD
nested*: BOOLEAN;
useFilter*: BOOLEAN;
filter*: Label;
newLabel*: Label
END;
action: Action;
fingerprint: INTEGER; (* for the property inspector *)
PROCEDURE (d: Directory) New* (collapsed: BOOLEAN; label: Label;
hiddenText: TextModels.Model): Fold, NEW, ABSTRACT;
PROCEDURE GetPair (fold: Fold; VAR l, r: Fold);
VAR c: Models.Context; text: TextModels.Model; rd: TextModels.Reader; v: Views.View;
nest: INTEGER;
BEGIN
c := fold.context; l := NIL; r := NIL;
WITH c: TextModels.Context DO
text := c.ThisModel(); rd := text.NewReader(NIL);
IF fold.leftSide THEN l := fold;
rd.SetPos(c.Pos()+1); nest := 1;
REPEAT rd.ReadView(v);
IF (v # NIL) & (v IS Fold) THEN
IF v(Fold).leftSide THEN INC(nest) ELSE DEC(nest) END
END
UNTIL (v = NIL) OR (nest = 0);
IF v # NIL THEN r := v(Fold) ELSE r := NIL END
ELSE r := fold;
rd.SetPos(c.Pos()); nest := 1;
REPEAT rd.ReadPrevView(v);
IF (v # NIL) & (v IS Fold) THEN
IF ~v(Fold).leftSide THEN INC(nest) ELSE DEC(nest) END
END
UNTIL (v = NIL) OR (nest = 0);
IF v # NIL THEN l := v(Fold) ELSE l := NIL END
END
ELSE (* fold not embedded in a text *)
END;
ASSERT((l = NIL) OR l.leftSide & (l.hidden # NIL), 100);
ASSERT((r = NIL) OR ~r.leftSide & (r.hidden = NIL), 101)
END GetPair;
PROCEDURE (fold: Fold) HiddenText* (): TextModels.Model, NEW;
VAR l, r: Fold;
BEGIN
IF fold.leftSide THEN RETURN fold.hidden
ELSE GetPair(fold, l, r);
IF l # NIL THEN RETURN l.hidden ELSE RETURN NIL END
END
END HiddenText;
PROCEDURE (fold: Fold) MatchingFold* (): Fold, NEW;
VAR l, r: Fold;
BEGIN
GetPair(fold, l, r);
IF l # NIL THEN
IF fold = l THEN RETURN r ELSE RETURN l END
ELSE RETURN NIL
END
END MatchingFold;
PROCEDURE CalcSize (f: Fold; VAR w, h: INTEGER);
VAR c: Models.Context; font: Fonts.Font;
asc, dsc, fw: INTEGER;
BEGIN
c := f.context;
IF (c # NIL) & (c IS TextModels.Context) THEN
font := c(TextModels.Context).Attr().font
ELSE font := Fonts.dir.Default()
END;
font.GetBounds(asc, dsc, fw);
w := asc * 29 DIV 20;
h := asc + dsc
END CalcSize;
PROCEDURE Update (f: Fold);
VAR w, h: INTEGER;
BEGIN
CalcSize(f, w, h);
f.context.SetSize(w, h);
Views.Update(f, Views.keepFrames)
END Update;
PROCEDURE FlipPair (l, r: Fold);
VAR text, hidden: TextModels.Model; cl, cr: Models.Context;
lpos, rpos: INTEGER;
BEGIN
IF (l # NIL) & (r # NIL) THEN
ASSERT(l.leftSide, 100);
ASSERT(~r.leftSide, 101);
ASSERT(l.hidden # NIL, 102);
ASSERT(r.hidden = NIL, 103);
cl := l.context; cr := r.context;
text := cl(TextModels.Context).ThisModel();
lpos := cl(TextModels.Context).Pos() + 1; rpos := cr(TextModels.Context).Pos();
ASSERT(lpos <= rpos, 104);
hidden := TextModels.CloneOf(text);
hidden.Insert(0, text, lpos, rpos);
text.Insert(lpos, l.hidden, 0, l.hidden.Length());
l.hidden := hidden; Stores.Join(l, hidden);
l.collapsed := ~l.collapsed;
r.collapsed := l.collapsed;
Update(l); Update(r);
TextControllers.SetCaret(text, lpos)
END
END FlipPair;
PROCEDURE (op: FlipOp) Do;
VAR rd: TextModels.Reader; left, right: Views.View;
BEGIN
rd := op.text.NewReader(NIL);
rd.SetPos(op.leftpos); rd.ReadView(left);
rd.SetPos(op.rightpos); rd.ReadView(right);
FlipPair(left(Fold), right(Fold));
op.leftpos := left.context(TextModels.Context).Pos();
op.rightpos := right.context(TextModels.Context).Pos()
END Do;
PROCEDURE (op: SetLabelOp) Do;
VAR rd: TextModels.Reader; fold: Views.View; left, right: Fold; lab: Label;
BEGIN
rd := op.text.NewReader(NIL);
rd.SetPos(op.pos); rd.ReadView(fold);
WITH fold: Fold DO
GetPair(fold, left, right);
IF left # NIL THEN
lab := fold.label; left.label := op.oldlabel; op.oldlabel := lab;
right.label := left.label
END
END
END Do;
PROCEDURE SetProp (fold: Fold; p : Properties.Property);
VAR op: SetLabelOp; left, right: Fold;
BEGIN
WHILE p # NIL DO
WITH p: Controls.Prop DO
IF (Controls.label IN p.valid) & (p.label # fold.label) THEN
GetPair(fold, left, right);
IF left # NIL THEN
NEW(op); op.oldlabel := p.label$;
op.text := fold.context(TextModels.Context).ThisModel();
op.pos := fold.context(TextModels.Context).Pos();
Views.Do(fold, setLabelKey, op)
END
END
ELSE
END;
p := p.next
END
END SetProp;
PROCEDURE (fold: Fold) Flip*, NEW;
VAR op: FlipOp; left, right: Fold;
BEGIN
ASSERT(fold # NIL, 20);
NEW(op);
GetPair(fold, left, right);
IF (left # NIL) & (right # NIL) THEN
op.text := fold.context(TextModels.Context).ThisModel();
op.leftpos := left.context(TextModels.Context).Pos();
op.rightpos := right.context(TextModels.Context).Pos();
Views.BeginModification(Views.clean, fold);
IF ~left.collapsed THEN Views.Do(fold, collapseFoldKey, op)
ELSE Views.Do(fold, expandFoldKey, op)
END;
Views.EndModification(Views.clean, fold)
END
END Flip;
PROCEDURE ReadNext (rd: TextModels.Reader; VAR fold: Fold);
VAR v: Views.View;
BEGIN
REPEAT rd.ReadView(v) UNTIL rd.eot OR (v IS Fold);
IF ~rd.eot THEN fold := v(Fold) ELSE fold := NIL END
END ReadNext;
PROCEDURE (fold: Fold) FlipNested*, NEW;
VAR text: TextModels.Model; rd: TextModels.Reader; l, r: Fold; level: INTEGER;
op: Stores.Operation;
BEGIN
ASSERT(fold # NIL, 20);
GetPair(fold, l, r);
IF (l # NIL) & (l.context # NIL) & (l.context IS TextModels.Context) THEN
text := l.context(TextModels.Context).ThisModel();
Models.BeginModification(Models.clean, text);
rd := text.NewReader(NIL);
rd.SetPos(l.context(TextModels.Context).Pos());
IF l.collapsed THEN
Models.BeginScript(text, expandFoldsKey, op);
ReadNext(rd, fold); level := 1;
WHILE (fold # NIL) & (level > 0) DO
IF fold.leftSide & fold.collapsed THEN fold.Flip END;
ReadNext(rd, fold);
IF fold.leftSide THEN INC(level) ELSE DEC(level) END
END
ELSE (* l.state = expanded *)
Models.BeginScript(text, collapseFoldsKey, op);
level := 0;
REPEAT ReadNext(rd, fold);
IF fold.leftSide THEN INC(level) ELSE DEC(level) END;
IF (fold # NIL) & ~fold.leftSide & ~fold.collapsed THEN
fold.Flip;
rd.SetPos(fold.context(TextModels.Context).Pos()+1)
END
UNTIL (fold = NIL) OR (level = 0)
END;
Models.EndScript(text, op);
Models.EndModification(Models.clean, text)
END
END FlipNested;
PROCEDURE (fold: Fold) HandlePropMsg- (VAR msg: Properties.Message);
VAR prop: Controls.Prop; c: Models.Context; a: TextModels.Attributes; asc, w: INTEGER;
BEGIN
WITH msg: Properties.SizePref DO
CalcSize(fold, msg.w, msg.h)
| msg: Properties.ResizePref DO
msg.fixed := TRUE
| msg: Properties.FocusPref DO msg.hotFocus := TRUE
| msg: Properties.PollMsg DO NEW(prop);
prop.known := {Controls.label}; prop.valid := {Controls.label}; prop.readOnly := {};
prop.label := fold.label$;
msg.prop := prop
| msg: Properties.SetMsg DO SetProp(fold, msg.prop)
| msg: TextSetters.Pref DO c := fold.context;
IF (c # NIL) & (c IS TextModels.Context) THEN
a := c(TextModels.Context).Attr();
a.font.GetBounds(asc, msg.dsc, w)
END
ELSE
END
END HandlePropMsg;
PROCEDURE Track (fold: Fold; f: Views.Frame; x, y: INTEGER; buttons: SET; VAR hit: BOOLEAN);
VAR a: TextModels.Attributes; font: Fonts.Font; c: Models.Context;
w, h, asc, dsc, fw: INTEGER; isDown, in, in0: BOOLEAN; modifiers: SET;
BEGIN
c := fold.context; hit := FALSE;
WITH c: TextModels.Context DO
a := c.Attr(); font := a.font;
c.GetSize(w, h); in0 := FALSE;
in := (0 <= x) & (x < w) & (0 <= y) & (y < h);
REPEAT
IF in # in0 THEN
f.MarkRect(0, 0, w, h, Ports.fill, Ports.hilite, FALSE); in0 := in
END;
f.Input(x, y, modifiers, isDown);
in := (0 <= x) & (x < w) & (0 <= y) & (y < h)
UNTIL ~isDown;
IF in0 THEN hit := TRUE;
font.GetBounds(asc, dsc, fw);
f.MarkRect(0, 0, w, asc + dsc, Ports.fill, Ports.hilite, FALSE)
END
ELSE
END
END Track;
PROCEDURE (fold: Fold) HandleCtrlMsg* (f: Views.Frame; VAR msg: Views.CtrlMessage;
VAR focus: Views.View);
VAR hit: BOOLEAN; pos: INTEGER; l, r: Fold;
context: TextModels.Context; text: TextModels.Model;
BEGIN
WITH msg: Controllers.TrackMsg DO
IF fold.context IS TextModels.Context THEN
Track(fold, f, msg.x, msg.y, msg.modifiers, hit);
IF hit THEN
IF Controllers.modify IN msg.modifiers THEN
fold.FlipNested
ELSE
fold.Flip;
context := fold.context(TextModels.Context);
text := context.ThisModel();
IF TextViews.FocusText() = text THEN
GetPair(fold, l, r);
pos := context.Pos();
IF fold = l THEN
TextControllers.SetCaret(text, pos + 1)
ELSE
TextControllers.SetCaret(text, pos)
END;
TextViews.ShowRange(text, pos, pos + 1, TRUE)
END
END
END
END
| msg: Controllers.PollCursorMsg DO
msg.cursor := Ports.refCursor
ELSE
END
END HandleCtrlMsg;
PROCEDURE GetIconPath (fold: Fold; f: Views.Frame; w, h_dummy, asc: INTEGER;
VAR path: ARRAY OF Ports.Point);
VAR i, xoff, w2, w4: INTEGER;
BEGIN
(* use device coordinates for symmetric arrow rendering*)
w := w DIV f.unit;
asc := asc DIV f.unit;
w2 := w * 10 DIV 18;
IF ~ODD(w2) THEN DEC(w2) END ;
w4 := w2 DIV 2;
xoff := (w - w2 - w4) DIV 2;
IF xoff < 1 THEN xoff := 1 END ;
WHILE xoff + w2 + w4 > w DO DEC(w2, 2); DEC(w4) END ;
(* left side icon *)
path[0].x := xoff; path[0].y := asc; (* lower left *)
path[1].x := path[0].x; path[1].y := path[0].y - w2; (* upper left *)
path[2].x := path[1].x + w2; path[2].y := path[1].y; (* upper middle *)
path[3].x := path[2].x + w4; path[3].y := path[2].y + w4; (* right arrow *)
path[4].x := path[2].x - 1; path[4].y := path[0].y; (* lower middle, x offset -1 needed for symmetric filling *)
IF ~fold.leftSide THEN (* mirror *)
FOR i := 0 TO LEN(path) - 1 DO path[i].x := w - path[i].x END
END ;
(* convert to universal coordinates *)
FOR i := 0 TO LEN(path) - 1 DO path[i].x := path[i].x * f.unit; path[i].y := path[i].y * f.unit; END
END GetIconPath;
PROCEDURE DrawMarkers(fold: Fold; f: Views.Frame; IN path: ARRAY OF Ports.Point);
VAR w2, height, thickness, margin, len, left, top: INTEGER;
BEGIN
(* scale size and thickness of +/- markers, thickness / height = 1 / 7*)
w2 := ABS(path[2].x - path[1].x); (* universal coordinates *)
height := (path[0].y - path[1].y); (* universal coordinates *)
thickness := height DIV f.unit DIV 7; (* device coordinates *)
IF thickness < 1 THEN thickness := 1
(* ELSIF ~ODD(thickness) THEN (* alternative for perfect symmetry but scales in larger increments *)
DEC(thickness) *)
END ;
thickness := thickness * f.unit; (* universal coordinates *)
margin := height DIV f.unit DIV 4; (* device coordinates *)
IF margin < 1 THEN margin := 1 END; (* for small fonts *)
margin := margin * f.unit; (* universal coordinates *)
len := w2 - margin * 2; (* universal coordinates *)
IF ((len DIV f.unit) MOD 2 = 1) & ((thickness DIV f.unit) MOD 2 = 0) THEN
INC(len, f.unit) (* avoid cross assymetry *)
END;
IF len < 1 THEN len := 1 END ; (* avoid TRAP in DrawRect for very small sizes *)
(* draw - *)
IF fold.leftSide THEN left := path[0].x + margin ELSE left := path[2].x + margin END ;
top := path[1].y + (height - thickness) DIV 2;
f.DrawRect(left, top, left + len, top + thickness, Ports.fill, Ports.background);
IF fold.collapsed THEN (* draw | *)
left := left + (len - thickness) DIV 2;
top := path[1].y + margin;
f.DrawRect(left, top, left + thickness, top + len, Ports.fill, Ports.background)
END
END DrawMarkers;
PROCEDURE (fold: Fold) Restore* (f: Views.Frame; l, t, r, b: INTEGER);
VAR a: TextModels.Attributes; color: Ports.Color; c: Models.Context; font: Fonts.Font;
w, h: INTEGER; asc, dsc, fw: INTEGER; path: ARRAY 5 OF Ports.Point;
BEGIN
CalcSize(fold, w, h); (* important side effect: initializes Log window for drawing folds! *)
c := fold.context;
IF (c # NIL) & (c IS TextModels.Context) THEN
a := fold.context(TextModels.Context).Attr();
font := a.font;
color := a.color;
IF color = Ports.defaultColor THEN
color := Dialog.defaultColor
END
ELSE
font := Fonts.dir.Default(); color := Dialog.defaultColor
END;
font.GetBounds(asc, dsc, fw);
GetIconPath(fold, f, w, h, asc, path);
f.DrawPath(path, LEN(path), Ports.fill, color, Ports.closedPoly);
DrawMarkers(fold, f, path)
END Restore;
PROCEDURE (fold: Fold) CopyFromSimpleView- (source: Views.View);
BEGIN
(* fold.CopyFrom^(source); *)
WITH source: Fold DO
ASSERT(source.leftSide = (source.hidden # NIL), 100);
fold.leftSide := source.leftSide;
fold.collapsed := source.collapsed;
fold.label := source.label;
IF source.hidden # NIL THEN
fold.hidden := TextModels.CloneOf(source.hidden); Stores.Join(fold.hidden, fold);
fold.hidden.InsertCopy(0, source.hidden, 0, source.hidden.Length())
END
END
END CopyFromSimpleView;
PROCEDURE (fold: Fold) Internalize- (VAR rd: Stores.Reader);
VAR version: INTEGER; store: Stores.Store; xint: INTEGER;
BEGIN
fold.Internalize^(rd);
IF rd.cancelled THEN RETURN END;
rd.ReadVersion(minVersion, currentVersion, version);
IF rd.cancelled THEN RETURN END;
rd.ReadXInt(xint);fold.leftSide := xint = 0;
rd.ReadXInt(xint); fold.collapsed := xint = 0;
IF version >= 1 THEN rd.ReadString(fold.label)
ELSE rd.ReadXString(fold.label)
END;
rd.ReadStore(store);
IF store # NIL THEN fold.hidden := store(TextModels.Model); Stores.Join(fold.hidden, fold)
ELSE fold.hidden := NIL
END;
fold.leftSide := store # NIL
END Internalize;
PROCEDURE HasWideChars (IN s: ARRAY OF CHAR): BOOLEAN;
VAR i: INTEGER; ch: CHAR;
BEGIN i := 0; ch := s[0];
WHILE (ch # 0X) & (ch <= 0FFX) DO INC(i); ch := s[i] END;
RETURN ch # 0X
END HasWideChars;
PROCEDURE (fold: Fold) Externalize- (VAR wr: Stores.Writer);
VAR xint, version: INTEGER;
BEGIN
fold.Externalize^(wr);
IF HasWideChars(fold.label) THEN version := 1 ELSE version := 0 END;
wr.WriteVersion(version);
IF fold.hidden # NIL THEN xint := 0 ELSE xint := 1 END;
wr.WriteXInt(xint);
IF fold.collapsed THEN xint := 0 ELSE xint := 1 END;
wr.WriteXInt(xint);
IF version >= 1 THEN wr.WriteString(fold.label)
ELSE wr.WriteXString(fold.label)
END;
wr.WriteStore(fold.hidden)
END Externalize;
(* --------------------- expanding and collapsing in focus text ------------------------ *)
PROCEDURE ExpandFolds* (text: TextModels.Model; nested: BOOLEAN; IN label: ARRAY OF CHAR);
VAR op: Stores.Operation; fold, l, r: Fold; rd: TextModels.Reader;
BEGIN
ASSERT(text # NIL, 20);
Models.BeginModification(Models.clean, text);
IF nested THEN Models.BeginScript(text, expandFoldsKey, op)
ELSE Models.BeginScript(text, zoomInKey, op)
END;
rd := text.NewReader(NIL); rd.SetPos(0);
ReadNext(rd, fold);
WHILE ~rd.eot DO
IF fold.leftSide & fold.collapsed THEN
IF (label = "") OR (label = fold.label) THEN
fold.Flip;
IF ~nested THEN
GetPair(fold, l, r);
rd.SetPos(r.context(TextModels.Context).Pos())
END
END
END;
ReadNext(rd, fold)
END;
Models.EndScript(text, op);
Models.EndModification(Models.clean, text)
END ExpandFolds;
PROCEDURE CollapseFolds* (text: TextModels.Model; nested: BOOLEAN; IN label: ARRAY OF CHAR);
VAR op: Stores.Operation; fold, r, l: Fold; rd: TextModels.Reader;
BEGIN
ASSERT(text # NIL, 20);
Models.BeginModification(Models.clean, text);
IF nested THEN Models.BeginScript(text, collapseFoldsKey, op)
ELSE Models.BeginScript(text, zoomOutKey, op)
END;
rd := text.NewReader(NIL); rd.SetPos(0);
ReadNext(rd, fold);
WHILE ~rd.eot DO
IF ~fold.leftSide & ~fold.collapsed THEN
GetPair(fold, l, r);
IF (label = "") OR (label = l.label) THEN
fold.Flip;
GetPair(l, l, r);
rd.SetPos(r.context(TextModels.Context).Pos()+1);
IF ~nested THEN REPEAT ReadNext(rd, fold) UNTIL rd.eot OR fold.leftSide
ELSE ReadNext(rd, fold)
END
ELSE ReadNext(rd, fold)
END
ELSE ReadNext(rd, fold)
END
END;
Models.EndScript(text, op);
Models.EndModification(Models.clean, text)
END CollapseFolds;
PROCEDURE ZoomIn*;
VAR text: TextModels.Model;
BEGIN
text := TextViews.FocusText();
IF text # NIL THEN ExpandFolds(text, FALSE, "") END
END ZoomIn;
PROCEDURE ZoomOut*;
VAR text: TextModels.Model;
BEGIN
text := TextViews.FocusText();
IF text # NIL THEN CollapseFolds(text, FALSE, "") END
END ZoomOut;
PROCEDURE Expand*;
VAR text: TextModels.Model;
BEGIN
text := TextViews.FocusText();
IF text # NIL THEN ExpandFolds(text, TRUE, "") END
END Expand;
PROCEDURE Collapse*;
VAR text: TextModels.Model;
BEGIN
text := TextViews.FocusText();
IF text # NIL THEN CollapseFolds(text, TRUE, "") END
END Collapse;
(* ---------------------- foldData dialogbox --------------------------- *)
PROCEDURE FilterGuard* (VAR par: Dialog.Par);
BEGIN
par.disabled := (TextViews.Focus() = NIL) OR ~foldData.useFilter
END FilterGuard;
PROCEDURE SetLabelGuard* ( VAR p : Dialog.Par );
VAR v: Views.View;
BEGIN
Controllers.SetCurrentPath(Controllers.targetPath);
v := Containers.FocusSingleton();
p.disabled := (v = NIL) OR ~(v IS Fold) OR ~v(Fold).leftSide;
Controllers.ResetCurrentPath()
END SetLabelGuard;
PROCEDURE ExpandLabel*;
VAR text: TextModels.Model;
BEGIN
IF ~foldData.useFilter & (foldData.filter # "") THEN
foldData.filter := ""; Dialog.Update(foldData)
END;
text := TextViews.FocusText();
IF text # NIL THEN
IF foldData.useFilter THEN ExpandFolds(text, foldData.nested, foldData.filter)
ELSE ExpandFolds(text, foldData.nested, "")
END
END
END ExpandLabel;
PROCEDURE CollapseLabel*;
VAR text: TextModels.Model;
BEGIN
IF ~foldData.useFilter & (foldData.filter # "") THEN
foldData.filter := ""; Dialog.Update(foldData)
END;
text := TextViews.FocusText();
IF text # NIL THEN
IF foldData.useFilter THEN CollapseFolds(text, foldData.nested, foldData.filter)
ELSE CollapseFolds(text, foldData.nested, "")
END
END
END CollapseLabel;
PROCEDURE FindFold(first: BOOLEAN);
VAR c : TextControllers.Controller; r: TextModels.Reader;
v : Views.View; pos, i : INTEGER;
BEGIN
c := TextControllers.Focus();
IF c # NIL THEN
IF first THEN pos := 0
ELSE
pos := c.CaretPos();
IF pos = TextControllers.none THEN
c.GetSelection(i, pos);
IF pos = i THEN pos := 0 ELSE INC(pos) END;
pos := MIN(pos, c.text.Length()-1)
END
END;
r := c.text.NewReader(NIL); r.SetPos(pos);
REPEAT r.ReadView(v)
UNTIL r.eot OR ((v IS Fold) & v(Fold).leftSide) & (~foldData.useFilter OR (v(Fold).label$ = foldData.filter$));
IF r.eot THEN
c.SetCaret(0); Dialog.Beep
ELSE
pos := r.Pos();
c.view.ShowRange(pos-1, pos, FALSE);
c.SetSelection(pos-1, pos);
IF LEN(v(Fold).label) > 0 THEN
foldData.newLabel := v(Fold).label
END;
Dialog.Update(foldData)
END
ELSE
Dialog.Beep
END
END FindFold;
PROCEDURE FindNextFold*;
BEGIN
FindFold(FALSE)
END FindNextFold;
PROCEDURE FindFirstFold*;
BEGIN
FindFold(TRUE)
END FindFirstFold;
PROCEDURE SetLabel*;
VAR v: Views.View;
BEGIN
Controllers.SetCurrentPath(Controllers.targetPath);
v := Containers.FocusSingleton();
IF (v # NIL) & (v IS Fold) & (LEN(foldData.newLabel) > 0) THEN
v(Fold).label := foldData.newLabel
ELSE
Dialog.Beep
END;
Controllers.ResetCurrentPath()
END SetLabel;
PROCEDURE (a: Action) Do;
VAR v: Views.View; fp: INTEGER;
BEGIN
Controllers.SetCurrentPath(Controllers.targetPath);
v := Containers.FocusSingleton();
IF (v = NIL) OR ~(v IS Fold) THEN
fingerprint := 0;
foldData.newLabel := ""
ELSE
fp := Services.AdrOf(v);
IF fp # fingerprint THEN
foldData.newLabel := v(Fold).label;
fingerprint := fp;
Dialog.Update(foldData)
END
END;
Controllers.ResetCurrentPath();
Services.DoLater(action, Services.Ticks() + Services.resolution DIV 2)
END Do;
(* ------------------------ inserting folds ------------------------ *)
PROCEDURE Overlaps* (text: TextModels.Model; beg, end: INTEGER): BOOLEAN;
VAR n, level: INTEGER; rd: TextModels.Reader; v: Views.View;
BEGIN
ASSERT(text # NIL, 20);
ASSERT((beg >= 0) & (end <= text.Length()) & (beg <= end), 21);
rd := text.NewReader(NIL); rd.SetPos(beg);
n := 0; level := 0;
REPEAT rd.ReadView(v);
IF ~rd.eot & (rd.Pos() <= end) THEN
WITH v: Fold DO INC(n);
IF v.leftSide THEN INC(level) ELSE DEC(level) END
ELSE
END
END
UNTIL rd.eot OR (level < 0) OR (rd.Pos() >= end);
RETURN (level # 0) OR ODD(n)
END Overlaps;
PROCEDURE InsertionAttr (text: TextModels.Model; pos: INTEGER): TextModels.Attributes;
VAR rd: TextModels.Reader; ch: CHAR;
BEGIN
rd := text.NewReader(NIL);
rd.SetPos(pos); rd.ReadChar(ch);
RETURN rd.attr
END InsertionAttr;
PROCEDURE Insert* (text: TextModels.Model; label: Label; beg, end: INTEGER; collapsed: BOOLEAN);
VAR w: TextModels.Writer; fold: Fold; insop: Stores.Operation; a: TextModels.Attributes;
BEGIN
ASSERT(text # NIL, 20);
ASSERT((beg >= 0) & (end <= text.Length()) & (beg <= end), 21);
a := InsertionAttr(text, beg);
w := text.NewWriter(NIL); w.SetPos(beg);
IF a # NIL THEN w.SetAttr(a) END;
NEW(fold);
fold.leftSide := TRUE; fold.collapsed := collapsed;
fold.hidden := TextModels.CloneOf(text); Stores.Join(fold, fold.hidden);
fold.label := label$;
Models.BeginScript(text, insertFoldKey, insop);
w.WriteView(fold, 0, 0);
w.SetPos(end+1);
a := InsertionAttr(text, end+1);
IF a # NIL THEN w.SetAttr(a) END;
NEW(fold);
fold.leftSide := FALSE; fold.collapsed := collapsed;
fold.hidden := NIL; fold.label := "";
w.WriteView(fold, 0, 0);
Models.EndScript(text, insop)
END Insert;
PROCEDURE CreateGuard* (VAR par: Dialog.Par);
VAR c: TextControllers.Controller; beg, end: INTEGER;
BEGIN c := TextControllers.Focus();
IF (c # NIL) & ~(Containers.noCaret IN c.opts) THEN
IF c.HasSelection() THEN c.GetSelection(beg, end);
IF Overlaps(c.text, beg, end) THEN par.disabled := TRUE END
END
ELSE par.disabled := TRUE
END
END CreateGuard;
PROCEDURE Create* (state: INTEGER); (* menu cmd parameters don't accept Booleans *)
VAR c: TextControllers.Controller; beg, end: INTEGER; collapsed: BOOLEAN;
BEGIN
collapsed := state = 0;
c := TextControllers.Focus();
IF (c # NIL) & ~(Containers.noCaret IN c.opts) THEN
IF c.HasSelection() THEN c.GetSelection(beg, end);
IF ~Overlaps(c.text, beg, end) THEN Insert(c.text, "", beg, end, collapsed) END
ELSE beg := c.CaretPos(); Insert(c.text, "", beg, beg, collapsed)
END
END
END Create;
PROCEDURE (d: StdDirectory) New (collapsed: BOOLEAN; label: Label;
hiddenText: TextModels.Model): Fold;
VAR fold: Fold;
BEGIN
NEW(fold); fold.leftSide := hiddenText # NIL; fold.collapsed := collapsed;
fold.label := label; fold.hidden := hiddenText;
IF hiddenText # NIL THEN Stores.Join(fold, fold.hidden) END;
RETURN fold
END New;
PROCEDURE SetDir* (d: Directory);
BEGIN
ASSERT(d # NIL, 20);
dir := d
END SetDir;
PROCEDURE InitMod;
VAR d: StdDirectory;
BEGIN
foldData.useFilter := FALSE; foldData.nested := FALSE; foldData.filter := ""; foldData.newLabel := "";
NEW(d); dir := d; stdDir := d;
NEW(action); Services.DoLater(action, Services.now);
END InitMod;
BEGIN
InitMod
END StdFolds.
| Std/Mod/Folds.odc |
MODULE StdGrids;
(**
project = "BlackBox 2.0, new module"
organization = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Contributors, Anton Dmitriev, Ivan Denisov, Ketmar Dark"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 20230107, k8, don't allow to scroll the tabs away
- 20230107, k8, make newly activated tab visible
"
issues = "
- AD: "technical debt" issues (specific to a particular source code part) are marked with color 0BC2AF4H
- both Divider and Stack need to HandlePropMsg if they want to be universal
"
**)
IMPORT
Views, Controllers, Ports, Models, Fonts, Stores, Services, Properties, Windows, Dialog, StdWindows, StdCFrames, StdDocuments;
CONST
version = 1;
mm = Ports.mm;
magicWidth = -28051978;
fixedPointBase = 32768;
(* keep in synch with HostPorts constants *)
resizeHCursor = 16; resizeVCursor = 17; stopCursor = 22;
stack* = 0; divider* = 1; (* kind of View *)
remove* = 0; activate* = 1; setTitle* = 2;
vertical* = FALSE; horizontal* = ~vertical;
append* = -1; (** possible value for PROCEDURE Transfer(... pos: INTEGER...) *)
(* navigation methods *)
navMethodDefault* = 0; (* Ctrl+PageUp, Ctrl+PageDown *)
navMethodAltPg* = 1; (* Alt+PageUp, Alt+PageDown *)
navMethodCtrlAltArr* = 3; (* Ctrl+Alt+Left, Ctrl+Alt+Right *)
(* these constants need to be in sync with Containers docu *)
PageLeft = 10X;
PageRight = 11X;
PageUp = 12X;
PageDown = 13X;
LeftArrow = 1CX;
RightArrow = 1DX;
left = TRUE; right = ~left;
none = -1;
TYPE
Pixels = INTEGER; (* for values in pixel coordinates *)
UCs = INTEGER; (* used for values in universal coordinates *)
GenericContext* = POINTER TO ABSTRACT RECORD (Models.Context) (* revisit *)
fnt: Fonts.Font;
asc, dsc: INTEGER;
END;
View* = POINTER TO ABSTRACT RECORD (Views.View)
kind-: BYTE;
ctx-: POINTER TO ARRAY OF Context;
active: INTEGER;
canDrop*: PROCEDURE (v: View; ind: INTEGER): BOOLEAN;
transferCopy*: (* may not be necessary, cf. StdTiles.Proxy.CopyFromSimpleView *)
PROCEDURE (source: Views.View; toV: View; toF: Views.Frame): Views.View;
backdrop*: Views.View; (** this view is restored in empty filler views *)
track: Views.Title; (* optional track name, a control property *)
END;
Context* = POINTER TO EXTENSIBLE RECORD (GenericContext)
filler-: View; (* = NIL => context removed from filler *)
view-: Views.View;
title-: Views.Title;
w, h: INTEGER
END;
Divider = POINTER TO RECORD (View)
(** devide window to several areas *)
isHorizontal: BOOLEAN
END;
Tile = POINTER TO RECORD (Context)
x, (** left or top border of tile inside it's divider *)
size, esize: UCs; (** size in pixels; effective size, used for calculations, ~permanent *)
pSize: INTEGER; (** size in percent ( fixed point, [0..1], the base is 32768) *)
END;
CheckDirtyAction = POINTER TO RECORD (Services.Action)
stack: Stack
END;
Stack = POINTER TO RECORD (View)
tb: Tabulator;
newTitle: Views.Title; (** parameter for Insert: title of newly inserted view *)
dirtyChecker: CheckDirtyAction;
END;
Tab = POINTER TO RECORD (Context)
closer: Closer;
titleView: TitleView
END;
TabVerb* = PROCEDURE (c: Context);
Tabulator = POINTER TO RECORD (Views.View)
(** ribbon of tabs, normally at the top of a Stack *)
stack: Stack;
dropMark, actL, actR, scrollShift: INTEGER; (* passed from Restore to RestoreMarks *)
END;
TabGeometry = RECORD
(** encapsulates geometry of embedded objects *)
stack: Stack;
ind: INTEGER;
closerWidth, titleWidth, closerLeft, titleLeft, width: INTEGER;
closerSide: BOOLEAN
END;
Closer = POINTER TO RECORD (Views.View)
(** show close button on a tab and closes the tab when clicked *)
tab: Tab;
afterTrack: BOOLEAN; (* reduce selection after canceling close dialog *)
END;
CloserCtx = POINTER TO RECORD (GenericContext)
wid: INTEGER;
END;
TitleView = POINTER TO RECORD (Views.View)
tab: Tab;
dirty: BOOLEAN;
wid, hei: INTEGER
END;
TitleCtx = POINTER TO RECORD (GenericContext)
view: TitleView
END;
BackdropCtx = POINTER TO RECORD (GenericContext)
filler: View
END;
Proposal* = RECORD (Models.Proposal)
(** a proposal to remove view from View *)
op*: INTEGER;
title*: Views.Title
END;
DropTabPollMsg = RECORD (Controllers.TransferMessage)
frame: Views.Frame;
filler: View;
ind: INTEGER;
END;
DropFeedbackMsg = RECORD (Controllers.Message)
x, y, ind: INTEGER;
show: BOOLEAN;
END;
(* DropFeedbackMsg is expected to be delivered directly to the receiver thru Views.ForwardCtrlMsg; this implies that containers do not forward it to focus views or views at certain locations *)
ActivateMsg = RECORD (Views.Message) (* used by Divider *)
was, is: INTEGER; (** active view changes from was to is *)
END;
FindFrameMsg = RECORD (Views.Message)
frame: Views.Frame
END;
RemoveMsg* = RECORD (Controllers.Message)
(** sent to a view before it is removed from a Divider or Stack. Receiver may have no frame!! *)
processed*: BOOLEAN (** callee => caller. Callee may ask to not be removed by resetting .ok. Preset to FALSE *)
END;
RefocusAction = POINTER TO RECORD (Services.Action)
frame: Views.Frame;
view: Divider
END;
WindowPref* = RECORD (Properties.Preference)
win*: StdWindows.Window
END;
StackCreator = POINTER TO RECORD (Services.Action)
clickTime: LONGINT;
n: INTEGER;
d: Divider
END;
Param* = POINTER TO RECORD
color*, colorFocus*,
tabHeight*, minTabWidth*: INTEGER;
bgColor*, (** background color *)
gutterColor*, marksColor*,
closerColor*: Ports.Color; (** color to draw close button in *)
closerSide*: BOOLEAN; (** close button position (left or right) *)
closerMark*: ARRAY 4 OF CHAR; (** (unicode) character for close button *)
boldenFront*: BOOLEAN; (** make a tab's title boldface if it's on front *)
selectedBgColor*: Ports.Color; (** background of selected tab when it's on the front path *)
nonselectedBgColor*: Ports.Color; (** background of selected tab when it's on the front path *)
strokeColor*, strokeColorShaded*: Ports.Color;
markColor*: Ports.Color;
margins*, gutterWidth*: INTEGER;
debug*, markDirty*: BOOLEAN;
navigationMethod*: INTEGER;
InitDefaults-, Init-: PROCEDURE (par: ANYPTR)
END;
TrackMsg* = RECORD (Views.Message)
name*: Views.Title;
cnt*: INTEGER;
track*: View;
frame*: Views.Frame; (* .frame.view = .track *)
END;
TrackPropMsg* = RECORD (Properties.Message)
done*: BOOLEAN; (* callee => caller *)
poll*: BOOLEAN; (* poll or set *)
name*: Views.Title (* the track name for the receiver *)
END;
VAR
refocusAction: RefocusAction;
param*: Param;
globalStackCreator: StackCreator;
hotBtn: Views.View;
PROCEDURE^ GetActiveTabPosition (f: Views.Frame; st: Stack; OUT x0, x1: INTEGER): BOOLEAN;
PROCEDURE Focus* (v: View): Context;
VAR c: Context;
BEGIN
ASSERT(v # NIL, 20); IF v.active # none THEN c := v.ctx[v.active] END;
RETURN c
END Focus;
PROCEDURE Len* (f: View): INTEGER;
VAR len: INTEGER;
BEGIN
IF f.ctx = NIL THEN len := 0 ELSE len := LEN(f.ctx) END;
RETURN len
END Len;
PROCEDURE Recalc (d: Divider; wid, hei, dot: UCs);
VAR i, len, undef: INTEGER; x, defined, std: UCs; gross: LONGINT;
ctx: Context; tile: Tile;
BEGIN
IF d.isHorizontal THEN gross := wid ELSE gross := hei END;
len := Len(d); DEC(gross, dot * MAX(0, len - 1)); defined := 0; undef := 0;
i := 0;
WHILE i < len DO
tile := d.ctx[i](Tile); (* 1st pass:figure out desired e(ffective) size *)
IF tile.size # 0 THEN
tile.esize := tile.size
ELSIF tile.pSize # 0 THEN
tile.esize := SHORT(gross * tile.pSize DIV fixedPointBase)
ELSE
tile.esize := 0; INC(undef)
END;
INC(defined, tile.esize);
INC(i)
END;
IF undef > 0 THEN
std := MAX(0, (SHORT(gross) - defined) DIV undef)
ELSE
std := 0
END;
i := 0; x := 0;
WHILE i < len DO
tile := d.ctx[i](Tile); (* 2nd pass: shrink tiles that don't fit *)
tile.x := x;
IF tile.esize = 0 THEN tile.esize := std END;
tile.esize := MAX(0, MIN(SHORT(gross - x), tile.esize));
ASSERT(tile.esize >= 0, 60);
INC(x, tile.esize); INC(x, dot * param.gutterWidth);
ctx := d.ctx[i];
IF d.isHorizontal THEN
ctx.w := tile.esize; ctx.h := hei
ELSE
ctx.w := wid; ctx.h := tile.esize
END;
INC(i)
END
END Recalc;
PROCEDURE CheckTitleWidth (tv: TitleView; force: BOOLEAN);
VAR ctx: TitleCtx; dummy: UCs; font: Fonts.Font;
BEGIN
ctx := tv.context(TitleCtx);
IF force OR (ctx.fnt # StdCFrames.defaultFont) THEN
ctx.fnt := StdCFrames.defaultFont;
IF param.boldenFront THEN
font := Fonts.dir.This(ctx.fnt.typeface, ctx.fnt.size, ctx.fnt.style, Fonts.bold);
font.GetBounds(ctx.asc, ctx.dsc, dummy);
tv.wid := font.StringWidth(tv.tab.title) + param.margins * 3
ELSE
ctx.fnt.GetBounds(ctx.asc, ctx.dsc, dummy);
tv.wid := ctx.fnt.StringWidth(tv.tab.title) + param.margins * 3
END;
IF param.closerSide = left THEN
INC(tv.wid, param.margins);
END;
IF tv.wid < param.minTabWidth THEN
tv.wid := param.minTabWidth
END;
INC(tv.wid, mm);
tv.hei := param.tabHeight - param.margins - Ports.point * 2;
END
END CheckTitleWidth;
PROCEDURE InitGenericCtx (c: GenericContext);
VAR dummy: INTEGER;
BEGIN
ASSERT(c # NIL, 20);
c.fnt := StdCFrames.defaultFont;
c.fnt.GetBounds(c.asc, c.dsc, dummy)
END InitGenericCtx;
PROCEDURE NewFillerCtx (f: View): Context;
VAR c: Context;
BEGIN NEW(c); InitGenericCtx(c); c.filler := f; c.w := magicWidth; RETURN c
END NewFillerCtx;
PROCEDURE ThisInd (c: Context): INTEGER;
VAR i, len: INTEGER; ctx: POINTER TO ARRAY OF Context;
BEGIN
i:= 0; ctx := c.filler.ctx; len := LEN(ctx);
WHILE (i < len) & (ctx[i] # c) DO INC(i) END;
ASSERT(i < len, 20 (* c expected to be part of c.filler.ctx *) );
RETURN i
END ThisInd;
PROCEDURE (f: View) Activate (ind: INTEGER), NEW, EXTENSIBLE;
VAR msg: ActivateMsg;
BEGIN
IF f.active # ind THEN
msg.was := f.active; msg.is := ind; f.active := ind; Views.Broadcast(f, msg);
Views.Update(f, Views.keepFrames);
END
END Activate;
PROCEDURE (f: View) Remove (ind: INTEGER), NEW, EXTENSIBLE;
VAR new, j, k, len: INTEGER; ctx, copy: POINTER TO ARRAY OF Context;
BEGIN
ASSERT(f.ctx # NIL, 20); ctx := f.ctx;
len := LEN(ctx); ASSERT((0 <= ind) & (ind < len), 21 (* w is not in f *) );
IF ind = f.active THEN
IF f.active < len - 1 THEN
new := f.active + 1
ELSE
new := f.active - 1
END;
f.Activate(new);
IF new > ind THEN f.active := ind END
ELSIF ind < f.active THEN DEC(f.active)
END;
f.ctx[ind].filler := NIL;
IF len > 1 THEN
NEW(copy, len - 1);
j := 0; k := 0;
WHILE j < len DO
IF j # ind THEN copy[k] := ctx[j]; INC(k) END;
INC(j)
END;
f.ctx := copy
ELSE ASSERT(ind = 0, 60); f.ctx := NIL
END;
Views.Update(f, Views.rebuildFrames);
ASSERT(f.active < Len(f), 60)
END Remove;
PROCEDURE Remove* (c: Context);
BEGIN ASSERT(c # NIL, 20); c.filler.Remove(ThisInd(c))
END Remove;
PROCEDURE SetTitle (f: View; ind: INTEGER; IN title: ARRAY OF CHAR);
BEGIN ASSERT((0 <= ind) & (ind < Len(f)), 20);
f.ctx[ind].title := title$;
WITH f: Stack DO CheckTitleWidth(f.ctx[ind](Tab).titleView, TRUE);
Views.Update(f.tb, Views.keepFrames)
ELSE
END
END SetTitle;
PROCEDURE (f: View) Insert (view: Views.View; pos: INTEGER), NEW, EMPTY;
PROCEDURE Insert (f: View; view: Views.View; pos: INTEGER; IN title: ARRAY OF CHAR;
context: Context
);
VAR j, k, len: INTEGER; ctx, copy: POINTER TO ARRAY OF Context;
BEGIN
ASSERT(f # NIL, 20); ASSERT(context # NIL, 21);
ASSERT(0 <= pos, 22); ASSERT(pos <= Len(f), 23);
IF view # NIL THEN
context.view := view; view.InitContext(context); Stores.Join(f, view)
END;
InitGenericCtx(context); context.filler := f; context.w := magicWidth;
ctx := f.ctx; len := Len(f);
ASSERT(pos <= len, 20);
NEW(copy, len + 1);
j := 0; k := 0; WHILE k <= len DO
IF k = pos THEN copy[k] := context ELSE copy[k] := ctx[j]; INC(j) END;
INC(k)
END;
f.ctx := copy;
SetTitle(f, pos, title);
IF pos <= f.active THEN INC(f.active)
ELSIF f.active = none THEN f.active := pos
END
END Insert;
PROCEDURE (d: Divider) Insert (view: Views.View; pos: INTEGER);
VAR tile: Tile;
BEGIN
ASSERT(0 <= pos, 20); ASSERT(pos <= Len(d), 21);
NEW(tile); tile.pSize := 0; tile.size := 0; tile.esize := 0;
IF pos = 0 THEN
tile.x := 0
ELSE
tile.x := d.ctx[pos-1](Tile).x + d.ctx[pos-1](Tile).esize
END;
Insert(d, view, pos, '', tile)
END Insert;
PROCEDURE CheckCloserWidth (c: Closer): INTEGER;
VAR ctx: CloserCtx;
BEGIN
ctx := c.context(CloserCtx);
IF param.closerMark = "" THEN
ctx.wid := 11 * Ports.point;
ELSE
ctx.wid := ctx.fnt.StringWidth(param.closerMark)
END;
RETURN ctx.wid
END CheckCloserWidth;
PROCEDURE (st: Stack) Insert (view: Views.View; pos: INTEGER);
VAR tab: Tab; clCtx: CloserCtx; tCtx: TitleCtx; tv: TitleView; r_: INTEGER;
BEGIN
ASSERT(0 <= pos, 20); ASSERT(pos <= Len(st), 21);
NEW(tab);
NEW(tab.closer); NEW(clCtx); InitGenericCtx(clCtx);
tab.closer.InitContext(clCtx); Stores.Join(tab.closer, st);
NEW(tv); tv.dirty := FALSE;
tab.titleView := tv; tv.tab := tab; NEW(tCtx); tCtx.view := tv;
InitGenericCtx(tCtx); tv.InitContext(tCtx); Stores.Join(tv, st);
tab.closer.tab := tab;
tab.closer.afterTrack := FALSE;
clCtx.wid := 0;
Insert(st, view, pos, st.newTitle, tab);
r_ := CheckCloserWidth(tab.closer);
st.newTitle := ''
END Insert;
PROCEDURE (f: View) Append (view: Views.View), NEW, EXTENSIBLE;
BEGIN f.Insert(view, Len(f))
END Append;
PROCEDURE InitFiller (f: View);
BEGIN ASSERT(f # NIL, 20); f.ctx := NIL; f.active := none
END InitFiller;
PROCEDURE AppendDivTile* (f: View; view: Views.View; size: UCs; pSize: REAL);
VAR i: INTEGER; tile: Tile; d: Divider;
BEGIN
ASSERT(f IS Divider, 20); d := f(Divider);
d.Append(view); i := Len(d) - 1;
tile := d.ctx[i](Tile); tile.size := size;
IF pSize > 0 THEN
tile.pSize := SHORT(ENTIER(pSize * fixedPointBase))
ELSE
tile.pSize := 0
END;
Views.Update(d, Views.rebuildFrames)
END AppendDivTile;
PROCEDURE AppendStackTab* (f: View; view: Views.View; IN title: Views.Title);
VAR st: Stack;
BEGIN ASSERT((f # NIL) & (f IS Stack), 20); st := f(Stack);
IF view # NIL THEN ASSERT(view.context = NIL) END;
st.newTitle := title$;
st.Append(view);
ASSERT(st.ctx[LEN(st.ctx) - 1].view = view, 60);
Views.Update(st, Views.rebuildFrames)
END AppendStackTab;
PROCEDURE NewDivider* (vertical: BOOLEAN): Divider;
VAR d: Divider;
BEGIN
NEW(d);
d.kind := divider;
InitFiller(d);
d.isHorizontal := vertical;
RETURN d
END NewDivider;
PROCEDURE Activate* (c: Context);
BEGIN ASSERT(c # NIL, 20); ASSERT(c.filler # NIL, 21); c.filler.Activate(ThisInd(c))
END Activate;
PROCEDURE HandleViewMsg (v: View; f: Views.Frame; VAR msg: Views.Message);
(** Handle view messages common to any View *)
BEGIN
WITH msg: TrackMsg DO
IF msg.name = v.track THEN
INC(msg.cnt);
IF msg.cnt = 1 THEN msg.track := v; msg.frame := f END
END
ELSE
END
END HandleViewMsg;
PROCEDURE (d: Divider) HandleViewMsg- (f: Views.Frame; VAR msg: Views.Message);
CONST focusChange = TRUE;
VAR mark: Controllers.MarkMsg; g: Views.Frame;
BEGIN
HandleViewMsg(d, f, msg);
WITH msg: ActivateMsg DO
mark.focus := focusChange;
IF msg.was # none THEN
g := Views.ThisFrame(f, d.ctx[msg.was].view);
IF g # NIL THEN
mark.show := Controllers.hide;
Views.ForwardCtrlMsg(g, mark)
END
END;
IF msg.is # none THEN
g := Views.ThisFrame(f, d.ctx[msg.is].view);
IF g # NIL THEN
mark.show := Controllers.show;
Views.ForwardCtrlMsg(g, mark)
END
END
| msg: FindFrameMsg DO
ASSERT(msg.frame = NIL, 126 (* divider in multiple frames NIY*));
msg.frame := f
ELSE
END
END HandleViewMsg;
PROCEDURE InstallActiveFrame (st: Stack; f: Views.Frame; wid, hei: INTEGER);
(** Install into f a frame for st's active view, assuming st's wid and hei *)
VAR c: Context;
BEGIN
IF st.active # none THEN c := st.ctx[st.active];
IF c.view # NIL THEN
c.w := wid;
c.h := hei - param.tabHeight;
Views.InstallFrame(f, c.view, 0, param.tabHeight, 0, TRUE)
END
END
END InstallActiveFrame;
PROCEDURE (st: Stack) HandleViewMsg- (f: Views.Frame; VAR msg: Views.Message);
VAR wid, hei: INTEGER; g: Views.Frame; mark: Controllers.MarkMsg;
PROCEDURE MakeActiveVisible;
VAR
width, height: INTEGER;
x0, x1: INTEGER;
BEGIN
st.tb.context.GetSize(width, height);
IF (width > Ports.mm) & GetActiveTabPosition(f, st, x0, x1) THEN
(* k8: check of current tab is visible *)
INC(x0, st.tb.scrollShift + 2 * mm);
INC(x1, st.tb.scrollShift + 2 * mm);
IF x0 < 4 * mm THEN
DEC(st.tb.scrollShift, x0 - 4 * mm)
ELSIF x1 + 6 * mm > width THEN
INC(st.tb.scrollShift, width - x1 - 6 * mm)
END;
st.tb.scrollShift := MIN(st.tb.scrollShift, 0); (* left limit *)
(* k8: FIXME: better right limit processing granularity! *)
(*
st.tb.scrollShift := MAX(st.tb.scrollShift, -(totalW - width + Ports.mm * 4)); (* right limit *)
*)
END
END MakeActiveVisible;
BEGIN
HandleViewMsg(st, f, msg);
WITH msg: FindFrameMsg DO
msg.frame := f
| msg: ActivateMsg DO
(* Cannot call Views.Update from here, so do frame work manually *)
ASSERT((none <= msg.was) & (msg.was < LEN(st.ctx)), 20);
ASSERT((none <= msg.is) & (msg.is < LEN(st.ctx)), 21);
ASSERT(msg.is = st.active, 22);
IF msg.was # none THEN
g := Views.ThisFrame(f, st.ctx[msg.was].view);
IF g # NIL THEN Views.RemoveFrame(f, g) END
END;
IF msg.is # none THEN
st.context.GetSize(wid, hei);
InstallActiveFrame(st, f, wid, hei);
MakeActiveVisible;
g := Views.ThisFrame(f, st.ctx[st.active].view);
IF g # NIL THEN
mark.focus := TRUE; mark.show := Controllers.show;
Views.ForwardCtrlMsg(g, mark)
END
END
ELSE
END
END HandleViewMsg;
PROCEDURE ContextAt (d: Divider; x, y: INTEGER): Context;
VAR len, i: INTEGER; ctx: POINTER TO ARRAY OF Context; res: Context;
BEGIN
ctx := d.ctx; len := Len(d) - 1; i := -1;
IF d.isHorizontal THEN
WHILE (x > 0) & (i < len) DO INC(i); DEC(x, ctx[i].w) END;
ELSE
WHILE (y > 0) & (i < len) DO INC(i); DEC(y, ctx[i].h) END;
END;
IF (0 <= i) & (i < len) THEN res := ctx[i] END;
RETURN res
END ContextAt;
PROCEDURE HandlePropMsg (v: View; VAR msg: Properties.Message);
BEGIN
WITH msg: TrackPropMsg DO msg.done := TRUE;
IF msg.poll THEN msg.name := v.track$ ELSE v.track := msg.name$ END
ELSE
END
END HandlePropMsg;
PROCEDURE (d: Divider) HandlePropMsg (VAR msg: Properties.Message);
VAR i, len: INTEGER; ctx: Context;
BEGIN
HandlePropMsg(d, msg);
WITH msg: Properties.FocusPref DO
IF msg.atLocation THEN ctx := ContextAt(d, msg.x, msg.y)
ELSIF d.active # none THEN ctx := d.ctx[d.active]
END;
IF ctx # NIL THEN Views.HandlePropMsg(ctx.view, msg) END
ELSE
END
END HandlePropMsg;
PROCEDURE (s: Stack) HandlePropMsg (VAR msg: Properties.Message);
VAR w, h: INTEGER;
BEGIN
HandlePropMsg(s, msg);
WITH msg: Properties.FocusPref DO
IF msg.atLocation THEN
s.context.GetSize(w, h);
IF (0 <= msg.x) & (msg.x < w) & (0 <= msg.y) & (msg.y < tabHeight) THEN
msg.hotFocus := TRUE
ELSE msg.setFocus := Len(s) > 0
END
ELSE msg.setFocus := Len(s) > 0
ENDmsg.setFocus := Len(s) > 0
ELSE
END
END HandlePropMsg;
PROCEDURE DoTransfer (fromV: View; from: INTEGER; toV: View; VAR to: INTEGER; toF: Views.Frame);
(** Upon return, to may be adjusted *)
VAR copy: Views.View; c: Context; ctx: POINTER TO ARRAY OF Context; i: INTEGER; focus: Context;
BEGIN
ASSERT(from < LEN(fromV.ctx), 21);
IF toV.ctx = NIL THEN ASSERT(to = 0, 22) ELSE ASSERT(to <= LEN(toV.ctx), 23) END;
IF (fromV = toV) & (from = to) THEN (* nothing *)
ELSIF fromV = toV THEN (* just reorder contexts *)
IF from # to THEN
focus := fromV.ctx[fromV.active];
c := fromV.ctx[from]; ctx := toV.ctx;
IF to < from THEN i := from; WHILE i > to DO ctx[i] := ctx[i - 1]; DEC(i) END
ELSIF from < to THEN DEC(to); i := from; WHILE i < to DO ctx[i] := ctx[i + 1]; INC(i) END
END;
ctx[to] := c;
Activate(focus)
END
ELSE
IF fromV.transferCopy # NIL THEN copy := fromV.transferCopy(fromV.ctx[from].view, toV, toF)
ELSE copy := Views.CopyOf(fromV.ctx[from].view, Views.shallow)
END;
WITH toV: Stack DO toV.newTitle := fromV.ctx[from].title$ ELSE END;
fromV.Remove(from);
toV.Insert(copy, to)
END;
Views.Update(fromV, Views.rebuildFrames);
IF fromV # toV THEN Views.Update(toV, Views.rebuildFrames) END
END DoTransfer;
PROCEDURE Transfer* (what: Views.View; where: View; pos: INTEGER);
(** Request to transfer what (embedded into some View) into where at position pos. pos = append => at the end *)
VAR msg: FindFrameMsg; from, len: INTEGER; c: Models.Context; fromV: View;
BEGIN ASSERT(what # NIL, 20); ASSERT(where # NIL, 21); ASSERT(pos >= append, 22);
c := what.context;
WITH c: Context DO
fromV := c.filler; from := 0;
WHILE fromV.ctx[from] # c DO INC(from) END;
len := Len(where); ASSERT(pos <= len, 23);
IF pos = append THEN pos := len END;
Views.Broadcast(where, msg);
IF msg.frame # NIL THEN DoTransfer(fromV, from, where, pos, msg.frame) END
ELSE HALT(24)
END
END Transfer;
(* Persistency *)
PROCEDURE (s: Stack) Externalize (VAR wr: Stores.Writer);
VAR i, len: INTEGER; tab: Context;
BEGIN
wr.WriteVersion(version);
len := Len(s); wr.WriteString(s.track); wr.WriteInt(len);
i := 0;
WHILE i < len DO
tab := s.ctx[i];
wr.WriteString(tab.title);
Views.WriteView(wr, tab.view);
INC(i)
END
END Externalize;
PROCEDURE InitStack (st: Stack);
BEGIN
st.kind := stack; InitFiller(st);
NEW(st.tb);
st.tb.stack := st; st.tb.dropMark := -1;
st.tb.scrollShift := 0;
st.tb.InitContext(NewFillerCtx(NIL)); Stores.Join(st.tb, st);
IF param.markDirty THEN
NEW(st.dirtyChecker);
st.dirtyChecker.stack := st;
Services.DoLater(st.dirtyChecker, Services.now);
END;
END InitStack;
PROCEDURE (s: Stack) Internalize (VAR rd: Stores.Reader);
VAR i, ver, len: INTEGER; title: Views.Title; v: Views.View;
BEGIN
rd.ReadVersion(version, version, ver);
IF ~rd.cancelled THEN
InitStack(s);
rd.ReadString(s.track); rd.ReadInt(len);
WHILE len > 0 DO DEC(len);
rd.ReadString(title);
Views.ReadView(rd, v);
IF v # NIL THEN AppendStackTab(s, v, title) END
END
END
END Internalize;
PROCEDURE (d: Divider) Externalize (VAR wr: Stores.Writer);
VAR i, len: INTEGER; tile: Tile;
BEGIN
wr.WriteVersion(version);
len := Len(d);
wr.WriteString(d.track);
wr.WriteBool(d.isHorizontal);
wr.WriteInt(len);
i := 0;
WHILE i < len DO
tile := d.ctx[i](Tile);
wr.WriteString(tile.title);
wr.WriteInt(tile.size);
wr.WriteInt(tile.pSize);
Views.WriteView(wr, tile.view);
INC(i)
END
END Externalize;
PROCEDURE (d: Divider) Internalize (VAR rd: Stores.Reader);
VAR size, pSize, ver, len: INTEGER; v: Views.View; title_: Views.Title;
BEGIN
rd.ReadVersion(version, version, ver);
IF ~rd.cancelled THEN
d.kind := divider; InitFiller(d);
rd.ReadString(d.track);
rd.ReadBool(d.isHorizontal);
rd.ReadInt(len);
WHILE len > 0 DO DEC(len);
rd.ReadString(title_);
rd.ReadInt(size);
rd.ReadInt(pSize);
Views.ReadView(rd, v);
IF v # NIL THEN AppendDivTile(d, v, size, pSize) END;
END
;len := Len(d); WHILE len > 0 DO DEC(len); ASSERT(d.ctx[len] = d.ctx[len].view.context) END
END
END Internalize;
PROCEDURE (d: Divider) CopyFromSimpleView (src: Views.View);
VAR len: INTEGER; tile, style: Tile;
BEGIN
(* this is temporary! Nested views are embeded directly into the divider, which is a no-go. TO make a valid copy of the Divider, you'd need shallow copies of all nested views. But this is just for a persistency experiment, the copy is made, externalized, then disposed. So, it shall go. Otherwise, you'd need actual shallow copies of embedded view, or, alternatively and more BB-way - the Divider should be a model view, and views shall be embedded into a model rather than directly the Divivder. *)
WITH src: Divider DO
d.kind := divider;
len := Len(src); IF len # 0 THEN NEW(d.ctx, len);
REPEAT DEC(len); stile := src.ctx[len](Tyle);
NEW(tile); d.ctx[len] := tile;
tile.filler := d; tile.view := stile.view; tile.title := stile.title$; tile.w := stile.w; tile.h := stile.h;
tile.x := stile.x; tile.size := stile.size; tile.pSize := stile.pSize
UNTIL len = 0
END;d.ctx := src.ctx;
d.active := src.active; d.canDrop := src.canDrop; d.transferCopy := src.transferCopy;
d.backdrop := src.backdrop; d.track := src.track$;
d.isHorizontal := src.isHorizontal
END
(* debug
; IF param.debug THEN Con.String("Divider.CopyFromSimpleView"); Con.Ln; END;
*)
END CopyFromSimpleView;
(* Stack and Divider *)
PROCEDURE (bc: BackdropCtx) GetSize (OUT w, h: INTEGER);
BEGIN
IF (bc.filler # NIL) & (bc.filler.context # NIL) THEN
bc.filler.context.GetSize(w, h);
DEC(h, param.tabHeight)
END
END GetSize;
PROCEDURE (st: Stack) Restore* (f: Views.Frame; l, t, r, b: INTEGER);
VAR c: Context; wid, hei: UCs; bc: BackdropCtx;
BEGIN
st.context.GetSize(wid, hei);
IF st.ctx # NIL THEN
c := st.tb.context(Context);
c.w := wid;
c.h := param.tabHeight;
Views.InstallFrame(f, st.tb, 0, 0, 0, FALSE);
InstallActiveFrame(st, f, wid, hei)
END;
IF (st.active = none) & (st.backdrop # NIL) THEN
IF st.backdrop.context = NIL THEN NEW(bc); bc.filler := st;
st.backdrop.InitContext(bc); Stores.Join(st, st.backdrop);
END;
ASSERT(Stores.Joined(st, st.backdrop), 20);
Views.InstallFrame(f, st.backdrop, 0, param.tabHeight, 0, FALSE)
END
END Restore;
PROCEDURE StackEditOp (_: Views.Frame; st: Stack; IN msg: Controllers.EditMsg;
VAR focus: Views.View
);
VAR to: INTEGER;
BEGIN
IF (msg.op = Controllers.pasteChar) & (Len(st) > 0) THEN
to := st.active;
CASE param.navigationMethod OF
| navMethodAltPg:
IF Controllers.pick IN msg.modifiers THEN
(* Alt *)
CASE msg.char OF
| PageUp: DEC(to)
| PageDown: INC(to)
ELSE END
END
| navMethodCtrlAltArr:
IF msg.modifiers*{Controllers.pick,Controllers.modify} = {Controllers.pick,Controllers.modify} THEN
(* Ctrl+Alt *)
CASE msg.char OF
| LeftArrow: DEC(to)
| RightArrow: INC(to)
ELSE END
END
ELSE (* default *)
IF msg.modifiers*{0..7} = {} THEN
(*
Ctrl+PageUp=PageLeft
Ctrl+PageDown=PageRight
*)
CASE msg.char OF
| PageLeft: DEC(to)
| PageRight: INC(to)
ELSE END
END
END;
IF to # st.active THEN focus := NIL END;
to := MAX(0, MIN(to, Len(st) - 1));
IF to # st.active THEN st.Activate(to) END
END
END StackEditOp;
PROCEDURE (st: Stack) HandleCtrlMsg* (f: Views.Frame; VAR msg: Views.CtrlMessage;
VAR focus: Views.View
);
VAR g: Views.Frame; ctx: GenericContext; wid, hei, asc, dsc, dummy: INTEGER; fnt: Fonts.Font;
BEGIN
WITH msg: DropFeedbackMsg DO
IF msg.show THEN st.context.GetSize(wid, hei);
IF st.context IS GenericContext THEN
ctx := st.context(GenericContext);
fnt := ctx.fnt;
fnt := Fonts.dir.This(fnt.typeface, 10 * mm, fnt.style, Fonts.bold)
ELSE
fnt := Fonts.dir.This(StdCFrames.defaultFont.typeface, 10 * mm, fnt.style, Fonts.bold)
END;
fnt.GetBounds(asc, dsc, dummy);
f.DrawString((wid - fnt.StringWidth("*")) DIV 2, (hei - asc - dsc) DIV 2 + asc, param.marksColor, "*", fnt)
ELSE
Views.Update(st, Views.keepFrames); Views.ValidateRoot(Views.RootOf(f))
END
ELSE
WITH msg: Controllers.CursorMessage DO
g := Views.FrameAt(f, msg.x, msg.y)
ELSE END;
IF g # NIL THEN focus := g.view
ELSIF st.active # none THEN focus := st.ctx[st.active].view
ELSE focus := NIL
END;
WITH msg: Controllers.EditMsg DO StackEditOp(f, st, msg, focus) ELSE END;
IF focus = NIL THEN
WITH msg: DropTabPollMsg DO
IF st.active = none THEN msg.ind := 0 ELSE msg.ind := st.active END;
msg.frame := f; msg.filler := st
ELSE
END
END
END
END HandleCtrlMsg;
PROCEDURE (d: Divider) GetBackground* (VAR color: Ports.Color);
BEGIN
color := param.bgColor
END GetBackground;
PROCEDURE (d: Divider) Restore* (f: Views.Frame; l, t, r, b: UCs);
VAR wid, hei, x, y: UCs; i, len: INTEGER; tile: Tile;
BEGIN
d.context.GetSize(wid, hei);
Recalc(d, wid, hei, f.dot);
len := Len(d);
IF d.isHorizontal THEN y := 0 ELSE x := 0 END;
i := 0;
WHILE i < len DO
tile := d.ctx[i](Tile);
IF d.isHorizontal THEN x := tile.x ELSE y := tile.x END;
IF i > 0 THEN (* draw gutter *)
IF d.isHorizontal THEN
f.DrawRect(x - f.dot * param.gutterWidth, t, x, b, Ports.fill, param.gutterColor)
ELSE
f.DrawRect(l, y - f.dot * param.gutterWidth, r, y, Ports.fill, param.gutterColor)
END
END;
IF tile.view # NIL THEN
Views.InstallFrame(f, tile.view, x, y, 0, i = d.active)
END;
INC(i)
END
END Restore;
PROCEDURE (d: Divider) RestoreMarks* (f: Views.Frame; l, t, r, b: INTEGER);
VAR col: INTEGER; tile: Tile;
BEGIN
IF param.debug THEN
IF d.active # none THEN
tile := d.ctx[d.active](Tile);
IF d.isHorizontal THEN
t := 0; l := tile.x; r := l + tile.w; b := tile.h;
col := Ports.red + Ports.blue
ELSE
l := 0; r := tile.w; t := tile.x; b := t + tile.h;
col := Ports.red + Ports.green
END
ELSE l := 0; t := 0; d.context.GetSize(r, b)
END;
f.DrawRect(l, t, r, b, 0, col);
f.DrawLine(l, t, r, b, 0, col)
END
END RestoreMarks;
PROCEDURE ThisIndex (d: Divider; x, y: UCs): INTEGER;
VAR i, len, ind: INTEGER; u: UCs; ctx: POINTER TO ARRAY OF Context;
BEGIN
ctx := d.ctx; len := Len(d);
IF d.isHorizontal THEN u := x ELSE u := y END;
i := 0; WHILE (i < len) & ((ctx[i](Tile).x + ctx[i](Tile).esize) <= u) DO INC(i) END;
IF (i < len) THEN
IF u < ctx[i](Tile).x THEN ind := -i - 1 (* falls in the gap *) ELSE ind := i END
ELSE ind := -1
END;
RETURN ind;
END ThisIndex;
PROCEDURE InResizer (d: Divider; x, y: UCs; OUT ind: INTEGER): BOOLEAN;
VAR u: UCs; res: BOOLEAN;
BEGIN
ind := ThisIndex(d, x, y);
IF d.isHorizontal THEN u := x ELSE u := y END;
IF ind < -1 THEN ind := -ind - 2; res := TRUE
ELSIF (ind >= 0) & (ind < Len(d) - 1) THEN
IF d.isHorizontal THEN u := x ELSE u := y END;
res := ((d.ctx[ind + 1](Tile).x - u) < Ports.point * 30 DIV 10)
ELSE res := FALSE END;
RETURN res
END InResizer;
PROCEDURE CursorAt (f: Views.Frame; x, y: UCs): INTEGER;
VAR cur, dummy: INTEGER; d: Divider;
BEGIN
ASSERT(f.view IS Divider, 20);
d := f.view(Divider);
IF InResizer(d, x, y, dummy) THEN
IF d.isHorizontal THEN cur := resizeHCursor ELSE cur := resizeVCursor END
ELSE cur := Ports.arrowCursor
END;
RETURN cur
END CursorAt;
PROCEDURE TrackResize (f: Views.Frame; xo, yo: UCs);
VAR min, max, wid, hei: UCs;
isDown: BOOLEAN; mod: SET;
d: Divider; (* divider in which the resizing should occur *)
ind: INTEGER; (* index of tile which should be resized *)
ind2: INTEGER; (* index of the adjacent tile which should be resized; IF tracking started on a gutter's boundary, THEN ind + 2 = ind, ELSE ind + 1 = ind END *)
t1, t2: Tile; (* Tiles that should be resized *)
gross: Pixels; (* size of the divider *)
esize: UCs; (* new esize of the view being recalculated *)
together: UCs; (* size of the two affected divisions; invariant!! *)
ox, oy: UCs; (* old x, old y - pixel coords that have been previousely used in recalc *)
x, y: UCs; (* current tracking coordinates *)
gs: UCs; (* gutter size *)
ticks: LONGINT;
ffm: FindFrameMsg;
BEGIN
d := f.view(Divider);
d.context.GetSize(wid, hei); Recalc(d, wid, hei, f.dot);
(* seek the tiler whose resizer was clicked *)
IF InResizer(d, xo, yo, ind) THEN
gs := f.dot * param.gutterWidth ; ind2 := ind + 1;
t1 := d.ctx[ind](Tile); t2 := d.ctx[ind2](Tile);
together := t1.esize + t2.esize;
min := t1.x + mm; max := t2.x + t2.esize;
IF d.isHorizontal THEN gross := wid ELSE gross := hei END;
x := xo; y := yo; ox := x; oy := y;
ticks := Services.Ticks();
REPEAT
IF (x < min) OR (x >= max) THEN x := ox END;
IF (y < min) OR (y >= max) THEN y := oy END;
esize := -1;
IF d.isHorizontal & (x # ox) THEN esize := x - t1.x - gs
ELSIF ~d.isHorizontal & (y # oy) THEN esize := y - t1.x - gs
END;
IF esize # -1 THEN
IF t1.pSize # 0 THEN t1.pSize := SHORT(LONG(esize) * fixedPointBase DIV gross)
ELSE t1.size := esize
END;
t1.esize := esize;
(* now recalculate the next (to the right or to the bottom) divider section *)
esize := together - esize;
IF t2.size # 0 THEN
t2.size := esize
ELSIF t2.pSize # 0 THEN
t2.pSize := SHORT(LONG(esize) * fixedPointBase DIV gross)
END;
t2.esize := esize;
ASSERT(together = t1.esize + t2.esize);
IF Services.Ticks() - ticks > 20 THEN
Views.Update(f.view, Views.keepFrames);
Views.ValidateRoot(Views.RootOf(f));
IF f.rider = NIL (* f closed while validating *) THEN
Views.Broadcast(d, ffm); f := ffm.frame
END;
ticks := Services.Ticks()
END
END;
ox := x; oy := y;
IF f # NIL THEN ASSERT(f.rider # NIL); f.Input(x, y, mod, isDown) END
UNTIL (f = NIL) OR ~isDown;
Views.Update(f.view, Views.keepFrames);
Views.ValidateRoot(Views.RootOf(f));
END
END TrackResize;
PROCEDURE ClaimFocus (v: Views.View): BOOLEAN;
VAR p: Properties.FocusPref; (* adapted from Containers *)
BEGIN
p.atLocation := FALSE;
p.hotFocus := FALSE; p.setFocus := FALSE;
Views.HandlePropMsg(v, p);
RETURN p.setFocus
END ClaimFocus;
PROCEDURE ClaimFocusAt (v: Views.View; f, g: Views.Frame; x, y: INTEGER): BOOLEAN;
VAR p: Properties.FocusPref; (* adapted from Containers *)
BEGIN
p.atLocation := TRUE; p.x := x + f.gx - g.gx; p.y := y + f.gy - g.gy;
p.hotFocus := FALSE; p.setFocus := FALSE;
Views.HandlePropMsg(v, p);
RETURN p.setFocus & ~p.hotFocus
END ClaimFocusAt;
PROCEDURE SetFocus (d: Divider; focus: Views.View);
VAR i, len: INTEGER;
BEGIN
i := 0; len := Len(d); WHILE (i < len) & (d.ctx[i].view # focus) DO INC(i) END;
IF i < len THEN
d.Activate(i)
END
END SetFocus;
PROCEDURE ThisTile (d: Divider; x, y: UCs): INTEGER;
VAR ind: INTEGER;
BEGIN
ind := ThisIndex(d, x, y);
IF ind < -1 THEN ind := -ind - 2 END;
RETURN ind
END ThisTile;
PROCEDURE ShowDropMark (f: Views.Frame; d: Divider; VAR msg: DropFeedbackMsg);
VAR ctx: GenericContext; wid, hei, asc, dsc, x, y, dummy: INTEGER; fnt: Fonts.Font;
ch: ARRAY 2 OF CHAR; tile: Tile;
BEGIN
ASSERT(msg.ind >= 0, 20);
IF msg.show THEN d.context.GetSize(wid, hei);
IF d.ctx = NIL THEN x := 0; y := 0
ELSE
IF msg.ind > 0 THEN DEC(msg.ind) END;
tile := d.ctx[msg.ind](Tile);
IF d.isHorizontal THEN
x := tile.x; wid := tile.esize; y := 0
ELSE
x := 0; y := tile.x; hei := tile.esize
END
END;
IF d.context IS GenericContext THEN
ctx := d.context(GenericContext);
fnt := ctx.fnt;
fnt := Fonts.dir.This(fnt.typeface, 10 * mm, fnt.style, Fonts.bold)
ELSE
fnt := StdCFrames.defaultFont;
fnt := Fonts.dir.This(fnt.typeface, fnt.size, fnt.style, Fonts.bold)
END;
fnt.GetBounds(asc, dsc, dummy);
IF d.isHorizontal THEN
ch := '▶' (*→*);
INC(x, wid - fnt.StringWidth(ch) - mm);
y := (hei - asc - dsc) DIV 2
ELSE
ch := '↓' (*▼*);
x := (wid - fnt.StringWidth(ch)) DIV 2;
INC(y, hei - dsc - mm)
END;
f.DrawString(x, y, param.marksColor, ch, fnt)
ELSE
Views.Update(d, Views.keepFrames); Views.ValidateRoot(Views.RootOf(f))
END
END ShowDropMark;
PROCEDURE CheckMaskFocus (f: Views.Frame; d: Divider; VAR focus: Views.View);
VAR i, len: INTEGER;
msg: Controllers.MarkMsg; g: Views.Frame;
BEGIN
IF (*f.mark &*) ((focus = NIL) OR ~ClaimFocus(focus)) THEN
i := 0; len := Len(d);
WHILE (i < len) & (d.ctx[i].view # NIL) & ~ClaimFocus(d.ctx[i].view) DO
INC(i)
END;
IF i < len THEN d.Activate(i) END;
focus := NIL
ELSIF focus # NIL THEN
g := Views.ThisFrame(f, focus);
IF g # NIL THEN
msg.focus := FALSE; msg.show := TRUE;
Views.ForwardCtrlMsg(g, msg)
END
END
END CheckMaskFocus;
PROCEDURE (a: RefocusAction) Do;
VAR _: Views.View; ffm: FindFrameMsg; f: Views.Frame;
BEGIN
f := a.frame;
IF f.rider = NIL THEN Views.Broadcast(a.view, ffm); f := ffm.frame END;
IF f # NIL THEN CheckMaskFocus(f, a.view, _) END
END Do;
PROCEDURE NewStack* (): Stack;
VAR st: Stack;
BEGIN
NEW(st);
InitStack(st);
RETURN st
END NewStack;
PROCEDURE (sc: StackCreator) Do;
VAR s: Stack; dev: View; i: INTEGER;
BEGIN
IF Services.Ticks() - sc.clickTime > Services.resolution DIV 2 THEN
IF sc.n > 1 THEN
dev := NewDivider(vertical);
FOR i := 1 TO sc.n DO
s := NewStack();
AppendDivTile(dev, s, 0, 0);
END;
AppendDivTile(sc.d, dev, 0, 0);
ELSE
s := NewStack();
AppendDivTile(sc.d, s, 0, 0);
END;
globalStackCreator := NIL;
ELSE
Services.DoLater(sc, Services.Ticks() + Services.resolution DIV 5)
END
END Do;
PROCEDURE CreateStack(d: Divider);
BEGIN
IF globalStackCreator = NIL THEN
NEW(globalStackCreator);
globalStackCreator.n := 1;
globalStackCreator.d := d;
globalStackCreator.clickTime := Services.Ticks();
Services.DoLater(globalStackCreator, Services.now);
ELSE
INC(globalStackCreator.n);
globalStackCreator.clickTime := Services.Ticks()
END
END CreateStack;
PROCEDURE (d: Divider) HandleCtrlMsg* (f: Views.Frame; VAR msg: Views.CtrlMessage;
VAR focus: Views.View
);
VAR dummy: INTEGER; g: Views.Frame; dx, dy: UCs; w, h: INTEGER;
BEGIN
d.context.GetSize(w, h);
WITH msg: DropFeedbackMsg DO
ShowDropMark(f, d, msg)
| msg: Controllers.MarkMsg DO
IF d.active # none THEN focus := d.ctx[d.active].view END;
IF msg.show & (focus # NIL) & ~ClaimFocus(focus) THEN
focus := NIL; (* don't relay the message, because focus will likely change *)
refocusAction.view := d;
refocusAction.frame := f;
Services.DoLater(refocusAction, Services.immediately)
END
| msg: Controllers.TickMsg DO
IF d.active # none THEN focus := d.ctx[d.active].view END;
CheckMaskFocus(f, d, focus)
| msg: Controllers.CursorMessage DO
IF InResizer(d, msg.x, msg.y, dummy)
& ((msg IS Controllers.TrackMsg) OR (msg IS Controllers.PollCursorMsg)) THEN
WITH
| msg: Controllers.TrackMsg DO
TrackResize(f, msg.x, msg.y)
| msg: Controllers.PollCursorMsg DO
msg.cursor := CursorAt(f, msg.x, msg.y)
END
ELSIF (msg.x > w - f.dot * 10) & (msg.y < param.tabHeight) THEN
WITH
| msg: Controllers.TrackMsg DO
CreateStack(d)
| msg: Controllers.PollCursorMsg DO
msg.cursor := Ports.tableCursor
ELSE END
ELSE
g := Views.FrameAt(f, msg.x, msg.y);
IF g # NIL THEN focus := g.view END;
IF (focus # NIL) & (msg IS Controllers.TrackMsg)
& ClaimFocusAt(focus, f, g, msg.x, msg.y) THEN
SetFocus(d, focus)
END
END
ELSE
IF d.active = none THEN
focus := NIL
ELSE
focus := d.ctx[d.active].view
END
END;
WITH msg: DropTabPollMsg DO
IF focus # NIL THEN g := Views.ThisFrame(f, focus);
IF g # NIL THEN
dx := f.gx - g.gx; dy := f.gy - g.gy;
INC(msg.x, dx); INC(msg.y, dy);
Views.ForwardCtrlMsg(g, msg);
DEC(msg.x, dx); DEC(msg.y, dy)
END;
focus := NIL
END;
IF (msg.filler = NIL) & (f.l <= msg.x) & (msg.x < f.r) & (f.t <= msg.y) & (msg.y < f.b) THEN
msg.ind := ThisTile(d, msg.x, msg.y);
IF (msg.ind = -1) & (Len(d) = 0) THEN
msg.ind := 0
ELSIF msg.ind >= 0 THEN
INC(msg.ind)
END;
IF (msg.ind # -1) & (d.canDrop # NIL) & ~d.canDrop(d, msg.ind) THEN
msg.ind := -1
END;
IF msg.ind # -1 THEN
msg.frame := f; msg.filler := d
END
END
ELSE
END
END HandleCtrlMsg;
(* GenericContext *)
PROCEDURE (c: GenericContext) Normalize* (): BOOLEAN; BEGIN RETURN TRUE END Normalize;
PROCEDURE (c: GenericContext) ThisModel* (): Models.Model; BEGIN RETURN NIL END ThisModel;
PROCEDURE CloseTab (f: Views.Frame; VAR tab: Tab);
VAR close: RemoveMsg; focus_, v: Views.View;
BEGIN
ASSERT(f # NIL, 20); ASSERT(tab # NIL, 21);
v := tab.view; ASSERT(v # NIL, 22);
close.processed := FALSE;
v.HandleCtrlMsg(Views.ThisFrame(f, v), close, focus_);
IF tab.filler # NIL THEN
IF close.processed THEN Activate(tab)
ELSE Remove(tab); tab := NIL
END
END
END CloseTab;
(* Closer context and button *)
PROCEDURE (ctx: CloserCtx) GetSize (OUT w, h: INTEGER);
BEGIN
w := ctx.wid;
IF param.closerMark[0] # 0X THEN
h := ctx.asc + ctx.dsc
ELSE
h := ctx.wid
END
END GetSize;
PROCEDURE (btn: Closer) Restore (f: Views.Frame; l, t, r, b: INTEGER);
VAR ctx: CloserCtx;
VAR color, w, w2, nw, s, s2, h: INTEGER;
BEGIN
ctx := btn.context(CloserCtx);
IF param.closerMark[0] # 0X THEN
f.DrawString(0, ctx.asc, param.closerColor, param.closerMark, ctx.fnt);
ELSE
w := 9 * Ports.point;
nw := ((w DIV f.unit) - (w DIV f.unit) MOD 2 + 1) * f.unit;
IF (nw # w) OR (nw # h) THEN btn.context.SetSize(nw, nw); w := nw END;
w2 := w DIV 2;
s := 5 * Ports.point - (5 * Ports.point) MOD f.unit;
s2 := s + f.unit;
IF (hotBtn # NIL) & (hotBtn = btn) THEN
color := Ports.black;
f.DrawRect(w2-s, w2-s, w2+s2, w2+s2, Ports.fill, Ports.RGBColor(200, 200, 200));
s := 4 * Ports.point - (4 * Ports.point) MOD f.unit;
f.DrawLine(w2, w2, w2 + s, w2 + s, f.dot, color);
f.DrawLine(w2, w2, w2 + s, w2 - s, f.dot, color);
f.DrawLine(w2, w2, w2 - s, w2 + s, f.dot, color);
f.DrawLine(w2, w2, w2 - s, w2 - s, f.dot, color);
ELSE
IF param.markDirty & btn.tab.titleView.dirty THEN
f.DrawOval(w2-s, w2-s, w2+s2-f.dot, w2+s2-f.dot, Ports.fill, param.color)
ELSE
color := Ports.grey50;
s := 4 * Ports.point - (4 * Ports.point) MOD f.unit;
f.DrawLine(w2, w2, w2 + s, w2 + s, f.dot, color);
f.DrawLine(w2, w2, w2 + s, w2 - s, f.dot, color);
f.DrawLine(w2, w2, w2 - s, w2 + s, f.dot, color);
f.DrawLine(w2, w2, w2 - s, w2 - s, f.dot, color);
END
END
END
END Restore;
PROCEDURE (btn: Closer) HandleCtrlMsg (f: Views.Frame; VAR msg: Views.CtrlMessage;
VAR focus: Views.View
);
BEGIN
WITH msg: Controllers.TrackMsg DO
CloseTab(f, btn.tab);
btn.afterTrack := TRUE;
(* just after TrackMsg there is PollCursorMsg called,
btn should be marked for not to be focused then *)
| msg: Controllers.PollCursorMsg DO
IF (hotBtn = NIL) & ~ btn.afterTrack THEN
hotBtn := btn;
Views.Update(btn, Views.keepFrames)
END;
btn.afterTrack := FALSE
ELSE
END
END HandleCtrlMsg;
(* TitleView *)
PROCEDURE (a: CheckDirtyAction) Do;
VAR i: INTEGER; wpref: WindowPref; state: BOOLEAN; tv: TitleView;
BEGIN
FOR i:=0 TO Len(a.stack) - 1 DO
tv := a.stack.ctx[i](Tab).titleView;
Views.HandlePropMsg(tv.tab.view, wpref);
IF (wpref.win # NIL) & ~ (Windows.neverDirty IN wpref.win.flags) THEN
state := wpref.win.seq.Dirty();
IF state # tv.dirty THEN
tv.dirty := state;
Views.Update(tv.tab.closer, Views.keepFrames)
END
END
END;
Services.DoLater(a, Services.Ticks() + Services.resolution DIV 4)
END Do;
PROCEDURE IsFront(view: Views.View): BOOLEAN;
VAR wpref: WindowPref; msg: StdDocuments.PollOptsMsg; front: BOOLEAN;
BEGIN
front := FALSE;
Views.HandlePropMsg(view, wpref);
IF wpref.win # NIL THEN
msg.opts := {};
Views.Broadcast(wpref.win.doc, msg);
front := StdDocuments.front IN msg.opts
END;
RETURN front
END IsFront;
PROCEDURE (tv: TitleView) Restore (f: Views.Frame; l, t, r, b: INTEGER);
VAR
ctx: TitleCtx; fnt: Fonts.Font; w, h: INTEGER; col: Ports.Color;
name: ARRAY 32 OF CHAR; rf: Views.Frame;
BEGIN
tv.context.GetSize(w, h);
IF param.debug THEN
f.DrawRect(0, 0, w, h, Ports.fill, Ports.RGBColor(200, 100, 100))
END;
CheckTitleWidth(tv, FALSE);
ctx := tv.context(TitleCtx);
fnt := ctx.fnt;
IF IsFront(tv.tab.view) THEN
col := param.colorFocus;
IF param.boldenFront THEN
fnt := Fonts.dir.This(fnt.typeface, fnt.size, fnt.style, Fonts.bold)
END
ELSE
col := param.color
END;
IF col = Ports.defaultColor THEN
col := Dialog.defaultColor
END;
IF param.closerSide = left THEN
f.DrawString(param.margins, h DIV 2 + (ctx.asc - ctx.dsc) DIV 2, col, tv.tab.title, fnt)
ELSE
f.DrawString(param.margins * 2, h DIV 2 + (ctx.asc-ctx.dsc) DIV 2, col, tv.tab.title, fnt)
END
END Restore;
PROCEDURE (tv: TitleView) HandleViewMsg (f: Views.Frame; VAR msg: Views.Message);
BEGIN
WITH msg: FindFrameMsg DO
ASSERT(msg.frame = NIL, 126); msg.frame := f
ELSE END
END HandleViewMsg;
PROCEDURE (tv: TitleView) HandleCtrlMsg (f: Views.Frame; VAR msg: Views.CtrlMessage;
VAR focus: Views.View
);
VAR
poll: DropTabPollMsg; x, y, ox, oy, targInd: INTEGER; ticks: LONGINT; mod: SET;
isDown, wasActive: BOOLEAN; tell: DropFeedbackMsg; target: View; tFrame: Views.Frame;
prop: Proposal; wpref: WindowPref; ffm: FindFrameMsg;
BEGIN
WITH
| msg: StdWindows.PrefocusMsg DO
Views.HandlePropMsg(tv.tab.view, wpref);
IF wpref.win # NIL THEN msg.win := wpref.win END
| msg: Controllers.TrackMsg DO
x := msg.x; y := msg.y; ticks := Services.Ticks(); ox := x; oy := y; targInd := -1;
REPEAT
IF (((Services.Ticks() - ticks) > (Services.resolution DIV 5)) & (x # ox) & (y # oy))
OR ((Services.Ticks() - ticks) > (Services.resolution DIV 1)) THEN
f.SetCursor(Ports.refCursor);
poll.filler := NIL;
Controllers.Transfer(x, y, f, msg.x, msg.y, poll);
IF (target # poll.filler) OR (targInd # poll.ind) THEN
IF target # NIL THEN
tell.x := ox; tell.y := oy; tell.ind := targInd; tell.show := FALSE;
IF tFrame.rider = NIL THEN
ffm.frame := NIL;
Views.Broadcast(target, ffm); tFrame := ffm.frame
END;
Views.ForwardCtrlMsg(tFrame, tell)
END;
IF poll.filler # NIL THEN
f.SetCursor(Ports.refCursor);
tell.x := poll.x; tell.y := poll.y; tell.ind := poll.ind; tell.show := TRUE;
IF poll.frame.rider = NIL THEN
ffm.frame := NIL;
Views.Broadcast(poll.filler, ffm); poll.frame := ffm.frame
END;
Views.ForwardCtrlMsg(poll.frame, tell)
ELSE
f.SetCursor(stopCursor)
END
END;
ox := x; oy := y; target := poll.filler;
targInd := poll.ind; tFrame := poll.frame
END;
IF f.rider = NIL THEN
ffm.frame := NIL; Views.Broadcast(tv, ffm); f := ffm.frame
END;
IF f # NIL THEN f.Input(x, y, mod, isDown) ;ASSERT(f.rider # NIL) END
UNTIL (f = NIL) OR ~isDown;
IF target # NIL THEN
tell.x := ox; tell.y := oy; tell.ind := targInd; tell.show := FALSE;
IF tFrame.rider = NIL THEN
ffm.frame := NIL;
Views.Broadcast(target, ffm); tFrame := ffm.frame
END;
Views.ForwardCtrlMsg(tFrame, tell)
END;
IF poll.filler # NIL THEN
wasActive := tv.tab.filler.active = ThisInd(tv.tab);
DoTransfer(tv.tab.filler, ThisInd(tv.tab), poll.filler, poll.ind, poll.frame);
IF wasActive THEN (*poll.filler.Activate(poll.ind);*)
prop.op := activate; poll.filler.ctx[poll.ind].Consider(prop)
END;
ELSE
Activate(tv.tab)
END
ELSE
END
END HandleCtrlMsg;
PROCEDURE (tctx: TitleCtx) GetSize (OUT wid, hei: INTEGER);
BEGIN
CheckTitleWidth(tctx.view, FALSE);
wid := tctx.view.wid;
hei := tctx.view.hei
END GetSize;
(* Tabulator *)
PROCEDURE (tb: Tabulator) GetBackground (VAR bg: Ports.Color);
BEGIN bg := param.bgColor
END GetBackground;
PROCEDURE GetNextTabGeometry (VAR tg: TabGeometry);
VAR tab: Tab; width, height, len, margin: INTEGER;
BEGIN
INC(tg.ind); len := Len(tg.stack);
IF (0 = len) OR (tg.ind >= len) THEN
tg.ind := -1
ELSE
tab := tg.stack.ctx[tg.ind](Tab);
tg.stack.tb.context.GetSize(width, height);
CheckTitleWidth(tab.titleView, FALSE);
tg.titleWidth := tab.titleView.wid;
margin := ((height - param.margins) - tg.closerWidth) DIV 2;
IF tg.closerSide = left THEN
tg.closerLeft := margin;
tg.titleLeft := tg.closerLeft + tg.closerWidth;
ELSE
tg.closerLeft := tg.titleWidth;
tg.titleLeft := 0
END;
tg.width := tg.titleWidth + tg.closerWidth + margin;
END
END GetNextTabGeometry;
PROCEDURE GetFirstTabGeometry (st: Stack; closerSide: BOOLEAN; OUT tg: TabGeometry);
VAR tab: Tab;
BEGIN
ASSERT(st # NIL, 20);
tg.stack := st;
tg.ind := -1;
tg.closerSide := closerSide;
IF Len(st) > 0 THEN
tab := st.ctx[0](Tab);
tg.closerWidth := CheckCloserWidth(tab.closer);
GetNextTabGeometry(tg)
END
END GetFirstTabGeometry;
(** absolute, i.e. w/o shift *)
PROCEDURE GetActiveTabPosition (f: Views.Frame; st: Stack; OUT x0, x1: INTEGER): BOOLEAN;
VAR
x, margin, cwdt, w, tidx: INTEGER;
res: BOOLEAN;
tab: Tab;
BEGIN
x0 := 0; x1 := 0;
IF (st = NIL) OR (st.active < 0) OR (st.active >= LEN(st.ctx)) THEN
res := FALSE
ELSE
x := 0;
margin := Ports.point *2;
margin := margin - margin MOD f.unit;
FOR tidx := 0 TO st.active DO
tab := st.ctx[tidx](Tab);
cwdt := CheckCloserWidth(tab.closer);
CheckTitleWidth(tab.titleView, FALSE);
w := tab.titleView.wid + cwdt + margin;
IF st.tb.dropMark = tidx THEN INC(w, 18 * f.dot) END;
IF tidx = st.active THEN
IF st.tb.dropMark = tidx+1 THEN INC(w, 18 * f.dot) END;
x0 := x; x1 := x + w; res := TRUE
ELSE
INC(x, w + param.margins * 4)
END
END
END;
RETURN res
END GetActiveTabPosition;
PROCEDURE (tb: Tabulator) CalcTotalTabWidth (f: Views.Frame): INTEGER, NEW;
VAR
tabG: TabGeometry; x, w, h, margin: INTEGER;
BEGIN
x := 2 * mm;
margin := Ports.point * 2;
margin := margin - margin MOD f.unit;
GetFirstTabGeometry(tb.stack, param.closerSide, tabG);
WHILE (tabG.ind # -1) DO
INC(x, tabG.width + margin);
GetNextTabGeometry(tabG)
END;
RETURN x
END CalcTotalTabWidth;
PROCEDURE (tb: Tabulator) Restore (f: Views.Frame; l, t, r, b: INTEGER);
VAR
len, width, height, x, posX, posY, col, margin: INTEGER;
tabG: TabGeometry;
titleView: TitleView;
PROCEDURE DrawDropMark;
VAR i: INTEGER;
BEGIN
FOR i := 0 TO 7 DO
f.DrawLine(
x + (i+1) * f.dot,
param.margins DIV 2 + height DIV 2 - i * f.dot,
x + (i+1) * f.dot,
param.margins DIV 2 + height DIV 2 + i * f.dot,
f.dot, param.marksColor);
END;
f.DrawRect(
x + 8 * f.dot,
param.margins DIV 2 + height DIV 2 - 4 * f.dot,
x + 14 * f.dot,
param.margins DIV 2 + height DIV 2 + 5 * f.dot,
Ports.fill, param.marksColor);
INC(x, 18 * f.dot)
END DrawDropMark;
BEGIN
tb.context.GetSize(width, height);
x := tb.scrollShift + 2 * mm;
margin := Ports.point *2;
margin := margin - margin MOD f.unit;
IF tb.stack.ctx # NIL THEN
IF param.strokeColor # Views.transparent THEN
f.DrawRect(0, height - f.dot, width, height, Ports.fill, param.strokeColor)
END;
len := Len(tb.stack); ASSERT(LEN(tb.stack.ctx) = len, 100);
GetFirstTabGeometry(tb.stack, param.closerSide, tabG);
WHILE tabG.ind # -1 DO
tabG.width := tabG.width - tabG.width MOD f.unit;
IF tb.dropMark = tabG.ind THEN DrawDropMark END;
IF tabG.ind = tb.stack.active THEN
tb.actL := x;
tb.actR := x + tabG.width; (* for RestoreMarks *)
col := param.selectedBgColor;
IF col = Views.transparent THEN
tb.stack.ctx[tabG.ind].view.GetBackground(col)
END;
IF col # Views.transparent THEN
f.DrawRect(x, param.margins, x + tabG.width, height, Ports.fill, col)
END;
col := param.strokeColor;
IF col # Views.transparent THEN
f.DrawLine(x, param.margins, x, param.margins + height, f.dot, col);
f.DrawLine(x + tabG.width, param.margins, x + tabG.width, height, f.dot, col)
END;
ELSE
col := param.nonselectedBgColor;
IF col # Views.transparent THEN
f.DrawRect(x, param.margins + 2 * Ports.point, x + tabG.width, height, Ports.fill, col)
END;
col := param.strokeColorShaded;
IF col # Views.transparent THEN
f.DrawLine(x, param.margins + 3 * f.dot, x, height, f.dot, col);
f.DrawLine(x + tabG.width, param.margins + 3 * f.dot, x + tabG.width, height, f.dot, col);
f.DrawLine(x, param.margins + 3 * f.dot, x + tabG.width, param.margins + 3 * f.dot, f.dot, col);
END
END;
posX := x + tabG.closerLeft;
posX := posX - posX MOD f.unit; (* correct position with respect to f.unit *)
posY := param.margins
+ (height - param.margins) DIV 2 - tabG.closerWidth DIV 2 + 3 * f.dot;
(* posY := posY - posY MOD f.unit; *)
Views.InstallFrame(f, tb.stack.ctx[tabG.ind](Tab).closer, posX, posY, 0, FALSE);
titleView := tb.stack.ctx[tabG.ind](Tab).titleView;
posX := x + tabG.titleLeft;
posX := posX - posX MOD f.unit; (* correct position with respect to f.unit *)
posY := param.margins + 3 * f.dot;
posY := posY - posY MOD f.unit;
Views.InstallFrame(f, titleView, posX, posY, 0, FALSE);
INC(x, tabG.width + margin);
GetNextTabGeometry(tabG)
END
END;
IF tb.dropMark = len THEN DrawDropMark END
END Restore;
PROCEDURE (tb: Tabulator) RestoreMarks (f: Views.Frame; l, t, r, b: INTEGER);
VAR width, height, color: INTEGER;
BEGIN
tb.context.GetSize(width, height);
IF (tb.stack.active >= 0) & IsFront(tb.stack.ctx[tb.stack.active].view) THEN
f.DrawRect(tb.actL, param.margins, tb.actR,
param.margins + 2 * f.dot, Ports.fill, param.markColor)
END
END RestoreMarks;
PROCEDURE (tb: Tabulator) HandleCtrlMsg (f: Views.Frame;
VAR msg: Views.CtrlMessage; VAR focus: Views.View
);
VAR g: Views.Frame; tabG: TabGeometry; x, w, h, margin: INTEGER; tmp: Views.View;
BEGIN
WITH
| msg: DropTabPollMsg DO
msg.filler := tb.stack;
x := tb.scrollShift + 2 * mm;
margin := Ports.point *2;
margin := margin - margin MOD f.unit;
GetFirstTabGeometry(tb.stack, param.closerSide, tabG);
WHILE (tabG.ind # -1) & (msg.x >= (x + tabG.width)) DO
INC(x, tabG.width + margin);
GetNextTabGeometry(tabG)
END;
IF tabG.ind = -1 THEN
IF tb.stack = NIL THEN msg.ind := 0 ELSE msg.ind := Len(tb.stack)
END
ELSIF msg.x < (x + tabG.width DIV 2) THEN msg.ind := tabG.ind
ELSE msg.ind := tabG.ind + 1
END;
msg.frame := f
| msg: DropFeedbackMsg DO
IF msg.show THEN
tb.dropMark := msg.ind
ELSE
tb.dropMark := -1
END;
Views.Update(tb, Views.keepFrames); Views.ValidateRoot(Views.RootOf(f))
| msg: Controllers.WheelMsg DO
(* calculate total tab width *)
x := 2 * mm;
margin := Ports.point *2;
margin := margin - margin MOD f.unit;
GetFirstTabGeometry(tb.stack, param.closerSide, tabG);
WHILE (tabG.ind # -1) DO
INC(x, tabG.width + margin);
GetNextTabGeometry(tabG)
END;
tb.context.GetSize(w, h);
IF msg.op = Controllers.incLine THEN
INC(tb.scrollShift, Ports.mm * 10)
ELSIF msg.op = Controllers.decLine THEN
DEC(tb.scrollShift, Ports.mm * 10);
END;
IF x < w THEN
tb.scrollShift := 0
ELSE
tb.scrollShift := MIN(tb.scrollShift, 0); (* left limit *)
tb.scrollShift := MAX(tb.scrollShift, - (x - w + Ports.mm * 4) ); (* right limit *)
END;
msg.done := TRUE;
Views.Update(tb, Views.keepFrames)
| msg: Controllers.CursorMessage DO
g := Views.FrameAt(f, msg.x, msg.y); IF g # NIL THEN focus := g.view END;
IF hotBtn # NIL THEN
tmp := hotBtn;
hotBtn := NIL;
Views.Update(tmp, Views.keepFrames)
END;
ELSE
END
END HandleCtrlMsg;
(* AD: currently, a click inside a tab that falls in the gap between the Closer and the TitleView is just not handled; it should be as an activation click *)
PROCEDURE (c: Context) GetSize* (OUT w, h: UCs);
BEGIN
IF c.w = magicWidth THEN
IF (c.filler # NIL) & (c.filler.context # NIL) THEN
c.filler.context.GetSize(c.w, c.h);
DEC(c.h, 6 * mm)
END
END;
w := c.w; h := c.h
END GetSize;
PROCEDURE (fc: Context) Consider* (VAR p: Models.Proposal);
VAR f: View; len: INTEGER;
BEGIN
f := fc.filler; ASSERT(f # NIL, 20);
WITH p: Proposal DO
CASE p.op OF
| remove:
len := Len(f); Remove(fc); ASSERT(len = Len(f) + 1, 60)
| activate:
Activate(fc); f.context.Consider(p)
| setTitle:
IF f IS Stack THEN SetTitle(f(Stack), ThisInd(fc), p.title) END
ELSE HALT(20)
END
ELSE
END
END Consider;
PROCEDURE ThisFiller* (v: Views.View): View;
VAR res: View;
BEGIN
ASSERT(v # NIL, 20);
IF v.context IS Context THEN
res := v.context(Context).filler
END;
RETURN res
END ThisFiller;
PROCEDURE InitParam (p: ANYPTR);
BEGIN
WITH p: Param DO
p.nonselectedBgColor := Ports.grey25;
p.color := Ports.RGBColor(100, 100, 100);
p.colorFocus := Ports.black;
(* TODO: should be calculated from colorTheme settings... *)
END
END InitParam;
PROCEDURE InitDefaults (p: ANYPTR);
BEGIN
WITH p: Param DO
p.closerColor := Ports.red;
p.marksColor := Ports.RGBColor(255, 215, 50);
p.closerSide := right;
p.closerMark := "";
p.boldenFront := FALSE;
p.selectedBgColor := Views.transparent;
p.nonselectedBgColor := Ports.grey25;
p.strokeColor := Views.transparent;
p.strokeColorShaded := Views.transparent;
p.color := Ports.defaultColor;
p.colorFocus := Ports.defaultColor;
p.markDirty := TRUE;
p.bgColor := Ports.RGBColor(40, 40, 40);
p.markColor := Ports.RGBColor(255, 215, 50);
p.margins := mm;
p.gutterColor := Ports.RGBColor(50, 50, 50);
p.gutterWidth := 3;
p.tabHeight := 8 * Ports.mm;
p.minTabWidth := 15 * Ports.mm;
p.debug := FALSE;
p.navigationMethod := navMethodDefault;
p.InitDefaults := InitDefaults;
p.Init := InitParam;
END
END InitDefaults;
BEGIN
NEW(refocusAction);
NEW(param);
InitDefaults(param)
END StdGrids. | Std/Mod/Grids.odc |
MODULE StdHeaders;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- YYYYMMDD, nn, ...
"
issues = "
- ...
"
**)
(* headers / footers support the following macros:
&p - replaced by current page number as arabic numeral
&r - replaced by current page number as roman numeral
&R - replaced by current page number as capital roman numeral
&a - replaced by current page number as alphanumeric character
&A - replaced by current page number as capital alphanumeric character
&d - replaced by printing date
&t - replaced by printing time
&&- replaced by & character
&; - specifies split point
&f - filename with path/title
*)
IMPORT
Stores, Ports, Models, Views, Properties, Printing, TextModels, Fonts, Dialog,
TextViews, Dates, Windows, Controllers, Containers;
CONST
minVersion = 0; maxVersion = 2;
mm = Ports.mm; point = Ports.point;
maxWidth = 10000 * mm;
alternate* = 0; number* = 1; head* = 2; foot* = 3; showFoot* = 4;
TYPE
Banner* = RECORD
left*, right*: ARRAY 128 OF CHAR;
gap*: INTEGER
END;
NumberInfo* = RECORD
new*: BOOLEAN;
first*: INTEGER
END;
View = POINTER TO RECORD (Views.View)
alternate: BOOLEAN; (* alternate left/right *)
number: NumberInfo; (* new page number *)
head, foot: Banner;
font: Fonts.Font;
showFoot: BOOLEAN;
END;
Prop* = POINTER TO RECORD (Properties.Property)
alternate*, showFoot*: BOOLEAN;
number*: NumberInfo;
head*, foot*: Banner
END;
ChangeFontOp = POINTER TO RECORD (Stores.Operation)
header: View;
font: Fonts.Font
END;
ChangeAttrOp = POINTER TO RECORD (Stores.Operation)
header: View;
alternate, showFoot: BOOLEAN;
number: NumberInfo;
head, foot: Banner
END;
VAR
dialog*: RECORD
view: View;
alternate*, showFoot*: BOOLEAN;
number*: NumberInfo;
head*, foot*: Banner;
END;
PROCEDURE (p: Prop) IntersectWith* (q: Properties.Property; OUT equal: BOOLEAN);
VAR valid: SET;
PROCEDURE Equal(IN b1, b2: Banner): BOOLEAN;
BEGIN
RETURN (b1.left = b2.left) & (b1.right = b2.right) & (b1.gap = b2.gap)
END Equal;
BEGIN
WITH q: Prop DO
valid := p.valid * q.valid; equal := TRUE;
IF p.alternate # q.alternate THEN EXCL(valid, alternate) END;
IF p.showFoot # q.showFoot THEN EXCL(valid, showFoot) END;
IF (p.number.new # q.number.new) OR (p.number.first # q.number.first) THEN EXCL(valid, number) END;
IF ~Equal(p.head, q.head) THEN EXCL(valid, head) END;
IF ~Equal(p.foot, q.foot) THEN EXCL(valid, foot) END;
IF p.valid # valid THEN p.valid := valid; equal := FALSE END
END
END IntersectWith;
(* SetAttrOp *)
PROCEDURE (op: ChangeFontOp) Do;
VAR v: View; font: Fonts.Font; asc, dsc, w: INTEGER; c: Models.Context;
BEGIN
v := op.header;
font := op.font; op.font := v.font; v.font := font;
font.GetBounds(asc, dsc, w);
c := v.context;
c.SetSize(maxWidth, asc + dsc + 2*point);
Views.Update(v, Views.keepFrames)
END Do;
PROCEDURE DoChangeFontOp (v: View; font: Fonts.Font);
VAR op: ChangeFontOp;
BEGIN
IF v.font # font THEN
NEW(op); op.header := v; op.font := font;
Views.Do(v, "#System:SetProp", op)
END
END DoChangeFontOp;
PROCEDURE (op: ChangeAttrOp) Do;
VAR v: View; alternate, showFoot: BOOLEAN; number: NumberInfo; head, foot: Banner;
BEGIN
v := op.header;
alternate := op.alternate; showFoot := op.showFoot; number := op.number; head := op.head; foot := op.foot;
op.alternate := v.alternate; op.showFoot := v.showFoot; op.number := v.number; op.head := v.head;
op.foot := v.foot;
v.alternate := alternate; v.showFoot := showFoot; v.number := number; v.head := head; v.foot := foot;
Views.Update(v, Views.keepFrames)
END Do;
PROCEDURE DoChangeAttrOp (v: View; alternate, showFoot: BOOLEAN; number: NumberInfo;
head, foot: Banner);
VAR op: ChangeAttrOp;
BEGIN
NEW(op); op.header := v; op.alternate := alternate; op.showFoot := showFoot;
op.number := number; op.head := head; op.foot := foot;
Views.Do(v, "#Std:HeaderChange", op)
END DoChangeAttrOp;
PROCEDURE (v: View) CopyFromSimpleView (source: Views.View);
BEGIN
WITH source: View DO
v.alternate := source.alternate;
v.number.new := source.number.new; v.number.first := source.number.first;
v.head := source.head;
v.foot := source.foot;
v.font := source.font;
v.showFoot := source.showFoot
END
END CopyFromSimpleView;
PROCEDURE (v: View) Externalize (VAR wr: Stores.Writer);
BEGIN
v.Externalize^(wr);
wr.WriteVersion(maxVersion);
wr.WriteString(v.head.left);
wr.WriteString(v.head.right);
wr.WriteInt(v.head.gap);
wr.WriteString(v.foot.left);
wr.WriteString(v.foot.right);
wr.WriteInt(v.foot.gap);
wr.WriteString(v.font.typeface);
wr.WriteInt(v.font.size);
wr.WriteSet(v.font.style);
wr.WriteInt(v.font.weight);
wr.WriteBool(v.alternate);
wr.WriteBool(v.number.new);
wr.WriteInt(v.number.first);
wr.WriteBool(v.showFoot);
END Externalize;
PROCEDURE (v: View) Internalize (VAR rd: Stores.Reader);
VAR version: INTEGER; typeface: Fonts.Typeface; size: INTEGER; style: SET; weight: INTEGER;
BEGIN
v.Internalize^(rd);
IF ~rd.cancelled THEN
rd.ReadVersion(minVersion, maxVersion, version);
IF ~rd.cancelled THEN
IF version = 0 THEN
rd.ReadXString(v.head.left);
rd.ReadXString(v.head.right);
v.head.gap := 5*mm;
rd.ReadXString(v.foot.left);
rd.ReadXString(v.foot.right);
v.foot.gap := 5*mm;
rd.ReadXString(typeface);
rd.ReadXInt(size);
v.font := Fonts.dir.This(typeface, size * point, {}, Fonts.normal);
rd.ReadXInt(v.number.first);
rd.ReadBool(v.number.new);
rd.ReadBool(v.alternate)
ELSE
rd.ReadString(v.head.left);
rd.ReadString(v.head.right);
rd.ReadInt(v.head.gap);
rd.ReadString(v.foot.left);
rd.ReadString(v.foot.right);
rd.ReadInt(v.foot.gap);
rd.ReadString(typeface);
rd.ReadInt(size);
rd.ReadSet(style);
rd.ReadInt(weight);
v.font := Fonts.dir.This(typeface, size, style, weight);
rd.ReadBool(v.alternate);
rd.ReadBool(v.number.new);
rd.ReadInt(v.number.first);
IF version = 2 THEN rd.ReadBool(v.showFoot) ELSE v.showFoot := FALSE END
END
END
END
END Internalize;
PROCEDURE SetProp(v: View; msg: Properties.SetMsg);
VAR p: Properties.Property;
typeface: Fonts.Typeface; size: INTEGER; style: SET; weight: INTEGER;
alt, sf: BOOLEAN; num: NumberInfo; h, f: Banner;
BEGIN
p := msg.prop;
WHILE p # NIL DO
WITH p: Properties.StdProp DO
IF Properties.typeface IN p.valid THEN typeface := p.typeface
ELSE typeface := v.font.typeface
END;
IF Properties.size IN p.valid THEN size := p.size
ELSE size := v.font.size
END;
IF Properties.style IN p.valid THEN style := p.style.val
ELSE style := v.font.style
END;
IF Properties.weight IN p.valid THEN weight := p.weight
ELSE weight := v.font.weight
END;
DoChangeFontOp (v, Fonts.dir.This(typeface, size, style, weight) );
| p: Prop DO
IF alternate IN p.valid THEN alt := p.alternate ELSE alt := v.alternate END;
IF showFoot IN p.valid THEN sf := p.showFoot ELSE sf := v.showFoot END;
IF number IN p.valid THEN num := p.number ELSE num := v.number END;
IF head IN p.valid THEN h := p.head ELSE h := v.head END;
IF foot IN p.valid THEN f := p.foot ELSE f := v.foot END;
DoChangeAttrOp(v, alt, sf, num, h, f)
ELSE
END;
p := p.next
END
END SetProp;
PROCEDURE PollProp(v: View; VAR msg: Properties.PollMsg);
VAR sp: Properties.StdProp; p: Prop;
BEGIN
NEW(sp);
sp.known := {Properties.size, Properties.typeface, Properties.style, Properties.weight};
sp.valid := sp.known;
sp.size := v.font.size; sp.typeface := v.font.typeface;
sp.style.val := v.font.style; sp.style.mask := {Fonts.italic, Fonts.underline, Fonts.strikeout};
sp.weight := v.font.weight;
Properties.Insert(msg.prop, sp);
NEW(p);
p.known := {alternate, number, head, foot, showFoot}; p.valid := p.known;
p.head := v.head; p.foot := v.foot;
p.alternate := v.alternate;
p.showFoot := v.showFoot;
p.number := v.number;
Properties.Insert(msg.prop, p)
END PollProp;
PROCEDURE PageMsg(v: View; msg: TextViews.PageMsg);
BEGIN
IF Printing.par # NIL THEN
Dialog.MapString(v.head.left, Printing.par.header.left);
Dialog.MapString(v.head.right, Printing.par.header.right);
Dialog.MapString(v.foot.left, Printing.par.footer.left);
Dialog.MapString(v.foot.right, Printing.par.footer.right);
Printing.par.header.font := v.font;
Printing.par.footer.font := v.font;
Printing.par.page.alternate := v.alternate;
IF v.number.new THEN
Printing.par.page.first := v.number.first - msg.current
END;
Printing.par.header.gap := 5*Ports.mm;
Printing.par.footer.gap := 5*Ports.mm
END
END PageMsg;
PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER);
VAR d, w, h: INTEGER; (*line: Line; *)asc, dsc, x0, x1, y: INTEGER;
win: Windows.Window; title: Views.Title; dec: BOOLEAN;
pw, ph: INTEGER;
date: Dates.Date; time: Dates.Time; pageInfo: Printing.PageInfo; banner: Printing.Banner;
BEGIN
IF Views.IsPrinterFrame(f) THEN (* am drucken *) END;
v.font.GetBounds(asc, dsc, w);
win := Windows.dir.First();
WHILE (win # NIL) & (win.doc.Domain() # v.Domain()) DO win := Windows.dir.Next(win) END;
IF win = NIL THEN title := "(" + Dialog.appName + ")"
ELSE win.GetTitle(title)
END;
d := f.dot;
v.context.GetSize(w, h);
win.doc.PollPage(pw, ph, l, t, r, b, dec);
w := r - l;
f.DrawRect(0, 0, w, h, Ports.fill, Ports.grey25);
f.DrawRect(0, 0, w, h, 0, Ports.black);
x0 := d; x1 := w-2*d; y := asc + d;
Dates.GetDate(date);
Dates.GetTime(time);
pageInfo.alternate := FALSE;
pageInfo.title := title;
banner.font := v.font;
IF v.showFoot THEN
banner.gap := v.foot.gap;
Dialog.MapString(v.foot.left, banner.left); Dialog.MapString(v.foot.right, banner.right)
ELSE
banner.gap := v.head.gap;
Dialog.MapString(v.head.left, banner.left); Dialog.MapString(v.head.right, banner.right)
END;
Printing.PrintBanner(f, pageInfo, banner, date, time, x0, x1, y)
END Restore;
PROCEDURE (v: View) HandlePropMsg (VAR msg: Properties.Message);
VAR asc, dsc, w: INTEGER;
BEGIN
WITH msg: Properties.SizePref DO
msg.w := maxWidth;
IF msg.h = Views.undefined THEN
v.font.GetBounds(asc, dsc, w);
msg.h := asc + dsc + 2*point
END
| msg: Properties.ResizePref DO
msg.fixed := TRUE
| msg: TextModels.Pref DO
msg.opts := {TextModels.hideable}
| msg: Properties.PollMsg DO
PollProp(v, msg)
| msg: Properties.SetMsg DO
SetProp(v, msg)
| msg: TextViews.PageMsg DO
PageMsg(v, msg)
ELSE
END
END HandlePropMsg;
PROCEDURE (v: View) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message;
VAR focus: Views.View);
BEGIN
WITH msg: Properties.EmitMsg DO Views.HandlePropMsg(v, msg.set)
| msg: Properties.CollectMsg DO Views.HandlePropMsg(v, msg.poll)
ELSE
END
END HandleCtrlMsg;
PROCEDURE New*(p: Prop; f: Fonts.Font): Views.View;
VAR v: View;
BEGIN
NEW(v);
v.head := p.head;
v.foot := p.foot;
v.number := p.number;
v.alternate := p.alternate;
v.font := f;
v.showFoot := FALSE;
RETURN v;
END New;
PROCEDURE Deposit*;
VAR v: View;
BEGIN
NEW(v);
v.head.left := ""; v.head.right := "&d&;&p"; v.head.gap := 5*mm;
v.foot.left := ""; v.foot.right := ""; v.foot.gap := 5*mm;
v.font := Fonts.dir.Default();
v.number.first := 1; v.number.new := FALSE; v.alternate := FALSE; v.showFoot := FALSE;
Views.Deposit(v)
END Deposit;
(* property dialog *)
PROCEDURE InitDialog*;
VAR p: Properties.Property;
BEGIN
Properties.CollectProp(p);
WHILE p # NIL DO
WITH p: Properties.StdProp DO
| p: Prop DO
dialog.alternate := p.alternate; dialog.showFoot := p.showFoot;
dialog.number := p.number;
dialog.head := p.head; dialog.head.gap := dialog.head.gap DIV point;
dialog.foot := p.foot; dialog.foot.gap := dialog.foot.gap DIV point;
Dialog.Update(dialog)
ELSE
END;
p := p.next
END
END InitDialog;
PROCEDURE Set*;
VAR p: Prop;
BEGIN
NEW(p); p.valid := {alternate, number, head, foot, showFoot};
p.alternate := dialog.alternate; p.showFoot := dialog.showFoot;
p.number := dialog.number;
p.head := dialog.head; p.head.gap := p.head.gap * point;
p.foot := dialog.foot; p.foot.gap := p.foot.gap * point;
Properties.EmitProp(NIL, p)
END Set;
PROCEDURE HeaderGuard* (VAR par: Dialog.Par);
VAR v: Views.View;
BEGIN
v := Containers.FocusSingleton();
IF (v # NIL) & (v IS View) THEN
par.disabled := FALSE;
IF (dialog.view = NIL) OR (dialog.view # v) THEN
dialog.view := v(View);
InitDialog
END
ELSE
par.disabled := TRUE;
dialog.view := NIL
END
END HeaderGuard;
PROCEDURE AlternateGuard* (VAR par: Dialog.Par);
BEGIN
HeaderGuard(par);
IF ~par.disabled THEN par.disabled := ~ dialog.alternate END
END AlternateGuard;
PROCEDURE NewNumberGuard* (VAR par: Dialog.Par);
BEGIN
HeaderGuard(par);
IF ~par.disabled THEN par.disabled := ~ dialog.number.new END
END NewNumberGuard;
END StdHeaders.
| Std/Mod/Headers.odc |
MODULE StdInflate;
(**
project = "BlackBox 2.0"
organization = "www.oberon.ch blackbox.oberon.org"
contributors = "Oberon microsystems, Ketmar Dark"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
changes = "
- YYYYMMDD, nn, ...
"
issues = "
- ...
"
based on tinf — tiny inflate library (inflate, gzip, zlib)
version 1.00 (with later improvements)
streaming interface by Ketmar Dark
Copyright (c) 2003 by Joergen Ibsen / Jibz
All Rights Reserved
http://www.ibsensoftware.com/
This software is provided 'as-is', without any express
or implied warranty. In no event will the authors be
held liable for any damages arising from the use of
this software.
Permission is granted to anyone to use this software
for any purpose, including commercial applications,
and to alter it and redistribute it freely, subject to
the following restrictions:
1. The origin of this software must not be
misrepresented; you must not claim that you
wrote the original software. If you use this
software in a product, an acknowledgment in
the product documentation would be appreciated
but is not required.
2. Altered source versions must be plainly marked
as such, and must not be misrepresented as
being the original software.
3. This notice may not be removed or altered from
any source distribution.
This Ultra Pascal port was made by Ketmar // Invisible Vector
ketmar@ketmar.no-ip.org
the original code was heavily changed and uglified (sorry!)
Adler-32 algorithm taken from the zlib source, which is
Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler
**)
CONST
PKZIP_BUG_TOLERANCE = TRUE;
CONST
AdlerBase = 65521;
AdlerNMax = (*5552*) 4102; (* this should be totally safe *)
RD_BUFFER_SIZE = 2048;
(* current state *)
ExpectZLibHeader = 0; (* expecting ZLib header *)
ExpectBlock = 1; (* expecting new block *)
RawBlock = 2; (* uncompressed block *)
CompressedBlock = 3;
EOF = 4; (* inf.ReadByte() returns false before block header *)
Dead = 5; (* some error occured, throw exception on any read *)
(* stream format *)
ZLib* = 0; Deflate* = 1;
TYPE
Mode* = INTEGER;
State = INTEGER;
Tree = RECORD
counts: ARRAY 16 OF INTEGER; (* ushort: counts of code length counts *)
symbols: ARRAY 288 OF INTEGER; (* ushort: code -> symbol translation counts *)
maxsym: INTEGER
END;
Inflater* = POINTER TO ABSTRACT RECORD
(* state data *)
bytesLeft: INTEGER; (* bytes to copy both for compressed and for uncompressed blocks *)
matchOfs: INTEGER; (* match offset for inflated block *)
lt: Tree; (* dynamic length/symbol tree *)
dt: Tree; (* dynamic distance tree *)
lastBlockWasFixed: BOOLEAN; (* to avoid extra copies *)
doingFinalBlock: BOOLEAN; (* := false; *) (* stop on next processBlockHeader() *)
state: State; (* := State.ExpectZLibHeader; *)
mode: Mode; (* := Mode.ZLib; *)
(* other data *)
tag: INTEGER; (* ushort *)
bitcount: INTEGER;
(* adler-32 *)
a32s1, a32s2: INTEGER;
nmaxLeft: INTEGER; (* := Adler32.AdlerNMax; *)
cura32: INTEGER; (* unsigned *)
(* dictionary *)
dict: ARRAY 32768 OF SHORTCHAR;
dictEnd: INTEGER; (* current dict free byte *)
rdbuf: ARRAY RD_BUFFER_SIZE OF SHORTCHAR;
rbpos, rbused: INTEGER;
rbeof: BOOLEAN;
totalUnpacked-: INTEGER;
END;
VAR
sltree: Tree; (* fixed length/symbol tree *)
sdtree: Tree; (* fixed distance tree *)
lengthBits: ARRAY 30 OF INTEGER; (* extra bits and base tables for length codes *)
lengthBase: ARRAY 30 OF INTEGER;
distBits: ARRAY 30 OF INTEGER; (* extra bits and base tables for distance codes *)
distBase: ARRAY 30 OF INTEGER;
clcidx: ARRAY 19 OF INTEGER; (* special ordering of code length codes *)
(******** Tree ********)
PROCEDURE (VAR tree: Tree) Invalidate, NEW;
BEGIN tree.maxsym := -1
END Invalidate;
PROCEDURE (VAR tree: Tree) Wipe, NEW;
VAR f: INTEGER;
BEGIN
FOR f := 0 TO LEN(tree.counts) - 1 DO
tree.counts[f] := 0
END;
tree.maxsym := -1
END Wipe;
PROCEDURE (VAR tree: Tree) Valid (): BOOLEAN, NEW;
BEGIN RETURN (tree.maxsym >= 0) & (tree.maxsym <= 288)
END Valid;
(* given an array of code lengths, build a tree *)
PROCEDURE (VAR tree: Tree) BuildTree (IN lengths: ARRAY OF INTEGER; beg, end: INTEGER), NEW;
VAR
offs: ARRAY 16 OF INTEGER; (* ushort *)
f, l, available, numCodes, used: INTEGER;
BEGIN
ASSERT(beg < end, 20); ASSERT(beg >= 0, 21); ASSERT(end <= LEN(lengths), 22);
(* clear code length count counts *)
tree.Wipe;
(* count number of codes for each non-zero length *)
f := beg; WHILE f < end DO
l := lengths[f];
IF l # 0 THEN
IF (l < 0) OR (l > 15) THEN tree.Invalidate; RETURN END; (* error! *)
tree.maxsym := f - beg;
INC(tree.counts[l])
END;
INC(f)
END;
(* compute offset table for distribution sort *)
available := 1; numCodes := 0;
FOR f := 0 TO 15 DO
used := tree.counts[f];
(* Check length contains no more codes than available *)
IF used > available THEN tree.Invalidate; RETURN END; (* error! *)
available := 2 * (available - used);
offs[f] := numCodes;
INC(numCodes, used)
END;
(* check all codes were used, or for the special case of only one code that it has length 1 *)
IF ((numCodes > 1) & (available > 0)) OR
((numCodes = 1) & (tree.counts[1] # 1))
THEN
tree.Invalidate; RETURN (* error! *)
END;
(* fill in symbols sorted by code *)
f := beg; WHILE f < end DO
l := lengths[f];
IF l # 0 THEN
tree.symbols[offs[l]] := f - beg;
INC(offs[l])
END;
INC(f)
END;
(* for the special case of only one code (which will be 0) add a code 1 which results in a symbol that is too large *)
IF numCodes = 1 THEN
tree.counts[1] := 2;
tree.symbols[1] := tree.maxsym + 1
END
END BuildTree;
(******** Inflater ********)
(* read as much as you can, return number of read bytes *)
PROCEDURE (inf: Inflater) ReadBuf- (VAR buf: ARRAY OF SHORTCHAR): INTEGER, NEW, ABSTRACT;
PROCEDURE (inf: Inflater) Init* (mode: Mode), NEW;
BEGIN
ASSERT((mode = ZLib) OR (mode = Deflate), 20);
inf.bytesLeft := 0;
inf.matchOfs := 0;
inf.lastBlockWasFixed := FALSE; inf.lt.Invalidate; inf.dt.Invalidate;
inf.doingFinalBlock := FALSE;
inf.mode := mode;
inf.tag := 0;
inf.bitcount := 0;
inf.a32s1 := 0; inf.a32s2 := 0;
inf.nmaxLeft := AdlerNMax;
inf.cura32 := 0;
inf.dictEnd := 0;
inf.rbpos := 0; inf.rbused := 0; inf.rbeof := FALSE;
inf.totalUnpacked := 0;
IF mode = ZLib THEN
inf.state := ExpectZLibHeader
ELSE
inf.state := ExpectBlock
END
END Init;
PROCEDURE (inf: Inflater) PutByte (bt: SHORTCHAR), NEW;
BEGIN
inf.dict[inf.dictEnd] := bt;
inf.dictEnd := (inf.dictEnd + 1) MOD LEN(inf.dict);
IF inf.mode = ZLib THEN
INC(inf.a32s1, ORD(bt));
INC(inf.a32s2, inf.a32s1);
IF (inf.a32s1 < 0) OR (inf.a32s2 < 0) THEN
DEC(inf.a32s2, inf.a32s1);
DEC(inf.a32s1, ORD(bt));
inf.a32s1 := inf.a32s1 MOD AdlerBase;
inf.a32s2 := inf.a32s2 MOD AdlerBase;
INC(inf.a32s1, ORD(bt));
INC(inf.a32s2, inf.a32s1)
END
END;
INC(inf.totalUnpacked)
END PutByte;
PROCEDURE (inf: Inflater) FinishAdler32 (): INTEGER, NEW;
BEGIN
inf.a32s1 := inf.a32s1 MOD AdlerBase;
inf.a32s2 := inf.a32s2 MOD AdlerBase;
RETURN ASH(inf.a32s2, 16) + inf.a32s1
END FinishAdler32;
PROCEDURE (inf: Inflater) SetErrorState, NEW;
BEGIN
inf.state := Dead;
inf.lastBlockWasFixed := FALSE; inf.lt.Invalidate; inf.dt.Invalidate;
inf.doingFinalBlock := FALSE (* just in case too *)
END SetErrorState;
PROCEDURE (inf: Inflater) ReadByte (): SHORTCHAR, NEW;
VAR res: SHORTCHAR;
BEGIN
IF inf.state # Dead THEN
IF (inf.rbpos = inf.rbused) & ~inf.rbeof THEN
inf.rbpos := 0;
inf.rbused := inf.ReadBuf(inf.rdbuf);
inf.rbeof := (inf.rbused <= 0)
END;
IF ~inf.rbeof THEN res := inf.rdbuf[inf.rbpos]; INC(inf.rbpos)
ELSE inf.SetErrorState; res := 0X
END
ELSE res := 0X
END;
RETURN res
END ReadByte;
(* get one bit from source stream to `ubyte onebit` *)
PROCEDURE (inf: Inflater) ReadBit (): BOOLEAN, NEW;
VAR res: BOOLEAN;
BEGIN
DEC(inf.bitcount);
IF inf.bitcount = -1 THEN
inf.tag := ORD(inf.ReadByte());
inf.bitcount := 7
END;
res := ODD(inf.tag); inf.tag := inf.tag DIV 2;
RETURN res
END ReadBit;
(* read a num bit value from a stream and add base *)
PROCEDURE (inf: Inflater) ReadBits (num, base: INTEGER): INTEGER, NEW;
VAR val, mask: INTEGER;
BEGIN val := 0; mask := 0;
WHILE mask < num DO
IF inf.ReadBit() THEN INC(val, ASH(1, mask)) END;
INC(mask)
END;
RETURN val + base
END ReadBits;
PROCEDURE (inf: Inflater) ProcessZLibHeader, NEW;
VAR cmf, flg: SHORTCHAR;
BEGIN
(* 7 bytes *)
(* compression parameters *)
cmf := inf.ReadByte();
(* flags *)
(* if (!inf.ReadByte(readBuf, flg)) throw new Exception("out of input data"); *)
flg := inf.ReadByte();
(* check format *)
(* check checksum *)
IF ~((256 * ORD(cmf) + ORD(flg)) MOD 31 = 0) THEN inf.SetErrorState; RETURN END;
(* check method (only deflate allowed) *)
IF ~(ORD(cmf) MOD 10H = 8) THEN inf.SetErrorState; RETURN END;
(* check window size *)
IF ~(ORD(cmf) DIV 16 <= 7) THEN inf.SetErrorState; RETURN END;
(* there must be no preset dictionary *)
IF ODD(ORD(flg) DIV 020H) THEN inf.SetErrorState; RETURN END;
(* FYI: flg>>6 will give you compression level: *)
(* 0 - compressor used fastest algorithm *)
(* 1 - compressor used fast algorithm *)
(* 2 - compressor used default algorithm *)
(* 3 - compressor used maximum compression, slowest algorithm *)
(* not that you can make any sane use of that info though... *)
(* note that last 4 bytes is Adler32 checksum in big-endian format *)
(* init Adler32 counters *)
inf.a32s1 := 1; inf.a32s2 := 0;
inf.nmaxLeft := AdlerNMax;
(* ok, we can go now *)
inf.state := ExpectBlock
END ProcessZLibHeader;
PROCEDURE (inf: Inflater) FinishZLibData, NEW;
VAR a32: SET; bt: SHORTCHAR;
BEGIN
(* read Adler32 *)
a32 := {};
bt := inf.ReadByte(); a32 := a32 + BITS(ASH(ORD(bt), 24));
bt := inf.ReadByte(); a32 := a32 + BITS(ASH(ORD(bt), 16));
bt := inf.ReadByte(); a32 := a32 + BITS(ASH(ORD(bt), 8));
bt := inf.ReadByte(); a32 := a32 + BITS(ORD(bt));
IF ORD(a32) # inf.FinishAdler32() THEN inf.SetErrorState END (* invalid checksum *)
END FinishZLibData;
PROCEDURE (inf: Inflater) DecodeSymbol (IN t: Tree): INTEGER, NEW;
VAR base, ofs, len, c: INTEGER;
BEGIN
base := 0; ofs := 0;
(*
Get more bits while code index is above number of codes
Rather than the actual code, we are computing the position of the
code in the sorted order of codes, which is the index of the
corresponding symbol.
Conceptually, for each code length (level in the tree), there are
counts[len] leaves on the left and internal nodes on the right.
The index we have decoded so far is base + offs, and if that
falls within the leaves we are done. Otherwise we adjust the range
of offs and add one more bit to it.
*)
len := 1;
WHILE len # 0 DO
ofs := ofs * 2; IF inf.ReadBit() THEN INC(ofs) END;
IF len > 15 THEN inf.SetErrorState; RETURN -1 END; (* error *)
c := t.counts[len];
IF ofs < c THEN len := 0
ELSE
INC(base, c);
DEC(ofs, c);
INC(len)
END
END;
IF (base + ofs < 0) OR (base + ofs >= 288) THEN inf.SetErrorState; RETURN -1 END; (* error *)
RETURN t.symbols[base + ofs]
END DecodeSymbol;
(* given a data stream, decode dynamic trees from it *)
PROCEDURE (inf: Inflater) DecodeTrees, NEW;
VAR
codeTree: Tree;
lengths: ARRAY 288 + 32 OF INTEGER;
hlit, hdist, hclen, sym: INTEGER;
f, num, length, bt: INTEGER;
BEGIN
inf.lastBlockWasFixed := FALSE; inf.lt.Invalidate; inf.dt.Invalidate;
(* get 5 bits HLIT (257-286) *)
hlit := inf.ReadBits(5, 257);
(* get 5 bits HDIST (1-32) *)
hdist := inf.ReadBits(5, 1);
(* distances 31 and 32 are not technically allowed, but sometimes seen in the wild *)
IF ~PKZIP_BUG_TOLERANCE THEN
IF (hlit > 286) OR (hdist > 30) THEN inf.SetErrorState; RETURN END (* error *)
END;
(* get 4 bits HCLEN (4-19) *)
hclen := inf.ReadBits(4, 4);
FOR f := 0 TO 18 DO lengths[f] := 0 END;
(* read code lengths for code length alphabet *)
f := 0; WHILE f < hclen DO
lengths[clcidx[f]] := inf.ReadBits(3, 0); (* get 3 bits code length (0-7) *)
INC(f)
END;
(* build code length tree *)
codeTree.BuildTree(lengths, 0, 19);
IF ~codeTree.Valid() THEN inf.SetErrorState; RETURN END; (* error *)
(* decode code lengths for the dynamic trees *)
num := 0;
WHILE num < hlit + hdist DO
sym := inf.DecodeSymbol(codeTree);
IF (sym < 0) OR (sym > codeTree.maxsym) THEN inf.SetErrorState; RETURN END; (* error *)
CASE sym OF
| 16: (* copy previous code length 3-6 times (read 2 bits) *)
IF num = 0 THEN inf.SetErrorState; RETURN END; (* error *)
bt := lengths[num - 1];
length := inf.ReadBits(2, 3)
| 17: (* repeat code length 0 for 3-10 times (read 3 bits) *)
bt := 0;
length := inf.ReadBits(3, 3)
| 18: (* repeat code length 0 for 11-138 times (read 7 bits) *)
bt := 0;
length := inf.ReadBits(7, 11)
ELSE (* values 0-15 represent the actual code lengths *)
ASSERT((sym >= 0) & (sym < 16), 103); (* invalid tree symbol *)
length := 1;
bt := sym
END;
(* fill it *)
IF length > hlit + hdist - num THEN inf.SetErrorState; RETURN END; (* error *)
WHILE length # 0 DO DEC(length); lengths[num] := bt; INC(num) END
END;
(* check if EOB symbol is present *)
IF lengths[256] = 0 THEN inf.SetErrorState; RETURN END; (* error *)
(* build dynamic trees *)
inf.lt.BuildTree(lengths, 0, hlit);
IF ~inf.lt.Valid() THEN inf.SetErrorState; RETURN END; (* error *)
inf.dt.BuildTree(lengths, hlit, hlit + hdist);
IF ~inf.dt.Valid() THEN inf.SetErrorState; RETURN END (* error *)
END DecodeTrees;
(* can return zero-length slice (on state switch, for example) *)
PROCEDURE (inf: Inflater) InflatedBlock (VAR btdest: ARRAY OF SHORTCHAR; beg, end: INTEGER): INTEGER, NEW;
VAR
btpos, sym: INTEGER;
dist, length, offs: INTEGER;
bt: SHORTCHAR;
BEGIN ASSERT(beg < end, 20); ASSERT(beg >= 0, 21); ASSERT(end <= LEN(btdest), 22);
btpos := beg;
WHILE (btpos # end) & (inf.state # ExpectBlock) DO
IF inf.bytesLeft # 0 THEN
(* copying match; all checks already done *)
bt := inf.dict[(inf.dictEnd + LEN(inf.dict) - inf.matchOfs) MOD LEN(inf.dict)];
inf.PutByte(bt);
btdest[btpos] := bt; INC(btpos);
DEC(inf.bytesLeft)
ELSE
sym := inf.DecodeSymbol(inf.lt);
IF (sym < 0) OR (inf.state = Dead) THEN inf.SetErrorState; RETURN -1 END; (* error! *)
IF sym = 256 THEN
(* end of block, fix state *)
inf.state := ExpectBlock
ELSIF sym < 256 THEN
(* normal *)
bt := SHORT(CHR(sym));
inf.PutByte(bt);
btdest[btpos] := bt; INC(btpos)
ELSE
(* copy *)
(* check sym is within range and distance tree is not empty *)
IF (sym > inf.lt.maxsym) OR (sym - 257 > 28) THEN
inf.SetErrorState; RETURN -1 (* error! *)
END;
DEC(sym, 257);
(* possibly get more bits from length code *)
length := inf.ReadBits(lengthBits[sym], lengthBase[sym]);
dist := inf.DecodeSymbol(inf.dt);
IF (dist < 0) OR (dist > 29) OR (dist > inf.dt.maxsym) THEN inf.SetErrorState; RETURN -1 END; (* error! *)
(* possibly get more bits from distance code *)
offs := inf.ReadBits(distBits[dist], distBase[dist]);
IF (offs < 0) OR (offs > 32768(*inf.dictEnd*)) THEN inf.SetErrorState; RETURN -1 END; (* error! *)
offs := offs MOD 32768;
(* copy match *)
inf.bytesLeft := length;
inf.matchOfs := offs
END
END
END;
RETURN btpos - beg
END InflatedBlock;
(* can return zero-length slice (on state switch, for example) *)
PROCEDURE (inf: Inflater) UncompressedBlock (VAR btdest: ARRAY OF SHORTCHAR; beg, end: INTEGER): INTEGER, NEW;
VAR
btpos: INTEGER;
bt: SHORTCHAR;
BEGIN ASSERT(beg < end, 20); ASSERT(beg >= 0, 21); ASSERT(end <= LEN(btdest), 22);
btpos := beg;
WHILE (btpos # end) & (inf.bytesLeft # 0) DO
(* copying *)
bt := inf.ReadByte();
inf.PutByte(bt);
btdest[btpos] := bt; INC(btpos);
DEC(inf.bytesLeft)
END;
IF inf.bytesLeft = 0 THEN inf.state := ExpectBlock END; (* end of block, fix state *)
RETURN btpos - beg
END UncompressedBlock;
PROCEDURE (inf: Inflater) ReadU16 (): INTEGER, NEW;
VAR b0, b1: SHORTCHAR;
BEGIN
b0 := inf.ReadByte(); b1 := inf.ReadByte();
RETURN ORD(b0) + ASH(ORD(b1), 8)
END ReadU16;
PROCEDURE (inf: Inflater) ProcessRawHeader, NEW;
VAR length, invlength: INTEGER;
BEGIN
length := inf.ReadU16();
invlength := inf.ReadU16(); (* one's complement of length *)
(* check length *)
IF BITS(length) # (-BITS(invlength)) * {0..15} THEN
inf.SetErrorState;
RETURN (* error! *)
END;
inf.bitcount := 0; (* make sure we start next block on a byte boundary *)
inf.bytesLeft := length;
inf.state := RawBlock
END ProcessRawHeader;
PROCEDURE (inf: Inflater) ProcessFixedHeader, NEW;
BEGIN
IF ~inf.lastBlockWasFixed THEN
inf.lt := sltree; inf.dt := sdtree;
inf.lastBlockWasFixed := TRUE
END;
inf.bytesLeft := 0; (* force reading of symbol (just in case) *)
inf.state := CompressedBlock
END ProcessFixedHeader;
PROCEDURE (inf: Inflater) ProcessDynamicHeader, NEW;
BEGIN
(* decode trees from stream *)
inf.DecodeTrees;
inf.bytesLeft := 0; (* force reading of symbol (just in case) *)
inf.state := CompressedBlock
END ProcessDynamicHeader;
(* set state to State.EOF on correct EOF *)
PROCEDURE (inf: Inflater) ProcessBlockHeader, NEW;
BEGIN
IF inf.doingFinalBlock THEN
inf.state := EOF;
inf.doingFinalBlock := FALSE;
IF inf.mode = ZLib THEN inf.FinishZLibData END
ELSE
inf.doingFinalBlock := inf.ReadBit(); (* final block flag *)
(* read block type (2 bits) and fix state *)
CASE inf.ReadBits(2, 0) OF
| 0: inf.ProcessRawHeader (* uncompressed block *)
| 1: inf.ProcessFixedHeader (* block with fixed huffman trees *)
| 2: inf.ProcessDynamicHeader (* block with dynamic huffman trees *)
| 3: inf.SetErrorState (* invalid block code *)
END
END
END ProcessBlockHeader;
PROCEDURE (inf: Inflater) CheckStreamHeader*, NEW;
BEGIN
IF (inf.mode = ZLib) & (inf.state = ExpectZLibHeader) THEN
inf.ProcessZLibHeader
END
END CheckStreamHeader;
(* returns length *)
PROCEDURE (inf: Inflater) ReadSChars* (VAR btdest: ARRAY OF SHORTCHAR; beg, len: INTEGER): INTEGER, NEW;
VAR st, rd, end: INTEGER;
BEGIN
ASSERT(len >= 0, 20); ASSERT(beg >= 0, 21);
ASSERT(LEN(btdest) - beg >= len, 22);
IF inf.state = EOF THEN RETURN 0 END;
st := beg; end := beg + len;
WHILE (beg < end) & (inf.state # EOF) & (inf.state # Dead) DO
CASE inf.state OF
| ExpectZLibHeader:
inf.ProcessZLibHeader
| ExpectBlock:
inf.ProcessBlockHeader
| RawBlock:
rd := inf.UncompressedBlock(btdest, beg, end);
INC(beg, rd)
| CompressedBlock:
rd := inf.InflatedBlock(btdest, beg, end);
INC(beg, rd)
END
END;
IF inf.state = Dead THEN beg := 0; st := 1 END;
RETURN beg - st
END ReadSChars;
PROCEDURE (inf: Inflater) Eof* (): BOOLEAN, NEW;
BEGIN RETURN inf.state = EOF
END Eof;
PROCEDURE (inf: Inflater) Error* (): BOOLEAN, NEW;
BEGIN RETURN inf.state = Dead
END Error;
(******** data initialisers ********)
(* fixed length/symbol tree *)
PROCEDURE InitSLTree;
VAR f: INTEGER;
BEGIN
sltree.Wipe;
sltree.counts[7] := 24;
sltree.counts[8] := 152;
sltree.counts[9] := 112;
FOR f := 0 TO 23 DO sltree.symbols[f] := 256 + f END;
FOR f := 0 TO 143 DO sltree.symbols[24 + f] := f END;
FOR f := 0 TO 7 DO sltree.symbols[24 + 144 + f] := 280 + f END;
FOR f := 0 TO 111 DO sltree.symbols[24 + 144 + 8 + f] := 144 + f END;
sltree.maxsym := 285
END InitSLTree;
(* fixed distance tree *)
PROCEDURE InitSDTree;
VAR f: INTEGER;
BEGIN
sdtree.Wipe;
sdtree.counts[5] := 32;
FOR f := 0 TO 31 DO sdtree.symbols[f] := f END;
sdtree.maxsym := 29
END InitSDTree;
PROCEDURE FillBits (VAR bits: ARRAY OF INTEGER; delta: INTEGER);
VAR f: INTEGER;
BEGIN
FOR f := 0 TO delta - 1 DO bits[f] := 0 END;
FOR f := 0 TO 30 - delta - 1 DO bits[f + delta] := f DIV delta END;
END FillBits;
PROCEDURE FillBase (VAR base: ARRAY OF INTEGER; IN bits: ARRAY OF INTEGER; first: INTEGER);
VAR f, sum: INTEGER;
BEGIN
sum := first;
FOR f := 0 TO 29 DO base[f] := sum; INC(sum, ASH(1, bits[f])) END
END FillBase;
(* extra bits and base tables for length codes *)
PROCEDURE BuildLengthBitsBase;
VAR bits: ARRAY 30 OF INTEGER;
BEGIN
(* bits *)
FillBits(lengthBits, 4);
lengthBits[28] := 0; (* fix a special case *)
(* base *)
FillBits(bits, 4);
FillBase(lengthBase, bits, 3);
lengthBase[28] := 258 (* fix a special case *)
END BuildLengthBitsBase;
(* extra bits and base tables for distance codes *)
PROCEDURE BuildExtraBitsBase;
BEGIN
(* bits *)
FillBits(distBits, 2);
(* base *)
FillBase(distBase, distBits, 1)
END BuildExtraBitsBase;
PROCEDURE Init;
VAR pos: INTEGER;
PROCEDURE Put (v: INTEGER);
BEGIN clcidx[pos] := v; INC(pos)
END Put;
BEGIN
InitSLTree; InitSDTree; BuildLengthBitsBase; BuildExtraBitsBase;
pos := 0;
Put(16); Put(17); Put(18);
Put(0); Put(8); Put(7); Put(9); Put(6);
Put(10); Put(5); Put(11); Put(4); Put(12);
Put(3); Put(13); Put(2); Put(14);
Put(1); Put(15); ASSERT(pos = LEN(clcidx), 100)
END Init;
BEGIN
Init
END StdInflate.
| Std/Mod/Inflate.odc |
MODULE StdInterpreter;
(**
project = "BlackBox 2.0"
organization = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Oberon microsystems, A. Dmitriev, K8"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 20070209, bh, general command signatures
- 20141027, center #19, full Unicode support for Component Pascal identifiers added
- 20150403, center #36, support for long identifiers in StdInterpreter
- 20170819, center #172, adding BOOLEAN parameters to StdInterpreter
- 20191017, ad, check if string is too long
- 20230425, k8, added support for REALs, and integer conversions
"
issues = "
- ...
"
**)
IMPORT Kernel, Meta, Strings, Views, Dialog;
TYPE
IntValue = POINTER TO RECORD (Meta.Value) int: INTEGER; END;
StrValue = POINTER TO RECORD (Meta.Value) str: Dialog.String; END;
BoolValue = POINTER TO RECORD (Meta.Value) bool: BOOLEAN; END;
(* additional values for type conversions *)
BIntValue = POINTER TO RECORD (Meta.Value) bint: BYTE; END;
SIntValue = POINTER TO RECORD (Meta.Value) sint: SHORTINT; END;
LIntValue = POINTER TO RECORD (Meta.Value) lint: LONGINT; END;
RealValue = POINTER TO RECORD (Meta.Value) rval: REAL; END;
SRealValue = POINTER TO RECORD (Meta.Value) srval: SHORTREAL; END;
CallHook = POINTER TO RECORD (Dialog.CallHook) END;
PROCEDURE (hook: CallHook) Call (IN proc, errMsg: ARRAY OF CHAR; VAR res: INTEGER);
TYPE Ident = Kernel.Name;
CONST
modNotFound = 10; procNotFound = 11; identExpected = 12; unknownIdent = 13;
depositExpected = 14; noDepositExpected = 15; syntaxError = 16;
lparenExpected = 17; rparenExpected = 18; containerExpected = 19;
quoteExpected = 20; fileNotFound = 21; noController = 22;
noDialog = 23; cannotUnload = 24; commaExpected = 25;
incompParList = 26; stringTooLong = 27;
CONST
ident = 0; dot = 1; semicolon = 2; eot = 3;
lparen = 4; rparen = 5; quote = 6; comma = 7; int = 8; real = 9;
VAR
i, type: INTEGER; ch: CHAR; id: Ident; x: INTEGER; r: REAL; qch: CHAR;
par: ARRAY 100 OF POINTER TO Meta.Value; numPar: INTEGER;
PROCEDURE Error (n: INTEGER; msg, par0, par1: ARRAY OF CHAR);
VAR e, f: ARRAY 256 OF CHAR;
BEGIN
IF res = 0 THEN
res := n;
IF errMsg # "" THEN
Dialog.MapString(errMsg, e);
IF e = " " THEN Dialog.MapString("#System:CommandError", e) END;
Dialog.MapParamString(msg, par0, par1, "", f);
Dialog.ShowMsg(e + " " + f)
END
END
END Error;
PROCEDURE Init (VAR s: ARRAY OF CHAR);
VAR i: INTEGER;
BEGIN
i := 0; WHILE i < LEN(s) DO s[i] := 0X; INC(i) END
END Init;
PROCEDURE ShowLoaderResult (IN mod: ARRAY OF CHAR);
VAR res: INTEGER; importing, imported, object: ARRAY 256 OF CHAR;
BEGIN
Kernel.GetLoaderResult(res, importing, imported, object);
CASE res OF
| Kernel.fileNotFound:
Error(Kernel.fileNotFound, "#System:CodeFileNotFound", imported, "")
| Kernel.syntaxError:
Error(Kernel.syntaxError, "#System:CorruptedCodeFileFor", imported, "")
| Kernel.objNotFound:
Error(Kernel.objNotFound, "#System:ObjNotFoundImpFrom", imported, importing)
| Kernel.illegalFPrint:
Error(Kernel.illegalFPrint, "#System:ObjInconsImpFrom", imported, importing)
| Kernel.cyclicImport:
Error(Kernel.cyclicImport, "#System:CyclicImpFrom", imported, importing)
| Kernel.noMem:
Error(Kernel.noMem, "#System:NotEnoughMemoryFor", imported, "")
ELSE
Error(res, "#System:CannotLoadModule", mod, "")
END
END ShowLoaderResult;
(* convert ints to other integer types *)
PROCEDURE FixParams (VAR i: Meta.Item; VAR args: ARRAY OF POINTER TO Meta.Value): BOOLEAN;
VAR
res: BOOLEAN;
f, len: INTEGER;
t: Meta.Item;
par, npar: POINTER TO Meta.Value;
bi: BIntValue;
si: SIntValue;
li: LIntValue;
sr: SRealValue;
rv: RealValue;
smr, rrv: SHORTREAL;
BEGIN
res := TRUE; len := i.NumParam();
f := 0; WHILE res & (f < len) DO
i.GetParam(f, t);
ASSERT(t.typ # Meta.undef, 100);
par := args[f];
IF par = NIL THEN res := FALSE
ELSE npar := par;
WITH
| par: IntValue DO
CASE t.typ OF
| Meta.byteTyp:
IF (par.int >= MIN(BYTE)) & (par.int <= MAX(BYTE)) THEN
NEW(bi); bi.bint := SHORT(SHORT(par.int)); npar := bi
ELSE npar := NIL
END
| Meta.sIntTyp:
IF (par.int >= MIN(SHORTINT)) & (par.int <= MAX(SHORTINT)) THEN
NEW(si); si.sint := SHORT(par.int); npar := si
ELSE npar := NIL
END
| Meta.intTyp: (* ok *)
| Meta.longTyp:
NEW(li); li.lint := LONG(par.int); npar := li
| Meta.realTyp: (* REAL can represent any INTEGER *)
NEW(rv); rv.rval := par.int; npar := rv;
| Meta.sRealTyp:
smr := par.int; rrv := par.int;
IF LONG(smr) # rrv THEN npar := NIL
ELSE NEW(sr); sr.srval := smr; npar := sr
END
ELSE npar := NIL
END
| par: RealValue DO
IF t.typ # Meta.realTyp THEN
IF t.typ = Meta.sRealTyp THEN
smr := SHORT(par.rval);
IF LONG(smr) # par.rval THEN npar := NIL
ELSE NEW(sr); sr.srval := smr; npar := sr
END
ELSE npar := NIL
END
END
ELSE END;
res := (npar # NIL);
IF res THEN args[f] := npar END
END;
INC(f)
END;
RETURN res
END FixParams;
PROCEDURE CallProc (IN mod, proc: ARRAY OF CHAR);
VAR i, t: Meta.Item; ok: BOOLEAN;
BEGIN
ok := FALSE;
Meta.Lookup(mod, i);
IF i.obj = Meta.modObj THEN
i.Lookup(proc, i);
IF i.obj = Meta.procObj THEN
i.GetReturnType(t);
IF (t.typ = 0) & (i.NumParam() = numPar) & FixParams(i, par) THEN
i.ParamCallVal(par, t, ok)
ELSE ok := FALSE
END;
IF ~ok THEN
Error(incompParList, "#System:IncompatibleParList", mod, proc)
END
ELSE
Error(Kernel.commNotFound, "#System:CommandNotFoundIn", proc, mod)
END
ELSE
ShowLoaderResult(mod)
END
END CallProc;
PROCEDURE GetCh;
BEGIN
IF i < LEN(proc) THEN ch := proc[i]; INC(i) ELSE ch := 0X END
END GetCh;
PROCEDURE Scan;
VAR j: INTEGER; num: ARRAY 32 OF CHAR; ires: INTEGER;
BEGIN
IF res = 0 THEN
WHILE (ch # 0X) & (ch <= " ") DO GetCh END;
IF ch = 0X THEN
type := eot
ELSIF ch = "." THEN
type := dot; GetCh
ELSIF ch = ";" THEN
type := semicolon; GetCh
ELSIF ch = "(" THEN
type := lparen; GetCh
ELSIF ch = ")" THEN
type := rparen; GetCh
ELSIF (ch = "'") OR (ch = '"') OR (ch = "`") THEN
qch := ch; type := quote; GetCh
ELSIF ch = "," THEN
type := comma; GetCh
ELSIF (ch >= "0") & (ch <= "9") OR (ch = "-") OR (ch = "+") THEN
type := int; j := 0;
REPEAT
num[j] := ch; INC(j); GetCh
UNTIL (ch < "0") OR (ch > "9") & (ch < "A") OR (ch > "F");
CASE ch OF
| 'H':
num[j] := ch; INC(j); GetCh
| '.':
type := real;
REPEAT num[j] := ch; INC(j); GetCh UNTIL (ch < "0") OR (ch > "9")
| '%':
REPEAT num[j] := ch; INC(j); GetCh UNTIL (ch < "0") OR (ch > "9")
ELSE
END;
num[j] := 0X;
IF type = real THEN Strings.StringToReal(num, r, ires)
ELSE Strings.StringToInt(num, x, ires)
END;
IF ires # 0 THEN Error(syntaxError, "#System:SyntaxError", "", "") END
ELSIF Strings.IsIdentStart(ch) THEN
type := ident;
id[0] := ch; j := 1; GetCh;
WHILE (ch # 0X) & (i < LEN(proc)) & Strings.IsIdent(ch) DO
id[j] := ch; INC(j); GetCh
END;
id[j] := 0X
ELSE Error(syntaxError, "#System:SyntaxError", "", "")
END
END
END Scan;
PROCEDURE String (VAR s: ARRAY OF CHAR);
VAR j: INTEGER; s0: Dialog.String;
BEGIN
IF type = quote THEN
ASSERT(qch # 0X, 100);
j := 0;
WHILE (ch # 0X) & (ch # qch) & (j < LEN(s) - 1) DO
s[j] := ch; INC(j); GetCh
END;
s[j] := 0X;
IF j >= LEN(s) -1 THEN
Strings.IntToString(LEN(Dialog.String), s0);
Error(stringTooLong, "#System:StringTooLong", s0, s)
ELSIF ch = qch THEN
GetCh; Scan
ELSE Error(quoteExpected, "#System:QuoteExpected", "", "")
END
ELSE Error(quoteExpected, "#System:QuoteExpected", "", "")
END
END String;
PROCEDURE ParamList ();
VAR iv: IntValue; sv: StrValue; bv: BoolValue; rv: RealValue;
BEGIN
numPar := 0;
IF type = lparen THEN Scan;
WHILE (numPar < LEN(par)) & (type # rparen) & (res = 0) DO
IF type = quote THEN
NEW(sv);
String(sv.str);
par[numPar] := sv;
INC(numPar)
ELSIF type = int THEN
NEW(iv);
iv.int := x; Scan;
par[numPar] := iv;
INC(numPar)
ELSIF type = real THEN
NEW(rv);
rv.rval := r; Scan;
par[numPar] := rv;
INC(numPar)
ELSIF (type = ident) & ((id = "TRUE") OR (id = "FALSE")) THEN
NEW(bv);
bv.bool := (id = "TRUE"); Scan;
par[numPar] := bv;
INC(numPar)
ELSE Error(syntaxError, "#System:SyntaxError", "", "")
END;
IF type = comma THEN Scan
ELSIF type # rparen THEN
Error(rparenExpected, "#System:RParenExpected", "", "")
END
END;
Scan
END
END ParamList;
PROCEDURE Command;
VAR left, right: Ident;
BEGIN
(* protect from parasitic anchors on stack *)
Init(left); Init(right);
left := id; Scan;
IF type = dot THEN (* Oberon command *)
Scan;
IF type = ident THEN
right := id; Scan; ParamList();
IF res = 0 THEN CallProc(left, right) END
ELSE Error(identExpected, "#System:IdentExpected", "", "")
END
ELSE Error(unknownIdent, "#System:UnknownIdent", id, "")
END
END Command;
BEGIN
(* protect from parasitic anchors on stack *)
i := 0; type := 0; qch := 0X; Init(id); x := 0;
Views.ClearQueue;
res := 0; i := 0; GetCh;
Scan;
IF type = ident THEN
Command; WHILE (type = semicolon) & (res = 0) DO Scan; Command END;
IF type # eot THEN Error(syntaxError, "#System:SyntaxError", "", "") END
ELSE Error(syntaxError, "#System:SyntaxError", "", "")
END;
IF (res = 0) & (Views.Available() > 0) THEN
Error(noDepositExpected, "#System:NoDepositExpected", "", "")
END;
Views.ClearQueue
END Call;
PROCEDURE Init;
VAR hook: CallHook;
BEGIN
NEW(hook); Dialog.SetCallHook(hook)
END Init;
BEGIN
Init
END StdInterpreter.
| Std/Mod/Interpreter.odc |
MODULE StdLinks;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20150326, center #33, adding platform detection for wine, Windows 7, and Windows 8
- 20150430, center #44, fixing Unicode support for Link and Target content
- 20150703, center #64, high byte added to Wingdings codes, DefaultAppearance improved
- 20170905, center #173, adding new modifiers to Controllers
- 20170912, center #174, fixing resource keys in StdLinks
- 20170912, center #175, displaying Link and Target properties with mouse-right
"
issues = "
- ...
"
**)
IMPORT Kernel, Services,
Stores, Ports, Fonts, Models, Views, Controllers, Properties, Dialog, Containers,
TextModels, TextMappers, TextViews, TextControllers, TextSetters, TextRulers,
Strings, StdCmds;
CONST
kind* = 0; cmd* = 1; close* = 2; (* constants for Prop.valid *)
always* = 0; ifShiftDown* = 1; never* = 2; (* constants for close attribute *)
minLinkVersion = 0; maxLinkVersion = 2;
minTargVersion = 0; maxTargVersion = 1;
TYPE
Directory* = POINTER TO ABSTRACT RECORD END;
Link* = POINTER TO RECORD (Views.View)
leftSide-: BOOLEAN;
cmd: POINTER TO ARRAY OF CHAR;
close: INTEGER
END;
Target* = POINTER TO RECORD (Views.View)
leftSide-: BOOLEAN;
ident: POINTER TO ARRAY OF CHAR
END;
Prop* = POINTER TO RECORD (Properties.Property)
cmd*: POINTER TO ARRAY OF CHAR;
link-: BOOLEAN;
close*: INTEGER
END;
ChangeAttrOp = POINTER TO RECORD (Stores.Operation)
v: Views.View;
cmd: POINTER TO ARRAY OF CHAR;
close: INTEGER;
valid: SET
END;
StdDirectory = POINTER TO RECORD (Directory) END;
TrapCleaner = POINTER TO RECORD (Kernel.TrapCleaner) END;
VAR
dir-, stdDir-: Directory;
par-: Link;
iconFont: Fonts.Typeface;
linkLeft, linkRight, targetLeft, targetRight: ARRAY 3 OF CHAR;
coloredBackg: BOOLEAN;
cleaner: TrapCleaner;
dialog*: RECORD
cmd*: ARRAY 512 OF CHAR;
type-: ARRAY 32 OF CHAR;
close*: Dialog.List;
known, valid: SET;
readOnly: BOOLEAN; (* if container is read only *)
END;
fingerprint: INTEGER;
(** Cleaner **)
PROCEDURE (c: TrapCleaner) Cleanup;
BEGIN
par := NIL
END Cleanup;
(** Properties **)
PROCEDURE (p: Prop) IntersectWith* (q: Properties.Property; OUT equal: BOOLEAN);
VAR valid: SET;
BEGIN
WITH q: Prop DO
valid := p.valid * q.valid; equal := TRUE;
IF (cmd IN valid) & (p.cmd^ # q.cmd^) THEN EXCL(valid, cmd) END;
IF (kind IN valid) & (p.link # q.link) THEN EXCL(valid, kind) END;
IF (close IN valid) & (p.close # q.close) THEN EXCL (valid, close) END;
IF p.valid # valid THEN p.valid := valid; equal := FALSE END
END
END IntersectWith;
PROCEDURE (op: ChangeAttrOp) Do;
VAR v: Views.View; s: POINTER TO ARRAY OF CHAR; c: INTEGER;
BEGIN
v := op.v;
WITH
| v: Link DO
IF cmd IN op.valid THEN s := op.cmd; op.cmd := v.cmd; v.cmd := s END;
IF close IN op.valid THEN c := op.close; op.close := v.close; v.close := c END
| v: Target DO
IF cmd IN op.valid THEN s := op.cmd; op.cmd := v.ident; v.ident := s END
END
END Do;
PROCEDURE DoChangeAttrOp (v: Views.View; s: POINTER TO ARRAY OF CHAR; c: INTEGER; valid: SET);
VAR op: ChangeAttrOp;
BEGIN
NEW(op); op.v := v; op.valid := valid;
IF close IN valid THEN op.close := c END;
IF cmd IN valid THEN NEW(op.cmd, LEN(s)+1); op.cmd^ := s$ END;
Views.Do(v, "#Std:LinkChange", op)
END DoChangeAttrOp;
PROCEDURE SetProp(v: Views.View; msg: Properties.SetMsg);
VAR p: Properties.Property;
BEGIN
p := msg.prop;
WHILE p # NIL DO
WITH p: Prop DO
IF (cmd IN p.valid) OR (close IN p.valid) THEN DoChangeAttrOp(v, p.cmd, p.close, p.valid) END
ELSE
END;
p := p.next
END
END SetProp;
PROCEDURE PollProp(v: Views.View; VAR msg: Properties.PollMsg);
VAR p: Prop;
BEGIN
NEW(p);
WITH v: Link DO
p.known := {kind, cmd, close};
p.link := TRUE;
p.cmd := v.cmd;
p.close := v.close
| v: Target DO
p.known := {kind, cmd};
p.link := FALSE;
p.cmd := v.ident
ELSE
END;
p.valid := p.known;
Properties.Insert(msg.prop, p)
END PollProp;
PROCEDURE InitDialog*;
VAR p: Properties.Property;
BEGIN
IF (TextControllers.Focus() # NIL) & (Containers.noSelection IN TextControllers.Focus().opts) THEN
(* mask mode: dialog cannot be initialized from current selection *)
RETURN
END;
dialog.cmd := ""; dialog.type := ""; dialog.close.index := -1;
dialog.known := {}; dialog.valid := {};
dialog.readOnly := (TextControllers.Focus() # NIL) & (Containers.noCaret IN TextControllers.Focus().opts);
Properties.CollectProp(p);
WHILE p # NIL DO
WITH p: Prop DO
dialog.valid := p.valid; dialog.known := p.known;
IF cmd IN p.valid THEN
dialog.cmd := p.cmd$
END;
IF kind IN p.valid THEN
IF p.link THEN Dialog.MapString("#Std:Link", dialog.type)
ELSE Dialog.MapString("#Std:Target", dialog.type)
END
END;
IF close IN p.valid THEN
dialog.close.index := p.close
END
ELSE
END;
p := p.next
END;
Dialog.Update(dialog)
END InitDialog;
PROCEDURE SetGuard* (VAR par: Dialog.Par);
BEGIN
IF dialog.readOnly THEN par.disabled := TRUE END
END SetGuard;
PROCEDURE Set*;
VAR p: Prop;
BEGIN
NEW(p);
p.valid := dialog.valid;
IF cmd IN p.valid THEN
NEW(p.cmd, LEN(dialog.cmd) + 1);
p.cmd^ := dialog.cmd$
END;
p.close := dialog.close.index;
Properties.EmitProp(NIL, p);
fingerprint := 0 (* force actualization of fields *)
END Set;
PROCEDURE LinkGuard* (VAR par: Dialog.Par);
BEGIN
IF dialog.known # {} THEN
IF close IN dialog.known THEN Dialog.MapString("#Std:Link:", par.label)
ELSE Dialog.MapString("#Std:Target:", par.label)
END
END
END LinkGuard;
PROCEDURE CmdGuard* (VAR par: Dialog.Par);
VAR c: Containers.Controller; v: Views.View; fp: INTEGER;
BEGIN
IF ~(cmd IN dialog.known) THEN par.disabled := TRUE
ELSIF ~(cmd IN dialog.valid) THEN par.undef := TRUE
END;
Controllers.SetCurrentPath(Controllers.targetPath);
fp := 0;
c := Containers.Focus();
IF c # NIL THEN
c.GetFirstView(Containers.selection, v);
WHILE v # NIL DO fp := fp + Services.AdrOf(v); c.GetNextView(TRUE, v) END
END;
IF fp # fingerprint THEN fingerprint := fp; InitDialog END;
Controllers.ResetCurrentPath()
END CmdGuard;
PROCEDURE CloseGuard* (VAR par: Dialog.Par);
BEGIN
IF ~(close IN dialog.known) THEN par.disabled := TRUE
ELSIF ~(close IN dialog.valid) THEN par.undef := TRUE
END;
IF dialog.readOnly THEN par.readOnly := TRUE END
END CloseGuard;
PROCEDURE Notifier* (idx, op, from, to: INTEGER);
BEGIN
IF op = Dialog.changed THEN INCL(dialog.valid, idx) END
END Notifier;
PROCEDURE (d: Directory) NewLink* (IN cmd: ARRAY OF CHAR): Link, NEW, ABSTRACT;
PROCEDURE (d: Directory) NewTarget* (IN ident: ARRAY OF CHAR): Target, NEW, ABSTRACT;
PROCEDURE InFrame (f: Views.Frame; x, y: INTEGER): BOOLEAN;
BEGIN
RETURN (f.l <= x) & (x < f.r) & (f.t <= y) & (y < f.b)
END InFrame;
PROCEDURE Mark (f: Views.Frame; show: BOOLEAN);
BEGIN
f.MarkRect(f.l, f.t, f.r, f.b, Ports.fill, Ports.hilite, show)
END Mark;
PROCEDURE ThisPos (v: TextViews.View; f: Views.Frame; x, y: INTEGER): INTEGER;
(* "corrected" v.ThisPos: does not adjust position when crossing 50% boundary of characters *)
VAR loc: TextViews.Location; pos: INTEGER;
BEGIN
pos := v.ThisPos(f, x, y); v.GetThisLocation(f, pos, loc);
IF (loc.y <= y) & (y < loc.y + loc.asc + loc.dsc) & (x < loc.x) THEN DEC(pos) END;
RETURN pos
END ThisPos;
PROCEDURE GetLinkPair (this: Link; VAR l, r: Link);
(* POST: BalancedPair(l, r) & (l # r) & (l = this OR r = this) OR (l = r = NIL) *)
VAR t: TextModels.Model; rd: TextModels.Reader; v: Views.View; level: INTEGER;
BEGIN
l := NIL; r := NIL; level := 1;
IF (this.context # NIL) & (this.context IS TextModels.Context) THEN
t := this.context(TextModels.Context).ThisModel();
rd := t.NewReader(NIL);
IF this.leftSide THEN
rd.SetPos(this.context(TextModels.Context).Pos() + 1);
REPEAT
rd.ReadView(v);
IF (v # NIL) & (v IS Link) THEN
IF v(Link).leftSide THEN INC(level) ELSE DEC(level) END
END
UNTIL (v = NIL) OR (level = 0);
IF v # NIL THEN l := this; r := v(Link) END
ELSE
rd.SetPos(this.context(TextModels.Context).Pos());
REPEAT
rd.ReadPrevView(v);
IF (v # NIL) & (v IS Link) THEN
IF v(Link).leftSide THEN DEC(level) ELSE INC(level) END
END
UNTIL (v = NIL) OR (level = 0);
IF v # NIL THEN l := v(Link); r := this END
END
END
END GetLinkPair;
PROCEDURE GetTargetPair (this: Target; VAR l, r: Target);
(* POST: BalancedPair(l, r) & (l # r) & (l = this OR r = this) OR (l = r = NIL) *)
VAR t: TextModels.Model; rd: TextModels.Reader; v: Views.View; level: INTEGER;
BEGIN
l := NIL; r := NIL; level := 1;
IF (this.context # NIL) & (this.context IS TextModels.Context) THEN
t := this.context(TextModels.Context).ThisModel();
rd := t.NewReader(NIL);
IF this.leftSide THEN
rd.SetPos(this.context(TextModels.Context).Pos() + 1);
REPEAT
rd.ReadView(v);
IF (v # NIL) & (v IS Target) THEN
IF v(Target).leftSide THEN INC(level) ELSE DEC(level) END
END
UNTIL (v = NIL) OR (level = 0);
IF v # NIL THEN l := this; r := v(Target) END
ELSE
rd.SetPos(this.context(TextModels.Context).Pos());
REPEAT
rd.ReadPrevView(v);
IF (v # NIL) & (v IS Target) THEN
IF v(Target).leftSide THEN DEC(level) ELSE INC(level) END
END
UNTIL (v = NIL) OR (level = 0);
IF v # NIL THEN l := v(Target); r := this END
END
END
END GetTargetPair;
PROCEDURE GetRange (l, r: Views.View; VAR beg, end: INTEGER);
BEGIN
beg := l.context(TextModels.Context).Pos();
end := r.context(TextModels.Context).Pos() + 1
END GetRange;
PROCEDURE MarkRange (v: TextViews.View; f: Views.Frame; beg, end: INTEGER; show: BOOLEAN);
VAR b, e: TextViews.Location; r, t: INTEGER;
BEGIN
ASSERT(beg < end, 20);
v.GetThisLocation(f, beg, b); v.GetThisLocation(f, end, e);
IF (b.pos < e.pos) OR (b.pos = e.pos) & (b.x < e.x) THEN
IF b.start # e.start THEN
r := f.r; t := b.y + b.asc + b.dsc;
f.MarkRect(b.x, b.y, r, t, Ports.fill, Ports.hilite, show);
IF t < e.y THEN f.MarkRect(0, t, r, e.y, Ports.fill, Ports.hilite, show) END;
b.x := f.l; b.y := e.y
END;
f.MarkRect(b.x, b.y, e.x, e.y + e.asc + e.dsc, Ports.fill, Ports.hilite, show)
END
END MarkRange;
PROCEDURE Reveal (left, right: Views.View; str: ARRAY OF CHAR; opname: Stores.OpName);
VAR con: TextModels.Context; t: TextModels.Model; pos: INTEGER;
w: TextMappers.Formatter; op: Stores.Operation;
BEGIN
con := left.context(TextModels.Context);
t := con.ThisModel(); pos := con.Pos();
w.ConnectTo(t); w.SetPos(pos);
IF con.Attr() # NIL THEN w.rider.SetAttr(con.Attr()) END;
Models.BeginScript(t, opname, op);
t.Delete(pos, pos + 1);
w.WriteChar("<");
IF str # "" THEN w.WriteString(str) END;
w.WriteChar(">");
con := right.context(TextModels.Context);
pos := con.Pos();
w.SetPos(pos);
IF con.Attr() # NIL THEN w.rider.SetAttr(con.Attr()) END;
t.Delete(pos, pos + 1);
w.WriteString("<>");
Models.EndScript(t, op)
END Reveal;
PROCEDURE RevealCmd (v: Link);
VAR left, right: Link;
BEGIN GetLinkPair(v, left, right);
IF left # NIL THEN
IF v.cmd # NIL THEN Reveal(left, right, v.cmd^, "#Std:Reveal Link Command")
ELSE Reveal(left, right, "", "#Std:Reveal Link Command")
END
END
END RevealCmd;
PROCEDURE RevealTarget (targ: Target);
VAR left, right: Target;
BEGIN GetTargetPair(targ, left, right);
IF left # NIL THEN
IF left.ident # NIL THEN Reveal(left, right, left.ident^, "#Std:Reveal Target Ident")
ELSE Reveal(left, right, "", "#Std:Reveal Target Ident")
END
END
END RevealTarget;
PROCEDURE CallCmd (v: Link; close: BOOLEAN);
VAR res: INTEGER;
BEGIN
Kernel.PushTrapCleaner(cleaner);
par := v;
IF v.cmd^ # "" THEN
IF close & (v.close = ifShiftDown) OR (v.close = always) THEN
StdCmds.CloseDialog
END;
Dialog.Call(v.cmd^, "#Std:Link Call Failed", res)
END;
par := NIL;
Kernel.PopTrapCleaner(cleaner)
END CallCmd;
PROCEDURE TrackSingle (f: Views.Frame; VAR in: BOOLEAN);
VAR x, y: INTEGER; modifiers: SET; in0, isDown: BOOLEAN;
BEGIN
in := FALSE;
REPEAT
f.Input(x, y, modifiers, isDown);
in0 := in; in := InFrame(f, x, y);
IF in # in0 THEN Mark(f, in) END
UNTIL ~isDown;
IF in THEN Mark(f, FALSE) END
END TrackSingle;
PROCEDURE TrackRange (v: TextViews.View; f: Views.Frame; l, r: Views.View; x, y: INTEGER;
VAR in: BOOLEAN);
VAR pos, beg, end: INTEGER; modifiers: SET; in0, isDown: BOOLEAN;
BEGIN
in := FALSE;
GetRange(l, r, beg, end); pos := ThisPos(v, f, x, y);
IF (beg <= pos) & (pos < end) THEN
REPEAT
f.Input(x, y, modifiers, isDown); pos := ThisPos(v, f, x, y);
in0 := in; in := (beg <= pos) & (pos < end);
IF in # in0 THEN MarkRange(v, f, beg, end, in) END
UNTIL ~isDown;
IF in THEN
MarkRange(v, f, beg, end, FALSE)
END
END
END TrackRange;
PROCEDURE OpenProperties(l, r: Views.View; c: TextControllers.Controller;
IN type, cmd: ARRAY OF CHAR; close: INTEGER; known: SET);
VAR beg, end, res: INTEGER; linksProp: ARRAY 256 OF CHAR;
BEGIN
GetRange(l, r, beg, end); c.SetSelection(beg, end);
Dialog.MapString("#Std:Links.Prop", linksProp);
Dialog.Call(linksProp, "", res);
IF Containers.noSelection IN c.opts THEN (* mask mode: cannot use selection *)
Dialog.MapString(type, dialog.type);
dialog.cmd := cmd$; dialog.close.index := close;
dialog.known := known; dialog.valid := known; dialog.readOnly := TRUE; fingerprint := 0;
Dialog.Update(dialog)
END
END OpenProperties;
PROCEDURE Track (v: Link; f: Views.Frame; c: TextControllers.Controller;
x, y: INTEGER; modifiers: SET);
(* PRE: (c # NIL) & (f.view.ThisModel() = v.context.ThisModel()) OR (c = NIL) & (f.view = v) *)
VAR l, r: Link; in: BOOLEAN;
BEGIN
GetLinkPair(v, l, r);
IF l # NIL THEN
IF (Controllers.popup IN modifiers) & (c # NIL) THEN c.SetSelection(0, 0) END;
IF c # NIL THEN TrackRange(c.view, f, l, r, x, y, in)
ELSE TrackSingle(f, in)
END;
IF in THEN
IF Controllers.modify IN modifiers THEN
IF (Controllers.popup IN modifiers) & (c # NIL) THEN
OpenProperties(l, r, c, "#Std:Link", l.cmd, l.close, {kind, cmd, close})
ELSIF (c # NIL) & ~(Containers.noCaret IN c.opts) THEN
RevealCmd(l) (* for backwards compatibility *)
END
ELSE
CallCmd(l, Controllers.extend IN modifiers)
END
END
END
END Track;
PROCEDURE TrackTarget (targ: Target; f: Views.Frame; c: TextControllers.Controller;
x, y: INTEGER; modifiers: SET);
VAR in: BOOLEAN; l, r: Target;
BEGIN
GetTargetPair(targ, l, r);
IF l # NIL THEN
IF (Controllers.popup IN modifiers) & (c # NIL) THEN c.SetSelection(0, 0) END;
IF c # NIL THEN TrackRange(c.view, f, l, r, x, y, in)
ELSE TrackSingle(f, in)
END;
IF in THEN
IF (Controllers.modify IN modifiers) & (c # NIL) THEN
IF Controllers.popup IN modifiers THEN
OpenProperties(l, r, c, "#Std:Target", l.ident, -1, {kind, cmd, close})
ELSIF ~(Containers.noCaret IN c.opts) THEN
RevealTarget(targ) (* for backwards compatibility *)
END
END
END
END
END TrackTarget;
PROCEDURE (v: Link) CopyFromSimpleView- (source: Views.View);
BEGIN
WITH source: Link DO
ASSERT(source.leftSide = (source.cmd # NIL), 100);
v.leftSide := source.leftSide;
v.close := source.close;
IF source.cmd # NIL THEN
NEW(v.cmd, LEN(source.cmd^));
v.cmd^ := source.cmd^$
ELSE v.cmd := NIL
END
END
END CopyFromSimpleView;
PROCEDURE (t: Target) CopyFromSimpleView- (source: Views.View);
BEGIN
WITH source: Target DO
ASSERT(source.leftSide = (source.ident # NIL), 100);
t.leftSide := source.leftSide;
IF source.ident # NIL THEN
NEW(t.ident, LEN(source.ident^));
t.ident^ := source.ident^$
ELSE t.ident := NIL
END
END
END CopyFromSimpleView;
PROCEDURE (v: Link) Internalize- (VAR rd: Stores.Reader);
VAR len, version, pos: INTEGER;
BEGIN
v.Internalize^(rd);
IF rd.cancelled THEN RETURN END;
rd.ReadVersion(minLinkVersion, maxLinkVersion, version);
IF rd.cancelled THEN RETURN END;
rd.ReadBool(v.leftSide);
rd.ReadInt(len);
IF len = 0 THEN v.cmd := NIL
ELSE NEW(v.cmd, len);
IF version <= 1 THEN rd.ReadXString(v.cmd^) ELSE rd.ReadString(v.cmd^) END
END;
v.leftSide := v.cmd # NIL;
IF v.leftSide THEN
IF version >= 1 THEN
rd.ReadInt(v.close)
ELSE
Strings.Find(v.cmd, "StdLinks.ShowTarget", 0, pos);
IF (pos # 0) THEN v.close := ifShiftDown
ELSE v.close := never
END
END
END
END Internalize;
PROCEDURE HasWideChars (IN s: ARRAY OF CHAR): BOOLEAN;
VAR i: INTEGER; ch: CHAR;
BEGIN i := 0; ch := s[0];
WHILE (ch # 0X) & (ch <= 0FFX) DO INC(i); ch := s[i] END;
RETURN ch # 0X
END HasWideChars;
(* version history for left side Link:
0: 'cmd' stored as ASCII, standard closing behavior only
1: like 0 but 'close' attribute added for non-standard closing behavior
2. like 1 but 'cmd' stored as Unicode *)
PROCEDURE (v: Link) Externalize- (VAR wr: Stores.Writer);
VAR pos, version: INTEGER;
BEGIN
v.Externalize^(wr);
IF v.leftSide THEN
IF HasWideChars(v.cmd) THEN
version := 2
ELSE
Strings.Find(v.cmd, "StdLinks.ShowTarget", 0, pos);
IF (pos = 0) & (v.close = never) OR (v.close = ifShiftDown) THEN version := 0
ELSE version := 1
END
END
ELSE
version := 0
END;
wr.WriteVersion(version);
wr.WriteBool(v.cmd # NIL);
IF v.cmd = NIL THEN wr.WriteInt(0)
ELSE wr.WriteInt(LEN(v.cmd^));
IF version <= 1 THEN wr.WriteXString(v.cmd^) ELSE wr.WriteString(v.cmd^) END
END;
IF version >= 1 THEN wr.WriteInt(v.close) END
END Externalize;
PROCEDURE (t: Target) Internalize- (VAR rd: Stores.Reader);
VAR len, version: INTEGER;
BEGIN
t.Internalize^(rd);
IF rd.cancelled THEN RETURN END;
rd.ReadVersion(minTargVersion, maxTargVersion, version);
IF rd.cancelled THEN RETURN END;
rd.ReadBool(t.leftSide);
rd.ReadInt(len);
IF len = 0 THEN t.ident := NIL
ELSE NEW(t.ident, len);
IF version = 0 THEN rd.ReadXString(t.ident^) ELSE rd.ReadString(t.ident^) END
END;
t.leftSide := t.ident # NIL
END Internalize;
(* version history for left side Target:
0: 'ident' stored as ASCII
1: like 0 but 'ident' stored as Unicode *)
PROCEDURE (t: Target) Externalize- (VAR wr: Stores.Writer);
VAR version: INTEGER;
BEGIN
t.Externalize^(wr);
IF t.leftSide & HasWideChars(t.ident) THEN version := 1 ELSE version := 0 END;
wr.WriteVersion(version);
wr.WriteBool(t.ident # NIL);
IF t.ident = NIL THEN wr.WriteInt(0)
ELSE wr.WriteInt(LEN(t.ident^));
IF version = 0 THEN wr.WriteXString(t.ident^) ELSE wr.WriteString(t.ident^) END
END
END Externalize;
PROCEDURE RestoreView (v: Views.View; f: Views.Frame; icon: ARRAY OF CHAR);
VAR c: Models.Context; a: TextModels.Attributes; font: Fonts.Font; color: Ports.Color;
asc, dsc, w: INTEGER;
BEGIN
c := v.context;
IF (c # NIL) & (c IS TextModels.Context) THEN
a := c(TextModels.Context).Attr();
font := Fonts.dir.This(iconFont, a.font.size, {}, Fonts.normal);
color := a.color
ELSE font := Fonts.dir.Default(); color := Ports.black
END;
IF coloredBackg THEN
f.DrawRect(f.l, f.t, f.r, f.b, Ports.fill, Ports.grey25) END;
font.GetBounds(asc, dsc, w);
f.DrawString(1*Ports.mm DIV 2, asc, color, icon, font)
END RestoreView;
PROCEDURE (v: Link) Restore* (f: Views.Frame; l, t, r, b: INTEGER);
BEGIN
IF v.leftSide THEN RestoreView(v, f, linkLeft)
ELSE RestoreView(v, f, linkRight)
END
END Restore;
PROCEDURE (targ: Target) Restore* (f: Views.Frame; l, t, r, b: INTEGER);
BEGIN
IF targ.leftSide THEN RestoreView(targ, f, targetLeft)
ELSE RestoreView(targ, f, targetRight)
END
END Restore;
PROCEDURE SizePref (v: Views.View; icon: ARRAY OF CHAR; VAR msg: Properties.SizePref);
VAR c: Models.Context; a: TextModels.Attributes; font: Fonts.Font;
asc, dsc, w: INTEGER;
BEGIN
c := v.context;
IF (c # NIL) & (c IS TextModels.Context) THEN
a := c(TextModels.Context).Attr();
font := Fonts.dir.This(iconFont, a.font.size, {}, Fonts.normal)
ELSE
font := Fonts.dir.Default()
END;
msg.w := font.StringWidth(icon) + 1*Ports.mm;
font.GetBounds(asc, dsc, w);
msg.h := asc + dsc
END SizePref;
PROCEDURE (v: Link) HandlePropMsg- (VAR msg: Properties.Message);
VAR a: TextModels.Attributes; c: Models.Context; asc, dsc, w: INTEGER; l, r: Link;
BEGIN
WITH msg: Properties.SizePref DO
IF v.leftSide THEN SizePref(v, linkLeft, msg)
ELSE SizePref(v, linkRight, msg)
END
| msg: Properties.FocusPref DO
msg.hotFocus := TRUE
| msg: Properties.ResizePref DO
msg.fixed := TRUE
| msg: TextModels.Pref DO
msg.opts := {TextModels.hideable}
| msg: TextControllers.FilterPref DO
msg.filter := TRUE
| msg: TextSetters.Pref DO c := v.context;
IF (c # NIL) & (c IS TextModels.Context) THEN
a := c(TextModels.Context).Attr();
a.font.GetBounds(asc, dsc, w);
msg.dsc := dsc
END
| msg: Properties.PollMsg DO
IF v.leftSide THEN PollProp(v, msg)
ELSE
GetLinkPair(v, l, r);
IF l # NIL THEN PollProp(l, msg) END
END
| msg: Properties.SetMsg DO
IF v.leftSide THEN SetProp(v, msg)
ELSE GetLinkPair(v, l, r); SetProp(l, msg)
END
ELSE
END
END HandlePropMsg;
PROCEDURE (targ: Target) HandlePropMsg- (VAR msg: Properties.Message);
VAR a: TextModels.Attributes; c: Models.Context; asc, dsc, w: INTEGER; l, r: Target;
BEGIN
WITH msg: Properties.SizePref DO
IF targ.leftSide THEN SizePref(targ, targetLeft, msg)
ELSE SizePref(targ, targetRight, msg)
END
| msg: Properties.FocusPref DO
msg.hotFocus := TRUE
| msg: Properties.ResizePref DO
msg.fixed := TRUE
| msg: TextModels.Pref DO
msg.opts := {TextModels.hideable}
| msg: TextControllers.FilterPref DO
msg.filter := TRUE
| msg: TextSetters.Pref DO c := targ.context;
IF (c # NIL) & (c IS TextModels.Context) THEN
a := c(TextModels.Context).Attr();
a.font.GetBounds(asc, dsc, w);
msg.dsc := dsc
END
| msg: Properties.PollMsg DO
IF targ.leftSide THEN PollProp(targ, msg)
ELSE
GetTargetPair(targ, l, r);
IF l # NIL THEN PollProp(l, msg) END
END
| msg: Properties.SetMsg DO
IF targ.leftSide THEN SetProp(targ, msg)
ELSE GetTargetPair(targ, l, r); SetProp(l, msg)
END
ELSE
END
END HandlePropMsg;
PROCEDURE isHot(v: Views.View; f: Views.Frame; leftSide: BOOLEAN; c: TextControllers.Controller;
x, y: INTEGER; mod: SET): BOOLEAN;
VAR pos, beg, end: INTEGER;
BEGIN
(* ignore 'pick' (alt, cmd, and middle clicks) in edit mode *)
IF ~(Containers.noCaret IN c.opts) & (Controllers.pick IN mod) THEN RETURN FALSE END;
pos := ThisPos(c.view, f, x, y);
(* ignore clicks in selection *)
c.GetSelection(beg, end);
IF (end > beg) & (pos >= beg) & (pos <= end) THEN RETURN FALSE END;
IF leftSide THEN RETURN pos >= v.context(TextModels.Context).Pos()
ELSE RETURN pos <= v.context(TextModels.Context).Pos()
END
END isHot;
PROCEDURE (v: Link) HandleCtrlMsg* (f: Views.Frame;
VAR msg: Controllers.Message; VAR focus: Views.View);
BEGIN
WITH msg: Controllers.PollCursorMsg DO
msg.cursor := Ports.refCursor
| msg: TextControllers.FilterPollCursorMsg DO
IF isHot(v, f, v.leftSide, msg.controller, msg.x, msg.y, {}) THEN
msg.cursor := Ports.refCursor; msg.done := TRUE
END
| msg: Controllers.TrackMsg DO
Track(v, f, NIL, msg.x, msg.y, msg.modifiers)
| msg: TextControllers.FilterTrackMsg DO
IF isHot(v, f, v.leftSide, msg.controller, msg.x, msg.y, msg.modifiers) THEN
Track(v, f, msg.controller, msg.x, msg.y, msg.modifiers);
msg.done := TRUE
END
ELSE
END
END HandleCtrlMsg;
PROCEDURE (targ: Target) HandleCtrlMsg* (f: Views.Frame; VAR msg: Controllers.Message;
VAR focus: Views.View);
BEGIN
WITH msg: Controllers.TrackMsg DO
TrackTarget(targ, f, NIL, msg.x, msg.y, msg.modifiers)
| msg: TextControllers.FilterTrackMsg DO
IF (msg.modifiers * {Controllers.extend, Controllers.modify} # {})
& isHot(targ, f, targ.leftSide, msg.controller, msg.x, msg.y, msg.modifiers) THEN
TrackTarget(targ, f, msg.controller, msg.x, msg.y, msg.modifiers);
msg.done := TRUE
END
ELSE
END
END HandleCtrlMsg;
PROCEDURE (v: Link) GetCmd* (OUT cmd: ARRAY OF CHAR), NEW;
BEGIN
ASSERT(v.leftSide, 20);
ASSERT(v.cmd # NIL, 100);
cmd := v.cmd$
END GetCmd;
PROCEDURE (t: Target) GetIdent* (OUT ident: ARRAY OF CHAR), NEW;
BEGIN
ASSERT(t.leftSide, 20);
ASSERT(t.ident # NIL, 100);
ident := t.ident$
END GetIdent;
(* --------------- create commands and menu guards ------------------------ *)
PROCEDURE GetParam (c: TextControllers.Controller; VAR param: ARRAY OF CHAR;
VAR lbrBeg, lbrEnd, rbrBeg, rbrEnd: INTEGER);
VAR rd: TextModels.Reader; i, beg, end: INTEGER;
ch0, ch1, ch2: CHAR;
BEGIN
param[0] := 0X; lbrBeg := -1;
IF (c # NIL) & c.HasSelection() THEN
rd := c.text.NewReader(NIL);
c.GetSelection(beg, end);
IF end - beg > 4 THEN
rd.SetPos(beg); rd.ReadChar(ch0);
rd.SetPos(end-2); rd.ReadChar(ch1); rd.ReadChar(ch2);
IF (ch0 = "<") & (ch1 = "<") & (ch2 = ">") THEN
rd.SetPos(beg+1); rd.ReadChar(ch0); i := 0;
WHILE ~rd.eot & (ch0 # ">") DO
IF i < LEN(param) - 1 THEN param[i] := ch0; INC(i) END;
rd.ReadChar(ch0)
END;
param[i] := 0X;
lbrBeg := beg; lbrEnd := rd.Pos();
rbrBeg := end -2; rbrEnd := end
END
END;
IF lbrBeg = -1 THEN (* lbrBeg = -1 means selection without syntax*)
rd.SetPos(beg); rd.ReadChar(ch0); i := 0;
WHILE ~rd.eot & (ch0 # 0X) DO
IF i < LEN(param) - 1 THEN param[i] := ch0; INC(i) END;
rd.ReadChar(ch0)
END;
param[i] := 0X;
END
END
END GetParam;
PROCEDURE CreateGuard* (VAR par: Dialog.Par);
VAR param: ARRAY 512 OF CHAR; lbrBeg, lbrEnd, rbrBeg, rbrEnd: INTEGER;
BEGIN
GetParam(TextControllers.Focus(), param, lbrBeg, lbrEnd, rbrBeg, rbrEnd);
par.disabled := param = ""
END CreateGuard;
PROCEDURE InsertionAttr (c: TextControllers.Controller; pos: INTEGER): TextModels.Attributes;
VAR rd: TextModels.Reader; r: TextRulers.Ruler; a: TextModels.Attributes; ch: CHAR;
BEGIN
rd := c.text.NewReader(NIL); a := NIL;
rd.SetPos(pos); rd.ReadChar(ch); a := rd.attr;
IF a = NIL THEN c.view.PollDefaults(r, a) END;
RETURN a
END InsertionAttr;
PROCEDURE CreateLink*;
VAR lbrBeg, lbrEnd, rbrBeg, rbrEnd, beg, end: INTEGER;
left, right: Link; c: TextControllers.Controller;
cmd: ARRAY 512 OF CHAR;
op: Stores.Operation;
w: TextModels.Writer; a: TextModels.Attributes;
BEGIN
c := TextControllers.Focus();
GetParam(TextControllers.Focus(), cmd, lbrBeg, lbrEnd, rbrBeg, rbrEnd);
IF cmd # "" THEN
w := c.text.NewWriter(NIL);
Models.BeginScript(c.text, "#Std:Create Link", op);
IF lbrBeg >= 0 THEN
a := InsertionAttr(c, rbrBeg);
c.text.Delete(rbrBeg, rbrEnd);
right := dir.NewLink("");
w.SetPos(rbrBeg);
IF a # NIL THEN w.SetAttr(a) END;
w.WriteView(right, 0, 0);
a := InsertionAttr(c, lbrBeg);
c.text.Delete(lbrBeg, lbrEnd);
left := dir.NewLink(cmd);
w.SetPos(lbrBeg);
IF a # NIL THEN w.SetAttr(a) END;
w.WriteView(left, 0, 0)
ELSE (* selection is unformatted and used as link text *)
c.GetSelection(beg, end);
a := InsertionAttr(c, beg);
IF a # NIL THEN w.SetAttr(a) END;
right := dir.NewLink("");
w.SetPos(end);
w.WriteView(right, 0, 0);
left := dir.NewLink("dummy");
left.cmd[0] := 0X;
w.SetPos(beg);
w.WriteView(left, 0, 0);
a := TextModels.NewColor(w.attr, Ports.blue);
a := TextModels.NewStyle(a, a.font.style + {Fonts.underline});
c.text.SetAttr(beg + 1, end + 1, a)
END;
Models.EndScript(c.text, op);
IF lbrBeg < 0 THEN OpenProperties(left, right, c, "#Std:Link", left.cmd, ifShiftDown, {kind..close}) END
END
END CreateLink;
PROCEDURE CreateTarget*;
VAR lbrBeg, lbrEnd, rbrBeg, rbrEnd, beg, end: INTEGER;
left, right: Target; c: TextControllers.Controller;
ident: ARRAY 512 OF CHAR;
op: Stores.Operation;
w: TextModels.Writer; a: TextModels.Attributes;
BEGIN
c := TextControllers.Focus();
GetParam(TextControllers.Focus(), ident, lbrBeg, lbrEnd, rbrBeg, rbrEnd);
IF ident # "" THEN
w := c.text.NewWriter(NIL);
Models.BeginScript(c.text, "#Std:Create Target", op);
IF lbrBeg >= 0 THEN
a := InsertionAttr(c, rbrBeg);
c.text.Delete(rbrBeg, rbrEnd);
right := dir.NewTarget("");
w.SetPos(rbrBeg);
IF a # NIL THEN w.SetAttr(a) END;
w.WriteView(right, 0, 0);
a := InsertionAttr(c, lbrBeg);
c.text.Delete(lbrBeg, lbrEnd);
left := dir.NewTarget(ident);
w.SetPos(lbrBeg);
IF a # NIL THEN w.SetAttr(a) END;
w.WriteView(left, 0, 0)
ELSE (* selection is unformatted and used as target text *)
c.GetSelection(beg, end);
a := InsertionAttr(c, beg);
IF a # NIL THEN w.SetAttr(a) END;
right := dir.NewTarget("");
w.SetPos(end);
w.WriteView(right, 0, 0);
left := dir.NewTarget("dummy");
left.ident[0] := 0X;
w.SetPos(beg);
w.WriteView(left, 0, 0);
END;
Models.EndScript(c.text, op);
IF lbrBeg < 0 THEN OpenProperties(left, right, c, "#Std:Target", left.ident, -1, {kind, cmd}) END
END
END CreateTarget;
PROCEDURE ShowTarget* (IN ident: ARRAY OF CHAR);
VAR c: TextControllers.Controller; rd: TextModels.Reader;
v: Views.View; left, right: Target; beg, end: INTEGER;
BEGIN
c := TextControllers.Focus();
IF c # NIL THEN
rd := c.text.NewReader(NIL);
REPEAT rd.ReadView(v)
UNTIL rd.eot OR (v # NIL) & (v IS Target) & v(Target).leftSide & (v(Target).ident^ = ident);
IF ~rd.eot THEN
GetTargetPair(v(Target), left, right);
IF (left # NIL) & (right # NIL) THEN
beg := left.context(TextModels.Context).Pos();
end := right.context(TextModels.Context).Pos() + 1;
c.SetSelection(beg, end);
c.view.SetOrigin(beg, 0)
ELSE
Dialog.ShowParamMsg("#Std:Target Not Found", ident, "", "")
END
ELSE
Dialog.ShowParamMsg("#Std:Target Not Found", ident, "", "")
END
END
END ShowTarget;
(* programming interface *)
PROCEDURE (d: StdDirectory) NewLink (IN cmd: ARRAY OF CHAR): Link;
VAR link: Link; i: INTEGER;
BEGIN
NEW(link); link.leftSide := cmd # "";
IF link.leftSide THEN
i := 0; WHILE cmd[i] # 0X DO INC(i) END;
NEW(link.cmd, i + 1); link.cmd^ := cmd$
ELSE
link.cmd := NIL
END;
link.close := ifShiftDown;
RETURN link
END NewLink;
PROCEDURE (d: StdDirectory) NewTarget (IN ident: ARRAY OF CHAR): Target;
VAR t: Target; i: INTEGER;
BEGIN
NEW(t); t.leftSide := ident # "";
IF t.leftSide THEN
i := 0; WHILE ident[i] # 0X DO INC(i) END;
NEW(t.ident, i + 1); t.ident^ := ident$
ELSE
t.ident := NIL
END;
RETURN t
END NewTarget;
PROCEDURE SetDir* (d: Directory);
BEGIN
ASSERT(d # NIL, 20);
dir := d
END SetDir;
PROCEDURE Init;
VAR font: Fonts.Font; d: StdDirectory;
PROCEDURE DefaultAppearance;
BEGIN font := Fonts.dir.Default(); iconFont := font.typeface;
linkLeft := "=>"; linkRight := "<=";
targetLeft := ">>"; targetRight := "<<";
coloredBackg := TRUE
END DefaultAppearance;
BEGIN
NEW(d); dir := d; stdDir := d;
IF (Dialog.platform = Dialog.windows) & ~ Dialog.isWine THEN
iconFont := "Wingdings";
font := Fonts.dir.This(iconFont, 10*Fonts.point (*arbitrary*), {}, Fonts.normal);
IF font.IsAlien() THEN DefaultAppearance
ELSE
(* high byte F0 required for Russian Windows versions *)
linkLeft := 0F0F6X; linkRight := 0F0F5X; (* "烶" "烵" *)
targetLeft := 0F0A4X; targetRight := 0F0A1X; (* "炤" "炡" *)
coloredBackg := FALSE
END
ELSE
DefaultAppearance
END;
NEW(cleaner);
dialog.close.SetResources("#Std:links")
END Init;
BEGIN
Init
END StdLinks.
| Std/Mod/Links.odc |
MODULE StdLoader;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20141027, center #19, adding 16-bit Unicode support for Component Pascal identifiers
"
issues = "
- ...
"
**)
IMPORT S := SYSTEM, Kernel, Files;
CONST
done = Kernel.done;
fileNotFound = Kernel.fileNotFound;
syntaxError = Kernel.syntaxError;
objNotFound = Kernel.objNotFound;
illegalFPrint = Kernel.illegalFPrint;
cyclicImport = Kernel.cyclicImport;
noMem = Kernel.noMem;
descNotFound = -1;
OFdir = "Code";
SYSdir = "System";
initMod = "Init";
OFtag = 6F4F4346H;
(* meta interface consts *)
mConst = 1; mTyp = 2; mVar = 3; mProc = 4; mField = 5;
mBool = 1; mChar = 2; mLChar = 3; mSInt = 4; mInt = 5; mLInt = 6;
mReal = 7; mLReal = 8; mSet = 9; mString = 10; mLString = 11;
mRecord = 1; mArray = 2; mPointer = 3; mProctyp = 4;
mInternal = 1; mReadonly = 2; mPrivate = 3; mExported = 4;
(* fixup types *)
absolute = 100; relative = 101; copy = 102; table = 103; tableend = 104; deref = 105; halfword = 106;
TYPE
Name = Kernel.Name;
ModSpec = POINTER TO RECORD
next, link, imp: ModSpec;
name: Name;
file: Files.File;
mod: Kernel.Module;
hs, ms, ds, cs, vs: INTEGER; (* headSize, metaSize, descSize, codeSize, dataSize *)
mad, dad: INTEGER (* modAdr, descAdr *)
END;
Hook = POINTER TO RECORD (Kernel.LoaderHook) END;
VAR
res-: INTEGER;
importing-, imported-, object-: Name;
inp: Files.Reader;
m: Kernel.Module;
PROCEDURE Error (r: INTEGER; impd, impg: ModSpec);
BEGIN
res := r; imported := impd.name$;
IF impg # NIL THEN importing := impg.name$ END;
END Error;
PROCEDURE Append (VAR s: ARRAY OF CHAR; t: ARRAY OF CHAR);
VAR len, i, j: INTEGER; ch: CHAR;
BEGIN
len := LEN(s);
i := 0; WHILE s[i] # 0X DO INC(i) END;
j := 0; REPEAT ch := t[j]; s[i] := ch; INC(j); INC(i) UNTIL (ch = 0X) OR (i = len);
s[len - 1] := 0X
END Append;
PROCEDURE IsUpper (ch: CHAR): BOOLEAN;
BEGIN
CASE ch OF
| 041X..05AX, 0C0X..0D6X, 0D8X..0DEX, 0178X..0179X, 0181X..0182X, 0186X..0187X, 0189X..018BX, 018EX..0191X, 0193X..0194X, 0196X..0198X, 019CX..019DX, 019FX..01A0X, 01A6X..01A7X, 01A9X, 01AEX..01AFX, 01B1X..01B3X, 01B7X..01B8X, 01BCX, 01C4X..01C5X, 01C7X..01C8X, 01CAX..01CBX, 01F1X..01F2X, 01F6X..01F8X, 023AX..023BX, 023DX..023EX, 0243X..0246X, 0376X, 037FX, 0388X..038AX, 038EX..038FX, 0391X..03A1X, 03A3X..03ABX, 03CFX, 03D2X..03D4X, 03F4X, 03F9X..03FAX, 03FDX..042FX, 04C0X..04C1X, 0531X..0556X, 010A0X..010C5X, 010C7X, 010CDX, 013A0X..013F5X, 01F08X..01F0FX, 01F18X..01F1DX, 01F28X..01F2FX, 01F38X..01F3FX, 01F48X..01F4DX, 01F68X..01F6FX, 01F88X..01F8FX, 01F98X..01F9FX, 01FA8X..01FAFX, 01FB8X..01FBCX, 01FC8X..01FCCX, 01FD8X..01FDBX, 01FE8X..01FECX, 01FF8X..01FFCX, 02102X, 02107X, 0210BX..0210DX, 02110X..02112X, 02115X, 02119X..0211DX, 0212AX..0212DX, 02130X..02133X, 0213EX..0213FX, 02145X, 02160X..0216FX, 02183X, 024B6X..024CFX, 02C00X..02C2EX, 02C62X..02C64X, 02C6DX..02C70X, 02C72X, 02C75X, 02C7EX..02C80X, 02CF2X, 0A77DX..0A77EX, 0A7AAX..0A7AEX, 0A7B0X..0A7B4X, 0A7B6X, 0FF21X..0FF3AX: RETURN TRUE
| 0100X..0137X, 014AX..0177X, 0184X..0185X, 01A2X..01A5X, 01ACX..01ADX, 01DEX..01EFX, 01F4X..01F5X, 01FAX..0233X, 0248X..024FX, 0370X..0373X, 0386X..0387X, 038CX..038DX, 03D8X..03EFX, 0460X..0481X, 048AX..04BFX, 04D0X..052FX, 01E00X..01E95X, 01E9EX..01EFFX, 02124X..02129X, 02C60X..02C61X, 02C82X..02CE3X, 0A640X..0A66DX, 0A680X..0A69BX, 0A722X..0A72FX, 0A732X..0A76FX, 0A780X..0A787X, 0A790X..0A793X, 0A796X..0A7A9X: RETURN ~ODD(ORD(ch))
| 0139X..0148X, 017BX..017EX, 01B5X..01B6X, 01CDX..01DCX, 0241X..0242X, 03F7X..03F8X, 04C3X..04CEX, 01F59X..01F60X, 02C67X..02C6CX, 02CEBX..02CEEX, 0A779X..0A77CX, 0A78BX..0A78EX: RETURN ODD(ORD(ch))
ELSE RETURN FALSE
END
END IsUpper;
PROCEDURE SplitName (IN name: ARRAY OF CHAR; VAR head, tail: ARRAY OF CHAR);
VAR i, j: INTEGER; ch, lch: CHAR;
BEGIN
i := 0; ch := name[0];
IF ch # 0X THEN
REPEAT
head[i] := ch; lch := ch; INC(i); ch := name[i]
UNTIL (ch = 0X) OR (ch = ".") OR IsUpper(ch) & ~IsUpper(lch);
IF ch = "." THEN i := 0; ch := name[0] END;
head[i] := 0X; j := 0;
WHILE ch # 0X DO tail[j] := ch; INC(i); INC(j); ch := name[i] END;
tail[j] := 0X;
IF tail = "" THEN tail := head$; head := "" END
ELSE head := ""; tail := ""
END
END SplitName;
PROCEDURE ThisObjFile (VAR name: ARRAY OF CHAR): Files.File;
VAR f: Files.File; loc: Files.Locator; dir, fname: Files.Name;
BEGIN
SplitName(name, dir, fname);
Files.dir.GetFileName(fname, Files.objType, fname);
loc := Files.dir.This(dir); loc := loc.This(OFdir);
f := Files.dir.Old(loc, fname, TRUE);
IF (f = NIL) & (dir = "") THEN
loc := Files.dir.This(SYSdir); loc := loc.This(OFdir);
f := Files.dir.Old(loc, fname, TRUE)
END;
RETURN f
END ThisObjFile;
PROCEDURE RWord (VAR x: INTEGER);
VAR b: BYTE; y: INTEGER;
BEGIN
inp.ReadByte(b); y := b MOD 256;
inp.ReadByte(b); y := y + 100H * (b MOD 256);
inp.ReadByte(b); y := y + 10000H * (b MOD 256);
inp.ReadByte(b); x := y + 1000000H * b
END RWord;
PROCEDURE RNum (VAR x: INTEGER);
VAR b: BYTE; s, y: INTEGER;
BEGIN
s := 0; y := 0; inp.ReadByte(b);
WHILE b < 0 DO INC(y, ASH(b + 128, s)); INC(s, 7); inp.ReadByte(b) END;
x := ASH((b + 64) MOD 128 - 64, s) + y
END RNum;
(* inline from module Utf to avoid import *)
PROCEDURE Utf8ToString (IN in: ARRAY OF SHORTCHAR; OUT out: ARRAY OF CHAR;
OUT res: INTEGER);
VAR i, j, val, max: INTEGER; ch: SHORTCHAR;
PROCEDURE FormatError();
BEGIN out := in$; res := 2 (*format error*)
END FormatError;
BEGIN
ch := in[0]; i := 1; j := 0; max := LEN(out) - 1;
WHILE (ch # 0X) & (j < max) DO
IF ch < 80X THEN
out[j] := ch; INC(j)
ELSIF ch < 0E0X THEN
val := ORD(ch) - 192;
IF val < 0 THEN FormatError; RETURN END ;
ch := in[i]; INC(i); val := val * 64 + ORD(ch) - 128;
IF (ch < 80X) OR (ch >= 0E0X) THEN FormatError; RETURN END ;
out[j] := CHR(val); INC(j)
ELSIF ch < 0F0X THEN
val := ORD(ch) - 224;
ch := in[i]; INC(i); val := val * 64 + ORD(ch) - 128;
IF (ch < 80X) OR (ch >= 0E0X) THEN FormatError; RETURN END ;
ch := in[i]; INC(i); val := val * 64 + ORD(ch) - 128;
IF (ch < 80X) OR (ch >= 0E0X) THEN FormatError; RETURN END ;
out[j] := CHR(val); INC(j)
ELSE
FormatError; RETURN
END ;
ch := in[i]; INC(i)
END;
out[j] := 0X;
IF ch = 0X THEN res := 0 (*ok*) ELSE res := 1 (*truncated*) END
END Utf8ToString;
PROCEDURE RName (VAR name: ARRAY OF CHAR);
VAR b: BYTE; i, n, res: INTEGER; s: Kernel.Utf8Name;
BEGIN
i := 0; n := LEN(name) - 1; inp.ReadByte(b);
WHILE (i < n) & (b # 0) DO s[i] := SHORT(CHR(b MOD 256)); INC(i); inp.ReadByte(b) END;
WHILE b # 0 DO inp.ReadByte(b) END;
s[i] := 0X;
Utf8ToString(s, name, res); ASSERT(res = 0)
END RName;
PROCEDURE Fixup (adr: INTEGER; mod: ModSpec);
VAR link, offset, linkadr, t, n, x, low, hi: INTEGER;
BEGIN
RNum(link);
WHILE link # 0 DO
RNum(offset);
WHILE link # 0 DO
IF link > 0 THEN linkadr := mod.mad + mod.ms + link
ELSE link := -link;
IF link < mod.ms THEN linkadr := mod.mad + link
ELSE linkadr := mod.dad + link - mod.ms
END
END;
S.GET(linkadr, x); t := x DIV 1000000H;
n := (x + 800000H) MOD 1000000H - 800000H;
IF t = absolute THEN x := adr + offset
ELSIF t = relative THEN x := adr + offset - linkadr - 4
ELSIF t = copy THEN S.GET(adr + offset, x)
ELSIF t = table THEN x := adr + n; n := link + 4
ELSIF t = tableend THEN x := adr + n; n := 0
ELSIF t = deref THEN S.GET(adr+2, x); INC(x, offset);
ELSIF t = halfword THEN
x := adr + offset;
low := (x + 8000H) MOD 10000H - 8000H;
hi := (x - low) DIV 10000H;
S.GET(linkadr + 4, x);
S.PUT(linkadr + 4, x DIV 10000H * 10000H + low MOD 10000H);
x := x * 10000H + hi MOD 10000H
ELSE Error(syntaxError, mod, NIL)
END;
S.PUT(linkadr, x); link := n
END;
RNum(link)
END
END Fixup;
PROCEDURE ReadHeader (mod: ModSpec);
VAR n, p: INTEGER; name: Name; imp, last: ModSpec;
BEGIN
mod.file := ThisObjFile(mod.name);
IF (mod.file = NIL) & (mod.link # NIL) THEN (* try closing importing obj file *)
mod.link.file.Close; mod.link.file := NIL;
mod.file := ThisObjFile(mod.name)
END;
IF mod.file # NIL THEN
inp := mod.file.NewReader(inp);
IF inp # NIL THEN
inp.SetPos(0); RWord(n); RWord(p);
IF (n = OFtag) & (p = Kernel.processor) THEN
RWord(mod.hs); RWord(mod.ms); RWord(mod.ds); RWord(mod.cs); RWord(mod.vs);
RNum(n); RName(name);
IF name = mod.name THEN
mod.imp := NIL; last := NIL;
WHILE n > 0 DO
NEW(imp); RName(imp.name);
IF last = NIL THEN mod.imp := imp ELSE last.next := imp END;
last := imp; imp.next := NIL; DEC(n)
END
ELSE Error(fileNotFound, mod, NIL)
END
ELSE Error(syntaxError, mod, NIL)
END
ELSE Error(noMem, mod, NIL)
END
ELSE Error(fileNotFound, mod, NIL)
END
END ReadHeader;
PROCEDURE ReadModule (mod: ModSpec);
TYPE BlockPtr = POINTER TO ARRAY [untagged] 1000000H OF BYTE;
VAR imptab, x, fp, ofp, opt, a: INTEGER;
name: Name; dp, mp: BlockPtr; imp: ModSpec; obj: Kernel.Object;
BEGIN
IF mod.file = NIL THEN mod.file := ThisObjFile(mod.name) END;
inp := mod.file.NewReader(inp);
IF inp # NIL THEN
inp.SetPos(mod.hs);
Kernel.AllocModMem(mod.ds, mod.ms + mod.cs + mod.vs, mod.dad, mod.mad);
IF (mod.dad # 0) & (mod.mad # 0) THEN
dp := S.VAL(BlockPtr, mod.dad); mp := S.VAL(BlockPtr, mod.mad);
inp.ReadBytes(mp^, 0, mod.ms);
inp.ReadBytes(dp^, 0, mod.ds);
inp.ReadBytes(mp^, mod.ms, mod.cs);
mod.mod := S.VAL(Kernel.Module, mod.dad);
Fixup(S.ADR(Kernel.NewRec), mod);
Fixup(S.ADR(Kernel.NewArr), mod);
Fixup(mod.mad, mod);
Fixup(mod.dad, mod);
Fixup(mod.mad + mod.ms, mod);
Fixup(mod.mad + mod.ms + mod.cs, mod);
imp := mod.imp; imptab := S.VAL(INTEGER, mod.mod.imports);
WHILE (res = done) & (imp # NIL) DO
RNum(x);
WHILE (res <= done) & (x # 0) DO
RName(name); RNum(fp); opt := 0;
IF imp.mod # NIL THEN
IF name = "" THEN obj := Kernel.ThisDesc(imp.mod, fp)
ELSE
obj := Kernel.ThisObject(imp.mod, name)
END;
IF (obj # NIL) & (obj.id MOD 16 = x) THEN
ofp := obj.fprint;
IF x = mTyp THEN
RNum(opt);
IF ODD(opt) THEN ofp := obj.offs END;
IF (opt > 1) & (obj.id DIV 16 MOD 16 # mExported) THEN
Error(objNotFound, imp, mod); object := name$
END;
Fixup(S.VAL(INTEGER, obj.struct), mod)
ELSIF x = mVar THEN
Fixup(imp.mod.varBase + obj.offs, mod)
ELSIF x = mProc THEN
Fixup(imp.mod.procBase + obj.offs, mod)
END;
IF ofp # fp THEN Error(illegalFPrint, imp, mod); object := name$ END
ELSIF name # "" THEN
Error(objNotFound, imp, mod); object := name$
ELSE
Error(descNotFound, imp, mod); (* proceed to find failing named object *)
RNum(opt); Fixup(0, mod)
END
ELSE (* imp is dll *)
IF x IN {mVar, mProc} THEN
a := Kernel.ThisDllObj(x, fp, imp.name, name);
IF a # 0 THEN Fixup(a, mod)
ELSE Error(objNotFound, imp, mod); object := name$
END
ELSIF x = mTyp THEN
RNum(opt); RNum(x);
IF x # 0 THEN Error(objNotFound, imp, mod); object := name$ END
END
END;
RNum(x)
END;
S.PUT(imptab, imp.mod); INC(imptab, 4); imp := imp.next
END;
IF res # done THEN
Kernel.DeallocModMem(mod.ds, mod.ms + mod.cs + mod.vs, mod.dad, mod.mad); mod.mod := NIL
END
ELSE Error(noMem, mod, NIL)
END
ELSE Error(noMem, mod, NIL)
END;
mod.file.Close; mod.file := NIL
END ReadModule;
PROCEDURE LoadMod (mod: ModSpec);
VAR i: ModSpec; ok: BOOLEAN; j: INTEGER;
BEGIN
importing := ""; imported := ""; object := ""; i := mod;
WHILE (i.link # NIL) & (i.link.name # mod.name) DO i := i.link END;
IF i.link = NIL THEN ReadHeader(mod)
ELSE Error(cyclicImport, i, i.link)
END;
i := mod.imp;
WHILE (res = done) & (i # NIL) DO (* get imported module *)
IF i.name = "$$" THEN i.name := "Kernel" END;
IF i.name[0] = "$" THEN (* dll *)
j := 1;
WHILE i.name[j] # 0X DO i.name[j - 1] := i.name[j]; INC(j) END;
i.name[j - 1] := 0X;
Kernel.LoadDll(i.name, ok);
IF ~ok THEN Error(fileNotFound, i, NIL) END
ELSE
i.mod := Kernel.ThisLoadedMod(i.name); (* loaded module *)
IF i.mod = NIL THEN i.link := mod; LoadMod(i) END (* new module *)
END;
i := i.next
END;
IF res = done THEN
mod.mod := Kernel.ThisLoadedMod(mod.name); (* guaranties uniqueness *)
IF mod.mod = NIL THEN
ReadModule(mod);
IF res = done THEN
Kernel.RegisterMod(mod.mod);
res := done
END
END
END;
IF res = descNotFound THEN res := objNotFound; object := "<TypeDesc>" END;
IF object # "" THEN Append(imported, "."); Append(imported, object); object := "" END
END LoadMod;
PROCEDURE (h: Hook) ThisMod (IN name: ARRAY OF CHAR): Kernel.Module;
VAR m: Kernel.Module; ms: ModSpec;
BEGIN
res := done;
m := Kernel.ThisLoadedMod(name);
IF m = NIL THEN
NEW(ms); ms.link := NIL; ms.name := name$;
LoadMod(ms);
m := ms.mod;
inp := NIL (* free last file *)
END;
h.res := res;
h.importing := importing$;
h.imported := imported$;
h.object := object$;
RETURN m
END ThisMod;
PROCEDURE Init;
VAR h: Hook;
BEGIN
NEW(h); Kernel.SetLoaderHook(h)
END Init;
BEGIN
Init;
(*
m := Kernel.ThisMod("Init");
IF res # 0 THEN
CASE res OF
| fileNotFound: Append(imported, ": code file not found")
| syntaxError: Append(imported, ": corrupted code file")
| objNotFound: Append(imported, " not found")
| illegalFPrint: Append(imported, ": wrong fingerprint")
| cyclicImport: Append(imported, ": cyclic import")
| noMem: Append(imported, ": not enough memory")
ELSE Append(imported, ": loader error")
END;
IF res IN {objNotFound, illegalFPrint, cyclicImport} THEN
Append(imported, " (imported from "); Append(imported, importing); Append(imported, ")")
END;
Kernel.FatalError(res, imported)
END
*)
END StdLoader.
| Std/Mod/Loader.odc |
MODULE StdLog;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20160408, center #111, code cleanups
- 20210225, dia, reduce HostDialog dependency
"
issues = "
- ...
"
**)
IMPORT
Log, Fonts, Ports, Stores, Models, Views, Dialog, StdDialog,
TextModels, TextMappers, TextRulers, TextViews, TextControllers;
CONST
(** IntForm base **)
charCode* = TextMappers.charCode; decimal* = TextMappers.decimal; hexadecimal* = TextMappers.hexadecimal;
(** IntForm showBase **)
hideBase* = TextMappers.hideBase; showBase* = TextMappers.showBase;
mm = Ports.mm;
TYPE
ShowHook = POINTER TO RECORD (Dialog.ShowHook) END;
LogHook = POINTER TO RECORD (Log.Hook) END;
VAR
logAlerts: BOOLEAN;
text-, buf-: TextModels.Model;
defruler-: TextRulers.Ruler;
dir-: TextViews.Directory;
out, subOut: TextMappers.Formatter;
showHook: ShowHook;
PROCEDURE Flush;
BEGIN
text.Append(buf); Views.RestoreDomain(text.Domain())
END Flush;
PROCEDURE Char* (ch: CHAR);
BEGIN
out.WriteChar(ch); Flush
END Char;
PROCEDURE Int* (i: LONGINT);
BEGIN
out.WriteChar(" "); out.WriteInt(i); Flush
END Int;
PROCEDURE Real* (x: REAL);
BEGIN
out.WriteChar(" "); out.WriteReal(x); Flush
END Real;
PROCEDURE String* (IN str: ARRAY OF CHAR);
BEGIN
out.WriteString(str); Flush
END String;
PROCEDURE Bool* (x: BOOLEAN);
BEGIN
out.WriteChar(" "); out.WriteBool(x); Flush
END Bool;
PROCEDURE Set* (x: SET);
BEGIN
out.WriteChar(" "); out.WriteSet(x); Flush
END Set;
PROCEDURE IntForm* (x: LONGINT; base, minWidth: INTEGER; fillCh: CHAR; showBase: BOOLEAN);
BEGIN
out.WriteIntForm(x, base, minWidth, fillCh, showBase); Flush
END IntForm;
PROCEDURE RealForm* (x: REAL; precision, minW, expW: INTEGER; fillCh: CHAR);
BEGIN
out.WriteRealForm(x, precision, minW, expW, fillCh); Flush
END RealForm;
PROCEDURE Tab*;
BEGIN
out.WriteTab; Flush
END Tab;
PROCEDURE Ln*;
BEGIN
out.WriteLn; Flush;
TextViews.ShowRange(text, text.Length(), text.Length(), TextViews.any)
END Ln;
PROCEDURE Para*;
BEGIN
out.WritePara; Flush;
TextViews.ShowRange(text, text.Length(), text.Length(), TextViews.any)
END Para;
PROCEDURE View* (v: Views.View);
BEGIN
out.WriteView(v); Flush
END View;
PROCEDURE ViewForm* (v: Views.View; w, h: INTEGER);
BEGIN
out.WriteViewForm(v, w, h); Flush
END ViewForm;
PROCEDURE ParamMsg* (IN msg, p0, p1, p2: ARRAY OF CHAR);
BEGIN
out.WriteParamMsg(msg, p0, p1, p2); Flush
END ParamMsg;
PROCEDURE Msg* (IN msg: ARRAY OF CHAR);
BEGIN
out.WriteMsg(msg); Flush
END Msg;
PROCEDURE^ Open*;
PROCEDURE (hook: ShowHook) ShowParamMsg (IN s, p0, p1, p2: ARRAY OF CHAR);
BEGIN
(*IF Dialog.showsStatus THEN
Dialog.ShowParamStatus(s, p0, p1, p2);
IF logAlerts THEN
ParamMsg(s, p0, p1, p2); Ln
END
ELSE*)
IF logAlerts THEN
Open;
ParamMsg(s, p0, p1, p2); Ln
ELSE
IF ~(Dialog.defShowHook IS ShowHook) THEN
Dialog.defShowHook.ShowParamMsg(s, p0, p1, p2)
END
END
(*END*)
END ShowParamMsg;
PROCEDURE (hook: ShowHook) ShowParamStatus (IN s, p0, p1, p2: ARRAY OF CHAR);
BEGIN
IF ~(Dialog.defShowHook IS ShowHook) THEN
Dialog.defShowHook.ShowParamStatus(s, p0, p1, p2)
END
END ShowParamStatus;
PROCEDURE NewView* (): TextViews.View;
VAR v: TextViews.View;
BEGIN
Flush;
Dialog.SetShowHook(showHook); (* attach alert dialogs *)
v := dir.New(text);
v.SetDefaults(TextRulers.CopyOf(defruler, Views.deep), dir.defAttr);
RETURN v
END NewView;
PROCEDURE New*;
BEGIN
Views.Deposit(NewView())
END New;
PROCEDURE SetDefaultRuler* (ruler: TextRulers.Ruler);
BEGIN
defruler := ruler
END SetDefaultRuler;
PROCEDURE SetDir* (d: TextViews.Directory);
BEGIN
ASSERT(d # NIL, 20); dir := d
END SetDir;
PROCEDURE Open*;
VAR v: Views.View; pos: INTEGER;
BEGIN
v := NewView();
StdDialog.Open(v, "#Dev:Log", NIL, "", NIL, FALSE, TRUE, FALSE, FALSE, TRUE);
Views.RestoreDomain(text.Domain());
pos := text.Length();
TextViews.ShowRange(text, pos, pos, TextViews.any);
TextControllers.SetCaret(text, pos)
END Open;
PROCEDURE Clear*;
BEGIN
Models.BeginModification(Models.notUndoable, text);
text.Delete(0, text.Length());
buf.Delete(0, buf.Length());
Models.EndModification(Models.notUndoable, text)
END Clear;
(* Sub support *)
PROCEDURE Guard (o: ANYPTR): BOOLEAN;
BEGIN
RETURN
(o # NIL) &
~( (o IS TextModels.Model) & (o = text)
OR (o IS Stores.Domain) & (o = text.Domain())
OR (o IS TextViews.View) & (o(TextViews.View).ThisModel() = text)
)
END Guard;
PROCEDURE ClearBuf;
VAR subBuf: TextModels.Model;
BEGIN
subBuf := subOut.rider.Base(); subBuf.Delete(0, subBuf.Length())
END ClearBuf;
PROCEDURE FlushBuf;
VAR buf: TextModels.Model;
BEGIN
buf := subOut.rider.Base();
IF buf.Length() > 0 THEN
IF ~Log.synch THEN Open() END;
text.Append(buf)
END
END FlushBuf;
PROCEDURE SubFlush;
BEGIN
IF Log.synch THEN
FlushBuf;
IF Log.force THEN Views.RestoreDomain(text.Domain()) END
END;
END SubFlush;
PROCEDURE (log: LogHook) Guard* (o: ANYPTR): BOOLEAN;
BEGIN RETURN Guard(o)
END Guard;
PROCEDURE (log: LogHook) ClearBuf*;
BEGIN ClearBuf
END ClearBuf;
PROCEDURE (log: LogHook) FlushBuf*;
BEGIN FlushBuf
END FlushBuf;
PROCEDURE (log: LogHook) Beep*;
BEGIN Dialog.Beep
END Beep;
PROCEDURE (log: LogHook) Char* (ch: CHAR);
BEGIN
subOut.WriteChar(ch); SubFlush
END Char;
PROCEDURE (log: LogHook) Int* (n: LONGINT);
BEGIN
subOut.WriteChar(" "); subOut.WriteInt(n); SubFlush
END Int;
PROCEDURE (log: LogHook) Real* (x: REAL);
BEGIN
subOut.WriteChar(" "); subOut.WriteReal(x); SubFlush
END Real;
PROCEDURE (log: LogHook) String* (IN str: ARRAY OF CHAR);
BEGIN
subOut.WriteString(str); SubFlush
END String;
PROCEDURE (log: LogHook) Bool* (x: BOOLEAN);
BEGIN
subOut.WriteChar(" "); subOut.WriteBool(x); SubFlush
END Bool;
PROCEDURE (log: LogHook) Set* (x: SET);
BEGIN
subOut.WriteChar(" "); subOut.WriteSet(x); SubFlush
END Set;
PROCEDURE (log: LogHook) IntForm* (x: LONGINT; base, minWidth: INTEGER; fillCh: CHAR; showBase: BOOLEAN);
BEGIN
subOut.WriteIntForm(x, base, minWidth, fillCh, showBase); SubFlush
END IntForm;
PROCEDURE (log: LogHook) RealForm* (x: REAL; precision, minW, expW: INTEGER; fillCh: CHAR);
BEGIN
subOut.WriteRealForm(x, precision, minW, expW, fillCh); SubFlush
END RealForm;
PROCEDURE (log: LogHook) Tab*;
BEGIN
subOut.WriteTab; SubFlush
END Tab;
PROCEDURE (log: LogHook) Ln*;
BEGIN
subOut.WriteLn; SubFlush;
IF Log.synch THEN Views.RestoreDomain(text.Domain()) END
END Ln;
PROCEDURE (log: LogHook) Para*;
BEGIN
subOut.WritePara; SubFlush;
IF Log.synch THEN Views.RestoreDomain(text.Domain()) END
END Para;
PROCEDURE (log: LogHook) View* (v: ANYPTR);
BEGIN
IF (v # NIL) & (v IS Views.View) THEN
subOut.WriteView(v(Views.View)); SubFlush
END
END View;
PROCEDURE (log: LogHook) ViewForm* (v: ANYPTR; w, h: INTEGER);
BEGIN
ASSERT(v # NIL, 20);
IF (v # NIL) & (v IS Views.View) THEN
subOut.WriteViewForm(v(Views.View), w, h); SubFlush
END
END ViewForm;
PROCEDURE (log: LogHook) ParamMsg* (IN s, p0, p1, p2: ARRAY OF CHAR);
VAR msg: ARRAY 256 OF CHAR; i: INTEGER; ch: CHAR;
BEGIN
IF logAlerts THEN
IF Log.synch THEN Open END;
Dialog.MapParamString(s, p0, p1, p2, msg);
i := 0; ch := msg[0];
WHILE ch # 0X DO
IF ch = TextModels.line THEN subOut.WriteLn
ELSIF ch = TextModels.para THEN subOut.WritePara
ELSIF ch = TextModels.tab THEN subOut.WriteTab
ELSIF ch >= " " THEN subOut.WriteChar(ch)
END;
INC(i); ch := msg[i];
END;
subOut.WriteLn; SubFlush
ELSE
Dialog.defShowHook.ShowParamMsg(s, p0, p1, p2)
END
END ParamMsg;
PROCEDURE AttachSubLog;
VAR h: LogHook;
BEGIN
subOut.ConnectTo(TextModels.dir.New());
NEW(h);
Log.SetHook(h);
END AttachSubLog;
PROCEDURE DetachSubLog;
BEGIN
Log.SetHook(NIL);
END DetachSubLog;
PROCEDURE Init;
VAR font: Fonts.Font; p: TextRulers.Prop; x: INTEGER; i: INTEGER;
BEGIN
logAlerts := TRUE; (* logReports := FALSE; *)
text := TextModels.dir.New();
buf := TextModels.CloneOf(text);
out.ConnectTo(buf);
font := TextModels.dir.attr.font;
defruler := TextRulers.dir.New(NIL);
TextRulers.SetRight(defruler, 80*mm);
dir := TextViews.dir;
NEW(showHook)
END Init;
BEGIN
Init; AttachSubLog
CLOSE
DetachSubLog;
END StdLog.
| Std/Mod/Log.odc |
MODULE StdMenus;
(**
project = "BlackBox 2.0"
organizations = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Contributors, Anton Dmitriev, Ivan Denisov"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
-
"
issues = "
-
"
**)
IMPORT
Kernel, Views, Models, Ports, Controllers, Properties, Fonts, Dialog, Services, Stores,
StdCFrames, StdDialog, StdMenuTool, Containers, StdDocuments, Strings;
CONST
version = 0;
hidden* = "-"; (* items with this label are not shown in the menu *)
mm = Ports.mm;
(* Safe actions *)
guardA = 1; executeA = 2;
(* Item status *)
itTrappedDbg = 0; itFailedDbg = 1; itTrapped = 2; itFailed = 3;
itHidden = 4; itSeparator = 5; itRelabelled = 6; itDefault = 7;
(* key codes *)
ENTER = 0DX; ESC = 1BX;
DL = 14X; DR = 15X; (* DU = 16X; DD = 17X; *)
AL = 1CX; AR = 1DX; AU = 1EX; AD = 1FX;
(* MainMenuUpdateMsg.what *)
menuUpdate = 0; targetTypeNameChange = 1;
cleanup = 100; (** cf. VAR executions *)
allocKey = "#Std:AllocatedMemory";
totalKey = "#Std:Total";
byteKey = "#Std:Bytes";
actionsKey = "#Std:ActionsInTheQueue";
useSeparators = TRUE;
TYPE
Item = POINTER TO RECORD (StdDialog.Item)
par: Dialog.Par;
failed, trapped: BOOLEAN; (* Guard failed (# trapped) *)
code: INTEGER; (* shortcut key code, may be host-specific *)
mod: SET; (* shortcut modifiers *)
END;
Model = POINTER TO RECORD
first: Item;
label: Dialog.String;
typeName: Stores.TypeName;
link: Model;
era: INTEGER
END;
View = POINTER TO RECORD (Views.View)
paramEra: INTEGER; (* synch with Param *)
menu: Model;
main: LineView;
focus: Item; (* focused item, may be NIL *)
era: INTEGER; (* (.menu.era = .era) = view synchronized with .menu *)
link: View;
cache: RECORD wid, hei: INTEGER END;
END;
LineView = POINTER TO RECORD (Views.View)
main: Model;
first, active, dropped: View;
removed: LONGINT;
focussed: BOOLEAN; (* because the main menu never lies on the front path, the frames it is displayed in never have .front sent. So, when the main menu becomes focussed/defocussed, it has to remember this fact. This is done with .focussed and in handling of Controllers.MarkMsg *)
END;
SafeAction = RECORD (Services.SafeAction)
what: INTEGER;
item: Item
END;
Param* = POINTER TO RECORD
typeface*: Fonts.Typeface;
size*: INTEGER;
check*: ARRAY 2 OF CHAR;
font: Fonts.Font;
itemH, separH, checkW, asc, dsc,
margin, (* margin between label and menu item boundary *)
initX (* init horizontal position to start draw of line menu *)
: INTEGER;
color*, colorLine*, bgColor*, bgColorLine*,
disabledColor*, focusColorLine*, shortcutColor*,
focusColor*, focusBg*, focusBgLine*,
statusBg*, statusColor*: Ports.Color;
debug*: BOOLEAN;
era: INTEGER;
Init-, InitDefaults-: PROCEDURE (p: ANYPTR)
END;
Directory = POINTER TO RECORD (StdMenuTool.Directory)
main, this: Model;
last: Item;
END;
ControlledTrackMsg = RECORD (Controllers.CursorMessage) END;
MainMenuUpdateMsg = RECORD (Views.Message)
what: INTEGER
END;
DropMenuMsg = RECORD (Views.Message) END;
(** Asks LineView to drop menu for dropReq.menu *)
Actor = POINTER TO RECORD (Services.Action) END;
StatusBarUpdater = POINTER TO RECORD (Services.Action)
bar: StatusBar;
END;
StatusBar = POINTER TO RECORD (Views.View)
updater: StatusBarUpdater;
END;
VAR
dir: Directory;
status-: ARRAY 256 OF CHAR;
param*: Param;
updateStatusBar: BOOLEAN;
metrics: RECORD
alloc, used: INTEGER
END;
metricsStr, allocStr, totalStr, byteStr, actionsStr: ARRAY 128 OF CHAR;
trappedLbl, failedLbl: ARRAY 32 OF CHAR;
main: Model;
targetTypeName: Stores.TypeName;
actor: Actor;
executions: INTEGER; (** menu item execution counter to do Kernel.Cleanup every cleanup executions *)
dropReq: RECORD (* for handling Alt+CHAR menu activation requests *)
item: Item; (* 'orphaned' item used to drop a main menu when Alt+CHAR is pressed *)
menu: Model; (* main menu that is to be dropped *)
END;
executeItem: Item;
PROCEDURE Hidden (m: Model): BOOLEAN;
BEGIN RETURN (m.label = '*') OR (m.typeName # '') & (m.typeName # targetTypeName)
END Hidden;
PROCEDURE NextShownModel (m: Model): Model;
BEGIN WHILE (m # NIL) & Hidden(m) DO m := m.link END; RETURN m
END NextShownModel;
PROCEDURE (h: Directory) FirstMatch* (VAR m: StdMenuTool.ShortcutMatcher): StdDialog.Item;
VAR n: Model; it: Item; i: INTEGER; ch: CHAR;
BEGIN
n := NextShownModel(main); it := n.first;
WHILE (it # NIL) & ~m.Match(it, it.code, it.mod) DO
IF it.next # NIL THEN it := it.next(Item)
ELSIF n # NIL THEN
n := NextShownModel(n.link); IF n # NIL THEN it := n.first ELSE it := NIL END
ELSE it := NIL
END
END;
IF (it = NIL) THEN
n := NextShownModel(main);
REPEAT
i := -1; REPEAT INC(i); ch := n.label[i] UNTIL (ch = '&') OR (ch = 0X);
IF ch = '&' THEN ch := n.label[i + 1] END;
IF m.Match(NIL, ORD(ch), { Controllers.pick }) THEN
it := dropReq.item; dropReq.menu := n
END;
n := NextShownModel(n.link)
UNTIL (it # NIL) OR (n = NIL)
END;
RETURN it
END FirstMatch;
PROCEDURE (VAR a: SafeAction) Do;
VAR failed_, ok: BOOLEAN;
BEGIN
ASSERT(a.item # NIL, 20);
IF a.what = guardA THEN
StdDialog.CheckFilter(a.item, failed_, ok, a.item.par);
a.item.failed := ~ok
ELSIF a.what = executeA THEN
StdDialog.HandleItem(a.item)
ELSE
HALT(21)
END
END Do;
PROCEDURE Prepare (v: View);
VAR it: Item; guard: SafeAction; m: Model;
BEGIN
m := v.menu; guard.what := guardA;
it := m.first; WHILE it # NIL DO
IF it.item^ # '' THEN
IF it.filter^ # "" THEN
guard.item := it;
IF param.debug THEN
StdDialog.ClearGuards(it); Services.Try(guard); it.trapped := guard.trapped
ELSIF ~it.trapped & ~it.failed THEN
Services.Try(guard); it.trapped := guard.trapped
END;
IF ~it.trapped & ~it.failed & (it.par.label # "-") & (it.par.label # it.item^) THEN
Dialog.MapString(it.par.label, it.par.label)
END
END
END;
IF it.next = NIL THEN it := NIL ELSE it := it.next(Item) END
END;
INC(m.era)
END Prepare;
(* View *)
PROCEDURE ItemStatus (it: Item): INTEGER;
VAR res: INTEGER;
BEGIN
IF param.debug & it.trapped THEN res := itTrappedDbg
ELSIF param.debug & it.failed THEN res := itFailedDbg
ELSIF it.trapped THEN res := itTrapped
ELSIF it.failed THEN res := itFailed
ELSIF it.par.label = hidden THEN res := itHidden
ELSIF it.item^ = '' THEN res := itSeparator
ELSIF it.par.label # '' THEN res := itRelabelled
ELSE res := itDefault
END;
RETURN res
END ItemStatus;
PROCEDURE LabelWidth (lbl: ARRAY OF CHAR; fnt: Fonts.Font): INTEGER;
VAR amp, i: INTEGER; under: ARRAY 2 OF CHAR; ch: CHAR;
BEGIN
i := -1; REPEAT INC(i); ch := lbl[i] UNTIL (ch = '&') OR (ch = 0X);
IF ch = '&' THEN
amp := i; REPEAT INC(i); ch := lbl[i]; lbl[i - 1] := ch UNTIL ch = 0X
ELSE amp := -1
END;
RETURN fnt.StringWidth(lbl)
END LabelWidth;
PROCEDURE PrepareLabelAnsShortcut (it: Item; OUT label, shortcut: ARRAY OF CHAR);
VAR str: ARRAY 64 OF CHAR; i, j, len: INTEGER;
BEGIN
str := it.shortcut$;
label := it.par.label$;
IF str[0] = 0X THEN
i:=0; len := LEN(label$);
WHILE (i < len) & (label[i] # 09X) DO
INC(i)
END;
IF label[i] = 09X THEN
j := 0;
label[i] := 0X;
INC(i);
WHILE i < len DO
shortcut[j] := label[i];
INC(i); INC(j)
END;
shortcut[j] := 0X;
ELSE
shortcut := ""
END
ELSIF (str[0] # "F") & (str[0] # "*") THEN
IF str$ = " " THEN str := "Space" END;
shortcut := "Ctrl+" + str$;
ELSIF str[0] = "*" THEN
shortcut := "Ctrl+Shift" + str$;
shortcut[10] := "+";
ELSE
shortcut := str$
END;
END PrepareLabelAnsShortcut;
PROCEDURE Bounds (v: View; OUT w, h: INTEGER);
VAR it: Item; m: Model; label, shortcut: ARRAY 64 OF CHAR;
items, separators, lw, kw: INTEGER; (* max label width and key width *)
BEGIN
m := v.menu;
IF (param.era # v.paramEra) OR (m.era # v.era) THEN
v.era := m.era;
lw := 0; kw := 0; items := 0; separators := 0;
it := m.first;
WHILE it # NIL DO (* optimize! *)
CASE ItemStatus(it) OF
| itTrappedDbg:
lw := MAX(lw, param.font.StringWidth(trappedLbl));
INC(items)
| itFailedDbg:
lw := MAX(lw, param.font.StringWidth(failedLbl));
INC(items)
| itHidden:
| itSeparator:
INC(separators)
| itRelabelled:
PrepareLabelAnsShortcut(it, label, shortcut);
INC(items);
lw := MAX(lw, LabelWidth(label, param.font));
kw := MAX(kw, LabelWidth(shortcut, param.font))
| itDefault, itTrapped, itFailed:
PrepareLabelAnsShortcut(it, label, shortcut);
INC(items);
lw := MAX(lw, LabelWidth(it.item^, param.font));
kw := MAX(kw, LabelWidth(shortcut, param.font))
END;
IF it.next = NIL THEN it := NIL ELSE it := it.next(Item) END
END;
w := 8 * Ports.mm + param.checkW + lw + kw;
h := items * param.itemH + separators * param.separH;
v.cache.wid := w; v.cache.hei := h
ELSE w := v.cache.wid; h := v.cache.hei
END
END Bounds;
PROCEDURE (m: View) GetBackground (VAR color: Ports.Color);
BEGIN color := param.bgColor
END GetBackground;
PROCEDURE ItemHeight (v: View; it: Item): INTEGER;
VAR res: INTEGER;
BEGIN (* v is passed as a provision for if Views will have distinct Params *)
IF it.item^ = "" THEN res := param.separH
ELSIF it.par.label = hidden THEN res := 0
ELSE res := param.itemH
END;
RETURN res
END ItemHeight;
PROCEDURE DrawLabel (f: Views.Frame; x, y: INTEGER; col: Ports.Color; lbl: ARRAY OF CHAR; fnt: Fonts.Font);
VAR amp, i: INTEGER; under: ARRAY 2 OF CHAR; ch: CHAR;
BEGIN
i := -1; REPEAT INC(i); ch := lbl[i] UNTIL (ch = '&') OR (ch = 0X);
IF ch = '&' THEN
amp := i; REPEAT INC(i); ch := lbl[i]; lbl[i - 1] := ch UNTIL ch = 0X
ELSE amp := -1
END;
f.DrawString(x, y, col, lbl, fnt);
IF amp # -1 THEN
under[0] := lbl[amp]; under[1] := 0X;
lbl[amp] := 0X;
INC(x, fnt.StringWidth(lbl));
f.DrawLine(x, y+f.dot, x + fnt.StringWidth(under), y+f.dot, f.dot, col)
END
END DrawLabel;
PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER); (* vertical menu *)
VAR it: Item; status, col, wid, hei, x, y: INTEGER;
label, shortcut: ARRAY 64 OF CHAR;
BEGIN
IF v.era # v.menu.era THEN Bounds(v, x, y) END;
v.context.GetSize(wid, hei);
y := 0; x := 3 * mm + param.checkW;
it := v.menu.first; WHILE it # NIL DO
status := ItemStatus(it);
IF ~it.par.disabled & ~(status IN { itSeparator, itHidden, itTrappedDbg, itFailedDbg, itTrapped, itFailed }) & (it = v.focus) THEN
f.DrawRect(l, y, r, y + ItemHeight(v, it), Ports.fill, param.focusBg)
END;
INC(y, mm + param.asc);
IF (status IN { itTrappedDbg, itFailedDbg, itTrapped, itFailed }) OR it.par.disabled THEN
col := param.disabledColor
ELSIF it = v.focus THEN
col := param.focusColor
ELSE
col := param.color
END;
CASE status OF
| itTrappedDbg:
f.DrawString(x, y, param.disabledColor, trappedLbl, param.font);
| itFailedDbg:
f.DrawString(x, y, param.disabledColor, failedLbl, param.font)
| itHidden:
DEC(y, mm + param.asc)
| itSeparator:
INC(y, - mm - param.asc + param.separH DIV 2);
f.DrawRect(0, y, wid, y + f.dot, Ports.fill, Ports.grey50);
INC(y, param.separH DIV 2)
| itTrapped, itFailed, itRelabelled, itDefault:
PrepareLabelAnsShortcut(it, label, shortcut);
IF it.par.checked THEN
f.DrawString(2 * mm, y, col, param.check, param.font)
END;
IF status = itRelabelled THEN
DrawLabel(f, x, y, col, label, param.font)
ELSE
DrawLabel(f, x, y, col, it.item, param.font)
END;
f.DrawString(wid - 2 * mm - param.font.StringWidth(shortcut),
y, param.shortcutColor, shortcut, param.font);
ELSE HALT(20)
END;
IF status IN { itTrappedDbg, itFailedDbg, itTrapped, itFailed, itRelabelled, itDefault } THEN
INC(y, param.dsc + mm)
END;
IF it.next = NIL THEN it := NIL ELSE it := it.next(Item) END
END
END Restore;
PROCEDURE ThisDropPos (v: LineView; drop: View; OUT x, y: INTEGER);
VAR d: View;
BEGIN
x := param.initX;
d := v.first;
WHILE (d # NIL) & (d # drop) DO
IF ~Hidden(d.menu) THEN
INC(x, param.margin * 2 + LabelWidth(d.menu.label, param.font))
END;
d := d.link
END;
y := param.asc + param.dsc + 2 * mm
END ThisDropPos;
PROCEDURE ShowDropIn (ctx: Models.Context; x, y: INTEGER; drop: View; owner, revalidate: Views.View);
VAR p: StdDocuments.OverlayProposal;
BEGIN
Controllers.SetCurrentPath(Controllers.frontPath);
Prepare(drop);
IF (revalidate # NIL) & Views.IsInvalid(revalidate) THEN
Views.RevalidateView(revalidate)
END;
p.x := x; p.y := y; p.op := StdDocuments.show; p.view := drop; p.owner := owner;
ctx.Consider(p);
Controllers.ResetCurrentPath
END ShowDropIn;
PROCEDURE ShowDrop (v: LineView; drop: View; revalidate: Views.View);
VAR x, y: INTEGER;
BEGIN
ThisDropPos(v, drop, x, y);
ShowDropIn(v.context, x, y, drop, v, revalidate);
v.dropped := drop
END ShowDrop;
PROCEDURE HideDrop (v: View);
VAR p: StdDocuments.OverlayProposal;
BEGIN
p.op := StdDocuments.hide;
v.context.Consider(p);
IF v.main # NIL THEN v.main.dropped := NIL END
END HideDrop;
PROCEDURE DoExecute (it: Item; OUT trapped: BOOLEAN);
VAR execute: SafeAction;
BEGIN
Controllers.SetCurrentPath(Controllers.frontPath);
execute.what := executeA;
execute.item := it;
Services.Try(execute);
trapped := execute.trapped;
Controllers.ResetCurrentPath;
INC(executions);
IF executions > cleanup THEN
executions := 0;
Kernel.Cleanup
END
END DoExecute;
PROCEDURE (h: Directory) Execute* (it: StdDialog.Item);
VAR trapped_: BOOLEAN;
BEGIN WITH it: Item DO DoExecute(it, trapped_) ELSE HALT(20) END
END Execute;
PROCEDURE ExecActive (v: View);
CONST bad = { itTrapped, itTrappedDbg, itFailed, itFailedDbg, itSeparator, itHidden };
VAR p: StdDocuments.OverlayProposal; trapped: BOOLEAN;
BEGIN
IF (v.focus # NIL) & ~(ItemStatus(v.focus) IN bad) & ~v.focus.par.disabled THEN
HideDrop(v);
executeItem := v.focus
END
END ExecActive;
PROCEDURE ItemAt (v: View; y: INTEGER): Item;
VAR it: Item;
BEGIN
it := v.menu.first;
REPEAT
IF it # NIL THEN DEC(y, ItemHeight(v, it));
IF y > 0 THEN
IF it.next = NIL THEN it := NIL ELSE it := it.next(Item) END
END
END
UNTIL (it = NIL) OR (y <= 0);
RETURN it
END ItemAt;
PROCEDURE NextShown (v: View): View;
BEGIN WHILE (v # NIL) & Hidden(v.menu) DO v := v.link END; RETURN v
END NextShown;
PROCEDURE MainRight (v: LineView; dropped: BOOLEAN; revalidate: Views.View);
VAR next: View;
BEGIN
next := NextShown(v.active.link);
IF next # NIL THEN
v.active := next;
IF dropped THEN
ShowDrop(v, v.active, revalidate)
ELSE
Views.Update(v, Views.keepFrames)
END
END
END MainRight;
PROCEDURE MainLeft (v: LineView; dropped: BOOLEAN; revalidate: Views.View);
VAR next, drop: View;
BEGIN
ASSERT(v.active # NIL);
next := NextShown(v.first); ASSERT(next # NIL); (* because v.focus follows and is ~Hidden *)
WHILE next # v.active DO drop := next; next := NextShown(next.link) END;
IF drop # NIL THEN v.active := drop;
IF dropped THEN
ShowDrop(v, drop, revalidate)
ELSE
Views.Update(v, Views.keepFrames)
END
END
END MainLeft;
PROCEDURE Activatable (it: Item): BOOLEAN;
CONST bad = { itTrapped, itTrappedDbg, itFailed, itFailedDbg, itSeparator, itHidden };
BEGIN RETURN ~it.par.disabled & ~(ItemStatus(it) IN bad)
END Activatable;
PROCEDURE NextActivatable (it: StdDialog.Item): Item;
VAR res: Item;
BEGIN
IF it # NIL THEN
WHILE (it # NIL) & ~Activatable(it(Item)) DO it := it.next END;
IF it = NIL THEN res := NIL ELSE res := it(Item) END
END;
RETURN res
END NextActivatable;
PROCEDURE IsShortcut (shcut, char: CHAR): BOOLEAN;
(** Placeholder for complex shortcut equivalence evaluation.
Returts TRUE if char is equivalent to shortcut shcut *)
BEGIN RETURN Strings.Upper(shcut) = Strings.Upper(char)
END IsShortcut;
PROCEDURE HandleLabelShortcut (v: View; char: CHAR);
VAR i: INTEGER; ch: CHAR; it: Item;
BEGIN
REPEAT
IF it = NIL THEN
it := NextActivatable(v.menu.first)
ELSE
it := NextActivatable(it.next)
END;
IF it # NIL THEN
i := -1; REPEAT INC(i); ch := it.item[i] UNTIL (ch = '&') OR (ch = 0X);
IF ch = '&' THEN ch := it.item[i + 1] ELSE ch := 0X END
END
UNTIL (it = NIL) OR IsShortcut(ch, char);
IF it # NIL THEN v.focus := it; ExecActive(v) END
END HandleLabelShortcut;
PROCEDURE (v: View) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View);
VAR x, y: INTEGER; mod: SET; isDown: BOOLEAN; it: Item; refocus: StdDialog.Item;
BEGIN
WITH
| msg: Controllers.EditMsg DO
IF msg.op = Controllers.pasteChar THEN
refocus := v.focus;
IF msg.char = ESC THEN HideDrop(v)
ELSIF msg.char = ENTER THEN ExecActive(v)
ELSIF msg.char = AD THEN
IF v.focus = NIL THEN refocus := NextActivatable(v.menu.first)
ELSIF v.focus.next # NIL THEN refocus := NextActivatable(v.focus.next(Item))
END
ELSIF (msg.char = AU) & (v.menu.first # v.focus) THEN
it := v.menu.first;
REPEAT
IF Activatable(it) THEN refocus := it END;
IF it.next = NIL THEN it := NIL ELSE it := it.next(Item) END
UNTIL it = v.focus
ELSIF (msg.char = DL) & (v.focus # v.menu.first) THEN refocus := v.menu.first
ELSIF (msg.char = DR) & (v.menu.first # NIL) THEN
refocus := v.menu.first; WHILE refocus.next # NIL DO refocus := refocus.next END
ELSIF (msg.char = AR) & (v.main # NIL) THEN MainRight(v.main, TRUE, v)
ELSIF (msg.char = AL) & (v.main # NIL) THEN MainLeft(v.main, TRUE, v)
ELSE
HandleLabelShortcut(v, msg.char)
END;
IF refocus # v.focus THEN
IF refocus = NIL THEN v.focus := NIL ELSE v.focus := refocus(Item) END;
Views.Update(v, Views.keepFrames)
END
END
| msg: Controllers.TrackMsg DO
v.focus := ItemAt(v, msg.y);
REPEAT
f.Input(x, y, mod, isDown);
it := ItemAt(v, y);
IF it # v.focus THEN
v.focus := it;
Views.Update(v, Views.keepFrames);
Views.ValidateRoot(Views.RootOf(f))
END
UNTIL ~isDown;
ExecActive(v)
| msg: ControlledTrackMsg DO
REPEAT f.Input(x, y, mod, isDown);
it := ItemAt(v, y);
IF it # v.focus THEN
v.focus := it; Views.Update(v, Views.keepFrames);
Views.ValidateRoot(Views.RootOf(f))
END
UNTIL ~isDown OR ~((f.l <= x) & (x < f.r) & (f.t <= y) & (y < f.b));
IF ~isDown & ((f.l <= x) & (x < f.r) & (f.t <= y) & (y < f.b)) THEN ExecActive(v) END
| msg: Controllers.PollCursorMsg DO
IF (f.l <= msg.x) & (msg.x < f.r) THEN it := ItemAt(v, msg.y) ELSE it := NIL END;
IF it # v.focus THEN
v.focus := it;
Views.Update(v, Views.keepFrames);
Views.ValidateRoot(Views.RootOf(f))
END
ELSE
END
END HandleCtrlMsg;
PROCEDURE (m: View) HandlePropMsg (VAR msg: Properties.Message);
BEGIN
WITH msg: Properties.SizePref DO Bounds(m, msg.w, msg.h)
| msg: Properties.BoundsPref DO Bounds(m, msg.w, msg.h)
| msg: Properties.FocusPref DO msg.setFocus := TRUE
| msg: StdDocuments.PanWindowPref DO msg.panWindow := TRUE
ELSE
END
END HandlePropMsg;
PROCEDURE (v: View) CopyFromSimpleView (source: Views.View);
BEGIN
WITH source: View DO
v.paramEra := source.paramEra;
v.menu := source.menu;
v.era := source.era;
v.link := source.link
END
END CopyFromSimpleView;
(* LineView menu view *)
PROCEDURE NewView (menu: Model; line: LineView): View;
VAR v: View;
BEGIN
NEW(v);
v.main := line; v.menu := menu; v.era := menu.era; v.cache.wid := 0; v.cache.hei := 0;
RETURN v
END NewView;
PROCEDURE LineViewBounds (v: LineView; OUT w, h: INTEGER);
VAR m: Model;
BEGIN
w := param.margin;
m := v.first.menu;
WHILE m # NIL DO
IF ~Hidden(m) THEN
INC(w, LabelWidth(m.label, param.font));
IF m.link # NIL THEN INC(w, param.margin * 2) END
END;
m := m.link
END;
h := 2 * mm + param.asc + param.dsc;
END LineViewBounds;
PROCEDURE Rebuild (v: LineView);
VAR m: Model; last, drop: View; w, h: INTEGER;
BEGIN
v.first := NIL;
v.main := main;
m := main;
WHILE m # NIL DO
drop := NewView(m, v);
IF v.first = NIL THEN v.first := drop ELSE last.link := drop END; last := drop;
m := m.link
END;
v.active := v.first;
IF (v # NIL) & (v.context # NIL) & (v.first # NIL) THEN
(* TODO доделать, чтобы обновлялось окно с новым размером меню *)
LineViewBounds(v, w, h);
v.context.SetSize(w, h);
END;
END Rebuild;
PROCEDURE IsAnyDropped (v: LineView): BOOLEAN;
VAR p: StdDocuments.OverlayProposal; d: View;
BEGIN
p.op := StdDocuments.poll; v.context.Consider(p);
IF p.view # NIL THEN
d := v.first; WHILE (d # NIL) & (d # p.view) DO d := d.link END
END;
RETURN d # NIL
END IsAnyDropped;
PROCEDURE IsDroppedMenu (line: LineView; drop: View): BOOLEAN;
(** Returns TRUE if drop, a drop menu view in line, is dropped*)
VAR p: StdDocuments.OverlayProposal; res: BOOLEAN;
BEGIN
ASSERT(line # NIL, 20); ASSERT(drop # NIL, 21);
p.op := StdDocuments.poll; line.context.Consider(p);
IF (p.view # NIL) & (p.view IS View) THEN
res := drop.menu = p.view(View).menu
ELSE
res := FALSE
END;
RETURN res
END IsDroppedMenu;
PROCEDURE (v: LineView) Restore (f: Views.Frame; l, t, r, b: INTEGER); (* horisontal *)
VAR m: Model; col, x, z, w: INTEGER;
BEGIN
IF v.main # main THEN Rebuild(v) END;
x := param.initX;
m := v.first.menu;
WHILE (m # NIL) & (x < r) DO
IF ~Hidden(m) THEN
w := LabelWidth(m.label, param.font);
z := x + w + 2 * param.margin;
IF (v.active # NIL) & (m = v.active.menu) THEN
IF f.mark OR IsAnyDropped(v) THEN
col := param.focusColorLine;
f.DrawRect(x, t, z, b, Ports.fill, param.focusBgLine)
ELSE
col := param.colorLine
END
ELSE
col := param.colorLine
END;
IF (l <= x) & (x < r) OR (l <= z) & (z < r) THEN
DrawLabel(f, x + param.margin, 1 * mm + param.asc, col, m.label, param.font)
END;
x := z
END;
m := m.link
END
END Restore;
PROCEDURE (v: LineView) HandleViewMsg (f: Views.Frame; VAR msg: Views.Message);
VAR u: View;
BEGIN
WITH msg: MainMenuUpdateMsg DO
IF msg.what = menuUpdate THEN Rebuild(v) END;
Views.Update(v, Views.keepFrames)
| msg: DropMenuMsg DO
IF dropReq.menu # NIL THEN
u := v.first; WHILE (u # NIL) & (u.menu # dropReq.menu) DO u := u.link END;
IF u # NIL THEN v.active := u; ShowDrop(v, u, v) END
END
| msg: StdDocuments.RemoveOverlayMsg DO
v.removed := Services.Ticks()
ELSE
END
END HandleViewMsg;
PROCEDURE (v: LineView) HandlePropMsg (VAR msg: Properties.Message);
BEGIN
WITH msg: Properties.SizePref DO
LineViewBounds(v, msg.w, msg.h)
| msg: StdDocuments.PanWindowPref DO msg.panWindow := TRUE
ELSE
END
END HandlePropMsg;
PROCEDURE ThisDrop (v: LineView; x, y: INTEGER): View;
VAR r: INTEGER; next, drop: View;
BEGIN
r := 0; next := v.first;
REPEAT
drop := next;
IF (drop # NIL) THEN
IF ~Hidden(drop.menu) THEN
INC(r, LabelWidth(drop.menu.label, param.font) + param.margin * 2)
END;
next := drop.link
END;
UNTIL (next = NIL) OR (r >= x);
IF r < x THEN drop := NIL END;
RETURN drop
END ThisDrop;
PROCEDURE (v: LineView) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View);
VAR drop: View; x, y: INTEGER; mod: SET; isDown: BOOLEAN;
close: View; ctm: ControlledTrackMsg; op: StdDocuments.OverlayProposal;
BEGIN
WITH
| msg: Controllers.PollCursorMsg DO
IF IsAnyDropped(v) THEN
drop := ThisDrop(v, msg.x, msg.y);
IF (drop # NIL) & (drop # v.active) THEN
v.active := drop;
ShowDrop(v, drop, v);
Views.ValidateRoot(Views.RootOf(f))
END
END
| msg: Controllers.TrackMsg DO
x := msg.x; y := msg.y;
close := ThisDrop(v, x, y);
IF (Services.Ticks() - v.removed > Services.resolution DIV 10)
OR (v.dropped # close) THEN close := NIL END;
REPEAT
IF y < f.b THEN
drop := ThisDrop(v, x, y);
IF drop # NIL THEN
IF (drop # v.active) OR ~IsDroppedMenu(v, drop) THEN
v.active := drop; ShowDrop(v, drop, v); Views.ValidateRoot(Views.RootOf(f))
END
ELSE
IF IsAnyDropped(v) THEN
HideDrop(v.dropped);
Views.ValidateRoot(Views.RootOf(f))
END;
v.active := NIL
END
ELSIF v.active # NIL THEN (* fwd to dropped menu *)
(*focus := v.active doesn't work and doesn't fit*)
op.op := StdDocuments.pollFrame; op.frame := f;
v.active.context.Consider(op);
IF op.frame # NIL THEN
ctm.x := x - (op.frame.gx - f.gx); ctm.y := y - (op.frame.gy - f.gy);
IF (op.frame.l <= ctm.x) & (ctm.x < op.frame.r)
& (op.frame.t <= ctm.y) & (ctm.y < op.frame.b) THEN
Views.ForwardCtrlMsg(op.frame, ctm)
END
END
END;
IF (f # NIL) & (f.rider # NIL) THEN f.Input(x, y, mod, isDown) ELSE isDown := FALSE END
UNTIL ~isDown;
IF (close # NIL) & (close = v.active) THEN HideDrop(close) END
| msg: Controllers.EditMsg DO
IF msg.op = Controllers.pasteChar THEN
IF (msg.char = AR) & (v.active # NIL) & (v.active.link # NIL) THEN
MainRight(v, FALSE, v)
ELSIF (msg.char = AL) & (v.active # NIL) THEN
drop := v.first; WHILE (drop # NIL) & (drop.link # v.focus) DO drop := drop.link END;
IF drop # NIL THEN v.focus := drop; upd := TRUE ENDMainLeft(v, FALSE, v)
ELSIF (msg.char = ENTER) OR (msg.char = AD) & (v.active # NIL) THEN
ThisDropPos(v, v.active, x, y);
ShowDrop(v, v.active, v)
END
END
| msg: Controllers.MarkMsg DO
IF msg.focus THEN
IF v.focussed # msg.show THEN
Views.Update(v, Views.keepFrames)
END;
v.focussed := msg.show; IF ~v.focussed THEN v.active := NIL END
END
ELSE
END
END HandleCtrlMsg;
PROCEDURE (v: LineView) GetBackground (VAR col: Ports.Color);
BEGIN col := param.bgColorLine
END GetBackground;
PROCEDURE (lv: LineView) CopyFromSimpleView (source: Views.View);
VAR u, last, v: View;
BEGIN
WITH source: LineView DO
lv.main := source.main;
v := source.first;
WHILE v.link # NIL DO u := Views.CopyOf(v, Views.shallow)(View);
u.main := lv;
IF last = NIL THEN
lv.first := u
ELSE
last.link := u
END;
last := u;
v := v.link
END
ELSE
END
END CopyFromSimpleView;
PROCEDURE SetShortcut (it: Item);
VAR j, n: INTEGER; ch, nch: CHAR; str: ARRAY 8 OF CHAR;
BEGIN
it.code := 0;
it.mod := {};
j := 0;
ch := it.shortcut[0];
WHILE (ch # 0X) & (it.code = 0) DO
INC(j); nch := it.shortcut[j];
IF (ch >= "a") & (ch <= "z") THEN ch := CAP(ch) END;
IF ch = "*" THEN INCL(it.mod, Controllers.extend)
ELSIF ch = "^" THEN INCL(it.mod, Controllers.modify)
ELSIF ch = "@" THEN INCL(it.mod, Controllers.pick)
ELSIF (ch >= "A") & (ch <= "Z") OR (ch >= "0") & (ch <= "9") OR (ch = " ") OR (ch = "-") THEN
IF (nch >= "a") & (nch <= "z") THEN nch := CAP(nch) END;
IF nch = 0X THEN it.code := ORD(ch); INCL(it.mod, Controllers.modify)
ELSIF StdMenuTool.encodeShortcut # NIL THEN
(*str[0] := it.shortcut[j - 1]; ch := 0X;*) n := 0; DEC(j);
REPEAT ch := it.shortcut[j]; str[n] := ch; INC(j); INC(n) UNTIL ch = 0X;
(*WHILE nch # 0X DO str[n] := nch; INC(n); INC(j); nch := it.shortcut[j] END;*)
StdMenuTool.encodeShortcut(str, it.code)
END
END;
ch := nch
END;
IF it.code = -1 THEN Dialog.ShowMsg("Unrecognized shortcut: " + it.shortcut + str) END
(*ASSERT(it.code # -1, 60 (* Unrecognized shortcut *)); (* need better error reporting *)*)
END SetShortcut;
PROCEDURE (d: Directory) AddItem (IN item, cmd, shortcut, filter: Dialog.String);
VAR it: Item; n: StdDialog.Item; label: Dialog.String;
BEGIN
ASSERT(d.this # NIL, 20);
Dialog.MapString(item, label);
NEW(it);
StdDialog.AddItem(it, label, cmd, filter, shortcut);
SetShortcut(it);
n := d.this.first;
IF n = NIL THEN
d.this.first := it
ELSE
WHILE n.next # NIL DO n := n.next END;
n.next := it
END;
d.last := it;
END AddItem;
PROCEDURE (d: Directory) AddSeparator;
BEGIN d.AddItem('', '', '', '')
END AddSeparator;
PROCEDURE (d: Directory) Open (IN menuLabel: Dialog.String; IN typeName: Stores.TypeName);
VAR m: Model;
BEGIN
NEW(m); m.era := 0; m.label := menuLabel; m.typeName := typeName;
Dialog.MapString(menuLabel, m.label);
IF d.main = NIL THEN d.main := m ELSE d.this.link := m END;
d.this := m
END Open;
PROCEDURE (d: Directory) Close, EMPTY;
PROCEDURE (d: Directory) DeleteAll, EMPTY;
PROCEDURE (d: Directory) InitMenus;
VAR upd: MainMenuUpdateMsg;
BEGIN
ASSERT(d.main # NIL, 20);
main := d.main; d.main := NIL; d.this := NIL; d.last := NIL;
upd.what := menuUpdate; Views.Omnicast(upd)
END InitMenus;
PROCEDURE (d: Directory) PopupMenu;
VAR menu: Model; found: BOOLEAN; f: Views.Frame; doc: Views.View; c: Models.Context;
x, y: INTEGER; isDown_: SET; modifiers_: BOOLEAN;
BEGIN
menu := main;
REPEAT
found := (menu # NIL)
& (menu.label = "*")
& ((menu.typeName = targetTypeName) & (targetTypeName # '') OR (menu.typeName = ''));
IF ~found THEN menu := menu.link END
UNTIL found OR (menu = NIL);
IF menu # NIL THEN
f := Controllers.FocusFrame();
IF f # NIL THEN f := Views.UltimateRootOf(f) END;
IF (f # NIL) & (f.view # NIL) THEN
doc := f.view;
WITH doc: StdDocuments.Document DO c := doc.ThisView().context ELSE END;
IF c # NIL THEN
f.Input(x, y, isDown_, modifiers_);
ShowDropIn(c, x, y, NewView(menu, NIL), NIL, NIL)
END
END
END
END PopupMenu;
PROCEDURE SetFocus;
VAR c: Containers.Controller; f: Views.Frame; v, s: Views.View;
BEGIN
f := Controllers.FocusFrame(); v := f.view;
WITH v: Containers.View DO
c := v.ThisController();
s := c.Singleton();
IF s # NIL THEN c.SetFocus(s) END
ELSE
END
END SetFocus;
PROCEDURE HandleVerb (n: INTEGER);
VAR v: Views.View; dvm: Properties.DoVerbMsg;
BEGIN
v := Containers.FocusSingleton();
IF v # NIL THEN
dvm.frame := Views.ThisFrame(Controllers.FocusFrame(), v);
dvm.verb := n;
Views.HandlePropMsg(v, dvm)
END
END HandleVerb;
PROCEDURE CheckVerb (v: Views.View; n: INTEGER; VAR pvm: Properties.PollVerbMsg);
BEGIN
pvm.verb := n;
pvm.label := "";
pvm.disabled := FALSE; pvm.checked := FALSE;
Views.HandlePropMsg(v, pvm)
END CheckVerb;
PROCEDURE (d: Directory) PrimaryVerb;
VAR v: Views.View; pvm: Properties.PollVerbMsg;
BEGIN
v := Containers.FocusSingleton();
IF v # NIL THEN
CheckVerb(v, 0, pvm);
IF pvm.label # "" THEN HandleVerb(0)
ELSE SetFocus
END
END
END PrimaryVerb;
PROCEDURE (d: Directory) RevalidateGuards; (* Based on DevCmds.FlushResources *)
VAR m: Model; i: StdDialog.Item;
BEGIN
m := main;
WHILE m # NIL DO
i := m.first; WHILE i # NIL DO StdDialog.ClearGuards(i); i := i.next END;
m := m.link
END
END RevalidateGuards;
PROCEDURE (a: Actor) Do;
VAR ops: Controllers.PollOpsMsg; upd: MainMenuUpdateMsg;
it: Item; _: BOOLEAN;
BEGIN
IF executeItem # NIL THEN it := executeItem; executeItem := NIL; DoExecute(it, _) END;
Controllers.SetCurrentPath(Controllers.targetPath);
Controllers.PollOps(ops);
IF (main # NIL) & (ops.type # targetTypeName) THEN
targetTypeName := ops.type$;
upd.what := targetTypeNameChange;
Views.Omnicast(upd)
END;
Controllers.ResetCurrentPath();
Services.DoLater(a, Services.now)
END Do;
PROCEDURE AppendInt (VAR s: ARRAY OF CHAR; n: INTEGER; useSeparators: BOOLEAN);
VAR len: INTEGER; i, j: INTEGER; d: ARRAY 32 OF CHAR;
BEGIN
ASSERT(n >= 0, 20);
i := 0; REPEAT
d[i] := CHR(30H + n MOD 10); INC(i); n := n DIV 10;
IF useSeparators & (i MOD 4 = 3) & (n # 0) THEN d[i] := "'"; INC(i) END
UNTIL n = 0;
len := LEN(s) - 1;
j := 0; WHILE s[j] # 0X DO INC(j) END;
IF j + i < len THEN
REPEAT DEC(i); s[j] := d[i]; INC(j) UNTIL i = 0;
s[j] := 0X
END
END AppendInt;
PROCEDURE UpdateMetrics;
VAR alloc, used: INTEGER;
BEGIN
alloc := Kernel.Allocated(); used := Kernel.Used();
IF (alloc # metrics.alloc) OR (used # metrics.used) THEN
metrics.alloc := alloc; metrics.used := used;
metricsStr := allocStr$;
AppendInt(metricsStr, alloc, useSeparators);
metricsStr := metricsStr + " " + byteStr + " | " + actionsStr + " ";
AppendInt(metricsStr, Services.actionsInTheQueue, useSeparators);
updateStatusBar := TRUE
END
END UpdateMetrics;
PROCEDURE (v: StatusBar) GetBackground (VAR col: Ports.Color);
BEGIN col := param.statusBg
END GetBackground;
PROCEDURE (v: StatusBar) Restore (f: Views.Frame; l_, t_, r_, b_: INTEGER);
VAR asc, dsc, wid, w, h: INTEGER;
BEGIN
param.font.GetBounds(asc, dsc, wid);
f.DrawString(mm, mm + asc, param.statusColor, status, param.font);
wid := param.font.StringWidth(metricsStr);
IF Dialog.memInStatus THEN
v.context.GetSize(w, h);
f.DrawString(w - wid - mm, mm + asc, param.statusColor, metricsStr, param.font)
END
END Restore;
PROCEDURE GetStatusBounds (v: StatusBar; OUT w, h: INTEGER);
VAR w_: INTEGER;
BEGIN
param.font.GetBounds(w, h, w_); INC(h, w + 2 * mm);
w := 2 * mm + param.font.StringWidth(status);
IF Dialog.memInStatus THEN
INC(w, param.font.StringWidth(metricsStr))
END
END GetStatusBounds;
PROCEDURE (v: StatusBar) HandlePropMsg (VAR msg: Properties.Message);
BEGIN
WITH msg: Properties.BoundsPref DO GetStatusBounds(v, msg.w, msg.h)
| msg: Properties.SizePref DO GetStatusBounds(v, msg.w, msg.h)
ELSE
END
END HandlePropMsg;
PROCEDURE (a: StatusBarUpdater) Do;
BEGIN
IF Dialog.memInStatus THEN
UpdateMetrics
END;
IF updateStatusBar & (a.bar # NIL) THEN
Views.Update(a.bar, Views.keepFrames);
updateStatusBar := FALSE
END;
Services.DoLater(a, Services.immediately)
END Do;
PROCEDURE SetStatus* (IN in: ARRAY OF CHAR);
BEGIN
status := in$;
Dialog.UpdateString(status);
updateStatusBar := TRUE
END SetStatus;
PROCEDURE DepositStatusBar*;
VAR statusBar: StatusBar;
BEGIN
Dialog.MapString(allocKey, allocStr);
Dialog.MapString(totalKey, totalStr);
Dialog.MapString(byteKey, byteStr);
Dialog.MapString(actionsKey, actionsStr);
status := "";
metricsStr := "";
NEW(statusBar);
NEW(statusBar.updater);
statusBar.updater.bar := statusBar;
updateStatusBar := TRUE;
Views.Deposit(statusBar);
(* just because it is deposited doesn't mean it will be used, so the updater is out of place *)
Services.DoLater(statusBar.updater, Services.now)
END DepositStatusBar;
PROCEDURE NewMainLine* (): Views.View;
VAR ml: LineView;
BEGIN
NEW(ml);
ml.removed := Services.Ticks();
Rebuild(ml);
RETURN ml
END NewMainLine;
PROCEDURE (line: LineView) Externalize (VAR wr: Stores.Writer);
BEGIN wr.WriteVersion(version)
END Externalize;
PROCEDURE (line: LineView) Internalize (VAR rd: Stores.Reader);
VAR thisVersion_: INTEGER;
BEGIN
rd.ReadVersion(version, version, thisVersion_);
IF ~rd.cancelled THEN Rebuild(line) END
END Internalize;
PROCEDURE DropMenu*;
(** Drop the menu determined by the most recently used shortcut Alt+CHAR. Used internally *)
VAR msg: DropMenuMsg;
BEGIN
IF dropReq.menu # NIL THEN Views.Omnicast(msg) END;
dropReq.menu := NIL
END DropMenu;
PROCEDURE InitParam (p: ANYPTR);
VAR w: INTEGER;
BEGIN
WITH p: Param DO
p.font := Fonts.dir.This(p.typeface, p.size * Ports.point, {}, Fonts.normal);
p.checkW := p.font.StringWidth(p.check);
p.font.GetBounds(p.asc, p.dsc, w);
p.itemH := 2 * Ports.mm + p.asc + p.dsc;
p.separH := p.itemH DIV 2;
p.margin := p.asc;
p.initX := p.asc DIV 2
END
END InitParam;
PROCEDURE InitDefaults (p: ANYPTR);
BEGIN
WITH p: Param DO
param.typeface := StdCFrames.defaultFont.typeface;
param.size := StdCFrames.defaultFont.size DIV Ports.point;
IF Dialog.isWine THEN
p.check := "v"
ELSE
p.check := "✓"
END;
p.bgColorLine := Ports.RGBColor(50, 50, 50);
p.bgColor := Ports.RGBColor(70, 70, 70);
p.color := Ports.RGBColor(220, 220, 220);
p.colorLine := Ports.RGBColor(160, 160, 160);
p.disabledColor := Ports.grey50;
p.focusColor := Ports.black;
p.focusColorLine := Ports.white;
p.focusBgLine := Ports.RGBColor(70, 70, 70);
p.shortcutColor := Ports.grey50;
p.focusBg := Ports.RGBColor(255, 215, 50);
p.statusBg := Ports.RGBColor(50, 50, 50);
p.statusColor := Ports.grey25;
p.debug := FALSE;
p.era := 0;
p.InitDefaults := InitDefaults; p.Init := InitParam;
NEW(dropReq.item);
StdDialog.AddItem(dropReq.item, "Fake", "StdMenus.DropMenu", "", "")
END
END InitDefaults;
PROCEDURE HidingGuard* (VAR par: Dialog.Par);
BEGIN
par.label := hidden
END HidingGuard;
PROCEDURE SetFontFromDialogFont*;
VAR upd: MainMenuUpdateMsg;
BEGIN
param.typeface := StdCFrames.defaultFont.typeface;
param.size := StdCFrames.defaultFont.size DIV Ports.point;
InitParam(param);
INC(param.era);
upd.what := menuUpdate; Views.Omnicast(upd)
END SetFontFromDialogFont;
PROCEDURE Install*;
BEGIN
NEW(dir); StdMenuTool.SetDir(dir);
targetTypeName := '';
NEW(actor);
Services.DoLater(actor, Services.Ticks() + 100);
NEW(dir);
InitParam(param);
Dialog.MapString("#Tyler:Guard trapped", trappedLbl);
Dialog.MapString("#Tyler:Failed to call guard", failedLbl);
(* Need a laguage change notification! *)
END Install;
BEGIN
NEW(param);
InitDefaults(param)
END StdMenus. | Std/Mod/Menus.odc |
MODULE StdMenuTool;
(**
project = "BlackBox 2.0"
organization = "www.oberon.ch, blackbox.oberon.org"
contributors = "Oberon microsystems, Anton Dmitriev"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 20150922, center #71, fix for case insensitive sort in Comp
- 20161216, center #144, inconsistent docu and usage of Files.Locator error codes
- 202104, ad, Abstract directory introduced
"
issues = "
- ...
"
**)
IMPORT
Kernel, Files, Fonts, Ports, Models, Stores, Views, Dialog, Properties, Containers,
Documents, StdLinks, StdCmds, StdDialog, Strings,
TextModels, TextMappers, TextViews, TextControllers;
CONST
char = TextMappers.char; string = TextMappers.string; keyword = 100;
menuFile = "Menus"; rsrcDir = "Rsrc"; sysDir = "System";
TYPE
LangNotifier = POINTER TO RECORD (Dialog.LangNotifier) END;
Directory* = POINTER TO ABSTRACT RECORD END;
ShortcutMatcher* = ABSTRACT RECORD END;
VAR
noerr, showerr, gen: BOOLEAN;
includes: Files.LocInfo;
langNotifier: LangNotifier;
dir-: Directory;
encodeShortcut*: PROCEDURE (IN shortcut: ARRAY OF CHAR; OUT code: INTEGER);
PROCEDURE (VAR m: ShortcutMatcher) Match* (it: StdDialog.Item; code: INTEGER; mod: SET): BOOLEAN, NEW, ABSTRACT;
(** Returns TRUE if it matches some criteria. The criteria is to be specified by extenders. This is intended to check shortcut matches - that is, check if it's shortcut matches the most recently pressed key *)
PROCEDURE (d: Directory) FirstMatch* (VAR m: ShortcutMatcher): StdDialog.Item, NEW, ABSTRACT;
(** Returns the first Item that matches some criteria thru m *)
PROCEDURE (d: Directory) Execute* (it: StdDialog.Item), NEW, ABSTRACT;
PROCEDURE (d: Directory) AddSeparator*, NEW, ABSTRACT;
PROCEDURE (d: Directory) AddItem* (IN item, cmd, shortcut, filter: Dialog.String), NEW, ABSTRACT;
PROCEDURE (d: Directory) Open* (IN menu: Dialog.String; IN category: Stores.TypeName), NEW, ABSTRACT;
(** Start forming a new menu *)
PROCEDURE (d: Directory) Close*, NEW, ABSTRACT;
(** Finish forming the menu being formed since last Open *)
(* Redundant? A next Open and final InitMenus is siffucient to detect the end of menu formation *)
PROCEDURE (d: Directory) DeleteAll*, NEW, ABSTRACT;
(** Deletes all menus and items *)
PROCEDURE (d: Directory) InitMenus*, NEW, ABSTRACT;
(** To be called after all menu items have been entered into the menu (that is, the menu is formed) *)
PROCEDURE (d: Directory) RevalidateGuards*, NEW, ABSTRACT;
(** All item guards that have been invalidated (failed = not found, or trapped) are made valid again *)
PROCEDURE (d: Directory) PopupMenu*, NEW, ABSTRACT;
PROCEDURE (d: Directory) PrimaryVerb*, NEW, ABSTRACT;
PROCEDURE SetDir* (d: Directory);
BEGIN ASSERT(d # NIL, 20); dir := d
END SetDir;
PROCEDURE PopupMenu*; (* seldom referenced, could be replaced with StdMenuTool.dir.PopupMenu *)
BEGIN dir.PopupMenu
END PopupMenu;
PROCEDURE PrimaryVerb*; (* seldom referenced, could be replaced with StdMenuTool.dir.PrimaryVerb *)
BEGIN dir.PrimaryVerb
END PrimaryVerb;
PROCEDURE Scan (VAR s: TextMappers.Scanner);
VAR ch: CHAR; p: INTEGER;
BEGIN
s.Scan;
IF s.type = string THEN
p := s.rider.Pos() - 1;
IF ~s.rider.eot THEN DEC(p) END;
s.rider.SetPos(p); s.rider.ReadChar(ch); s.rider.Read;
IF ch # '"' THEN s.type := keyword END
END
END Scan;
PROCEDURE Comp (IN s1, s2: ARRAY OF CHAR): INTEGER;
VAR i: INTEGER; a, b: CHAR;
BEGIN
i := 0; a := Strings.Upper(s1[0]); b := Strings.Upper(s2[0]);
WHILE (a # 0X) & (a = b) DO
INC(i); a := Strings.Upper(s1[i]); b := Strings.Upper(s2[i])
END;
RETURN ORD(a) - ORD(b)
END Comp;
PROCEDURE Sort (VAR list: Files.LocInfo);
VAR inc, last, i1, i2: Files.LocInfo;
BEGIN
inc := list; list := NIL;
WHILE inc # NIL DO
i1 := inc; inc := inc.next;
i2 := list; last := NIL;
WHILE (i2 # NIL) & (Comp(i1.name, i2.name) > 0) DO last := i2; i2 := i2.next END;
IF last = NIL THEN
i1.next := list; list := i1 ELSE i1.next := last.next; last.next := i1
END
END
END Sort;
PROCEDURE ParseMenus (VAR s: TextMappers.Scanner; view: Views.View; loc: Files.Locator; name: Files.Name);
VAR menu: Dialog.String; category: Stores.TypeName; n: INTEGER;
PROCEDURE Error (VAR s: TextMappers.Scanner; err: ARRAY OF CHAR);
VAR end: INTEGER;
BEGIN
IF noerr & showerr THEN
IF loc # NIL THEN Views.Open(view, loc, name, NIL) END;
end := MAX(s.rider.Pos() - 1, s.start + 1);
end := MIN(end, s.rider.Base().Length());
TextControllers.SetSelection(s.rider.Base(), s.start, end);
TextViews.ShowRange(s.rider.Base(), s.start, end, TextViews.focusOnly);
Dialog.ShowMsg(err)
END;
noerr := FALSE
END Error;
PROCEDURE Category (VAR s: TextMappers.Scanner; VAR c: ARRAY OF CHAR);
BEGIN
IF (s.type = char) & (s.char = "(") THEN
Scan(s); IF s.type # string THEN Error(s, "string expected") END;
c := s.string$;
Scan(s);
IF (s.type # char) OR (s.char # ")") THEN Error(s, ") expected") END;
Scan(s)
ELSE c := ""
END
END Category;
PROCEDURE Item (VAR s: TextMappers.Scanner);
VAR item, str, shortcut, filter: Dialog.String;
BEGIN
IF s.type = keyword THEN
IF gen THEN dir.AddSeparator END;
Scan(s)
ELSE
IF s.len < LEN(item) THEN item := s.string$
ELSE item := ""; Error(s, "string too long")
END;
IF item = "" THEN Error(s, "nonempty string expected") END;
Scan(s);
shortcut := "";
IF s.type = string THEN
IF s.len < 8 THEN shortcut := s.string$
ELSE Error(s, "string too long")
END
ELSE Error(s, "string expected")
END;
Scan(s); IF s.type # string THEN Error(s, "string expected") END;
IF s.len < LEN(str) THEN str := s.string$
ELSE str := ""; Error(s, "string too long")
END;
IF str = "" THEN Error(s, "nonempty string expected") END;
Scan(s); IF s.type # string THEN Error(s, "string expected") END;
IF s.len < LEN(str) THEN filter := s.string$
ELSE filter := ""; Error(s, "string too long")
END;
IF gen THEN dir.AddItem(item, str, shortcut, filter) END;
Scan(s)
END
END Item;
PROCEDURE IncludeSub (sub: ARRAY OF CHAR);
VAR loc: Files.Locator; view: Views.View;
t: TextModels.Model; s: TextMappers.Scanner;
BEGIN
loc := Files.dir.This(sub); IF loc.res # 0 THEN RETURN END;
loc := loc.This(rsrcDir); IF loc.res # 0 THEN RETURN END;
view := Views.OldView(loc, menuFile);
IF (view # NIL) & (view IS TextViews.View) THEN
t := view(TextViews.View).ThisModel();
IF t # NIL THEN
s.ConnectTo(t); Scan(s); ParseMenus(s, view, loc, menuFile)
END
END
END IncludeSub;
PROCEDURE Include (sub: ARRAY OF CHAR);
VAR inc, last: Files.LocInfo;
BEGIN
IF sub = "*" THEN (* wildcard include *)
IF ~gen THEN (* first pass: generate complete list *)
IF includes # NIL THEN Error(s, "only one wildcard include allowed") END;
includes := Files.dir.LocList(Files.dir.This(""))
ELSE (* second pass: sort reduced list *)
Sort(includes)
END;
inc := includes;
WHILE (inc # NIL) & noerr DO
IF Comp(inc.name, sysDir) # 0 THEN IncludeSub(inc.name) END;
inc := inc.next
END
ELSE (* spedific includes *)
IncludeSub(sub);
inc := includes; last := NIL;
WHILE (inc # NIL) & (Comp(inc.name, sub) # 0) DO
last := inc; inc := inc.next
END;
IF inc # NIL THEN (* remove from wilcard list *)
IF last = NIL THEN includes := inc.next ELSE last.next := inc.next END
END
END
END Include;
BEGIN
n := 0;
WHILE noerr & (s.type = keyword) & ((s.string = "MENU") OR (s.string = "INCLUDE")) DO
IF s.string = "INCLUDE" THEN
Scan(s);
IF s.type # string THEN Error(s, "string expected") END;
Include(s.string);
Scan(s);
INC(n)
ELSE
INC(n); Scan(s);
IF s.type # string THEN Error(s, "string expected") END;
menu := s.string$;
IF menu = "" THEN Error(s, "nonempty string expected") END;
Scan(s);
Category(s, category);
IF gen THEN dir.Open(menu, category) END;
WHILE noerr & ((s.type = string) OR (s.type = keyword) & (s.string = "SEPARATOR")) DO
Item(s)
END;
IF (s.type # keyword) OR (s.string # "END") THEN Error(s, "END expected") END;
IF gen THEN dir.Close END;
Scan(s)
END
END;
IF (s.type # TextMappers.eot) OR (n = 0) THEN Error(s, "MENU expected") END;
END ParseMenus;
PROCEDURE InitNotifier;
BEGIN
IF langNotifier = NIL THEN
NEW(langNotifier); Dialog.RegisterLangNotifier(langNotifier)
END
END InitNotifier;
PROCEDURE UpdateFromText* (text: TextModels.Model);
VAR s: TextMappers.Scanner;
BEGIN
InitNotifier;
ASSERT(text # NIL, 20);
s.ConnectTo(text); s.SetPos(0);
Scan(s);
noerr := TRUE; showerr := FALSE; gen := FALSE; ParseMenus(s, NIL, NIL, "");
IF noerr THEN
s.SetPos(0); Scan(s); gen := TRUE;
dir.DeleteAll; ParseMenus(s, NIL, NIL, ""); dir.InitMenus
END;
includes := NIL
END UpdateFromText;
PROCEDURE UpdateMenus*;
VAR t: TextModels.Model; s: TextMappers.Scanner;
BEGIN
InitNotifier;
t := TextViews.FocusText();
IF t # NIL THEN
s.ConnectTo(t); s.SetPos(0); Scan(s);
noerr := TRUE; showerr := TRUE; gen := FALSE; ParseMenus(s, NIL, NIL, "");
IF noerr THEN
s.SetPos(0); Scan(s); gen := TRUE;
dir.DeleteAll; ParseMenus(s, NIL, NIL, ""); dir.InitMenus
END
END;
includes := NIL
END UpdateMenus;
PROCEDURE UpdateAllMenus*;
VAR view: Views.View; t: TextModels.Model; s: TextMappers.Scanner;
loc: Files.Locator;
BEGIN
ASSERT(dir # NIL, 20);
Dialog.FlushMappings;
InitNotifier;
loc := Files.dir.This(sysDir); IF loc.res # 0 THEN RETURN END;
loc := loc.This(rsrcDir); IF loc.res # 0 THEN RETURN END;
view := Views.OldView(loc, menuFile);
IF (view # NIL) & (view IS TextViews.View) THEN
t := view(TextViews.View).ThisModel();
IF t # NIL THEN
s.ConnectTo(t); Scan(s);
noerr := TRUE; showerr := TRUE; gen := FALSE;
ParseMenus(s, view, loc, menuFile);
IF noerr THEN
s.SetPos(0); Scan(s); gen := TRUE;
dir.DeleteAll; ParseMenus(s, NIL, NIL, ""); dir.InitMenus
ELSE
Dialog.ShowMsg("errors detected in menu file");
END
END
ELSE Dialog.ShowMsg("cannot open menu file")
END;
includes := NIL
END UpdateAllMenus;
PROCEDURE InsertLink (VAR w: TextMappers.Formatter; path: ARRAY OF CHAR);
VAR a0: TextModels.Attributes; cmd: ARRAY 256 OF CHAR;
BEGIN
a0 := w.rider.attr;
w.rider.SetAttr(TextModels.NewStyle(w.rider.attr, {Fonts.underline}));
w.rider.SetAttr(TextModels.NewColor(w.rider.attr, Ports.blue));
cmd := "StdCmds.OpenDoc('" + path + "')";
w.WriteView(StdLinks.dir.NewLink(cmd));
w.WriteString(path);
w.WriteView(StdLinks.dir.NewLink(""));
w.rider.SetAttr(a0);
END InsertLink;
PROCEDURE ListAllMenus*;
VAR sub: Files.LocInfo; loc: Files.Locator; f: Files.File; t: TextModels.Model;
w: TextMappers.Formatter; path: Files.Name; v: Views.View;
c: Containers.Controller; p: Properties.BoundsPref;
BEGIN
t := TextModels.dir.New(); w.ConnectTo(t);
w.WriteString("Menu Files:"); w.WriteLn; w.WriteLn;
path := sysDir + "/" + rsrcDir + "/" + menuFile;
InsertLink(w, path); w.WriteLn; w.WriteLn;
sub := Files.dir.LocList(Files.dir.This(""));
Sort(sub);
WHILE sub # NIL DO
IF Comp(sub.name, sysDir) # 0 THEN
loc := Files.dir.This(sub.name);
loc := loc.This(rsrcDir);
IF loc.res = 0 THEN
path := menuFile;
Files.dir.GetFileName(path, Files.docType, path);
f := Files.dir.Old(loc, path, Files.shared);
IF f # NIL THEN
path := sub.name + "/" + rsrcDir + "/" + menuFile;
InsertLink(w, path); w.WriteLn;
END
END
END;
sub := sub.next
END;
v := TextViews.dir.New(t);
c := v(Containers.View).ThisController();
c.SetOpts(c.opts + {Containers.noCaret});
p.w := Views.undefined; p.h := Views.undefined; Views.HandlePropMsg(v, p);
v := Documents.dir.New(v, p.w, p.h);
Views.OpenAux(v, "All Menus")
END ListAllMenus;
PROCEDURE ThisMenu*;
VAR s: TextMappers.Scanner; c: Models.Context; v: Views.View;
name: ARRAY 256 OF CHAR;
BEGIN
IF StdLinks.par # NIL THEN
c := StdLinks.par.context;
WITH c: TextModels.Context DO
s.ConnectTo(c.ThisModel()); s.SetPos(c.Pos() + 1);
s.rider.ReadView(v); (* right link view *)
s.Scan;
IF s.type = string THEN
IF s.string = "*" THEN ListAllMenus
ELSE
name := s.string + "/" + rsrcDir + "/" + menuFile;
StdCmds.OpenDoc(name)
END
END
ELSE
END
END
END ThisMenu;
PROCEDURE (n: LangNotifier) Notify;
BEGIN
UpdateAllMenus
END Notify;
END StdMenuTool.
| Std/Mod/MenuTool.odc |
MODULE StdPictures;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20070201, bh, Unicode support
- 20141215, center #23, fixing bugs in WinApi plus some refinements and extensions
- 20230120, k8, half-working port to standard drawer (mac images only)
- 20230211, k8, better rendering, support for fill patterns
"
issues = "
- 20230211, k8, QuickDraw actually draws pixels at the right and bottom of the coord; it also seems to render full lines
"
**)
IMPORT
Kernel, Dialog,
Files, Fonts, Ports, Stores, Models, Views, Controllers, Properties;
CONST
macPict = 0; winPict = 1; (* types *)
minVersion = 0; maxVersion = 0;
TYPE
Model = POINTER TO RECORD
file: Files.File;
pos, len: INTEGER;
ref: INTEGER; (* some pointer to resource like WinApi.HANDLE in WinPictures *)
data: POINTER TO ARRAY OF BYTE
END;
StdView = POINTER TO RECORD (Views.View)
model: Model;
unit: INTEGER;
w, h: INTEGER;
mode: SHORTCHAR;
type: BYTE
END;
POINT = Ports.Point;
HANDLE = INTEGER;
FillInfo = RECORD
pat: ARRAY 8 OF SHORTINT;
color, brushColor: Ports.Color;
patFill, patEmpty: BOOLEAN; (* pattern type, for fill optimisations *)
width: INTEGER (* for pens; <=0 means "no pen" *)
END;
ExternalDrawer* = POINTER TO ABSTRACT RECORD END;
VAR
drawBackRect*: BOOLEAN;
doDump: BOOLEAN;
externalDrawer: ExternalDrawer;
PROCEDURE (ex: ExternalDrawer) Prepare* (len: INTEGER; data: POINTER TO ARRAY OF BYTE): INTEGER, NEW, ABSTRACT;
PROCEDURE (ex: ExternalDrawer) GetBytes* (ref, len: INTEGER; data: POINTER TO ARRAY OF BYTE), NEW, ABSTRACT;
PROCEDURE (ex: ExternalDrawer) Finalize* (ref: INTEGER), NEW, ABSTRACT;
PROCEDURE (ex: ExternalDrawer) Draw* (f: Views.Frame; ref, mode, x, y, w, h: INTEGER), NEW, ABSTRACT;
PROCEDURE SetExternalDrawer* (d: ExternalDrawer);
BEGIN
externalDrawer := d
END SetExternalDrawer;
(* Mac Pictures *)
PROCEDURE ReadWord (rd: Files.Reader; VAR x: INTEGER);
VAR
b: BYTE;
BEGIN
rd.ReadByte(b); x := 256 * (b MOD 256);
rd.ReadByte(b); x := x + b MOD 256
END ReadWord;
PROCEDURE ReadDWord (rd: Files.Reader; VAR x: INTEGER);
VAR
w0, w1: INTEGER;
BEGIN
ReadWord(rd, w0); ReadWord(rd, w1);
x := 65536 * w1 + w0
END ReadDWord;
PROCEDURE ReadI16 (rd: Files.Reader; VAR x: INTEGER);
VAR
b: BYTE;
BEGIN
rd.ReadByte(b); x := 256 * (b MOD 256);
rd.ReadByte(b); x := x + b MOD 256;
x := (x + 32768) MOD 65536 - 32768
END ReadI16;
PROCEDURE ReadByte (rd: Files.Reader; VAR x: INTEGER);
VAR
b: BYTE;
BEGIN
rd.ReadByte(b); x := b
END ReadByte;
PROCEDURE Skip (rd: Files.Reader; n: INTEGER);
BEGIN
rd.SetPos(rd.Pos() + n)
END Skip;
PROCEDURE DrawMacPicture (v: StdView; f: Views.Frame; picw, pich: INTEGER);
CONST
brushPen = 0; brushFill = 1; brushBack = 2;
VAR
rd: Files.Reader; end, len, x, y, z, l, t, r, b: INTEGER; op: INTEGER; v2, clipped: BOOLEAN;
fgnd, bgnd: Ports.Color; str: ARRAY 256 OF CHAR; size, style: INTEGER;
poly, ppx: ARRAY 512 OF POINT;
bt: BYTE;
rl, rt, rr, rb, dl, dt, dr, db, ol, ot, or, ob, al, at, ar, ab, as, aa, gl, gt, gr, gb, ow, oh, lx, ly, tx, ty, plen: INTEGER;
brushes: ARRAY 3 OF FillInfo;
actBrush: INTEGER; actUsePen, actUseBrush: BOOLEAN;
(*actPen, backBrush, fillBrush: FillInfo;*)
curX, curY: INTEGER;
font: Fonts.Font;
scale: REAL;
expath: ARRAY 512 OF INTEGER;
expos: INTEGER;
PROCEDURE Round (n: INTEGER): INTEGER;
BEGIN RETURN SHORT(ENTIER(((n * scale) + 0.5) * f.unit));
END Round;
PROCEDURE ConvertX (x: INTEGER): INTEGER;
BEGIN RETURN Round(x)
END ConvertX;
PROCEDURE ConvertY (y: INTEGER): INTEGER;
BEGIN RETURN Round(y)
END ConvertY;
PROCEDURE ConvertWidth (w: INTEGER): INTEGER;
BEGIN
IF w > 0 THEN w := MAX(f.unit, Round(w)) END;
RETURN w
END ConvertWidth;
PROCEDURE ExInit;
BEGIN expos := 0
END ExInit;
PROCEDURE ExValue (v: INTEGER);
BEGIN expath[expos] := v; INC(expos)
END ExValue;
PROCEDURE ExCommand (v: INTEGER);
BEGIN ExValue(v)
END ExCommand;
PROCEDURE ExCoords (x, y: INTEGER);
BEGIN ExValue(ConvertX(x)); ExValue(ConvertY(y))
END ExCoords;
PROCEDURE ExCoordsNC (x, y: INTEGER);
BEGIN ExValue(x); ExValue(y)
END ExCoordsNC;
(*
PROCEDURE ExPattern (IN brush: FillInfo);
VAR
f: INTEGER;
BEGIN
IF brush.patFill THEN
ExCommand(Ports.pathColor); ExValue(Ports.black)
ELSIF brush.patEmpty THEN
ExCommand(Ports.pathColor); ExValue(Ports.background)
ELSE
ExCommand(Ports.pathPattern);
ExValue(Ports.black); ExValue(Ports.background);
FOR f := 0 TO 7 DO ExValue(brush.pat[f]) END
END
END ExPattern;
*)
PROCEDURE Point (VAR x, y: INTEGER);
BEGIN
ReadI16(rd, y); ReadI16(rd, x)
END Point;
PROCEDURE Data (n: INTEGER);
VAR
b: BYTE;
BEGIN
WHILE n > 0 DO rd.ReadByte(b); DEC(n) END
END Data;
PROCEDURE Region (VAR l, t, r, b: INTEGER);
VAR
len: INTEGER;
BEGIN
ReadWord(rd, len); ReadI16(rd, l); ReadI16(rd, t);
ReadI16(rd, r); ReadI16(rd, b); Data(len - 10)
END Region;
PROCEDURE Poly (VAR poly: ARRAY OF POINT; VAR len: INTEGER);
VAR
l, t, r, b, i: INTEGER;
BEGIN
ReadWord(rd, len); len := (len - 10) DIV 4;
(* this seems to be a polygon bounds *)
ReadI16(rd, l); ReadI16(rd, t);
ReadI16(rd, r); ReadI16(rd, b);
i := 0; WHILE i < len DO Point(poly[i].x, poly[i].y); INC(i) END
END Poly;
PROCEDURE Pattern (VAR brush: FillInfo);
VAR
i: INTEGER;
b: BYTE;
n: SHORTINT;
isFullPat, isEmptyPat: BOOLEAN;
BEGIN
isFullPat := TRUE; isEmptyPat := TRUE;
i := 0; WHILE i < 8 DO
rd.ReadByte(b); n := SHORT(b MOD 256);
brush.pat[i] := n;
IF n # 0 THEN isEmptyPat := FALSE END;
IF n # 255 THEN isFullPat := FALSE END;
INC(i)
END;
brush.patFill := isFullPat; brush.patEmpty := isEmptyPat;
IF isEmptyPat THEN brush.brushColor := Ports.background
ELSIF isFullPat THEN brush.brushColor := Ports.black
ELSE brush.brushColor := Ports.RGBColor(255, 128, 0)
END
END Pattern;
PROCEDURE Pen (x, y: INTEGER);
BEGIN
IF x < y THEN x := y END;
(* x is width; style is "inside frame"; zero width is checked in renderers *)
brushes[brushPen].width := x
END Pen;
PROCEDURE String (VAR s: ARRAY OF CHAR);
VAR
b: BYTE;
i, len: INTEGER;
BEGIN
rd.ReadByte(b); len := b MOD 256; i := 0;
WHILE i < len DO
rd.ReadByte(b);
(* mac to windows *)
IF b >= ORD(" ") THEN s[i] := CHR(b MOD 256); INC(i) ELSE DEC(len) END
END;
s[i] := 0X
END String;
PROCEDURE PixMap (VAR rowBytes, height: INTEGER; VAR v2: BOOLEAN);
VAR
x: INTEGER;
BEGIN
ReadWord(rd, rowBytes); v2 := rowBytes >= 32768;
ReadWord(rd, x); height := x;
ReadWord(rd, x);
ReadWord(rd, x); height := x - height;
ReadWord(rd, x);
IF v2 THEN
DEC(rowBytes, 32768);
ReadWord(rd, x); ReadWord(rd, x); ReadWord(rd, x); ReadWord(rd, x);
Point(x, y); Point(x, y);
Point(x, y); Point(x, y);
ReadWord(rd, x);
ReadWord(rd, x);
ReadWord(rd, x);
ReadWord(rd, x);
ReadWord(rd, x);
ReadWord(rd, x)
END
END PixMap;
PROCEDURE ColorTab;
VAR
x, n: INTEGER;
BEGIN
ReadWord(rd, x); ReadWord(rd, x); ReadWord(rd, x); ReadWord(rd, n);
WHILE n >= 0 DO
ReadWord(rd, x); ReadWord(rd, x); ReadWord(rd, x); ReadWord(rd, x);
DEC(n)
END
END ColorTab;
PROCEDURE PixData (rowBytes, height: INTEGER; v2: BOOLEAN);
VAR
n, m: INTEGER;
b: BYTE;
BEGIN
IF rowBytes < 8 THEN
Skip(rd, rowBytes * height)
ELSIF v2 THEN
WHILE height > 0 DO
IF rowBytes > 250 THEN ReadWord(rd, n) ELSE rd.ReadByte(b); n := b MOD 256 END;
REPEAT
ReadByte(rd, m); DEC(n);
IF m >= 0 THEN
WHILE m >= 0 DO rd.ReadByte(b); DEC(n); DEC(m) END
ELSE
ASSERT(m # -128, 100);
rd.ReadByte(b); DEC(n)
END
UNTIL n <= 0;
DEC(height)
END
ELSE
WHILE height > 0 DO
IF rowBytes > 250 THEN ReadWord(rd, n) ELSE rd.ReadByte(b); n := b MOD 256 END;
Skip(rd, n); DEC(height)
END
END
END PixData;
PROCEDURE BitMap (isRegion: BOOLEAN);
VAR
x, y, w, h, l, t, r, b: INTEGER;
v2: BOOLEAN;
BEGIN
PixMap(w, h, v2);
IF v2 THEN ColorTab END;
Point(x, y); Point(x, y); Point(x, y); Point(x, y); ReadWord(rd, x);
IF isRegion THEN Region(l, t, r, b) END;
PixData(w, h, v2)
END BitMap;
PROCEDURE PixPattern;
VAR
type, x, w, h: INTEGER;
v2: BOOLEAN;
BEGIN
ReadWord(rd, type); Data(8);
IF type = 1 THEN
PixMap(w, h, v2); ColorTab; PixData(w, h, v2)
ELSIF type = 2 THEN
ReadWord(rd, x); ReadWord(rd, x); ReadWord(rd, x)
ELSE HALT(100)
END
END PixPattern;
PROCEDURE Setup;
BEGIN
CASE op MOD 8 OF
| 0: (* line with active pen *)
actBrush := brushPen;
actUsePen := TRUE; actUseBrush := FALSE
| 1: (* fill with active brush *)
actBrush := brushPen;
actUsePen := FALSE; actUseBrush := TRUE
| 2: (* fill with background brush *)
actBrush := brushBack;
actUsePen := FALSE; actUseBrush := TRUE
| 4: (* fill with fill brush *)
actBrush := brushFill;
actUsePen := FALSE; actUseBrush := TRUE
| 3, 5..7: (* draw nothing *)
actUsePen := FALSE; actUseBrush := FALSE
END
END Setup;
PROCEDURE SetLn;
BEGIN
actBrush := brushPen;
actUsePen := TRUE; actUseBrush := FALSE
END SetLn;
PROCEDURE NewFont;
VAR
weight: INTEGER;
stl: SET;
BEGIN
IF ODD(style) THEN weight := Fonts.bold ELSE weight := Fonts.normal END;
stl := {};
IF 1 IN BITS(style) THEN INCL(stl, Fonts.italic) END;
IF 2 IN BITS(style) THEN INCL(stl, Fonts.underline) END;
font := Fonts.dir.This("Arial", Round(size), stl, weight)
END NewFont;
PROCEDURE LineTo (x, y: INTEGER);
VAR
w: INTEGER;
BEGIN
IF ~clipped & actUsePen & (brushes[actBrush].width > 0) THEN
w := ConvertWidth(brushes[actBrush].width);
f.DrawLine(ConvertX(curX), ConvertY(curY),
ConvertX(x), ConvertY(y), w, brushes[actBrush].color)
(* draw last pixel *)
(*
IF w < f.unit * 2 THEN
f.DrawLine(ConvertX(lx), ConvertY(ly),
ConvertX(lx) + f.unit, ConvertY(ly) + f.unit, w, drawWith.color)
END;
*)
END;
curX := x; curY := y
END LineTo;
PROCEDURE Text (x, y: INTEGER);
VAR
str: ARRAY 256 OF CHAR;
BEGIN
String(str);
IF ~clipped THEN
IF font = NIL THEN NewFont END;
f.DrawString(ConvertX(x), ConvertY(y), Ports.black, str, font)
END
END Text;
PROCEDURE Rectangle (l, t, r, b: INTEGER);
BEGIN
IF ~clipped THEN
IF actUseBrush THEN
(* switch fold if you don't have LC new `DrawComplexPath()` API *)
ExInit; ExPattern(brushes[actBrush]);
ExCommand(Ports.pathMoveTo); ExCoords(l, t);
ExCommand(Ports.pathLineTo); ExCoords(r, t);
ExCommand(Ports.pathLineTo); ExCoords(r, b);
ExCommand(Ports.pathLineTo); ExCoords(l, b);
ExCommand(Ports.pathClose);
f.DrawComplexPath(expath, expos, Ports.fill, brushes[actBrush].brushColor)
(* switch fold if you have LC new `DrawComplexPath()` API *)
f.DrawRect(ConvertX(l), ConvertY(t), ConvertX(r), ConvertY(b),
Ports.fill, brushes[actBrush].brushColor)
END;
IF actUsePen & (brushes[actBrush].width > 0) THEN
f.DrawRect(ConvertX(l), ConvertY(t), ConvertX(r), ConvertY(b),
ConvertWidth(brushes[actBrush].width), brushes[actBrush].color)
END
END
END Rectangle;
(*
PROCEDURE DrawRoundRect (l, t, r, b, rw, rh: INTEGER);
CONST
KAPPA90 = 0.5522847493; (* Length proportional to radius of a cubic bezier handle for 90deg arcs. *)
VAR
x, y, w, h: INTEGER;
PROCEDURE Coords (x, y: REAL);
BEGIN
ExCoordsNC(SHORT(ENTIER(x + 0.5)), SHORT(ENTIER(y + 0.5)))
END Coords;
BEGIN
l := ConvertX(l); t := ConvertY(t);
r := ConvertX(r); b := ConvertY(b);
IF (r - l <= 0) OR (b - t <= 0) THEN RETURN END; (* sorry! *)
IF (rw <= 0) OR (rh <= 0) THEN
ExCommand(Ports.pathMoveTo); ExCoordsNC(l, t);
ExCommand(Ports.pathLineTo); ExCoordsNC(r, t);
ExCommand(Ports.pathLineTo); ExCoordsNC(r, b);
ExCommand(Ports.pathLineTo); ExCoordsNC(l, b)
ELSE
x := l; y := t; w := r - l; h := b - t;
ExCommand(Ports.pathMoveTo); Coords(x + rw, y);
ExCommand(Ports.pathLineTo); Coords(x + w - rw, y);
ExCommand(Ports.pathBezierTo);
Coords(x + w - rw*(1 - KAPPA90), y);
Coords(x + w, y + rh * (1 - KAPPA90));
Coords(x + w, y + rh);
ExCommand(Ports.pathLineTo); Coords(x + w, y + h - rh);
ExCommand(Ports.pathBezierTo);
Coords(x + w, y + h - rh * (1 - KAPPA90));
Coords(x + w - rw * (1 - KAPPA90), y + h);
Coords(x + w - rw, y + h);
ExCommand(Ports.pathLineTo); Coords(x + rw, y + h);
ExCommand(Ports.pathBezierTo);
Coords(x + rw * (1 - KAPPA90), y + h);
Coords(x, y + h - rh * (1 - KAPPA90));
Coords(x, y + h - rh);
ExCommand(Ports.pathLineTo); Coords(x, y + rh);
ExCommand(Ports.pathBezierTo);
Coords(x, y + rh * (1 - KAPPA90));
Coords(x + rw * (1 - KAPPA90), y);
Coords(x + rw, y)
END;
ExCommand(Ports.pathClose);
f.DrawComplexPath(expath, expos, Ports.fill, brushes[actBrush].brushColor)
END DrawRoundRect;
*)
PROCEDURE RoundRect (l, t, r, b, w, h: INTEGER);
BEGIN
(* switch fold if you don't have LC new `DrawRoundRect()` API *)
IF ~clipped THEN
IF actUseBrush THEN
(*
f.DrawRoundRect(ConvertX(l), ConvertY(t), ConvertX(r), ConvertY(b),
ConvertX(w), ConvertY(h), Ports.fill, drawWith.brushColor)
*)
ExInit; ExPattern(brushes[actBrush]);
DrawRoundRect(l, t, r, b, w, h)
END;
IF actUsePen & (brushes[actBrush].width > 0) THEN
f.DrawRoundRect(ConvertX(l), ConvertY(t), ConvertX(r), ConvertY(b),
ConvertX(w), ConvertY(h), ConvertWidth(brushes[actBrush].width),
brushes[actBrush].color)
END
END
(* switch fold if you have LC new `DrawRoundRect()` API *)
Rectangle(l, t, r, b)
END RoundRect;
PROCEDURE Ellipse (l, t, r, b: INTEGER);
BEGIN
IF ~clipped THEN
IF actUseBrush THEN
(* switch fold if you don't have LC new `DrawComplexPath()` API *)
ExInit; ExPattern(brushes[actBrush]);
ExCommand(Ports.pathEllipseTo); ExCoords(l, t); ExCoords(r, b);
f.DrawComplexPath(expath, expos, Ports.fill, brushes[actBrush].brushColor)
(* switch fold if you have LC new `DrawComplexPath()` API *)
f.DrawOval(ConvertX(l), ConvertY(t), ConvertX(r), ConvertY(b),
Ports.fill, brushes[actBrush].brushColor)
END;
IF actUsePen & (brushes[actBrush].width > 0) THEN
f.DrawOval(ConvertX(l), ConvertY(t), ConvertX(r), ConvertY(b),
ConvertWidth(brushes[actBrush].width), brushes[actBrush].color)
END
END
END Ellipse;
PROCEDURE ConvertPath (IN poly: ARRAY OF POINT; len: INTEGER);
VAR
f: INTEGER;
BEGIN
FOR f := 0 TO len - 1 DO
ppx[f].x := ConvertX(poly[f].x);
ppx[f].y := ConvertY(poly[f].y)
END
END ConvertPath;
PROCEDURE Polyline (VAR poly: ARRAY OF POINT; len: INTEGER);
BEGIN
IF ~clipped & actUsePen & (brushes[actBrush].width > 0) THEN
IF len > 1 THEN
ConvertPath(poly, len);
f.DrawPath(ppx, len, ConvertWidth(brushes[actBrush].width), brushes[actBrush].color,
Ports.openPoly)
END
END
END Polyline;
PROCEDURE Polygon (IN poly: ARRAY OF POINT; len: INTEGER);
VAR
c, linecmd: INTEGER;
BEGIN
IF ~clipped THEN
IF actUseBrush THEN
IF len > 1 THEN
(* switch fold if you don't have LC new `DrawComplexPath()` API *)
IF len > LEN(expath) DIV 3 - 8 THEN
ConvertPath(poly, len);
f.DrawPath(ppx, len, Ports.fill, brushes[actBrush].brushColor, Ports.closedPoly)
ELSE
ExInit; ExPattern(brushes[actBrush]);
linecmd := Ports.pathMoveTo;
FOR c := 0 TO len - 1 DO
ExCommand(linecmd); ExCoords(poly[c].x, poly[c].y);
linecmd := Ports.pathLineTo
END;
ExCommand(Ports.pathClose);
f.DrawComplexPath(expath, expos, Ports.fill, brushes[actBrush].brushColor)
END
END
(* switch fold if you have LC new `DrawComplexPath()` API *)
IF len > 1 THEN
ConvertPath(poly, len);
f.DrawPath(ppx, len, Ports.fill, brushes[actBrush].brushColor, Ports.closedPoly)
END
END;
IF actUsePen & (brushes[actBrush].width > 0) THEN
IF len > 1 THEN
ConvertPath(poly, len);
f.DrawPath(ppx, len, ConvertWidth(brushes[actBrush].width), brushes[actBrush].color,
Ports.closedPoly)
END
END
END
END Polygon;
BEGIN
IF (picw < 1) OR (pich < 1) THEN RETURN END; (* sorry! *)
rd := v.model.file.NewReader(NIL);
rd.SetPos(v.model.pos); end := v.model.pos + v.model.len;
ReadWord(rd, x); Point(l, t); Point(r, b); v.w := r - l; v.h := b - t; v2 := FALSE;
IF (v.w < 1) OR (v.h < 1) THEN RETURN END; (* sorry! *)
scale := picw / v.w;
IF pich / v.h < scale THEN scale := pich / v.h END;
f.rider.GetRect(rl, rt, rr, rb);
(*f.rider(HostPorts.Rider).FixOrigin;*)
font := NIL;
brushes[brushPen].width := 1;
brushes[brushPen].color := Ports.black; brushes[brushPen].brushColor := Ports.black;
brushes[brushPen].patFill := TRUE; brushes[brushPen].patEmpty := FALSE;
FOR z := 0 TO 7 DO brushes[brushPen].pat[z] := 0FFH END;
brushes[brushFill].width := -1;
brushes[brushFill].color := Ports.black; brushes[brushFill].brushColor := Ports.black;
brushes[brushFill].patFill := TRUE; brushes[brushFill].patEmpty := FALSE;
FOR z := 0 TO 7 DO brushes[brushFill].pat[z] := 0FFH END;
brushes[brushBack].width := -1;
brushes[brushBack].color := Ports.background; brushes[brushBack].brushColor := Ports.background;
brushes[brushBack].patFill := FALSE; brushes[brushBack].patEmpty := TRUE;
FOR z := 0 TO 7 DO brushes[brushBack].pat[z] := 0 END;
actBrush := brushPen; actUsePen := FALSE; actUseBrush := FALSE;
curX := 0; curY := 0;
tx := 0; ty := 0; lx := 0; ly := 0; size := 10; style := 0; clipped := FALSE;
REPEAT
rd.ReadByte(bt); op := bt MOD 256;
IF v2 THEN rd.ReadByte(bt); op := 256 * op + bt MOD 256 END;
CASE op OF
| 0: (* nop *)
| 1: (* clip *) Region(l, t, r, b); clipped := (l = 0) & (t = 0) & (r = 0) & (b = 0)
| 2: (* bgnd pattern *) Pattern(brushes[brushBack])
| 3: (* text font *) ReadWord(rd, x)
| 4: (* text face *) rd.ReadByte(bt); style := bt; NewFont
| 5: (* text mode *) ReadWord(rd, x)
| 6: (* space extra *) Point(x, y)
| 7: (* pen size *) Point(x, y); Pen(x, y)
| 8: (* pen mode *) ReadWord(rd, x)
| 9: (* pen pattern *) Pattern(brushes[brushPen])
| 0AH: (* fill pattern *) Pattern(brushes[brushFill])
| 0BH: (* oval size *) Point(ow, oh)
| 0CH: (* origin *) Point(x, y)
| 0DH: (* text size *) ReadWord(rd, size); NewFont
| 0EH: (* foreground *) ReadWord(rd, x); ReadWord(rd, y); fgnd := x * 65536 + y
| 0FH: (* background *) ReadWord(rd, x); ReadWord(rd, y); bgnd := x * 65536 + y
| 10H: (* text ratio *) Point(x, y); Point(x, y)
| 11H: (* version *) rd.ReadByte(bt); v2 := bt = 2
| 12H: (* bg pix pattern *) PixPattern
| 13H: (* pen pix pattern *) PixPattern
| 14H: (* fill pix pattern *) PixPattern
| 15H: (* fract pen pos *) ReadWord(rd, x)
| 16H: (* char extra *) ReadWord(rd, x)
| 17H..19H: (* ??? *)
| 1AH: (* rgb fg col *) ReadWord(rd, x); ReadWord(rd, y); ReadWord(rd, z)
| 1BH: (* rgb bg col *) ReadWord(rd, x); ReadWord(rd, y); ReadWord(rd, z)
| 1CH: (* hilite mode *)
| 1DH: (* rgb hl col *) ReadWord(rd, x); ReadWord(rd, y); ReadWord(rd, z)
| 1EH: (* def hilite *)
| 1FH: (* rgb op col *) ReadWord(rd, x); ReadWord(rd, y); ReadWord(rd, z)
| 20H: (* line *) Point(curX, curY); Point(lx, ly); SetLn; LineTo(lx, ly)
| 21H: (* line from *) Point(lx, ly); SetLn; LineTo(lx, ly)
| 22H: (* short line *)
Point(lx, ly); curX := lx; curY := ly;
ReadByte(rd, z); INC(lx, z); ReadByte(rd, z); INC(ly, z);
SetLn; LineTo(lx, ly)
| 23H: (* short line from *) ReadByte(rd, z); INC(lx, z); ReadByte(rd, z); INC(ly, z); SetLn; LineTo(lx, ly)
| 24H..27H: (* ??? *) ReadWord(rd, len); Data(len)
| 28H: (* long text *) Point(tx, ty); Text(tx, ty)
| 29H: (* dh text *) rd.ReadByte(bt); INC(tx, bt MOD 256); Text(tx, ty)
| 2AH: (* dv text *) rd.ReadByte(bt); INC(ty, bt MOD 256); Text(tx, ty)
| 2BH: (* dhv text *) rd.ReadByte(bt); INC(tx, bt MOD 256); rd.ReadByte(bt); INC(ty, bt MOD 256); Text(tx, ty)
| 2CH: (* font typeface ? *) ReadWord(rd, len); ReadWord(rd, x); String(str)
| 2DH..2FH: (* ??? *) ReadWord(rd, len); Data(len)
| 30H..37H: (* rect *) Point(rl, rt); Point(rr, rb); Setup; Rectangle(rl, rt, rr, rb)
| 38H..3FH: (* same rect *) Setup; Rectangle(rl, rt, rr, rb)
| 40H..47H: (* rrect *) Point(dl, dt); Point(dr, db); Setup; RoundRect(dl, dt, dr, db, ow, oh)
| 48H..4FH: (* same rrect *) Setup; RoundRect(dl, dt, dr, db, ow, oh)
| 50H..57H: (* oval *) Point(ol, ot); Point(or, ob); Setup; Ellipse(ol, ot, or, ob)
| 58H..5FH: (* same oval *) Setup; Ellipse(ol, ot, or, ob)
| 60H..67H: (* arc *) Point(al, at); Point(ar, ab); Point(aa, as)
| 68H..6FH: (* same arc *) Point(aa, as)
| 70H: (* poly *) Poly(poly, plen); SetLn; Polyline(poly, plen)
| 71H..77H: (* poly *) Poly(poly, plen); Setup; Polygon(poly, plen)
| 78H: (* same poly *) SetLn; Polyline(poly, plen)
| 79H..7FH: (* same poly *) Setup; Polygon(poly, plen)
| 80H..87H: (* rgn *) Region(gl, gt, gr, gb)
| 88H..8FH: (* same rgn *)
| 90H: (* bits rect *) BitMap(FALSE)
| 91H: (* bits rgn *) BitMap(TRUE)
| 92H..97H: (* ??? *) ReadWord(rd, len); Data(len)
| 98H: (* packed bits rect *) BitMap(FALSE)
| 99H: (* packed bits rgn *) BitMap(TRUE)
| 9AH..9FH: (* ??? *) ReadWord(rd, len); Data(len)
| 0A0H: (* short comment *) ReadWord(rd, x)
| 0A1H: (* long comment *) ReadWord(rd, x); ReadWord(rd, len); Data(len)
| 0A2H..0AFH: (* ??? *) ReadWord(rd, len); Data(len)
| 0B0H..0CFH: (* ??? *)
| 0D0H..0FEH: (* ??? *) ReadWord(rd, x); ReadWord(rd, len); Data(x * 65536 + len)
| 0FFH: (* end *)
ELSE
IF op < 8000H THEN (* ??? *) Data(op DIV 256 * 2)
ELSIF op < 8100H THEN (* ??? *)
ELSE (* ??? *) ReadWord(rd, x); ReadWord(rd, len); Data(x * 65536 + len)
END
END;
IF v2 & ODD(rd.Pos() - v.model.pos) THEN rd.ReadByte(bt) END
UNTIL (op = 0FFH) OR (rd.Pos() >= end)
END DrawMacPicture;
(*
PROCEDURE Dump (v: StdView);
VAR
rd: Files.Reader;
op, end, len, x, y: INTEGER;
v2: BOOLEAN;
b: BYTE;
str: ARRAY 256 OF CHAR;
PROCEDURE DumpBox (l, t, r, b: INTEGER);
BEGIN
Log.String("(");
Log.IntForm(l, 10, 0, ' ', FALSE);
Log.String(", "); Log.IntForm(t, 10, 0, ' ', FALSE);
Log.String(", "); Log.IntForm(r, 10, 0, ' ', FALSE);
Log.String(", "); Log.IntForm(b, 10, 0, ' ', FALSE);
Log.String(" : "); Log.IntForm(r - l, 10, 0, ' ', FALSE);
Log.String("x"); Log.IntForm(b - t, 10, 0, ' ', FALSE);
Log.String(")")
END DumpBox;
PROCEDURE DumpPoint (x, y: INTEGER);
BEGIN
Log.String("P("); Log.IntForm(x, 10, 0, ' ', FALSE);
Log.String(", "); Log.IntForm(y, 10, 0, ' ', FALSE);
Log.String(")")
END DumpPoint;
PROCEDURE Box;
VAR
l, t, r, b: INTEGER;
BEGIN
ReadI16(rd, l); ReadI16(rd, t);
ReadI16(rd, r); ReadI16(rd, b);
Log.String("Box"); DumpBox(l, t, r, b)
END Box;
PROCEDURE Point;
VAR
x, y: INTEGER;
BEGIN
ReadI16(rd, y); ReadI16(rd, x);
DumpPoint(x, y)
END Point;
PROCEDURE ShortLine;
VAR
x, y: INTEGER;
b: BYTE;
BEGIN
ReadI16(rd, y); ReadI16(rd, x);
DumpPoint(x, y);
rd.ReadByte(b); INC(x, b);
rd.ReadByte(b); INC(y, b);
Log.String(" TO "); DumpPoint(x, y)
END ShortLine;
PROCEDURE ShortLineFrom;
VAR
dx, dy: BYTE;
BEGIN
rd.ReadByte(dx); rd.ReadByte(dy);
Log.String("DP("); Log.IntForm(dx, 10, 0, ' ', FALSE);
Log.String(", "); Log.IntForm(dy, 10, 0, ' ', FALSE);
Log.String(")")
END ShortLineFrom;
PROCEDURE Data (n: INTEGER);
VAR
i: INTEGER;
BEGIN
WHILE n > 0 DO
rd.ReadByte(b); DEC(n);
i := b; IF i < 0 THEN INC(i, 256) END;
Log.Char(" ");
Log.IntForm(i, 16, 2, "0", FALSE)
END
END Data;
PROCEDURE Region;
VAR
len: INTEGER;
l, t, r, b: INTEGER;
BEGIN
ReadWord(rd, len);
ReadI16(rd, l); ReadI16(rd, t);
ReadI16(rd, r); ReadI16(rd, b);
Log.String("Region"); DumpBox(l, t, r, b);
Data(len - 10)
END Region;
PROCEDURE Text;
VAR b: BYTE; len: INTEGER;
BEGIN
rd.ReadByte(b); len := b MOD 256;
Log.String(' "');
WHILE len > 0 DO rd.ReadByte(b); Log.Char(CHR(b MOD 256)); DEC(len) END;
Log.Char('"')
END Text;
PROCEDURE String (VAR s: ARRAY OF CHAR);
VAR
b: BYTE;
i, len: INTEGER;
BEGIN
rd.ReadByte(b); len := b MOD 256; i := 0;
WHILE i < len DO
rd.ReadByte(b);
(* mac to windows *)
IF b >= ORD(" ") THEN s[i] := CHR(b MOD 256); INC(i) ELSE DEC(len) END
END;
s[i] := 0X
END String;
PROCEDURE PixMap (VAR rowBytes, height: INTEGER; VAR v2: BOOLEAN);
VAR
x: INTEGER;
BEGIN
ReadWord(rd, rowBytes); v2 := rowBytes >= 32768;
Log.Int(rowBytes);
ReadWord(rd, x); Log.Int(x); height := x;
ReadWord(rd, x); Log.Int(x);
ReadWord(rd, x); Log.Int(x); height := x - height;
ReadWord(rd, x); Log.Int(x);
IF v2 THEN
DEC(rowBytes, 32768);
ReadWord(rd, x); ReadWord(rd, x); ReadWord(rd, x); ReadWord(rd, x);
Point; Point;
Point; Point;
ReadWord(rd, x);
ReadWord(rd, x);
ReadWord(rd, x);
ReadWord(rd, x);
ReadWord(rd, x);
ReadWord(rd, x)
END
END PixMap;
PROCEDURE ColorTab;
VAR
x, n: INTEGER;
BEGIN
ReadWord(rd, x); ReadWord(rd, x); ReadWord(rd, x); ReadWord(rd, n); Log.Int(n);
WHILE n >= 0 DO
ReadWord(rd, x); ReadWord(rd, x); ReadWord(rd, x); ReadWord(rd, x);
DEC(n)
END
END ColorTab;
PROCEDURE PixData (rowBytes, height: INTEGER; v2: BOOLEAN);
VAR
n, m, k: INTEGER;
b: BYTE;
BEGIN
IF rowBytes < 8 THEN
Skip(rd, rowBytes * height)
ELSIF v2 THEN
WHILE height > 0 DO
IF rowBytes > 250 THEN ReadWord(rd, n) ELSE rd.ReadByte(b); n := b MOD 256 END;
k := 0;
REPEAT
rd.ReadByte(b); DEC(n); m := b;
IF m >= 0 THEN
WHILE m >= 0 DO rd.ReadByte(b); DEC(n); DEC(m); INC(k) END
ELSE
ASSERT(m # -128, 100);
rd.ReadByte(b); DEC(n); INC(k, 1 - m)
END
UNTIL n <= 0;
ASSERT(n = 0, 101);
ASSERT(k = rowBytes, 102);
(* Skip(rd, n); *) DEC(height)
END
ELSE
WHILE height > 0 DO
IF rowBytes > 250 THEN ReadWord(rd, n) ELSE rd.ReadByte(b); n := b MOD 256 END;
Skip(rd, n); DEC(height)
END
END
END PixData;
PROCEDURE PixPattern;
VAR
type, w, h: INTEGER;
v2: BOOLEAN;
BEGIN
ReadWord(rd, type); Data(8);
IF type = 1 THEN
PixMap(w, h, v2); ColorTab; PixData(w, h, v2)
ELSIF type = 2 THEN
ReadWord(rd, x); Log.Int(x); ReadWord(rd, x); Log.Int(x); ReadWord(rd, x); Log.Int(x)
ELSE HALT(100)
END
END PixPattern;
PROCEDURE Bits (region: BOOLEAN);
VAR w, h: INTEGER; v2: BOOLEAN;
BEGIN
PixMap(w, h, v2);
IF v2 THEN ColorTab END;
Point; Point; Point; Point; ReadWord(rd, x); Log.Int(x);
IF region THEN Region END;
PixData(w, h, v2)
END Bits;
PROCEDURE Poly;
VAR
i, l, t, r, b, len: INTEGER;
BEGIN
ReadWord(rd, len); len := (len - 10) DIV 4;
ReadI16(rd, l); ReadI16(rd, t);
ReadI16(rd, r); ReadI16(rd, b);
Log.String("Region"); DumpBox(l, t, r, b);
Log.String(" points:"); Log.Int(len); Log.String(" :");
i := 0; WHILE i < len DO Log.String(" "); Point; INC(i) END
END Poly;
PROCEDURE LongComment;
VAR
type, len, i: INTEGER;
BEGIN
ReadWord(rd, type); Log.Int(type);
ReadWord(rd, len);
IF (type = 182) & (len = 1 * 4) THEN
Log.String(" : "); Point
ELSIF (type = 150) & (len = 3 * 4) THEN
Log.String(" :"); ReadDWord(rd, i); Log.Int(i);
ReadDWord(rd, i); Log.Int(i);
ReadDWord(rd, i); Log.Int(i)
ELSIF (type = 154) & (len = 2 * 4) THEN
Log.String(" : "); Point; Log.String(" "); Point
ELSE Data(len)
END
END LongComment;
BEGIN
rd := v.model.file.NewReader(NIL);
rd.SetPos(v.model.pos); end := v.model.pos + v.model.len;
Log.String("==== MACPIC: pos:"); Log.Int(v.model.pos); Log.String("; end:"); Log.Int(end);
Log.String(" ===="); Log.Ln;
ReadWord(rd, x); Log.Int(x); Box; Log.Ln; v2 := FALSE;
REPEAT
Log.IntForm(rd.Pos(), 10, 6, ' ', FALSE); Log.String(": ");
rd.ReadByte(b); op := b MOD 256;
IF v2 THEN rd.ReadByte(b); op := 256 * op + b MOD 256 END;
Log.IntForm(op, 16, 4, "0", FALSE);
Log.String("("); Log.IntForm(op MOD 8, 10, 1, "0", FALSE);
Log.String(") ");
CASE op OF
| 0: Log.String("nop")
| 1: Log.String("clip "); Region
| 2: Log.String("bkd pattern "); Data(8)
| 3: Log.String("text font "); ReadWord(rd, x); Log.Int(x)
| 4: Log.String("text face "); rd.ReadByte(b); Log.Int(b MOD 256)
| 5: Log.String("text mode "); ReadWord(rd, x); Log.Int(x)
| 6: Log.String("space extra "); Point
| 7: Log.String("pen size "); Point
| 8: Log.String("pen mode "); ReadWord(rd, x); Log.Int(x)
| 9: Log.String("pen pattern "); Data(8)
| 0AH: Log.String("pen pattern "); Data(8)
| 0BH: Log.String("oval size "); Point
| 0CH: Log.String("origin "); Point
| 0DH: Log.String("text size "); ReadWord(rd, x); Log.Int(x)
| 0EH: Log.String("foreground "); ReadWord(rd, x); ReadWord(rd, y); Log.Int(x * 65536 + y)
| 0FH: Log.String("background "); ReadWord(rd, x); ReadWord(rd, y); Log.Int(x * 65536 + y)
| 10H: Log.String("text ratio "); Point; Point
| 11H: Log.String("version "); rd.ReadByte(b); Log.Int(b MOD 256); v2 := b = 2
| 12H: Log.String("bg pix pattern "); PixPattern
| 13H: Log.String("pen pix pattern "); PixPattern
| 14H: Log.String("fill pix pattern "); PixPattern
| 15H: Log.String("fract pen pos "); ReadWord(rd, x); Log.Int(x)
| 16H: Log.String("char extra "); ReadWord(rd, x); Log.Int(x)
| 17H..19H: Log.String("???")
| 1AH: Log.String("rgb fg col ");
ReadWord(rd, x); Log.Int(x); ReadWord(rd, x); Log.Int(x); ReadWord(rd, x); Log.Int(x)
| 1BH: Log.String("rgb bg col ");
ReadWord(rd, x); Log.Int(x); ReadWord(rd, x); Log.Int(x); ReadWord(rd, x); Log.Int(x)
| 1CH: Log.String("hilite mode")
| 1DH: Log.String("rgb hl col ");
ReadWord(rd, x); Log.Int(x); ReadWord(rd, x); Log.Int(x); ReadWord(rd, x); Log.Int(x)
| 1EH: Log.String("def hilite")
| 1FH: Log.String("rgb op col ");
ReadWord(rd, x); Log.Int(x); ReadWord(rd, x); Log.Int(x); ReadWord(rd, x); Log.Int(x)
| 20H: Log.String("line "); Point; Point
| 21H: Log.String("line from "); Point
| 22H: Log.String("short line "); ShortLine
| 23H: Log.String("short line from "); ShortLineFrom
| 24H..27H: Log.String("??? "); ReadWord(rd, len); Data(len)
| 28H: Log.String("long text "); Point; Text
| 29H: Log.String("dh text "); rd.ReadByte(b); Log.Int(b MOD 256); Text
| 2AH: Log.String("dv text "); rd.ReadByte(b); Log.Int(b MOD 256); Text
| 2BH: Log.String("dhv text ");
rd.ReadByte(b); Log.Int(b MOD 256); rd.ReadByte(b); Log.Int(b MOD 256); Text
| 2CH: (* font typeface ? *) ReadWord(rd, len); ReadWord(rd, x); String(str);
Log.String("font face: "); Log.String(str)
| 2DH..2FH: Log.String("??? "); ReadWord(rd, len); Data(len)
| 30H..37H: Log.String("rect "); Point; Point
| 38H..3FH: Log.String("same rect")
| 40H..47H: Log.String("rrect "); Point; Point
| 48H..4FH: Log.String("same rrect")
| 50H..57H: Log.String("oval "); Point; Point
| 58H..5FH: Log.String("same oval")
| 60H..67H: Log.String("arc "); Point; Point; Point
| 68H..6FH: Log.String("same arc "); Point
| 70H..77H: Log.String("poly "); Poly
| 78H..7FH: Log.String("same poly")
| 80H..87H: Log.String("rgn "); Region
| 88H..8FH: Log.String("same rgn")
| 90H: Log.String("bits rect "); Bits(FALSE)
| 91H: Log.String("bits rgn "); Bits(TRUE)
| 92H..97H: Log.String("??? "); ReadWord(rd, len); Data(len)
| 98H: Log.String("packed bits rect "); Bits(FALSE)
| 99H: Log.String("packed bits rgn "); Bits(TRUE)
| 9AH..9FH: Log.String("??? "); ReadWord(rd, len); Data(len)
| 0A0H: Log.String("short comment "); ReadWord(rd, x); Log.Int(x)
| 0A1H: Log.String("long comment "); LongComment
| 0A2H..0AFH: Log.String("??? "); ReadWord(rd, len); Data(len)
| 0B0H..0CFH: Log.String("???")
| 0D0H..0FEH: Log.String("??? "); ReadWord(rd, x); ReadWord(rd, len); Data(x * 65536 + len)
| 0FFH: Log.String("end")
ELSE
IF op < 8000H THEN Log.String("??? "); Data(op DIV 256 * 2)
ELSIF op < 8100H THEN Log.String("???")
ELSE Log.String("??? "); ReadWord(rd, x); ReadWord(rd, len); Data(x * 65536 + len)
END
END;
IF v2 & ODD(rd.Pos() - v.model.pos) THEN rd.ReadByte(b) END;
Log.Ln
UNTIL (op = 0FFH) OR (rd.Pos() >= end)
END Dump;
*)
PROCEDURE Evaluate (v: StdView);
VAR len: INTEGER; rd: Files.Reader;
BEGIN
len := v.model.len;
IF v.model.data = NIL THEN
rd := v.model.file.NewReader(NIL);
rd.SetPos(v.model.pos);
NEW(v.model.data, len);
rd.ReadBytes(v.model.data^, 0, len)
END;
IF externalDrawer # NIL THEN
v.model.ref := externalDrawer.Prepare(len, v.model.data);
ASSERT(v.model.ref # 0, 100);
END
END Evaluate;
(** **************** Model **************** **)
PROCEDURE (m: Model) FINALIZE;
BEGIN
IF (externalDrawer # NIL) & (m.ref # 0) THEN
externalDrawer.Finalize(m.ref);
m.ref := 0
END
END FINALIZE;
(** **************** View **************** **)
PROCEDURE (v: StdView) Internalize (VAR rd: Stores.Reader);
VAR m: Model; thisVersion: INTEGER;
BEGIN
v.Internalize^(rd);
IF rd.cancelled THEN RETURN END;
rd.ReadVersion(minVersion, maxVersion, thisVersion);
IF rd.cancelled THEN RETURN END;
rd.ReadByte(v.type);
IF (v.type # winPict) & (v.type # macPict) THEN rd.TurnIntoAlien(Stores.alienComponent); RETURN END;
rd.ReadInt(v.unit);
rd.ReadInt(v.w);
rd.ReadInt(v.h);
rd.ReadSChar(v.mode);
NEW(m); m.file := rd.rider.Base();
rd.ReadInt(m.len);
m.pos := rd.Pos();
m.ref := 0; (* lazy allocation of metafile *)
v.model := m;
rd.SetPos(m.pos + m.len)
END Internalize;
PROCEDURE (v: StdView) Externalize (VAR wr: Stores.Writer);
VAR len: INTEGER; r: Files.Reader; b: BYTE;
BEGIN
v.Externalize^(wr);
wr.WriteVersion(maxVersion);
wr.WriteByte(v.type);
wr.WriteInt(v.unit);
wr.WriteInt(v.w);
wr.WriteInt(v.h);
wr.WriteSChar(v.mode);
len := v.model.len;
wr.WriteInt(len);
IF v.model.data # NIL THEN
wr.rider.WriteBytes(v.model.data^, 0, len)
ELSIF v.model.file # NIL THEN
r := v.model.file.NewReader(NIL); r.SetPos(v.model.pos);
WHILE len # 0 DO r.ReadByte(b); wr.WriteSChar(SHORT(CHR(b))); DEC(len) END
ELSIF externalDrawer # NIL THEN
ASSERT(v.model.ref # 0, 100);
NEW(v.model.data, len);
externalDrawer.GetBytes(v.model.ref, len, v.model.data);
wr.rider.WriteBytes(v.model.data^, 0, len)
END
END Externalize;
PROCEDURE (v: StdView) ThisModel (): Models.Model;
BEGIN
RETURN NIL
END ThisModel;
PROCEDURE (v: StdView) CopyFromSimpleView (source: Views.View);
BEGIN
(* v.CopyFrom^(source); *)
WITH source: StdView DO
v.model := source.model;
v.type := source.type;
v.mode := source.mode;
v.w := source.w;
v.h := source.h;
v.unit := source.unit
END
END CopyFromSimpleView;
PROCEDURE (v: StdView) Restore (f: Views.Frame; l, t, r, b: INTEGER);
VAR
w, h: INTEGER;
BEGIN
ASSERT(v.model # NIL, 20);
v.context.GetSize(w, h);
IF v.type = winPict THEN
IF v.model.ref = 0 THEN Evaluate(v) END;
IF externalDrawer # NIL THEN
externalDrawer.Draw(f, v.model.ref, ORD(v.mode), f.gx, f.gy, w, h)
END;
ELSIF v.type = macPict THEN
IF drawBackRect THEN
f.DrawRect(l, t, r, b, Ports.fill, Ports.green)
ELSE
f.DrawRect(l, t, r, b, Ports.fill, Ports.background)
END;
DrawMacPicture(v, f, w DIV f.unit, h DIV f.unit)
END
END Restore;
PROCEDURE (v: StdView) GetBkgndFor (f: Views.Frame; VAR col: Ports.Color;
VAR homogeneous: BOOLEAN), NEW;
BEGIN
col := Ports.background
END GetBkgndFor;
PROCEDURE (v: StdView) HandlePropMsg (VAR msg: Properties.Message);
BEGIN
WITH msg: Properties.SizePref DO
IF (msg.w > Views.undefined) & (msg.h > Views.undefined) THEN
IF (v.type = macPict) & (v.w # 0) & (v.h # 0) OR (v.mode = 7X) THEN (* isotropic mode *)
Properties.ProportionalConstraint(ABS(v.w), ABS(v.h), msg.fixedW, msg.fixedH, msg.w, msg.h)
END
ELSE
IF (v.w > 0) & (v.h > 0) THEN (* default sizes *)
msg.w := ABS(v.w); msg.h := ABS(v.h)
END
END
ELSE
END
END HandlePropMsg;
(*
PROCEDURE (v: StdView) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message;
VAR focus: Views.View);
BEGIN
IF doDump THEN
WITH msg: Controllers.TrackMsg DO
IF v.type = macPict THEN Dump(v) END
ELSE
END
END
END HandleCtrlMsg;
*)
PROCEDURE PictType* (v: Views.View): INTEGER;
BEGIN
WITH v: StdView DO RETURN v.type
ELSE RETURN -1
END
END PictType;
PROCEDURE SetDrawBackRect*;
BEGIN
drawBackRect := TRUE
END SetDrawBackRect;
PROCEDURE ResetDrawBackRect*;
BEGIN
drawBackRect := FALSE
END ResetDrawBackRect;
PROCEDURE SetDoDump*;
BEGIN
doDump := TRUE
END SetDoDump;
PROCEDURE ResetDoDump*;
BEGIN
doDump := FALSE
END ResetDoDump;
BEGIN
IF Dialog.platform = Dialog.windows THEN Kernel.LoadMod("WinPictures") END;
drawBackRect := FALSE;
doDump := FALSE
END StdPictures.
| Std/Mod/Pictures.odc |
MODULE StdRasters;
(**
project = "BlackBox 2.0, new module"
organization = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Oberon microsystems, Anton Dmitriev, Ketmar Dark, Ivan Denisov"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 20231130, ivan, add scale by Ketmar Dark
"
issues = "
- ...
"
**)
IMPORT SYSTEM, Ports, Files, Models, Views, Stores, Properties;
CONST
minVersion = 0; maxVersion = 0;
cBadModel = 1;
(* InitFromFileRange: copy *)
shallow* = FALSE; deep* = TRUE;
(* NewFromFile, NewModelFromFile: reference *)
reference* = TRUE;
(** source color swapping *)
swap* = TRUE; noSwap* = FALSE;
(* drawable raster scaling quality *)
nearest* = 0; bilinear* = 1;
TYPE
ADDRESS = INTEGER;
SIZET = INTEGER;
TYPE
ImageLoader* = POINTER TO ABSTRACT RECORD END;
RasterData* = ARRAY OF Ports.Color;
Image* = POINTER TO RECORD
width*, height*: INTEGER;
dpiX*, dpiY*: INTEGER; (* can be 0 if unknown; if one is 0, then the other is 0 too *)
data*: POINTER TO RasterData;
END;
Raster* = POINTER TO ABSTRACT RECORD (Ports.Raster)
(** StdRaster's storage presentation is:
.rd.Base()[.beg, .end). .rd = NIL => uninitialized *)
rd-: Files.Reader;
beg-, end-: INTEGER;
END;
Model* = POINTER TO RECORD (Models.Model)
raster-: Raster;
type-: Files.Type;
filepath: Files.Name; (* # '' => .raster references external file filepath, = '' => Model carries file data for .raster, normally in the same file as Model itself *)
END;
View* = POINTER TO RECORD (Views.View)
model: Model;
END;
Directory* = POINTER TO ABSTRACT RECORD
type-: Files.Type;
loader: ImageLoader;
next: Directory;
END;
VAR
list: Directory;
buffer: ARRAY 10 * 1024 OF BYTE;
PROCEDURE (ldr: ImageLoader) Detect* (rd: Files.Reader): BOOLEAN, NEW, ABSTRACT;
PROCEDURE (ldr: ImageLoader) Load* (rd: Files.Reader): Image, NEW, ABSTRACT;
PROCEDURE (ldr: ImageLoader) GetInfo* (rd: Files.Reader): Image, NEW, ABSTRACT;
PROCEDURE Load* (r: Raster): Image;
VAR pos: INTEGER; img: Image; ok: BOOLEAN; d: Directory; rd: Files.Reader;
BEGIN
rd := r.rd;
img := NIL;
IF ~rd.eof THEN
pos := r.beg;
d := list;
WHILE (d # NIL) & (img = NIL) DO
IF d.loader # NIL THEN
ok := d.loader.Detect(rd);
rd.SetPos(pos);
IF ok THEN
img := d.loader.Load(rd);
IF img = NIL THEN
rd.SetPos(pos);
END
END
END;
d := d.next
END
END;
RETURN img
END Load;
PROCEDURE (d: Directory) New* (): Raster, NEW, ABSTRACT;
PROCEDURE (d: Directory) HandlesFType* (IN type: Files.Type): BOOLEAN, NEW, ABSTRACT;
PROCEDURE CanHandle* (IN ftype: Files.Type): BOOLEAN;
VAR d: Directory;
BEGIN
d := list; WHILE (d # NIL) & ~d.HandlesFType(ftype) DO d := d.next END;
RETURN d # NIL
END CanHandle;
PROCEDURE AddDirectory* (d: Directory; type: Files.Type; loader: ImageLoader);
VAR tmp: Directory;
BEGIN
ASSERT(d # NIL, 20);
d.type := type;
d.loader := loader;
IF list = NIL THEN
list := d;
ELSE
tmp := list;
ASSERT(tmp.type # type, 22);
WHILE tmp.next # NIL DO
tmp := tmp.next;
ASSERT(tmp.type # type, 22);
END;
tmp.next := d
END
END AddDirectory;
PROCEDURE ThisDirectory (ftype: Files.Type): Directory;
(** Fetch the first directory that handles file type ftype *)
VAR d: Directory;
BEGIN
d := list;
WHILE (d # NIL) & ~d.HandlesFType(ftype) DO
d := d.next
END;
RETURN d
END ThisDirectory;
PROCEDURE New* (type: Files.Type): Raster;
VAR dir: Directory;
BEGIN
dir := ThisDirectory(type); ASSERT(dir # NIL, 20);
RETURN dir.New()
END New;
PROCEDURE CopyFileRange (from: Files.Reader; beg, end: INTEGER; to: Files.Writer);
(** Make a copy of from.Base()[beg, end) into to *)
VAR len, chunk: INTEGER;
BEGIN
len := end - beg;
from.SetPos(beg);
WHILE len > 0 DO
chunk := MIN(len, LEN(buffer));
from.ReadBytes(buffer, 0, chunk);
to.WriteBytes(buffer, 0, chunk);
DEC(len, chunk)
END
END CopyFileRange;
PROCEDURE (r: Raster) InitFileRange-, NEW, EMPTY;
PROCEDURE InitFromFileRange* (r: Raster; rd: Files.Reader; beg, end: INTEGER; copy: BOOLEAN);
(** ~copy => r will reference rd.Base(); copy => a copy of rd.Base[beg, end) is made to be referenced by r *)
VAR f: Files.File;
BEGIN
ASSERT(r # NIL, 20); ASSERT(r.rd = NIL, 21); ASSERT(rd # NIL, 22);
IF ~copy THEN
r.rd := rd.Base().NewReader(NIL); r.beg := beg; r.end := end
ELSE
f := Files.dir.Temp(); r.rd := f.NewReader(NIL);
r.beg := 0; r.end := end - beg;
CopyFileRange(rd, beg, end, f.NewWriter(NIL))
END;
r.InitFileRange
END InitFromFileRange;
PROCEDURE NewModel* (r: Raster; IN type: Files.Type): Model;
VAR m: Model;
BEGIN
ASSERT(r # NIL, 20); NEW(m); m.raster := r; m.type := type$; m.filepath := ''; RETURN m
END NewModel;
PROCEDURE NewModelFromSpec* (loc: Files.Locator; IN fname: Files.Name; reference: BOOLEAN): Model;
(** reference => the model is to hold a reference to the file rather than the file content; ~reference => the model is to hold a copy of the file's content *)
VAR m: Model; f: Files.File; r: Raster; d: Directory;
BEGIN
ASSERT(loc # NIL, 20); ASSERT(loc.res = 0, 21); ASSERT(fname # '', 22);
IF reference THEN HALT(126)
ELSE
f := Files.dir.Old(loc, fname, Files.shared);
ASSERT(f # NIL, 23);
d := ThisDirectory(f.type); ASSERT(d # NIL, 24);
r := d.New(); ASSERT(r # NIL, 60);
NEW(m); m.raster := r; m.type := d.type$; m.filepath := '';
InitFromFileRange(m.raster, f.NewReader(NIL), 0, f.Length(), deep)
END;
RETURN m
END NewModelFromSpec;
PROCEDURE NewView* (m: Model): View;
VAR v: View;
BEGIN
ASSERT(m # NIL, 20); NEW(v); v.model := m; Stores.Join(v, m); RETURN v
END NewView;
PROCEDURE (m: Model) Externalize- (VAR wr: Stores.Writer);
BEGIN
wr.WriteVersion(maxVersion);
wr.WriteString(m.filepath);
wr.WriteString(m.type);
IF m.filepath = '' THEN (* Copy storage presentation of .raster into wr *)
wr.WriteInt(m.raster.end - m.raster.beg);
CopyFileRange(m.raster.rd, m.raster.beg, m.raster.end, wr.rider)
END;
END Externalize;
PROCEDURE (m: Model) Internalize- (VAR rd: Stores.Reader);
VAR beg, len, _version: INTEGER; d: Directory;
BEGIN
rd.ReadVersion(minVersion, maxVersion, _version);
IF ~rd.cancelled THEN
rd.ReadString(m.filepath);
rd.ReadString(m.type);
IF m.filepath = '' THEN
rd.ReadInt(len); beg := rd.Pos();
d := ThisDirectory(m.type);
IF d # NIL THEN
m.raster := d.New();
InitFromFileRange(m.raster, rd.rider, beg, beg + len, shallow);
rd.SetPos(beg +len)
ELSE
rd.SetPos(beg +len);
rd.TurnIntoAlien(Stores.alienComponent);
END
ELSE HALT(126)
END
END
END Internalize;
PROCEDURE (m: Model) CopyFrom- (source: Stores.Store);
VAR r: Raster;
BEGIN
WITH source: Model DO
r := source.raster;
m.type := source.type;
m.raster := New(m.type); ASSERT(m.raster # NIL, 60);
InitFromFileRange(m.raster, r.rd, r.beg, r.end, deep)
END
END CopyFrom;
(* View *)
PROCEDURE (v: View) Restore* (f: Views.Frame; _l, _t, _r, _b: INTEGER);
BEGIN ASSERT(v.model # NIL, 20);
f.DrawRaster(v.model.raster, 0, 0)
END Restore;
PROCEDURE (v: View) HandlePropMsg- (VAR msg: Properties.Message);
BEGIN
WITH
| msg: Properties.BoundsPref DO v.model.raster.GetSize(msg.w, msg.h)
| msg: Properties.SizePref DO
IF (msg.w = Views.undefined) OR (msg.h = Views.undefined) THEN
v.model.raster.GetSize(msg.w, msg.h)
END
| msg: Properties.ResizePref DO
msg.fixed := TRUE
ELSE
END
END HandlePropMsg;
PROCEDURE (v: View) Externalize- (VAR wr: Stores.Writer);
BEGIN
wr.WriteVersion(maxVersion);
wr.WriteStore(v.model)
END Externalize;
PROCEDURE (v: View) Internalize- (VAR rd: Stores.Reader);
VAR _version: INTEGER; s: Stores.Store;
BEGIN
rd.ReadVersion(minVersion, maxVersion, _version);
IF ~rd.cancelled THEN
rd.ReadStore(s);
WITH s: Model DO
v.model := s
ELSE
rd.TurnIntoAlien(cBadModel)
END
END
END Internalize;
PROCEDURE (v: View) CopyFromModelView- (source: Views.View; model: Models.Model);
BEGIN
IF model = NIL THEN v.model := Models.CopyOf(source(View).model)(Model)
ELSE v.model := model(Model)
END
END CopyFromModelView;
(* Converters *)
PROCEDURE Import* (f: Files.File; OUT s: Stores.Store);
VAR r: Raster; d: Directory;
BEGIN
ASSERT(f # NIL, 20); ASSERT(f.type # '', 21);
d := ThisDirectory(f.type); ASSERT(d # NIL, 22);
IF d # NIL THEN
r := d.New(); InitFromFileRange(r, f.NewReader(NIL), 0, f.Length(), deep);
s := NewView(NewModel(r, d.type))
END
END Import;
PROCEDURE Bounds (val, min, max: INTEGER): INTEGER;
BEGIN RETURN MAX(min, MIN(val, max))
END Bounds;
(* based on the code from A2 *)
(* swap R and B components *)
PROCEDURE [code] SwapRB (c: Ports.Color): Ports.Color 0FH, 0C8H, 0C1H, 0C8H, 08H;
PROCEDURE Q0BGRA8888BGRA8888Copy (srcadr, dstadr: ADDRESS; srcbpr, dstbpr, dl, dt, dr, db: INTEGER;
sx, sy, sdx, sdy, sw, sh: INTEGER);
VAR
x, y: INTEGER;
yadr, adr: ADDRESS;
col0: INTEGER;
yadd: ADDRESS;
fx, fy: INTEGER;
BEGIN
fy := sy;
yadr := dstadr + dl * 4 + dt * dstbpr;
FOR y := dt TO db - 1 DO
fx := sx; adr := yadr; yadd := srcadr + (fy DIV 65536) * srcbpr;
FOR x := dl TO dr - 1 DO
SYSTEM.GET(yadd + (fx DIV 65536) * 4, col0);
SYSTEM.PUT(adr, col0);
INC(fx, sdx);
INC(adr, 4)
END;
INC(fy, sdy);
INC(yadr, dstbpr)
END
END Q0BGRA8888BGRA8888Copy;
PROCEDURE Q0BGRA8888BGRA8888CopySW (srcadr, dstadr: ADDRESS; srcbpr, dstbpr, dl, dt, dr, db: INTEGER;
sx, sy, sdx, sdy, sw, sh: INTEGER);
VAR
x, y: INTEGER;
yadr, adr: ADDRESS;
col, col0: INTEGER;
yadd: ADDRESS;
fx, fy: INTEGER;
BEGIN
fy := sy;
yadr := dstadr + dl * 4 + dt * dstbpr;
FOR y := dt TO db - 1 DO
fx := sx; adr := yadr; yadd := srcadr + (fy DIV 65536) * srcbpr;
FOR x := dl TO dr - 1 DO
SYSTEM.GET(yadd + (fx DIV 65536) * 4, col0);
col0 := SwapRB(col0);
SYSTEM.PUT(adr, col0);
INC(fx, sdx);
INC(adr, 4)
END;
INC(fy, sdy);
INC(yadr, dstbpr)
END
END Q0BGRA8888BGRA8888CopySW;
PROCEDURE Q1BGRA8888BGRA8888Copy (srcadr, dstadr: ADDRESS; srcbpr, dstbpr, dl, dt, dr, db: INTEGER;
sx, sy, sdx, sdy, sw, sh: INTEGER);
VAR
x, y, xfleft, xfright, yftop, yfbottom: INTEGER;
yadr: ADDRESS;
col, col0, col1, col2, col3: INTEGER;
b0, g0, r0, a0, b1, g1, r1, a1, cb, cg, cr, ca: INTEGER;
fx, fy, xadd0, xadd1: INTEGER;
yadd0, yadd1: ADDRESS;
BEGIN
yadr := dstadr + dl * 4 + dt * dstbpr;
fy := sy - 8000H; sx := sx - 8000H;
FOR y := dt TO db - 1 DO
fx := sx; dstadr := yadr;
yadd0 := srcadr + Bounds(fy DIV 65536, 0, sh - 1) * srcbpr;
yadd1 := srcadr + Bounds(fy DIV 65536 + 1, 0, sh - 1) * srcbpr;
FOR x := dl TO dr - 1 DO
(* destination color *)
xadd0 := Bounds(fx DIV 65536, 0, sw - 1) * 4;
xadd1 := Bounds(fx DIV 65536 + 1, 0, sw - 1) * 4;
SYSTEM.GET(yadd0 + xadd0, col0);
SYSTEM.GET(yadd0 + xadd1, col1);
SYSTEM.GET(yadd1 + xadd0, col2);
SYSTEM.GET(yadd1 + xadd1, col3);
xfleft := (65536 - fx MOD 65536);
xfright := (fx MOD 65536);
yftop := (65536 - fy MOD 65536);
yfbottom := (fy MOD 65536);
a0 := ((col0 DIV 1000000H MOD 100H) * xfleft + (col1 DIV 1000000H MOD 100H) * xfright) DIV 65536;
a1 := ((col2 DIV 1000000H MOD 100H) * xfleft + (col3 DIV 1000000H MOD 100H) * xfright) DIV 65536;
ca := (a0 * yftop + a1 * yfbottom) DIV 65536;
IF ca # 0 THEN
b0 := ((col0 MOD 100H) * xfleft + (col1 MOD 100H) * xfright) DIV 65536;
g0 := ((col0 DIV 100H MOD 100H) * xfleft + (col1 DIV 100H MOD 100H) * xfright) DIV 65536;
r0 := ((col0 DIV 10000H MOD 100H) * xfleft + (col1 DIV 10000H MOD 100H) * xfright) DIV 65536;
b1 := ((col2 MOD 100H) * xfleft + (col3 MOD 100H) * xfright) DIV 65536;
g1 := ((col2 DIV 100H MOD 100H) * xfleft + (col3 DIV 100H MOD 100H) * xfright) DIV 65536;
r1 := ((col2 DIV 10000H MOD 100H) * xfleft + (col3 DIV 10000H MOD 100H) * xfright) DIV 65536;
cb := (b0 * yftop + b1 * yfbottom) DIV 65536;
cg := (g0 * yftop + g1 * yfbottom) DIV 65536;
cr := (r0 * yftop + r1 * yfbottom) DIV 65536;
SYSTEM.PUT(dstadr, cb + ASH(cg, 8) + ASH(cr, 16) + ASH(ca, 24))
END;
INC(fx, sdx);
INC(dstadr, 4);
END;
INC(fy, sdy);
INC(yadr, dstbpr)
END
END Q1BGRA8888BGRA8888Copy;
PROCEDURE Q1BGRA8888BGRA8888CopySW (srcadr, dstadr: ADDRESS; srcbpr, dstbpr, dl, dt, dr, db: INTEGER;
sx, sy, sdx, sdy, sw, sh: INTEGER);
VAR
x, y, xfleft, xfright, yftop, yfbottom: INTEGER;
yadr: ADDRESS;
col, col0, col1, col2, col3: INTEGER;
b0, g0, r0, a0, b1, g1, r1, a1, cb, cg, cr, ca: INTEGER;
fx, fy, xadd0, xadd1: INTEGER;
yadd0, yadd1: ADDRESS;
BEGIN
yadr := dstadr + dl * 4 + dt * dstbpr;
fy := sy - 8000H; sx := sx - 8000H;
FOR y := dt TO db - 1 DO
fx := sx; dstadr := yadr;
yadd0 := srcadr + Bounds(fy DIV 65536, 0, sh - 1) * srcbpr;
yadd1 := srcadr + Bounds(fy DIV 65536 + 1, 0, sh - 1) * srcbpr;
FOR x := dl TO dr - 1 DO
(* destination color *)
xadd0 := Bounds(fx DIV 65536, 0, sw - 1) * 4;
xadd1 := Bounds(fx DIV 65536 + 1, 0, sw - 1) * 4;
SYSTEM.GET(yadd0 + xadd0, col0);
col0 := SwapRB(col0);
SYSTEM.GET(yadd0 + xadd1, col1);
col1 := SwapRB(col1);
SYSTEM.GET(yadd1 + xadd0, col2);
col2 := SwapRB(col2);
SYSTEM.GET(yadd1 + xadd1, col3);
col3 := SwapRB(col3);
xfleft := (65536 - fx MOD 65536);
xfright := (fx MOD 65536);
yftop := (65536 - fy MOD 65536);
yfbottom := (fy MOD 65536);
a0 := ((col0 DIV 1000000H MOD 100H) * xfleft + (col1 DIV 1000000H MOD 100H) * xfright) DIV 65536;
a1 := ((col2 DIV 1000000H MOD 100H) * xfleft + (col3 DIV 1000000H MOD 100H) * xfright) DIV 65536;
ca := (a0 * yftop + a1 * yfbottom) DIV 65536;
IF ca # 0 THEN
b0 := ((col0 MOD 100H) * xfleft + (col1 MOD 100H) * xfright) DIV 65536;
g0 := ((col0 DIV 100H MOD 100H) * xfleft + (col1 DIV 100H MOD 100H) * xfright) DIV 65536;
r0 := ((col0 DIV 10000H MOD 100H) * xfleft + (col1 DIV 10000H MOD 100H) * xfright) DIV 65536;
b1 := ((col2 MOD 100H) * xfleft + (col3 MOD 100H) * xfright) DIV 65536;
g1 := ((col2 DIV 100H MOD 100H) * xfleft + (col3 DIV 100H MOD 100H) * xfright) DIV 65536;
r1 := ((col2 DIV 10000H MOD 100H) * xfleft + (col3 DIV 10000H MOD 100H) * xfright) DIV 65536;
cb := (b0 * yftop + b1 * yfbottom) DIV 65536;
cg := (g0 * yftop + g1 * yfbottom) DIV 65536;
cr := (r0 * yftop + r1 * yfbottom) DIV 65536;
SYSTEM.PUT(dstadr, cb + ASH(cg, 8) + ASH(cr, 16) + ASH(ca, 24))
END;
INC(fx, sdx);
INC(dstadr, 4);
END;
INC(fy, sdy);
INC(yadr, dstbpr)
END
END Q1BGRA8888BGRA8888CopySW;
(* blend *)
PROCEDURE Q0BGRA8888BGRA8888 (srcadr, dstadr: ADDRESS; srcbpr, dstbpr, dl, dt, dr, db, sx, sy, sdx, sdy, sw, sh: INTEGER);
VAR
x, y: INTEGER;
yadr, adr: ADDRESS;
col, col0: INTEGER;
cb, cg, cr, ca, dstb, dstg, dstr: INTEGER;
yadd: ADDRESS;
fx, fy: INTEGER;
BEGIN
fy := sy; yadr := dstadr + dl * 4 + dt * dstbpr;
FOR y := dt TO db - 1 DO
fx := sx;
adr := yadr;
yadd := srcadr + (fy DIV 65536) * srcbpr;
FOR x := dl TO dr - 1 DO
(* destination color *)
SYSTEM.GET(adr, col);
dstb := (col MOD 100H);
dstg := (col DIV 100H) MOD 100H;
dstr := (col DIV 10000H) MOD 100H;
SYSTEM.GET(yadd + (fx DIV 65536) * 4, col0);
ca := (col0 DIV 1000000H MOD 100H);
IF ca # 0 THEN
cb := (col0 MOD 100H);
cg := (col0 DIV 100H MOD 100H);
cr := (col0 DIV 10000H MOD 100H);
IF ca # 255 THEN
cb := MIN((cb * 256 + (256 - ca) * dstb) DIV 256, 255);
cg := MIN((cg * 256 + (256 - ca) * dstg) DIV 256, 255);
cr := MIN((cr * 256 + (256 - ca) * dstr) DIV 256, 255)
END;
SYSTEM.PUT(adr, cb + ASH(cg, 8) + ASH(cr, 16) + 0FF000000H)
END;
INC(fx, sdx);
INC(adr, 4)
END;
INC(fy, sdy);
INC(yadr, dstbpr)
END
END Q0BGRA8888BGRA8888;
(* blend *)
PROCEDURE Q0BGRA8888BGRA8888SW (srcadr, dstadr: ADDRESS; srcbpr, dstbpr, dl, dt, dr, db, sx, sy, sdx, sdy, sw, sh: INTEGER);
VAR
x, y: INTEGER;
yadr, adr: ADDRESS;
col, col0: INTEGER;
cb, cg, cr, ca, dstb, dstg, dstr: INTEGER;
yadd: ADDRESS;
fx, fy: INTEGER;
BEGIN
fy := sy; yadr := dstadr + dl * 4 + dt * dstbpr;
FOR y := dt TO db - 1 DO
fx := sx;
adr := yadr;
yadd := srcadr + (fy DIV 65536) * srcbpr;
FOR x := dl TO dr - 1 DO
(* destination color *)
SYSTEM.GET(adr, col);
col := SwapRB(col);
dstb := (col MOD 100H);
dstg := (col DIV 100H) MOD 100H;
dstr := (col DIV 10000H) MOD 100H;
SYSTEM.GET(yadd + (fx DIV 65536) * 4, col0);
ca := (col0 DIV 1000000H MOD 100H);
IF ca # 0 THEN
cb := (col0 MOD 100H);
cg := (col0 DIV 100H MOD 100H);
cr := (col0 DIV 10000H MOD 100H);
IF ca # 255 THEN
cb := MIN((cb * 256 + (256 - ca) * dstb) DIV 256, 255);
cg := MIN((cg * 256 + (256 - ca) * dstg) DIV 256, 255);
cr := MIN((cr * 256 + (256 - ca) * dstr) DIV 256, 255)
END;
SYSTEM.PUT(adr, cb + ASH(cg, 8) + ASH(cr, 16) + 0FF000000H)
END;
INC(fx, sdx);
INC(adr, 4)
END;
INC(fy, sdy);
INC(yadr, dstbpr)
END
END Q0BGRA8888BGRA8888SW;
(* blend *)
PROCEDURE Q1BGRA8888BGRA8888 (srcadr, dstadr: ADDRESS; srcbpr, dstbpr, dl, dt, dr, db, sx, sy, sdx, sdy, sw, sh: INTEGER);
VAR
x, y, xfleft, xfright, yftop, yfbottom: INTEGER;
yadr: ADDRESS;
col, col0, col1, col2, col3 : INTEGER;
b0, g0, r0, a0, b1, g1, r1, a1, cb, cg, cr, ca, dstb, dstg, dstr: INTEGER;
fx, fy, xadd0, xadd1: INTEGER;
yadd0, yadd1: ADDRESS;
BEGIN
yadr := dstadr + dl * 4 + dt * dstbpr;
fy := sy - 8000H; sx := sx - 8000H;
FOR y := dt TO db - 1 DO
fx := sx;
dstadr := yadr;
yadd0 := srcadr + Bounds(fy DIV 65536, 0, sh - 1) * srcbpr;
yadd1 := srcadr + Bounds(fy DIV 65536 + 1, 0, sh - 1) * srcbpr;
FOR x := dl TO dr - 1 DO
(* destination color *)
SYSTEM.GET(dstadr, col);
dstb := col MOD 100H;
dstg := col DIV 100H MOD 100H;
dstr := col DIV 10000H MOD 100H;
xadd0 := Bounds(fx DIV 65536, 0, sw - 1) * 4;
xadd1 := Bounds(fx DIV 65536 + 1, 0, sw - 1) * 4;
SYSTEM.GET(yadd0 + xadd0, col0);
SYSTEM.GET(yadd0 + xadd1, col1);
SYSTEM.GET(yadd1 + xadd0, col2);
SYSTEM.GET(yadd1 + xadd1, col3);
xfleft := (65536 - fx MOD 65536);
xfright := (fx MOD 65536);
yftop := (65536 - fy MOD 65536);
yfbottom := (fy MOD 65536);
a0 := ((col0 DIV 1000000H MOD 100H) * xfleft + (col1 DIV 1000000H MOD 100H) * xfright) DIV 65536;
a1 := ((col2 DIV 1000000H MOD 100H) * xfleft + (col3 DIV 1000000H MOD 100H) * xfright) DIV 65536;
ca := (a0 * yftop + a1 * yfbottom) DIV 65536;
IF ca # 0 THEN
b0 := ((col0 MOD 100H) * xfleft + (col1 MOD 100H) * xfright) DIV 65536;
g0 := ((col0 DIV 100H MOD 100H) * xfleft + (col1 DIV 100H MOD 100H) * xfright) DIV 65536;
r0 := ((col0 DIV 10000H MOD 100H) * xfleft + (col1 DIV 10000H MOD 100H) * xfright) DIV 65536;
a0 := ((col0 DIV 1000000H MOD 100H) * xfleft + (col1 DIV 1000000H MOD 100H) * xfright) DIV 65536;
b1 := ((col2 MOD 100H) * xfleft + (col3 MOD 100H) * xfright) DIV 65536;
g1 := ((col2 DIV 100H MOD 100H) * xfleft + (col3 DIV 100H MOD 100H) * xfright) DIV 65536;
r1 := ((col2 DIV 10000H MOD 100H) * xfleft + (col3 DIV 10000H MOD 100H) * xfright) DIV 65536;
a1 := ((col2 DIV 1000000H MOD 100H) * xfleft + (col3 DIV 1000000H MOD 100H) * xfright) DIV 65536;
cb := (b0 * yftop + b1 * yfbottom) DIV 65536;
cg := (g0 * yftop + g1 * yfbottom) DIV 65536;
cr := (r0 * yftop + r1 * yfbottom) DIV 65536;
ca := (a0 * yftop + a1 * yfbottom) DIV 65536;
IF ca # 255 THEN
cb := MIN((cb * 256 + (256 - ca) * dstb) DIV 256, 255);
cg := MIN((cg * 256 + (256 - ca) * dstg) DIV 256, 255);
cr := MIN((cr * 256 + (256 - ca) * dstr) DIV 256, 255)
END;
SYSTEM.PUT(dstadr, cb + ASH(cg, 8) + ASH(cr, 16) + 0FF000000H)
END;
INC(fx, sdx);
INC(dstadr, 4)
END;
INC(fy, sdy);
INC(yadr, dstbpr)
END
END Q1BGRA8888BGRA8888;
(* blend *)
PROCEDURE Q1BGRA8888BGRA8888SW (srcadr, dstadr: ADDRESS; srcbpr, dstbpr, dl, dt, dr, db, sx, sy, sdx, sdy, sw, sh: INTEGER);
VAR
x, y, xfleft, xfright, yftop, yfbottom: INTEGER;
yadr: ADDRESS;
col, col0, col1, col2, col3 : INTEGER;
b0, g0, r0, a0, b1, g1, r1, a1, cb, cg, cr, ca, dstb, dstg, dstr: INTEGER;
fx, fy, xadd0, xadd1: INTEGER;
yadd0, yadd1: ADDRESS;
BEGIN
yadr := dstadr + dl * 4 + dt * dstbpr;
fy := sy - 8000H; sx := sx - 8000H;
FOR y := dt TO db - 1 DO
fx := sx;
dstadr := yadr;
yadd0 := srcadr + Bounds(fy DIV 65536, 0, sh - 1) * srcbpr;
yadd1 := srcadr + Bounds(fy DIV 65536 + 1, 0, sh - 1) * srcbpr;
FOR x := dl TO dr - 1 DO
(* destination color *)
SYSTEM.GET(dstadr, col);
dstb := col MOD 100H;
dstg := col DIV 100H MOD 100H;
dstr := col DIV 10000H MOD 100H;
xadd0 := Bounds(fx DIV 65536, 0, sw - 1) * 4;
xadd1 := Bounds(fx DIV 65536 + 1, 0, sw - 1) * 4;
SYSTEM.GET(yadd0 + xadd0, col0);
col0 := SwapRB(col0);
SYSTEM.GET(yadd0 + xadd1, col1);
col1 := SwapRB(col1);
SYSTEM.GET(yadd1 + xadd0, col2);
col2 := SwapRB(col2);
SYSTEM.GET(yadd1 + xadd1, col3);
col3 := SwapRB(col3);
xfleft := (65536 - fx MOD 65536);
xfright := (fx MOD 65536);
yftop := (65536 - fy MOD 65536);
yfbottom := (fy MOD 65536);
a0 := ((col0 DIV 1000000H MOD 100H) * xfleft + (col1 DIV 1000000H MOD 100H) * xfright) DIV 65536;
a1 := ((col2 DIV 1000000H MOD 100H) * xfleft + (col3 DIV 1000000H MOD 100H) * xfright) DIV 65536;
ca := (a0 * yftop + a1 * yfbottom) DIV 65536;
IF ca # 0 THEN
b0 := ((col0 MOD 100H) * xfleft + (col1 MOD 100H) * xfright) DIV 65536;
g0 := ((col0 DIV 100H MOD 100H) * xfleft + (col1 DIV 100H MOD 100H) * xfright) DIV 65536;
r0 := ((col0 DIV 10000H MOD 100H) * xfleft + (col1 DIV 10000H MOD 100H) * xfright) DIV 65536;
a0 := ((col0 DIV 1000000H MOD 100H) * xfleft + (col1 DIV 1000000H MOD 100H) * xfright) DIV 65536;
b1 := ((col2 MOD 100H) * xfleft + (col3 MOD 100H) * xfright) DIV 65536;
g1 := ((col2 DIV 100H MOD 100H) * xfleft + (col3 DIV 100H MOD 100H) * xfright) DIV 65536;
r1 := ((col2 DIV 10000H MOD 100H) * xfleft + (col3 DIV 10000H MOD 100H) * xfright) DIV 65536;
a1 := ((col2 DIV 1000000H MOD 100H) * xfleft + (col3 DIV 1000000H MOD 100H) * xfright) DIV 65536;
cb := (b0 * yftop + b1 * yfbottom) DIV 65536;
cg := (g0 * yftop + g1 * yfbottom) DIV 65536;
cr := (r0 * yftop + r1 * yfbottom) DIV 65536;
ca := (a0 * yftop + a1 * yfbottom) DIV 65536;
IF ca # 255 THEN
cb := MIN((cb * 256 + (256 - ca) * dstb) DIV 256, 255);
cg := MIN((cg * 256 + (256 - ca) * dstg) DIV 256, 255);
cr := MIN((cr * 256 + (256 - ca) * dstr) DIV 256, 255)
END;
SYSTEM.PUT(dstadr, cb + ASH(cg, 8) + ASH(cr, 16) + 0FF000000H)
END;
INC(fx, sdx);
INC(dstadr, 4)
END;
INC(fy, sdy);
INC(yadr, dstbpr)
END
END Q1BGRA8888BGRA8888SW;
(* source rect must be completely in src, destination rect must be completely in dst *)
PROCEDURE Scale* (IN src: RasterData; srcw, srch, sx, sy, sw, sh: INTEGER;
VAR dst: RasterData; dstw, dsth, dx, dy, dw, dh: INTEGER;
swapColor: BOOLEAN; q: INTEGER);
VAR
fw, fh: REAL;
ssx, ssy: INTEGER;
BEGIN ASSERT((srcw > 0) & (srch > 0), 20); ASSERT((dstw > 0) & (dsth > 0), 21);
ASSERT(LEN(src) >= srcw * srch, 22); ASSERT(LEN(dst) >= dstw * dsth, 23);
ASSERT((sw > 0) & (sh > 0), 24); ASSERT((dw > 0) & (dh > 0), 25);
ASSERT((sx >= 0) & (sy >= 0) & (sx < srcw) & (sy < srch), 26);
ASSERT((srcw - sx >= sw) & (srch - sy >= sh), 27);
ASSERT((dx >= 0) & (dy >= 0) & (dx < dstw) & (dy < dsth), 28);
ASSERT((dstw - dx >= dw) & (dsth - dy >= dh), 29);
fw := sw / dw;
fh := sh / dh;
ssx := sx * 65536;
ssy := sy * 65536;
IF q = nearest THEN
IF swapColor THEN
Q0BGRA8888BGRA8888CopySW(
SYSTEM.ADR(src[0]),
SYSTEM.ADR(dst[0]),
srcw * 4, dstw * 4, dx, dy, dx + dw, dy + dh,
ssx, ssy,
SHORT(ENTIER(fw * 65536)), SHORT(ENTIER(fh * 65536)),
srcw, srch)
ELSE
Q0BGRA8888BGRA8888Copy(
SYSTEM.ADR(src[0]),
SYSTEM.ADR(dst[0]),
srcw * 4, dstw * 4, dx, dy, dx + dw, dy + dh,
ssx, ssy,
SHORT(ENTIER(fw * 65536)), SHORT(ENTIER(fh * 65536)),
srcw, srch)
END
ELSE
IF swapColor THEN
Q1BGRA8888BGRA8888CopySW(
SYSTEM.ADR(src[0]),
SYSTEM.ADR(dst[0]),
srcw * 4, dstw * 4, dx, dy, dx + dw, dy + dh,
ssx, ssy,
SHORT(ENTIER(fw * 65536)), SHORT(ENTIER(fh * 65536)),
srcw, srch)
ELSE
Q1BGRA8888BGRA8888Copy(
SYSTEM.ADR(src[0]),
SYSTEM.ADR(dst[0]),
srcw * 4, dstw * 4, dx, dy, dx + dw, dy + dh,
ssx, ssy,
SHORT(ENTIER(fw * 65536)), SHORT(ENTIER(fh * 65536)),
srcw, srch)
END
END
END Scale;
(* source rect must be completely in src, destination rect must be completely in dst *)
PROCEDURE ScaleBlend* (IN src: RasterData; srcw, srch, sx, sy, sw, sh: INTEGER;
VAR dst: RasterData; dstw, dsth, dx, dy, dw, dh: INTEGER;
swapColor: BOOLEAN; q: INTEGER);
VAR
fw, fh: REAL;
ssx, ssy: INTEGER;
BEGIN ASSERT((srcw > 0) & (srch > 0), 20); ASSERT((dstw > 0) & (dsth > 0), 21);
ASSERT(LEN(src) >= srcw * srch, 22); ASSERT(LEN(dst) >= dstw * dsth, 23);
ASSERT((sw > 0) & (sh > 0), 24); ASSERT((dw > 0) & (dh > 0), 25);
ASSERT((sx >= 0) & (sy >= 0) & (sx < srcw) & (sy < srch), 26);
ASSERT((srcw - sx >= sw) & (srch - sy >= sh), 27);
ASSERT((dx >= 0) & (dy >= 0) & (dx < dstw) & (dy < dsth), 28);
ASSERT((dstw - dx >= dw) & (dsth - dy >= dh), 29);
fw := sw / dw;
fh := sh / dh;
ssx := sx * 65536;
ssy := sy * 65536;
IF q = nearest THEN
IF swapColor THEN
Q0BGRA8888BGRA8888SW(
SYSTEM.ADR(src[0]),
SYSTEM.ADR(dst[0]),
srcw * 4, dstw * 4, dx, dy, dx + dw, dy + dh,
ssx, ssy,
SHORT(ENTIER(fw * 65536)), SHORT(ENTIER(fh * 65536)),
srcw, srch)
ELSE
Q0BGRA8888BGRA8888(
SYSTEM.ADR(src[0]),
SYSTEM.ADR(dst[0]),
srcw * 4, dstw * 4, dx, dy, dx + dw, dy + dh,
ssx, ssy,
SHORT(ENTIER(fw * 65536)), SHORT(ENTIER(fh * 65536)),
srcw, srch)
END
ELSE
IF swapColor THEN
Q1BGRA8888BGRA8888SW(
SYSTEM.ADR(src[0]),
SYSTEM.ADR(dst[0]),
srcw * 4, dstw * 4, dx, dy, dx + dw, dy + dh,
ssx, ssy,
SHORT(ENTIER(fw * 65536)), SHORT(ENTIER(fh * 65536)),
srcw, srch)
ELSE
Q1BGRA8888BGRA8888(
SYSTEM.ADR(src[0]),
SYSTEM.ADR(dst[0]),
srcw * 4, dstw * 4, dx, dy, dx + dw, dy + dh,
ssx, ssy,
SHORT(ENTIER(fw * 65536)), SHORT(ENTIER(fh * 65536)),
srcw, srch)
END
END
END ScaleBlend;
END StdRasters.
| Std/Mod/Rasters.odc |
MODULE StdRastersPng;
(**
project = "BlackBox 2.0"
organization = "www.oberon.ch blackbox.oberon.org"
contributors = "Oberon microsystems, Ketmar Dark"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- YYYYMMDD, nn, ...
"
issues = "
- ...
"
**)
IMPORT SYSTEM, Files, Ports, StdInflate, StdRasters, Log;
CONST
Crc32Init = -1;
defDPI = 96;
TYPE
ImageLoader* = POINTER TO RECORD (StdRasters.ImageLoader) END;
FilesOffset = INTEGER;
IDatReader = POINTER TO RECORD (StdInflate.Inflater)
rd: Files.Reader;
cleft: INTEGER;
crc: INTEGER;
nomore: BOOLEAN;
crcIsWrong: BOOLEAN
END;
LineArrayPtr = POINTER TO ARRAY OF SHORTCHAR;
VAR
DEBUG_PNG_LOADER*: BOOLEAN;
DEBUG_PNG_DEPACKER*: BOOLEAN;
crc32Table: ARRAY 16 OF SET;
PROCEDURE ColorsRGBA (r, g, b, a: INTEGER): INTEGER;
BEGIN
RETURN r + g * 100H + b * 10000H + a * 1000000H
END ColorsRGBA;
PROCEDURE ReadSChar (rd: Files.Reader; VAR c: SHORTCHAR);
VAR x: BYTE;
BEGIN rd.ReadByte(x); c := SHORT(CHR(x))
END ReadSChar;
PROCEDURE ReadSChars (rd: Files.Reader; VAR a: ARRAY OF SHORTCHAR; w, len: INTEGER);
VAR x: BYTE;
BEGIN
ASSERT(w >= 0, 20);
ASSERT(len > 0, 21);
ASSERT(w + len <= LEN(a), 22);
WHILE len > 0 DO
rd.ReadByte(x);
a[w] := SHORT(CHR(x));
INC(w);
DEC(len)
END
END ReadSChars;
(******** crc32 ********)
PROCEDURE Crc32Final (crc32: INTEGER): INTEGER;
BEGIN RETURN ORD(-BITS(crc32))
END Crc32Final;
PROCEDURE Crc32SChar (VAR crc32: INTEGER; b: SHORTCHAR);
VAR crc: INTEGER;
BEGIN
crc := crc32;
crc := ORD(BITS(crc) / BITS(ORD(b)));
crc := ORD(crc32Table[crc MOD 10H] / (BITS(ASH(crc, -4)) * {0..27}));
crc := ORD(crc32Table[crc MOD 10H] / (BITS(ASH(crc, -4)) * {0..27}));
crc32 := crc
END Crc32SChar;
PROCEDURE Crc32SChars (VAR crc32: INTEGER; IN arr: ARRAY OF SHORTCHAR; beg, len: INTEGER);
VAR crc, b: INTEGER;
BEGIN
(* k8: don't bother
ASSERT(beg >= 0, 20); ASSERT(len >= 0, 21); ASSERT(beg <= LEN(arr), 22); ASSERT(LEN(arr) - beg >= len, 23);
*)
crc := crc32;
INC(len, beg);
WHILE beg < len DO
b := ORD(arr[beg]); INC(beg);
crc := ORD(BITS(crc) / BITS(b));
crc := ORD(crc32Table[crc MOD 10H] / (BITS(ASH(crc, -4)) * {0..27}));
crc := ORD(crc32Table[crc MOD 10H] / (BITS(ASH(crc, -4)) * {0..27}))
END;
crc32 := crc
END Crc32SChars;
(******** big-endian integer readers ********)
PROCEDURE ReadByteBE (rd: Files.Reader; VAR crc: INTEGER; OUT x: INTEGER);
VAR bt: SHORTCHAR;
BEGIN
ReadSChar(rd, bt); Crc32SChar(crc, bt);
x := ORD(bt)
END ReadByteBE;
PROCEDURE ReadWordBE (rd: Files.Reader; VAR crc: INTEGER; OUT x: INTEGER);
VAR bt: ARRAY 2 OF SHORTCHAR;
BEGIN
ReadSChars(rd, bt, 0, 2); Crc32SChars(crc, bt, 0, 2);
x := ASH(ORD(bt[0]), 8) + ORD(bt[1])
END ReadWordBE;
PROCEDURE ReadIntBE (rd: Files.Reader; VAR crc: INTEGER; OUT x: INTEGER);
VAR bt: ARRAY 4 OF SHORTCHAR;
BEGIN
ReadSChars(rd, bt, 0, 4); Crc32SChars(crc, bt, 0, 4);
x := ORD(BITS(ASH(ORD(bt[0]), 24)) +
BITS(ASH(ORD(bt[1]), 16)) +
BITS(ASH(ORD(bt[2]), 8)) +
BITS(ORD(bt[3])))
END ReadIntBE;
(******** interlace tables ********)
(* 3, 3, 2, 2, 1, 1, 0, 0 *)
PROCEDURE WShift (pass: INTEGER): INTEGER;
BEGIN ASSERT((pass >= 0) & (pass <= 7), 20); RETURN (7 - pass) DIV 2
END WShift;
(* 3, 3, 3, 2, 2, 1, 1, 0 *)
PROCEDURE HShift (pass: INTEGER): INTEGER;
BEGIN ASSERT((pass >= 0) & (pass <= 7), 20); RETURN MIN(3, (8 - pass) DIV 2)
END HShift;
(* 0, 0, 4, 0, 2, 0, 1, 0 *)
PROCEDURE RowOfs (pass: INTEGER): INTEGER;
BEGIN ASSERT((pass >= 0) & (pass <= 7), 20); RETURN ASH(ASH(1, (8 - pass) DIV 2), -1) MOD 8 * ((pass + 1) MOD 2)
END RowOfs;
(* 0, 4, 0, 2, 0, 1, 0, 0 *)
PROCEDURE ColOfs (pass: INTEGER): INTEGER;
BEGIN ASSERT((pass >= 0) & (pass <= 7), 20); RETURN ASH(ASH(1, (7 - pass) DIV 2), -1) * (pass MOD 2)
END ColOfs;
(******** idat byte stream ********)
(* read as much as you can, return number of read bytes *)
PROCEDURE (inf: IDatReader) ReadBuf- (VAR buf: ARRAY OF SHORTCHAR): INTEGER;
VAR
pos, left, rd, filecrc: INTEGER;
sign: ARRAY 5 OF SHORTCHAR;
BEGIN pos := 0; left := LEN(buf);
WHILE ~inf.nomore & (left # 0) DO
rd := MIN(inf.cleft, left);
IF rd # 0 THEN
ReadSChars(inf.rd, buf, pos, rd);
IF inf.rd.eof THEN inf.nomore := TRUE; pos := 0
; IF DEBUG_PNG_LOADER THEN Log.String(" WRONG!"); Log.Ln END
ELSE
Crc32SChars(inf.crc, buf, pos, rd);
DEC(inf.cleft, rd); INC(pos, rd); DEC(left, rd)
END
ELSE (* want a new idat chunk *)
ReadIntBE(inf.rd, rd, filecrc); (* CRC *)
IF filecrc # Crc32Final(inf.crc) THEN
IF DEBUG_PNG_LOADER THEN Log.String(" CRC IS WRONG!"); Log.Ln END;
inf.nomore := TRUE; inf.crcIsWrong := TRUE
ELSE
ReadIntBE(inf.rd, rd, inf.cleft); (* chunk size *)
ReadSChars(inf.rd, sign, 0, 4); sign[4] := 0X; (* chunk signature *)
inf.crc := Crc32Init; Crc32SChars(inf.crc, sign, 0, 4);
inf.nomore := inf.rd.eof OR (sign # "IDAT")
END
END
END;
RETURN pos
END ReadBuf;
PROCEDURE Round16To8 (v: INTEGER): INTEGER;
VAR mv: INTEGER;
BEGIN
IF (v < 0) OR (v > 65535) THEN v := 1
ELSE
mv := v MOD 256; v := v DIV 256;
IF v # 255 THEN INC(v, mv DIV 128) END
END;
RETURN v
END Round16To8;
(******** main decoder ********)
PROCEDURE LoadPng* (rd: Files.Reader): StdRasters.Image;
VAR
sign: ARRAY 9 OF SHORTCHAR;
seenidat: BOOLEAN;
csize: INTEGER;
ncofs: FilesOffset;
f, width, height: INTEGER;
img: StdRasters.Image;
tR, tG, tB: INTEGER;
compression, filter, bitdepth: INTEGER;
colortype, interlace: INTEGER;
seenplte: BOOLEAN;
plte: ARRAY 256 OF Ports.Color;
trns: ARRAY 256 OF INTEGER;
sr, sg, sb: SHORTCHAR;
dpiX, dpiY: INTEGER;
gamma: INTEGER;
idat: IDatReader;
crc: INTEGER;
checkCRC: BOOLEAN;
PROCEDURE DecodeImage;
VAR
prevLine, currLine: LineArrayPtr;
bytesPerPixel, bytesPerFullRow, bytesPerRowPass: INTEGER;
pass: INTEGER; (* current deinterlacing pass *)
passwdt: INTEGER; (* width of the current pass *)
passxofs: INTEGER; (* starting x offset (in pixels) for the start of each line in the destination buffer *)
passyofs: INTEGER; (* starting y offset (in pixels) for the first line in the destination buffer *)
passxstep: INTEGER; (* x step in the destination buffer, in pixels *)
passystep: INTEGER; (* y step in the destination buffer, in pixels *)
curxofs, curxstep, curxval: INTEGER;
rcount: INTEGER;
curx, cury: INTEGER;
clr: Ports.Color;
dpos: INTEGER;
tmpline: LineArrayPtr;
(* get one pixel value; no converstion *)
PROCEDURE GetPixelData (): INTEGER;
VAR res: INTEGER;
BEGIN
CASE bitdepth OF
| 1:
IF curxstep = 8 THEN INC(curxofs); curxstep := 0; curxval := ORD(currLine[curxofs])
ELSE INC(curxstep)
END;
res := curxval DIV 128; ASSERT((res = 0) OR (res = 1), 100);
curxval := curxval * 2 MOD 256;
| 2:
IF curxstep = 4 THEN INC(curxofs); curxstep := 0; curxval := ORD(currLine[curxofs])
ELSE INC(curxstep)
END;
res := curxval DIV 64; ASSERT((res >= 0) & (res <= 3), 100);
curxval := curxval * 4 MOD 256;
| 4:
IF curxstep = 1 THEN INC(curxofs); curxstep := 0; curxval := ORD(currLine[curxofs])
ELSE INC(curxstep)
END;
res := curxval DIV 16; ASSERT((res >= 0) & (res <= 15), 100);
curxval := curxval * 16 MOD 256;
| 8: res := ORD(currLine[curxofs]); INC(curxofs)
| 16: res := ORD(currLine[curxofs]) * 256 + ORD(currLine[curxofs + 1]); INC(curxofs, 2)
END;
RETURN res
END GetPixelData;
PROCEDURE GetPixelValue (): Ports.Color;
VAR
pR, pG, pB, pA: INTEGER;
res: Ports.Color;
BEGIN
CASE colortype OF
| 0: (* grayscale *)
pR := GetPixelData();
IF pR = tR THEN pA := 0 ELSE pA := 255 END;
CASE bitdepth OF
| 1: pR := pR * 255
| 2:
CASE pR OF
| 0: (* ok *)
| 1: pR := 055H
| 2: pR := 0AAH
| 3: pR := 0FFH
END
| 4: pR := pR * 16 + pR
| 8: (* ok *)
| 16: pR := Round16To8(pR)
END;
res := ColorsRGBA(pR, pR, pR, pA)
| 2: (* rgb *)
pR := GetPixelData(); pG := GetPixelData(); pB := GetPixelData();
IF (pR = tR) & (pG = tG) & (pB = tB) THEN pA := 0 ELSE pA := 255 END;
IF bitdepth = 16 THEN
pR := Round16To8(pR); pG := Round16To8(pG); pB := Round16To8(pB)
END;
res := ColorsRGBA(pR, pG, pB, pA)
| 3: (* indexed *)
pR := GetPixelData();
res := ORD(BITS(plte[pR]) + BITS(ASH(trns[pR], 24)))
| 4: (* grayscale with alpha *)
pR := GetPixelData(); pA := GetPixelData();
IF bitdepth = 16 THEN
pR := Round16To8(pR); pA := Round16To8(pA)
END;
res := ColorsRGBA(pR, pR, pR, pA)
| 6: (* rgb with alpha *)
pR := GetPixelData(); pG := GetPixelData(); pB := GetPixelData(); pA := GetPixelData();
IF bitdepth = 16 THEN
pR := Round16To8(pR); pG := Round16To8(pG); pB := Round16To8(pB); pA := Round16To8(pA)
END;
res := ColorsRGBA(pR, pG, pB, pA)
END;
RETURN res
END GetPixelValue;
PROCEDURE SetupPass;
VAR rowofs, colofs: INTEGER;
BEGIN
DEC(pass);
REPEAT
INC(pass);
rowofs := RowOfs(pass); colofs := ColOfs(pass);
UNTIL (rowofs < height) & (colofs < width) OR (pass = 7);
IF (pass = 7) & (interlace # 0) THEN pass := 69
ELSE
passwdt := WShift(pass);
passwdt := ASH(width + ASH(1, passwdt) - 1 - colofs, -passwdt);
bytesPerRowPass := ((passwdt * bytesPerPixel) * bitdepth + 8 - 1) DIV 8;
passxofs := colofs;
passyofs := rowofs;
passxstep := ASH(1, WShift(pass));
passystep := ASH(1, HShift(pass));
(*curr = buffer+rowoffset*pitch+coloffset*bytesPerPixel;*)
(*passpitch = pitch<<passheightshift[pass];*)
IF DEBUG_PNG_LOADER THEN
Log.String("pass:"); Log.Int(pass); Log.Ln;
Log.String("passwdt:"); Log.Int(passwdt); Log.Ln;
Log.String("passxofs:"); Log.Int(passxofs); Log.Ln;
Log.String("passyofs:"); Log.Int(passyofs); Log.Ln;
Log.String("passxstep:"); Log.Int(passxstep); Log.Ln;
Log.String("passystep:"); Log.Int(passystep); Log.Ln;
Log.String("bytesPerRowPass:"); Log.Int(bytesPerRowPass); Log.Ln
END;
END;
END SetupPass;
PROCEDURE UnfilterLineSub;
VAR
line: LineArrayPtr;
bpp: INTEGER;
idx: INTEGER;
BEGIN
line := currLine; bpp := bytesPerPixel;
IF bitdepth = 16 THEN INC(bpp, bpp) END;
FOR idx := 16 TO bytesPerRowPass + 16 - 1 DO
line[idx] := SHORT(CHR((ORD(line[idx]) + ORD(line[idx - bpp])) MOD 256))
END;
END UnfilterLineSub;
PROCEDURE UnfilterLineUp;
VAR
line, prev: LineArrayPtr;
idx: INTEGER;
BEGIN
line := currLine; prev := prevLine;
FOR idx := 16 TO bytesPerRowPass + 16 - 1 DO
line[idx] := SHORT(CHR((ORD(line[idx]) + ORD(prev[idx])) MOD 256))
END;
END UnfilterLineUp;
PROCEDURE UnfilterLineAverage;
VAR
line, prev: LineArrayPtr;
bpp: INTEGER;
idx: INTEGER;
BEGIN
line := currLine; prev := prevLine; bpp := bytesPerPixel;
IF bitdepth = 16 THEN INC(bpp, bpp) END;
FOR idx := 16 TO bytesPerRowPass + 16 - 1 DO
line[idx] := SHORT(CHR((
ORD(line[idx]) + (ORD(line[idx - bpp]) + ORD(prev[idx])) DIV 2
) MOD 256))
END;
END UnfilterLineAverage;
PROCEDURE Paeth (a, b, c: INTEGER): INTEGER;
VAR p, pa, pb, pc: INTEGER;
BEGIN
p := a + b - c;
pa := ABS(p - a); pb := ABS(p - b); pc := ABS(p - c);
IF (pa <= pb) & (pa <= pc) THEN p := a
ELSIF pb <= pc THEN p := b
ELSE p := c
END;
RETURN p
END Paeth;
PROCEDURE UnfilterLinePaeth;
VAR
line, prev: LineArrayPtr;
bpp: INTEGER;
idx: INTEGER;
BEGIN
line := currLine; prev := prevLine; bpp := bytesPerPixel;
IF bitdepth = 16 THEN INC(bpp, bpp) END;
FOR idx := 16 TO bytesPerRowPass + 16 - 1 DO
line[idx] := SHORT(CHR((
ORD(line[idx]) + Paeth(ORD(line[idx - bpp]), ORD(prev[idx]), ORD(prev[idx - bpp]))
) MOD 256))
END;
END UnfilterLinePaeth;
BEGIN
IF DEBUG_PNG_LOADER THEN Log.String("==== ==== ===="); Log.Ln END;
CASE colortype OF
| 2: bytesPerPixel := 3 (* rgb *)
| 4: bytesPerPixel := 2 (* grayscale, alpha *)
| 6: bytesPerPixel := 4 (* rgba *)
ELSE bytesPerPixel := 1
END;
(*bytesPerFullRow := ((UP.width * bytesPerPixel) * UP.bitdepth + UP.bitdepth - 1) DIV UP.bitdepth;*)
bytesPerFullRow := ((width * bytesPerPixel) * bitdepth + 8 - 1) DIV 8;
IF DEBUG_PNG_LOADER THEN
Log.String("bytesPerPixel:"); Log.Int(bytesPerPixel); Log.Ln;
Log.String("bytesPerFullRow:"); Log.Int(bytesPerFullRow); Log.Ln
END;
NEW(prevLine, bytesPerFullRow + 32);
NEW(currLine, bytesPerFullRow + 32);
(*bytesPerRowOut := UP.width * bytesPerPixel;*)
IF interlace # 0 THEN pass := 0 ELSE pass := 7 END;
WHILE pass < 8 - interlace DO
SetupPass;
IF pass < 16 THEN
(* clear first line *)
FOR cury := 0 TO bytesPerRowPass + 31 - 1 DO currLine[cury] := 0X END;
cury := passyofs;
WHILE cury < height DO
(* swap lines *)
tmpline := currLine; currLine := prevLine; prevLine := tmpline;
(* read filter *)
rcount := idat.ReadSChars(currLine, 0, 1);
IF (rcount # 1) OR idat.Error() OR idat.crcIsWrong THEN
IF DEBUG_PNG_DEPACKER THEN
Log.String("RF-ERR: tup:"); Log.Int(idat.totalUnpacked);
Log.String("; rcount:"); Log.Int(rcount);
Log.String("; bytesPerRowPass:"); Log.Int(bytesPerRowPass);
Log.String("; idaterr:"); Log.Bool(idat.Error());
Log.String("; crc is wrong:"); Log.Bool(idat.crcIsWrong);
Log.Ln
END;
img := NIL;
RETURN
END;
filter := ORD(currLine[0]);
IF DEBUG_PNG_DEPACKER THEN
Log.String("cury:"); Log.Int(cury); Log.String("; filter:"); Log.Int(filter); Log.Ln;
END;
IF filter > 4 THEN
IF DEBUG_PNG_DEPACKER THEN
Log.String("FL-ERR: tup:"); Log.Int(idat.totalUnpacked);
Log.String("; rcount:"); Log.Int(rcount);
Log.String("; bytesPerRowPass:"); Log.Int(bytesPerRowPass);
Log.String("; idaterr:"); Log.Bool(idat.Error());
Log.String("; crc is wrong:"); Log.Bool(idat.crcIsWrong);
Log.Ln
END;
img := NIL;
RETURN
END;
(* read line data *)
currLine[0] := 0X;
rcount := idat.ReadSChars(currLine, 16, bytesPerRowPass);
IF (rcount # bytesPerRowPass) OR idat.Error() OR idat.crcIsWrong THEN
IF DEBUG_PNG_DEPACKER THEN
Log.String("RP-ERR: tup:"); Log.Int(idat.totalUnpacked);
Log.String("; rcount:"); Log.Int(rcount);
Log.String("; bytesPerRowPass:"); Log.Int(bytesPerRowPass);
Log.String("; idaterr:"); Log.Bool(idat.Error());
Log.String("; crc is wrong:"); Log.Bool(idat.crcIsWrong);
Log.Ln
END;
img := NIL;
RETURN
END;
(* restore original line data *)
CASE filter OF
| 0: (* do nothing *)
| 1: UnfilterLineSub
| 2: UnfilterLineUp
| 3: UnfilterLineAverage
| 4: UnfilterLinePaeth
END;
(* unpack line data *)
curxofs := 16; curxstep := 0; curxval := ORD(currLine[curxofs]);
curx := 0; dpos := cury * width + passxofs;
WHILE curx < passwdt DO
clr := GetPixelValue();
img.data[dpos] := clr;
INC(dpos, passxstep);
INC(curx)
END;
(* next line *)
INC(cury, passystep)
END;
INC(pass)
END
END;
IF DEBUG_PNG_DEPACKER THEN
Log.String("DONE: err="); Log.Bool(idat.Error()); Log.Ln;
END;
IF ~idat.Eof() THEN
(* this reads 0 bytes, but necessary to check the final Adler32 checksum of ZLib stream *)
rcount := idat.ReadSChars(currLine, 0, 1);
IF DEBUG_PNG_DEPACKER THEN
Log.String("DONE-EOF: err="); Log.Bool(idat.Error()); Log.Ln;
END;
IF idat.Error() OR idat.crcIsWrong THEN img := NIL END
END
END DecodeImage;
PROCEDURE FinishChunk (ncofs: FilesOffset; crc: INTEGER; check: BOOLEAN): BOOLEAN;
VAR
left: FilesOffset;
b, filecrc: INTEGER;
BEGIN
IF rd.eof OR (ncofs < 0) OR (ncofs >= rd.Base().Length()) THEN RETURN FALSE
ELSIF ~check THEN
IF rd.Base().Length() - ncofs < 12 THEN RETURN FALSE
ELSE rd.SetPos(ncofs + 4); RETURN TRUE
END
ELSE
left := ncofs - rd.Pos();
IF left < 0 THEN RETURN FALSE
ELSE
WHILE left # 0 DO ReadByteBE(rd, crc, b); DEC(left) END;
ReadIntBE(rd, b, filecrc);
RETURN ~rd.eof & (Crc32Final(crc) = filecrc)
END
END
END FinishChunk;
BEGIN
(*rd.SetPos(0);*)
IF rd.Base().Length() - rd.Pos() < 16 THEN RETURN NIL END;
ReadSChars(rd, sign, 0, 8); sign[8] := 0X;
IF sign # 89X+"PNG"+0DX+0AX+1AX+0AX THEN RETURN NIL END;
(* first chunk must be IHDR *)
ReadIntBE(rd, crc, csize); ReadSChars(rd, sign, 0, 4); sign[4] := 0X;
IF rd.eof OR (sign # "IHDR") OR (csize # 13) THEN RETURN NIL END;
crc := Crc32Init; Crc32SChars(crc, sign, 0, 4);
ncofs := rd.Pos() + csize; (* skip CRC *)
(* parse IHDR chunk *)
ReadIntBE(rd, crc, width); ReadIntBE(rd, crc, height);
IF DEBUG_PNG_LOADER THEN Log.String("PNG: width:"); Log.Int(width); Log.String("; height:"); Log.Int(height); Log.Ln END;
IF (width < 1) OR (width > 32768) OR (height < 1) OR (height > 32768) THEN RETURN NIL END;
NEW(img); img.width := width; img.height := height;
ReadByteBE(rd, crc, bitdepth);
ReadByteBE(rd, crc, colortype);
ReadByteBE(rd, crc, compression);
ReadByteBE(rd, crc, filter);
ReadByteBE(rd, crc, interlace);
IF rd.eof THEN RETURN NIL END;
IF DEBUG_PNG_LOADER THEN
Log.String(" bitdepth:"); Log.Int(bitdepth); Log.Ln;
Log.String(" colortype:"); Log.Int(colortype); Log.Ln;
Log.String(" compression:"); Log.Int(compression); Log.Ln;
Log.String(" filter:"); Log.Int(filter); Log.Ln;
Log.String(" interlace:"); Log.Int(interlace); Log.Ln
END;
IF (compression # 0) OR (filter # 0) OR (interlace > 1) THEN RETURN NIL END;
CASE colortype OF
| 0: (* grayscale *)
CASE bitdepth OF
| 1, 2, 4, 8, 16: (* ok *)
ELSE RETURN NIL
END;
| 2: (* rgb *)
CASE bitdepth OF
| 8, 16: (* ok *)
ELSE RETURN NIL
END;
| 3: (* indexed *)
CASE bitdepth OF
| 1, 2, 4, 8: (* ok *)
ELSE RETURN NIL
END;
| 4: (* grayscale with alpha *)
CASE bitdepth OF
| 8, 16: (* ok *)
ELSE RETURN NIL
END;
| 6: (* rgb with alpha *)
CASE bitdepth OF
| 8, 16: (* ok *)
ELSE RETURN NIL
END;
ELSE RETURN NIL
END;
seenidat := FALSE; seenplte := FALSE; tR := -1; dpiX := defDPI; dpiY := defDPI; gamma := 0;
FOR f := 0 TO 255 DO trns[f] := 255 END; (* default is fully opaque *)
checkCRC := TRUE;
WHILE ~rd.eof & ~seenidat DO
IF rd.Base().Length() - ncofs <= 8 THEN RETURN NIL END;
IF ~FinishChunk(ncofs, crc, checkCRC) THEN RETURN NIL END;
ReadIntBE(rd, crc, csize);
checkCRC := FALSE; crc := Crc32Init;
ReadSChars(rd, sign, 0, 4);
IF csize < 0 THEN RETURN NIL END;
Crc32SChars(crc, sign, 0, 4);
ncofs := rd.Pos() + csize;
IF DEBUG_PNG_LOADER THEN Log.String(" CHUNK: "); Log.String(sign$); Log.String(" : size:"); Log.Int(csize); Log.Ln END;
IF sign = "PLTE" THEN
checkCRC := TRUE;
IF seenplte THEN RETURN NIL END; (* no more than one such chunk allowed *)
IF (csize < 0) OR (csize MOD 3 # 0) THEN RETURN NIL END; (* invalid size *)
seenplte := TRUE;
IF colortype = 3 THEN (* we want chunk contents *)
FOR f := 0 TO 255 DO plte[f] := -1 END;
f := 0; WHILE (f # 256) & (csize # 0) DO
ReadSChar(rd, sr); Crc32SChar(crc, sr);
ReadSChar(rd, sg); Crc32SChar(crc, sg);
ReadSChar(rd, sb); Crc32SChar(crc, sb);
plte[f] := Ports.RGBColor(ORD(sr), ORD(sg), ORD(sb)); INC(f);
DEC(csize, 3)
END
END
ELSIF sign = "tRNS" THEN
checkCRC := TRUE;
CASE colortype OF
| 0: (* grayscale, 16-bit value *)
IF csize # 2 THEN RETURN NIL END;
ReadWordBE(rd, crc, tR);
CASE bitdepth OF
| 1: IF tR > 1 THEN tR := -1 ELSIF tR = 1 THEN tR := 255 END
| 2:
CASE tR OF
| 0: (* ok *)
| 1: tR := 055H
| 2: tR := 0AAH
| 3: tR := 0FFH
ELSE tR := -1
END
| 4: IF tR > 15 THEN tR := -1 ELSE tR := tR * 16 + tR END
| 8: IF tR > 255 THEN tR := -1 END
ELSE END;
| 2: (* rgb, 3 16-bit values *)
IF csize # 2 * 3 THEN RETURN NIL END;
ReadWordBE(rd, crc, tR); ReadWordBE(rd, crc, tG); ReadWordBE(rd, crc, tB);
IF bitdepth = 8 THEN
IF (tR > 255) OR (tG > 255) OR (tB > 255) THEN tR := 1 END
ELSE ASSERT(bitdepth = 16)
END
| 3: (* byte table *)
IF csize < 0 THEN RETURN NIL END;
f := 0; WHILE (f # 256) & (csize # 0) DO
ReadSChar(rd, sr); Crc32SChar(crc, sr);
trns[f] := ORD(sr); INC(f);
DEC(csize)
END;
END;
ELSIF sign = "gAMA" THEN
checkCRC := TRUE;
IF csize >= 4 THEN
ReadIntBE(rd, crc, gamma);
IF DEBUG_PNG_LOADER THEN
Log.String(" gamma:"); Log.Int(gamma DIV 100000); Log.String("."); Log.IntForm(gamma MOD 100000, 10, 0, '0', FALSE); Log.Ln;
END;
IF (gamma < 0) OR (gamma > 4 * 100000) THEN gamma := 0 END
END
ELSIF sign = "pHYs" THEN
checkCRC := TRUE;
IF csize >= 9 THEN
ReadIntBE(rd, crc, dpiX); ReadIntBE(rd, crc, dpiY);
ReadSChar(rd, sr); Crc32SChar(crc, sr);
IF DEBUG_PNG_LOADER THEN
Log.String(" dpiX:"); Log.Int(dpiX); Log.String("; dpiY"); Log.Int(dpiY); Log.String("; units:"); Log.Int(ORD(sr)); Log.Ln;
END;
IF sr = 01X THEN
dpiX := MAX(0, SHORT(ENTIER(dpiX * 0.0254 + 0.5)));
dpiY := MAX(0, SHORT(ENTIER(dpiY * 0.0254 + 0.5)));
IF (dpiX = 0) OR (dpiY = 0) OR (dpiX > 8192) OR (dpiY > 8192) THEN
dpiX := 0; dpiY := 0
END;
ELSE
dpiX := 0; dpiY := 0
END;
IF DEBUG_PNG_LOADER THEN
Log.String(" fin: dpiX:"); Log.Int(dpiX); Log.String("; dpiY"); Log.Int(dpiY); Log.Ln;
END;
END
ELSIF sign = "IEND" THEN RETURN NIL
ELSIF sign = "IDAT" THEN seenidat := TRUE
END
END;
IF ~seenidat OR rd.eof THEN RETURN NIL END;
IF (colortype = 3) & ~seenplte THEN RETURN NIL END;
IF rd.Base().Length() - ncofs <= 8 THEN RETURN NIL END;
NEW(img.data, width * height);
img.width := width; img.height := height;
img.dpiX := dpiX; img.dpiY := dpiY;
NEW(idat);
idat.rd := rd;
idat.cleft := csize;
idat.crc := crc;
idat.nomore := FALSE;
idat.Init(StdInflate.ZLib);
DecodeImage;
RETURN img
END LoadPng;
(* return Img.Image without data if the image is a PNG image, and sets rd position after the last image byte. If there is an error, rd position is undefined. *)
PROCEDURE ScanPng* (rd: Files.Reader): StdRasters.Image;
VAR
sign: ARRAY 9 OF SHORTCHAR;
seenidat: BOOLEAN;
csize: INTEGER;
ncofs: FilesOffset;
width, height: INTEGER;
img: StdRasters.Image;
compression, filter, bitdepth: INTEGER;
colortype, interlace: INTEGER;
seenplte: BOOLEAN;
dpiX, dpiY: INTEGER;
sr: SHORTCHAR;
crc: INTEGER;
checkCRC: BOOLEAN;
PROCEDURE FinishChunk (ncofs: FilesOffset; crc: INTEGER; check: BOOLEAN): BOOLEAN;
VAR
left: FilesOffset;
b, filecrc: INTEGER;
BEGIN
IF rd.eof OR (ncofs < 0) OR (ncofs >= rd.Base().Length()) THEN RETURN FALSE
ELSIF ~check THEN
IF rd.Base().Length() - ncofs < 12 THEN RETURN FALSE
ELSE rd.SetPos(ncofs + 4); RETURN TRUE
END
ELSE
left := ncofs - rd.Pos();
IF left < 0 THEN RETURN FALSE
ELSE
WHILE left # 0 DO ReadByteBE(rd, crc, b); DEC(left) END;
ReadIntBE(rd, b, filecrc);
RETURN ~rd.eof & (Crc32Final(crc) = filecrc)
END
END
END FinishChunk;
BEGIN
(*rd.SetPos(0);*)
IF rd.Base().Length() - rd.Pos() < 16 THEN RETURN NIL END;
ReadSChars(rd, sign, 0, 8); sign[8] := 0X;
IF sign # 89X+"PNG"+0DX+0AX+1AX+0AX THEN RETURN NIL END;
(* first chunk must be IHDR *)
ReadIntBE(rd, crc, csize); ReadSChars(rd, sign, 0, 4); sign[4] := 0X;
IF rd.eof OR (sign # "IHDR") OR (csize # 13) THEN RETURN NIL END;
crc := Crc32Init; Crc32SChars(crc, sign, 0, 4);
ncofs := rd.Pos() + csize; (* skip CRC *)
(* parse IHDR chunk *)
ReadIntBE(rd, crc, width); ReadIntBE(rd, crc, height);
IF DEBUG_PNG_LOADER THEN Log.String("PNG: width:"); Log.Int(width); Log.String("; height:"); Log.Int(height); Log.Ln END;
IF (width < 1) OR (width > 32768) OR (height < 1) OR (height > 32768) THEN RETURN NIL END;
NEW(img); img.width := width; img.height := height;
ReadByteBE(rd, crc, bitdepth);
ReadByteBE(rd, crc, colortype);
ReadByteBE(rd, crc, compression);
ReadByteBE(rd, crc, filter);
ReadByteBE(rd, crc, interlace);
IF rd.eof THEN RETURN NIL END;
IF DEBUG_PNG_LOADER THEN
Log.String(" bitdepth:"); Log.Int(bitdepth); Log.Ln;
Log.String(" colortype:"); Log.Int(colortype); Log.Ln;
Log.String(" compression:"); Log.Int(compression); Log.Ln;
Log.String(" filter:"); Log.Int(filter); Log.Ln;
Log.String(" interlace:"); Log.Int(interlace); Log.Ln
END;
IF (compression # 0) OR (filter # 0) OR (interlace > 1) THEN RETURN NIL END;
CASE colortype OF
| 0: (* grayscale *)
CASE bitdepth OF
| 1, 2, 4, 8, 16: (* ok *)
ELSE RETURN NIL
END;
| 2: (* rgb *)
CASE bitdepth OF
| 8, 16: (* ok *)
ELSE RETURN NIL
END;
| 3: (* indexed *)
CASE bitdepth OF
| 1, 2, 4, 8: (* ok *)
ELSE RETURN NIL
END;
| 4: (* grayscale with alpha *)
CASE bitdepth OF
| 8, 16: (* ok *)
ELSE RETURN NIL
END;
| 6: (* rgb with alpha *)
CASE bitdepth OF
| 8, 16: (* ok *)
ELSE RETURN NIL
END;
ELSE RETURN NIL
END;
seenidat := FALSE; seenplte := FALSE; dpiX := 0; dpiY := 0;
checkCRC := TRUE;
WHILE ~rd.eof & ~seenidat DO
IF rd.Base().Length() - ncofs <= 8 THEN RETURN NIL END;
IF ~FinishChunk(ncofs, crc, checkCRC) THEN RETURN NIL END;
ReadIntBE(rd, crc, csize);
checkCRC := FALSE; crc := Crc32Init;
ReadSChars(rd, sign, 0, 4);
IF csize < 0 THEN RETURN NIL END;
Crc32SChars(crc, sign, 0, 4);
ncofs := rd.Pos() + csize;
IF DEBUG_PNG_LOADER THEN Log.String(" CHUNK: "); Log.String(sign$); Log.String(" : size:"); Log.Int(csize); Log.Ln END;
IF sign = "PLTE" THEN
IF seenplte THEN RETURN NIL END; (* no more than one such chunk allowed *)
seenplte := TRUE;
ELSIF sign = "pHYs" THEN
checkCRC := TRUE;
IF csize >= 9 THEN
ReadIntBE(rd, crc, dpiX); ReadIntBE(rd, crc, dpiY);
ReadSChar(rd, sr); Crc32SChar(crc, sr);
IF DEBUG_PNG_LOADER THEN
Log.String(" dpiX:"); Log.Int(dpiX); Log.String("; dpiY"); Log.Int(dpiY); Log.String("; units:"); Log.Int(ORD(sr)); Log.Ln;
END;
IF sr = 01X THEN
dpiX := MAX(0, SHORT(ENTIER(dpiX * 0.0254 + 0.5)));
dpiY := MAX(0, SHORT(ENTIER(dpiY * 0.0254 + 0.5)));
IF (dpiX = 0) OR (dpiY = 0) OR (dpiX > 8192) OR (dpiY > 8192) THEN dpiX := 0; dpiY := 0 END;
ELSE dpiX := 0; dpiY := 0
END;
IF DEBUG_PNG_LOADER THEN
Log.String(" fin: dpiX:"); Log.Int(dpiX); Log.String("; dpiY"); Log.Int(dpiY); Log.Ln;
END;
END
ELSIF sign = "IEND" THEN RETURN NIL
ELSIF sign = "IDAT" THEN seenidat := TRUE
END
END;
IF ~seenidat OR rd.eof THEN RETURN NIL END;
IF (colortype = 3) & ~seenplte THEN RETURN NIL END;
IF rd.Base().Length() - ncofs <= 8 THEN RETURN NIL END;
img.dpiX := dpiX; img.dpiY := dpiY;
RETURN img
END ScanPng;
(******** Loader ********)
PROCEDURE (ldr: ImageLoader) Detect* (rd: Files.Reader): BOOLEAN;
VAR buf: ARRAY 16 OF SHORTCHAR;
BEGIN
ReadSChars(rd, buf, 0, 16);
RETURN ~rd.eof &
(buf[0] = 89X) & (buf[1] = 50X) & (buf[2] = 4EX) & (buf[3] = 47X) &
(buf[4] = 0DX) & (buf[5] = 0AX) & (buf[6] = 1AX)
END Detect;
PROCEDURE (ldr: ImageLoader) Load* (rd: Files.Reader): StdRasters.Image;
BEGIN RETURN LoadPng(rd)
END Load;
PROCEDURE (ldr: ImageLoader) GetInfo* (rd: Files.Reader): StdRasters.Image;
BEGIN RETURN ScanPng(rd)
END GetInfo;
PROCEDURE InitCRC;
CONST poly = 0EDB88320H;
VAR n, c, k: INTEGER;
BEGIN
(*
crc32Table[0] := BITS(00000000H);
crc32Table[1] := BITS(1DB71064H);
crc32Table[2] := BITS(3B6E20C8H);
crc32Table[3] := BITS(26D930ACH);
crc32Table[4] := BITS(76DC4190H);
crc32Table[5] := BITS(6B6B51F4H);
crc32Table[6] := BITS(4DB26158H);
crc32Table[7] := BITS(5005713CH);
crc32Table[8] := BITS(0EDB88320H);
crc32Table[9] := BITS(0F00F9344H);
crc32Table[10] := BITS(0D6D6A3E8H);
crc32Table[11] := BITS(0CB61B38CH);
crc32Table[12] := BITS(9B64C2B0H);
crc32Table[13] := BITS(86D3D2D4H);
crc32Table[14] := BITS(0A00AE278H);
crc32Table[15] := BITS(0BDBDF21CH);
*)
(* make exclusive-or pattern from polynomial (0EDB88320H).
terms of polynomial defining this crc (except x^32)
uint poly = 0; // polynomial exclusive-or pattern
foreach (immutable n; [0,1,2,4,5,7,8,10,11,12,16,22,23,26]) poly |= 1u<<(31-n);
*)
n := 0;
WHILE n < 16 DO
c := n * 16;
k := 8; WHILE k # 0 DO
DEC(k);
IF ODD(c) THEN c := ORD(BITS(SYSTEM.LSH(c, -1)) / BITS(poly))
ELSE c := SYSTEM.LSH(c, -1)
END
END;
crc32Table[n] := BITS(c);
INC(n);
END
END InitCRC;
BEGIN
InitCRC;
DEBUG_PNG_LOADER := FALSE; DEBUG_PNG_DEPACKER := FALSE
END StdRastersPng.
| Std/Mod/RastersPng.odc |
MODULE StdRegistry;
(**
project = "Лунь"
organization = ""
contributors = ""
version = "System/Rsrc/About"
copyright = "Kushnir Piotr Michailovich"
license = "Docu/BB-License"
purpose = "Registry модуль для сохранения настроек, изначально лежал в Хост и все его импортировали без стеснения, теперь для желающих поимпортировать будет модуль в Std"
changes = "
- 20130308, pk, автогенерация заголовка
-20130728, pk, добавил процедуру проверки готовности YHostRegistry
"
issues = ""
**)
IMPORT
Kernel;
TYPE
Hook* = POINTER TO ABSTRACT RECORD END;
VAR
hook: Hook;
PROCEDURE (h: Hook) ReadString* (IN key: ARRAY OF CHAR; OUT str: ARRAY OF CHAR; VAR res: INTEGER), NEW, ABSTRACT;
PROCEDURE (h: Hook) ReadInt* (IN key: ARRAY OF CHAR; OUT x: INTEGER; OUT res: INTEGER), NEW, ABSTRACT;
PROCEDURE (h: Hook) ReadBool* (IN key: ARRAY OF CHAR; OUT x: BOOLEAN; OUT res: INTEGER), NEW, ABSTRACT;
PROCEDURE (h: Hook) ReadIntList* (IN key: ARRAY OF CHAR; OUT x: ARRAY OF INTEGER; OUT res: INTEGER), NEW, ABSTRACT;
PROCEDURE (h: Hook) WriteString* (IN key: ARRAY OF CHAR; IN str: ARRAY OF CHAR), NEW, ABSTRACT;
PROCEDURE (h: Hook) WriteInt* (IN key: ARRAY OF CHAR; x: INTEGER), NEW, ABSTRACT;
PROCEDURE (h: Hook) WriteBool* (IN key: ARRAY OF CHAR; x: BOOLEAN), NEW, ABSTRACT;
PROCEDURE (h: Hook) WriteIntList* (IN key: ARRAY OF CHAR; IN x: ARRAY OF INTEGER), NEW, ABSTRACT;
PROCEDURE ReadString* (IN key: ARRAY OF CHAR; OUT str: ARRAY OF CHAR; VAR res: INTEGER);
BEGIN
IF hook#NIL THEN
hook.ReadString(key, str, res)
ELSE res:=-1 END;
END ReadString;
PROCEDURE ReadInt* (IN key: ARRAY OF CHAR; OUT x: INTEGER; OUT res: INTEGER);
BEGIN
IF hook#NIL THEN
hook.ReadInt(key, x, res)
ELSE res:=-1 END;
END ReadInt;
PROCEDURE ReadBool* (IN key: ARRAY OF CHAR; OUT x: BOOLEAN; OUT res: INTEGER);
BEGIN
IF hook#NIL THEN
hook.ReadBool(key, x, res)
ELSE res:=-1 END;
END ReadBool;
PROCEDURE ReadIntList* (IN key: ARRAY OF CHAR; OUT x: ARRAY OF INTEGER; OUT res: INTEGER);
BEGIN
IF hook#NIL THEN
hook.ReadIntList(key, x, res)
ELSE res:=-1 END;
END ReadIntList;
PROCEDURE WriteString* (IN key: ARRAY OF CHAR; IN str: ARRAY OF CHAR);
BEGIN
IF hook#NIL THEN
hook.WriteString(key, str)
END;
END WriteString;
PROCEDURE WriteInt* (IN key: ARRAY OF CHAR; x: INTEGER);
BEGIN
IF hook#NIL THEN
hook.WriteInt(key, x)
END;
END WriteInt;
PROCEDURE WriteBool* (IN key: ARRAY OF CHAR; x: BOOLEAN);
BEGIN
IF hook#NIL THEN
hook.WriteBool(key, x)
END;
END WriteBool;
PROCEDURE WriteIntList* (IN key: ARRAY OF CHAR; IN x: ARRAY OF INTEGER);
BEGIN
IF hook#NIL THEN
hook.WriteIntList(key, x)
END;
END WriteIntList;
PROCEDURE SetHook* (h: Hook);
BEGIN
hook:=h;
END SetHook;
PROCEDURE Ready*(): BOOLEAN;
BEGIN
RETURN (hook#NIL)
END Ready;
END StdRegistry. | Std/Mod/Registry.odc |
MODULE StdScrollbars;
(**
project = "BlackBox 2.0, new module"
organization = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Contributors, Anton Dmitriev, Ketmar Dark, Ivan Denisov"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 20230512, k8, changed scrollbars look
- 20240521, dia, prevent fall if scrollbar size is small
"
issues = "
-
"
**)
IMPORT
Views, Ports, Models, Controllers, Services, Properties;
CONST
left = 16; middle = 17; right = 18; (* HostPorts.left, .middle, .right *)
vertical* = TRUE; (* scrollbar orientation *)
minThumbSize = 9;
TYPE
UCs = INTEGER;
Pixels = INTEGER;
Scrollbar* = POINTER TO ABSTRACT RECORD (Views.View)
wholeSize*, partSize*, partPos*: INTEGER;
isVertical*: BOOLEAN;
lastDot-: INTEGER;
(* the following is set by Recalc *)
w, h: Pixels; (* last known width and height *)
size: Pixels; (* last known scrollbar size *)
thPos, thSize: Pixels (* last known thumbnail position and size *)
END;
StdScrollbar = POINTER TO RECORD (Scrollbar) END;
ScrollbarDirectory* = POINTER TO ABSTRACT RECORD END;
StdScrollbarDirectory = POINTER TO RECORD (ScrollbarDirectory) END;
(** a proposal indicating to the context that the scrollbar has been
scrolled by the user. It is up to the receiver of the proposal to request
(thru Views.Update) or force (thru Views.RestoreRoot) the
restoration of the scrollbar. *)
Proposal* = RECORD (Models.Proposal)
sb*: Scrollbar;
frame*: Views.Frame; (** the sender may specify .sb's frame to allow optimizations in the receiver.
ASSERT((.frame = NIL) OR (.frame.view = .sb)) *)
op*: INTEGER (** same constants as for Controllers.ScrollMsg.op *)
END;
Param* = RECORD
thumbColor*: Ports.Color;
thumbMin*: INTEGER;
shaftColor*: Ports.Color;
shaftShade*: INTEGER;
disabledColor*: Ports.Color;
leftGoto*: BOOLEAN;
smallerThumb*: BOOLEAN;
(* calculated colors *)
clrShaft: Ports.Color;
clrThumb: Ports.Color;
END;
FindFrameMsg = RECORD (Views.Message)
frame: Views.Frame
END;
VAR
sbDir*: ScrollbarDirectory;
stdSbDir-: StdScrollbarDirectory;
param: Param;
PROCEDURE (VAR p: Param) InitDefaults, NEW;
BEGIN
p.thumbColor := Ports.grey50;
p.thumbMin := 30;
p.shaftColor := Ports.grey25;
p.shaftShade := 0;
p.disabledColor := Ports.white;
p.leftGoto := TRUE;
p.smallerThumb := TRUE;
END InitDefaults;
PROCEDURE (VAR p: Param) Init*, NEW;
BEGIN
IF (p.shaftShade > 0) & (p.shaftShade < 100) THEN
p.clrShaft := Ports.blue
ELSE
p.clrShaft := p.shaftColor
END;
p.clrThumb := p.thumbColor;
END Init;
(** Scrollbar **)
PROCEDURE GetSBSize (sb: Scrollbar): INTEGER;
BEGIN
IF param.smallerThumb THEN
RETURN MAX(0, sb.size - 2)
ELSE
RETURN MAX(0, sb.size)
END;
END GetSBSize;
PROCEDURE GetThumbOfs (sb: Scrollbar): INTEGER;
BEGIN
IF param.smallerThumb THEN RETURN 1 ELSE RETURN 0 END;
END GetThumbOfs;
(* thum size is proportional to the visible area size *)
PROCEDURE CalcThumbSize (sb: Scrollbar): Pixels;
VAR
res: Pixels;
sbsize: INTEGER;
BEGIN
sbsize := GetSBSize(sb);
IF (sbsize <= 0) OR (sb.wholeSize <= 0) OR (sb.partSize > 0) & (sb.wholeSize <= sb.partSize) THEN
res := sbsize
ELSE
res := MAX(minThumbSize, param.thumbMin);
(* StdDocument often doesn't set part size *)
IF sb.partSize > 0 THEN
res := MAX(res, MIN(sbsize, SHORT(LONG(sbsize) * sb.partSize DIV sb.wholeSize)))
END
END;
RETURN res
END CalcThumbSize;
(* sb.thSize should be already set *)
PROCEDURE GetPartSize (sb: Scrollbar): INTEGER;
VAR res: INTEGER;
BEGIN
res := sb.partSize;
IF res <= 0 THEN ASSERT(sb.thSize >= minThumbSize, 100);
IF sb.thSize >= GetSBSize(sb) THEN res := 0
ELSE res := SHORT(LONG(sb.wholeSize) DIV (GetSBSize(sb) - sb.thSize))
END
END;
RETURN MAX(0, res)
END GetPartSize;
PROCEDURE Recalc (sb: Scrollbar; dot: UCs);
VAR pos, sz, sbsize: INTEGER;
BEGIN
sb.lastDot := dot;
sb.context.GetSize(sb.w, sb.h);
sb.w := sb.w DIV dot; sb.h := sb.h DIV dot;
sb.size := 0; sb.thPos := 0; sb.thSize := 0;
IF (sb.wholeSize > 0) & (sb.w > 0) & (sb.h > 0) THEN
IF sb.isVertical THEN sb.size := sb.h ELSE sb.size := sb.w END;
IF sb.size < minThumbSize + 3 THEN sb.size := 0
ELSE
sb.thSize := CalcThumbSize(sb);
sbsize := GetSBSize(sb);
IF (sbsize <= 0) OR (sb.wholeSize <= 0) OR (sb.wholeSize <= sb.partSize) THEN sb.thPos := 0
ELSIF sb.thSize >= sbsize THEN sb.thPos := 0
ELSE ASSERT(sb.thSize <= sbsize, 100);
sz := sb.wholeSize - GetPartSize(sb);
IF sz <= 0 THEN sz := 1 END;
pos := MAX(0, MIN(sb.partPos, sz));
sb.thPos := SHORT(LONG(sbsize - sb.thSize) * pos DIV sz)
END
END
END
END Recalc;
(* tp is thumb position (top/left); result is the position in the sb range.
should be called after Recalc. *)
PROCEDURE Thumb2Pos (sb: Scrollbar; tp: Pixels): INTEGER;
VAR res, sbsize: INTEGER;
BEGIN
sbsize := GetSBSize(sb);
IF (tp <= 0) OR (sb.wholeSize <= 0) OR (sb.thSize = 0) THEN res := 0
ELSIF tp >= sbsize - sb.thSize THEN res := sb.wholeSize - GetPartSize(sb)
ELSE res := SHORT(LONG(sb.wholeSize - GetPartSize(sb)) * tp DIV (sbsize - sb.thSize)) END;
RETURN res
END Thumb2Pos;
PROCEDURE (sb: StdScrollbar) Restore* (f: Views.Frame; l, t, r, b: INTEGER);
VAR w, h, dot: UCs;
BEGIN
dot := f.dot;
Recalc(sb, dot);
IF GetSBSize(sb) = 0 THEN
f.DrawRect(l, t, r, b, Ports.fill, param.disabledColor)
ELSE
f.DrawRect(l, t, r, b, Ports.fill, param.clrShaft);
sb.context.GetSize(w, h);
IF sb.isVertical THEN
IF param.smallerThumb THEN l := dot; t := dot; r := w - dot
ELSE l := 0; t := 0; r := w
END;
INC(t, sb.thPos * dot); b := t + sb.thSize * dot
ELSE
IF param.smallerThumb THEN l := dot; t := dot; b := h - dot
ELSE l := 0; t := 0; b := h
END;
INC(l, sb.thPos * dot); r := l + sb.thSize * dot
END;
f.DrawRect(l, t, r, b, Ports.fill, param.clrThumb);
END
END Restore;
PROCEDURE UpdateRoot (c: Views.Frame);
VAR
root: Views.RootFrame;
l, t, r, b: INTEGER;
BEGIN
root := Views.UltimateRootOf(Views.RootOf(c));
IF root # NIL THEN
l := root.l + root.gx; t := root.t + root.gy; r := root.r + root.gx; b := root.b + root.gy;
Views.RestoreRoot(root, l, t, r, b)
END
END UpdateRoot;
PROCEDURE TrackThumb (sb: StdScrollbar; f: Views.Frame; msg: Controllers.TrackMsg);
VAR
p: Proposal;
delta, q, x, y, ox, oy, partPos: INTEGER;
ticks: LONGINT;
mod: SET;
isDown: BOOLEAN;
ffm: FindFrameMsg;
BEGIN
IF GetSBSize(sb) > 0 THEN
x := msg.x; y := msg.y; ox := x; oy := y;
IF sb.isVertical THEN
delta := y DIV f.dot - sb.thPos
ELSE
delta := x DIV f.dot - sb.thPos
END;
INC(delta, GetThumbOfs(sb));
ticks := Services.Ticks();
REPEAT
IF f.rider # NIL THEN
f.Input(x, y, mod, isDown)
END;
IF (sb.isVertical & (y # oy)) OR (~ sb.isVertical & (x # ox)) THEN
IF sb.isVertical THEN q := y DIV f.dot ELSE q := x DIV f.dot END;
partPos := Thumb2Pos(sb, q - delta);
IF (partPos # sb.partPos) & (isDown OR (Services.Ticks() - ticks > 10)) THEN
sb.partPos := partPos;
p.sb := sb; p.op := Controllers.gotoPos; p.frame := f;
sb.context.Consider(p);
(* Consider may cause Views.Update with Views.rebuildFrames;
if so, obtain the new frame *)
IF f.rider = NIL THEN Views.Broadcast(sb, ffm); f := ffm.frame END; (* k8: we need to do it this way,
otherwise scrollbar and scroll visual positions could be wrong *)
UpdateRoot(f);
(* same check *)
IF f.rider = NIL THEN Views.Broadcast(sb, ffm); f := ffm.frame END;
ticks := Services.Ticks()
END;
ox := x; oy := y
END
UNTIL (f.rider = NIL) OR ~isDown
ELSE
REPEAT
IF f.rider # NIL THEN f.Input(x, y, mod, isDown) END
UNTIL (f.rider = NIL) OR ~isDown
END
END TrackThumb;
(** w, h - dimensions of sb; ltrb - thumb bounding box *)
PROCEDURE TrackShaft (sb: StdScrollbar; f: Views.Frame; msg: Controllers.TrackMsg);
CONST
interval = 500;
none = -1;
up = Controllers.decPage;
down = Controllers.incPage;
VAR
p: Proposal;
mod: SET;
isDown: BOOLEAN;
x, y, tp: INTEGER;
dir: INTEGER;
ticks, oticks: LONGINT;
BEGIN
p.sb := sb; x := msg.x; y := msg.y; oticks := 0;
REPEAT
ticks := Services.Ticks();
IF (ticks - oticks > interval) & (f.l <= x) & (x < f.r) & (f.t <= y) & (y < f.b) THEN
Recalc(sb, f.dot);
IF GetSBSize(sb) > 0 THEN
IF sb.isVertical THEN tp := y DIV f.dot ELSE tp := x DIV f.dot END;
IF tp < sb.thPos + GetThumbOfs(sb) THEN dir := up
ELSIF tp > sb.thPos + GetThumbOfs(sb) + sb.thSize THEN dir := down
ELSE dir := none
END;
IF dir # none THEN p.op := dir; p.frame := f; sb.context.Consider(p) END
END;
oticks := ticks
END;
IF f.rider # NIL THEN f.Input(x, y, mod, isDown) END;
UNTIL (f.rider = NIL) OR ~isDown
END TrackShaft;
PROCEDURE Goto (sb: StdScrollbar; f: Views.Frame; msg: Controllers.TrackMsg);
VAR
p: Proposal;
q: INTEGER;
partPos: INTEGER;
BEGIN
IF GetSBSize(sb) > 0 THEN
IF sb.isVertical THEN q := msg.y DIV f.dot ELSE q := msg.x DIV f.dot END;
DEC(q, sb.thSize DIV 2);
partPos := Thumb2Pos(sb, q);
IF partPos # sb.partPos THEN
sb.partPos := partPos; p.sb := sb; p.op := Controllers.gotoPos; p.frame := f;
sb.context.Consider(p)
END
END
END Goto;
PROCEDURE (sb: StdScrollbar) HandleCtrlMsg* (f: Views.Frame; VAR msg: Views.CtrlMessage; VAR focus: Views.View);
VAR
sbpos: Pixels;
BEGIN
WITH msg: Controllers.TrackMsg DO
Recalc(sb, f.dot);
IF sb.isVertical THEN sbpos := msg.y DIV f.dot ELSE sbpos := msg.x DIV f.dot END;
INC(sbpos, GetThumbOfs(sb));
IF middle IN msg.modifiers THEN
Goto(sb, f, msg)
ELSIF (sbpos >= sb.thPos) & (sbpos < sb.thPos + sb.thSize) THEN
TrackThumb(sb, f, msg)
ELSIF param.leftGoto & (left IN msg.modifiers) THEN
Goto(sb, f, msg)
ELSIF msg.modifiers * {left, right} # {} THEN
TrackShaft(sb, f, msg)
END
ELSE END
END HandleCtrlMsg;
PROCEDURE (sb: StdScrollbar) HandlePropMsg- (VAR msg: Properties.Message);
BEGIN WITH msg: Properties.FocusPref DO msg.hotFocus := TRUE ELSE END
END HandlePropMsg;
PROCEDURE (sb: StdScrollbar) HandleViewMsg- (f: Views.Frame; VAR msg: Views.Message);
BEGIN WITH msg: FindFrameMsg DO msg.frame := f ELSE END
END HandleViewMsg;
PROCEDURE (sb: StdScrollbar) GetBackground* (VAR col: Ports.Color);
BEGIN col := Views.transparent
END GetBackground;
(** Directory **)
PROCEDURE (d: ScrollbarDirectory) New* (): Scrollbar, NEW, ABSTRACT;
(** StdDirectory **)
PROCEDURE (d: StdScrollbarDirectory) New (): Scrollbar;
VAR sb: StdScrollbar;
BEGIN
NEW(sb);
sb.isVertical := TRUE;
sb.wholeSize := 0;
RETURN sb
END New;
BEGIN
NEW(stdSbDir);
sbDir := stdSbDir;
param.InitDefaults;
param.Init
END StdScrollbars.
| Std/Mod/Scrollbars.odc |
MODULE StdScrollers;
(**
project = "BlackBox 2.0"
organization = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Oberon microsystems, Ivan Denisov"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 20050715, mf, corrections in InnerFrame and its clients
- 20150714, center #66, adding procedure WrappedView and improving View.HandleCtrlMsg
- 20220531, dia, add WrapView
"
issues = "
- ...
"
**)
IMPORT Dialog, Ports, Services, Stores, Models, Views, Properties, Controllers, StdCFrames;
CONST
(* properties & options *)
horBar* = 0; verBar* = 1; horHide* = 2; verHide* = 3;
width* = 4; height* = 5; showBorder* = 6; savePos* = 7;
TYPE
Prop* = POINTER TO RECORD (Properties.Property)
horBar*, verBar*: BOOLEAN;
horHide*, verHide*: BOOLEAN;
width*, height*: INTEGER;
showBorder*: BOOLEAN;
savePos*: BOOLEAN
END;
ScrollBar = POINTER TO RECORD (Views.View)
v: View;
ver: BOOLEAN
END;
InnerView = POINTER TO RECORD (Views.View)
v: View
END;
View = POINTER TO RECORD (Views.View);
view: Views.View;
sbW: INTEGER;
orgX, orgY: INTEGER;
w, h: INTEGER; (* = 0: adapt to container *)
opts: SET;
(* not persistent *)
hor, ver: ScrollBar;
inner: InnerView;
rgap, bgap: INTEGER; (* = 0: no scrollbar *)
border: INTEGER;
update: Action
END;
Context = POINTER TO RECORD (Models.Context)
v: View;
type: INTEGER
END;
Action = POINTER TO RECORD (Services.Action)
v: View
END;
Op = POINTER TO RECORD (Stores.Operation)
v: View;
p: Prop
END;
SOp = POINTER TO RECORD (Stores.Operation)
v: View;
x, y: INTEGER
END;
UpdateMsg = RECORD (Views.Message)
changed: BOOLEAN
END;
VAR
dialog*: RECORD
horizontal*, vertical*: RECORD
mode*: INTEGER;
adapt*: BOOLEAN;
size*: REAL
END;
showBorder*: BOOLEAN;
savePos*: BOOLEAN;
valid, readOnly: SET
END;
(* tools *)
PROCEDURE CheckPos (v: View; VAR x, y: INTEGER);
VAR w, h: INTEGER;
BEGIN
v.context.GetSize(w, h);
DEC(w, v.rgap + 2 * v.border);
DEC(h, v.bgap + 2 * v.border);
IF x > v.w - w THEN x := v.w - w END;
IF x < 0 THEN x := 0 END;
IF y > v.h - h THEN y := v.h - h END;
IF y < 0 THEN y := 0 END
END CheckPos;
PROCEDURE InnerFrame (v: View; f: Views.Frame): Views.Frame;
VAR g, h: Views.Frame;
BEGIN
g := Views.ThisFrame(f, v.inner);
IF g = NIL THEN
Views.InstallFrame(f, v.inner, v.border, v.border, 0, TRUE);
g := Views.ThisFrame(f, v.inner)
END;
IF g # NIL THEN
h := Views.ThisFrame(g, v.view);
IF h = NIL THEN
Views.InstallFrame(g, v.view, -v.orgX, -v.orgY, 0, TRUE);
h := Views.ThisFrame(g, v.view)
END
END;
RETURN h
END InnerFrame;
PROCEDURE Scroll (v: View; dir: INTEGER; ver: BOOLEAN; p: INTEGER; OUT pos: INTEGER);
VAR x, y: INTEGER; last: Stores.Operation; op: SOp;
BEGIN
x := v.orgX; y := v.orgY;
IF ver THEN pos := y ELSE pos := x END;
IF dir = StdCFrames.lineUp THEN
DEC(pos, 10 * Ports.mm)
ELSIF dir = StdCFrames.lineDown THEN
INC(pos, 10 * Ports.mm)
ELSIF dir = StdCFrames.pageUp THEN
DEC(pos, 40 * Ports.mm)
ELSIF dir = StdCFrames.pageDown THEN
INC(pos, 40 * Ports.mm)
ELSIF dir = Controllers.gotoPos THEN
pos := p
END;
IF ver THEN CheckPos(v, x, pos); y := pos
ELSE CheckPos(v, pos, y); x := pos
END;
IF (x # v.orgX) OR (y # v.orgY) THEN
last := Views.LastOp(v);
IF ~(savePos IN v.opts) OR (last # NIL) & (last IS SOp) THEN
v.orgX := x; v.orgY := y;
Views.Update(v.view, Views.keepFrames)
ELSE
NEW(op); op.v := v; op.x := x; op.y := y;
Views.Do(v, "#System:Scrolling", op)
END
END
END Scroll;
PROCEDURE PollSection (v: View; ver: BOOLEAN; OUT size, sect, pos: INTEGER);
VAR w, h: INTEGER;
BEGIN
v.context.GetSize(w, h);
IF ver THEN size := v.h; sect := h - v.bgap - 2 * v.border; pos := v.orgY
ELSE size := v.w; sect := w - v.rgap - 2 * v.border; pos := v.orgX
END
END PollSection;
(* SOp *)
PROCEDURE (op: SOp) Do;
VAR x, y: INTEGER;
BEGIN
x := op.x; op.x := op.v.orgX; op.v.orgX := x;
y := op.y; op.y := op.v.orgY; op.v.orgY := y;
Views.Update(op.v.view, Views.keepFrames)
END Do;
(* properties *)
PROCEDURE (p: Prop) IntersectWith* (q: Properties.Property; OUT equal: BOOLEAN);
VAR valid: SET;
BEGIN
WITH q: Prop DO
valid := p.valid * q.valid; equal := TRUE;
IF p.horBar # q.horBar THEN EXCL(valid, horBar) END;
IF p.verBar # q.verBar THEN EXCL(valid, verBar) END;
IF p.horHide # q.horHide THEN EXCL(valid, horHide) END;
IF p.verHide # q.verHide THEN EXCL(valid, verHide) END;
IF p.width # q.width THEN EXCL(valid, width) END;
IF p.height # q.height THEN EXCL(valid, height) END;
IF p.showBorder # q.showBorder THEN EXCL(valid, showBorder) END;
IF p.savePos # q.savePos THEN EXCL(valid, savePos) END;
IF p.valid # valid THEN p.valid := valid; equal := FALSE END
END
END IntersectWith;
PROCEDURE SetProp (v: View; p: Properties.Property);
VAR op: Op;
BEGIN
WITH p: Prop DO
NEW(op); op.v := v; op.p := p;
Views.Do(v, "#System:SetProp", op)
END
END SetProp;
PROCEDURE PollProp (v: View; OUT prop: Prop);
VAR p: Prop;
BEGIN
NEW(p);
p.valid := {horBar, verBar, horHide, verHide, width, height, showBorder, savePos};
p.readOnly := {width, height} - v.opts;
p.horBar := horBar IN v.opts;
p.verBar := verBar IN v.opts;
p.horHide := horHide IN v.opts;
p.verHide := verHide IN v.opts;
p.width := v.w;
p.height := v.h;
p.showBorder := showBorder IN v.opts;
p.savePos := savePos IN v.opts;
p.known := p.valid; prop := p
END PollProp;
(* Op *)
PROCEDURE (op: Op) Do;
VAR p: Prop; v: View; valid: SET;
BEGIN
v := op.v; p := op.p; PollProp(v, op.p); op.p.valid := p.valid;
valid := p.valid * ({horBar, verBar, horHide, verHide, showBorder, savePos} + v.opts * {width, height});
IF horBar IN valid THEN
IF p.horBar THEN INCL(v.opts, horBar) ELSE EXCL(v.opts, horBar) END
END;
IF verBar IN valid THEN
IF p.verBar THEN INCL(v.opts, verBar) ELSE EXCL(v.opts, verBar) END
END;
IF horHide IN valid THEN
IF p.horHide THEN INCL(v.opts, horHide) ELSE EXCL(v.opts, horHide) END
END;
IF verHide IN valid THEN
IF p.verHide THEN INCL(v.opts, verHide) ELSE EXCL(v.opts, verHide) END
END;
IF width IN valid THEN v.w := p.width END;
IF height IN valid THEN v.h := p.height END;
IF showBorder IN valid THEN
IF p.showBorder THEN INCL(v.opts, showBorder); v.border := 2 * Ports.point
ELSE EXCL(v.opts, showBorder); v.border := 0
END
END;
IF savePos IN valid THEN
IF p.savePos THEN INCL(v.opts, savePos) ELSE EXCL(v.opts, savePos) END
END;
Views.Update(v, Views.rebuildFrames)
END Do;
(* Action *)
PROCEDURE (a: Action) Do;
VAR msg: UpdateMsg;
BEGIN
msg.changed := FALSE;
Views.Broadcast(a.v, msg);
IF msg.changed THEN Views.Update(a.v, Views.keepFrames)
ELSE
Views.Broadcast(a.v.hor, msg);
Views.Broadcast(a.v.ver, msg)
END
END Do;
(* ScrollBars *)
PROCEDURE TrackSB (f: StdCFrames.ScrollBar; dir: INTEGER; VAR pos: INTEGER);
VAR s: ScrollBar; msg: Controllers.ScrollMsg;
pmsg: Controllers.PollSectionMsg; host, inner: Views.Frame;
BEGIN
s := f.view(ScrollBar); host := Views.HostOf(f);
msg.focus := FALSE; msg.vertical := s.ver;
msg.op := dir; msg.done := FALSE;
inner := InnerFrame(s.v, host);
IF inner # NIL THEN Views.ForwardCtrlMsg(inner, msg) END;
IF msg.done THEN
pmsg.focus := FALSE; pmsg.vertical := s.ver;
pmsg.valid := FALSE; pmsg.done := FALSE;
inner := InnerFrame(s.v, host);
IF inner # NIL THEN Views.ForwardCtrlMsg(inner, pmsg) END;
IF pmsg.done THEN
pos := pmsg.partPos
END
ELSE
Scroll(s.v, dir, s.ver, 0, pos);
Views.ValidateRoot(Views.RootOf(host))
END
END TrackSB;
PROCEDURE SetSB (f: StdCFrames.ScrollBar; pos: INTEGER);
VAR s: ScrollBar; msg: Controllers.ScrollMsg; p: INTEGER; host, inner: Views.Frame;
BEGIN
s := f.view(ScrollBar); host := Views.HostOf(f);
msg.focus := FALSE; msg.vertical := s.ver;
msg.op := Controllers.gotoPos; msg.pos := pos;
msg.done := FALSE;
inner := InnerFrame(s.v, host);
IF inner # NIL THEN Views.ForwardCtrlMsg(inner, msg) END;
IF ~msg.done THEN
Scroll(s.v, Controllers.gotoPos, s.ver, pos, p);
Views.ValidateRoot(Views.RootOf(host))
END
END SetSB;
PROCEDURE GetSB (f: StdCFrames.ScrollBar; OUT size, sect, pos: INTEGER);
VAR s: ScrollBar; msg: Controllers.PollSectionMsg; host, inner: Views.Frame;
BEGIN
s := f.view(ScrollBar); host := Views.HostOf(f);
msg.focus := FALSE; msg.vertical := s.ver;
msg.wholeSize := 1; msg.partSize := 0; msg.partPos := 0;
msg.valid := FALSE; msg.done := FALSE;
inner := InnerFrame(s.v, host);
IF inner # NIL THEN Views.ForwardCtrlMsg(inner, msg) END;
IF msg.done THEN
IF msg.valid THEN
size := msg.wholeSize; sect := msg.partSize; pos := msg.partPos
ELSE
size := 1; sect := 1; pos := 0
END
ELSE
PollSection(s.v, s.ver, size, sect, pos)
END
END GetSB;
PROCEDURE (s: ScrollBar) GetNewFrame (VAR frame: Views.Frame);
VAR f: StdCFrames.ScrollBar;
BEGIN
f := StdCFrames.dir.NewScrollBar();
f.disabled := FALSE; f.undef := FALSE; f.readOnly := FALSE;
f.Track := TrackSB; f.Get := GetSB; f.Set := SetSB;
frame := f
END GetNewFrame;
PROCEDURE (s: ScrollBar) Restore (f: Views.Frame; l, t, r, b: INTEGER);
BEGIN
WITH f: StdCFrames.Frame DO f.Restore(l, t, r, b) END
END Restore;
PROCEDURE (s: ScrollBar) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message;
VAR focus: Views.View);
BEGIN
WITH f: StdCFrames.Frame DO
WITH msg: Controllers.PollCursorMsg DO
f.GetCursor(msg.x, msg.y, msg.modifiers, msg.cursor)
| msg: Controllers.TrackMsg DO
f.MouseDown(msg.x, msg.y, msg.modifiers)
ELSE
END
END
END HandleCtrlMsg;
PROCEDURE (s: ScrollBar) HandleViewMsg (f: Views.Frame; VAR msg: Views.Message);
BEGIN
WITH msg: UpdateMsg DO
WITH f: StdCFrames.Frame DO f.Update() END
ELSE
END
END HandleViewMsg;
(* View *)
PROCEDURE Update (v: View; f: Views.Frame);
VAR msg: Controllers.PollSectionMsg; w, h: INTEGER;
depends: BOOLEAN; inner: Views.Frame;
BEGIN
v.bgap := 0; v.rgap := 0; depends := FALSE;
v.context.GetSize(w, h);
DEC(w, 2 * v.border); DEC(h, 2 * v.border);
IF horBar IN v.opts THEN
IF horHide IN v.opts THEN
msg.focus := FALSE; msg.vertical := FALSE;
msg.wholeSize := 1; msg.partSize := 0; msg.partPos := 0;
msg.valid := FALSE; msg.done := FALSE;
inner := InnerFrame(v, f);
IF inner # NIL THEN Views.ForwardCtrlMsg(inner, msg) END;
IF msg.done THEN
IF msg.valid THEN v.bgap := v.sbW END
ELSIF v.w > 0 THEN
IF w < v.w THEN v.bgap := v.sbW
ELSIF w - v.sbW < v.w THEN depends := TRUE
END
END
ELSE v.bgap := v.sbW
END
END;
IF verBar IN v.opts THEN
IF verHide IN v.opts THEN
msg.focus := FALSE; msg.vertical := TRUE;
msg.wholeSize := 1; msg.partSize := 0; msg.partPos := 0;
msg.valid := FALSE; msg.done := FALSE;
inner := InnerFrame(v, f);
IF inner # NIL THEN Views.ForwardCtrlMsg(inner, msg) END;
IF msg.done THEN
IF msg.valid THEN v.rgap := v.sbW END
ELSIF v.h > 0 THEN
IF h - v.bgap < v.h THEN v.rgap := v.sbW END
END
ELSE v.rgap := v.sbW
END
END;
IF depends & (v.rgap > 0) THEN v.bgap := v.sbW END;
CheckPos(v, v.orgX, v.orgY)
END Update;
PROCEDURE Init (v: View; newView: BOOLEAN);
CONST min = 2 * Ports.mm; max = MAX(INTEGER); default = 50 * Ports.mm;
VAR c: Context; x: INTEGER; msg: Properties.ResizePref;
BEGIN
IF newView THEN
v.opts := v.opts + {horBar, verBar, horHide, verHide};
StdCFrames.dir.GetScrollBarSize(x, v.sbW);
IF v.view.context # NIL THEN
v.view.context.GetSize(v.w, v.h);
v.view := Views.CopyOf(v.view, Views.shallow)
ELSE
v.w := Views.undefined; v.h := Views.undefined;
Properties.PreferredSize(v.view, min, max, min, max, default, default, v.w, v.h)
END;
msg.fixed := FALSE;
msg.horFitToWin := FALSE; msg.verFitToWin := FALSE;
msg.horFitToPage := FALSE; msg.verFitToPage := FALSE;
Views.HandlePropMsg(v.view, msg);
IF ~msg.fixed THEN
INCL(v.opts, width); INCL(v.opts, height);
IF msg.horFitToWin OR msg.horFitToPage THEN v.w := 0 END;
IF msg.verFitToWin OR msg.verFitToPage THEN v.h := 0 END
END
END;
v.rgap := 0; v.bgap := 0;
IF showBorder IN v.opts THEN v.border := 2 * Ports.point ELSE v.border := 0 END;
NEW(v.inner); v.inner.v := v;
NEW(c); c.v := v; c.type := 3; v.inner.InitContext(c);
NEW(v.hor); v.hor.ver := FALSE; v.hor.v := v;
NEW(c); c.v := v; c.type := 2; v.hor.InitContext(c);
NEW(v.ver); v.ver.ver := TRUE; v.ver.v := v;
NEW(c); c.v := v; c.type := 1; v.ver.InitContext(c);
NEW(v.update); v.update.v := v;
Stores.Join(v, v.view);
Stores.Join(v, v.inner);
Stores.Join(v, v.hor);
Stores.Join(v, v.ver);
Services.DoLater(v.update, Services.now)
END Init;
PROCEDURE (v: View) Internalize (VAR rd: Stores.Reader);
VAR thisVersion: INTEGER;
BEGIN
v.Internalize^(rd);
IF ~rd.cancelled THEN
rd.ReadVersion(0, 0, thisVersion);
IF ~rd.cancelled THEN
Views.ReadView(rd, v.view);
rd.ReadInt(v.sbW);
rd.ReadInt(v.orgX);
rd.ReadInt(v.orgY);
rd.ReadInt(v.w);
rd.ReadInt(v.h);
rd.ReadSet(v.opts);
Init(v, FALSE)
END
END
END Internalize;
PROCEDURE (v: View) Externalize (VAR wr: Stores.Writer);
BEGIN
v.Externalize^(wr);
wr.WriteVersion(0);
Views.WriteView(wr, v.view);
wr.WriteInt(v.sbW);
IF savePos IN v.opts THEN
wr.WriteInt(v.orgX);
wr.WriteInt(v.orgY)
ELSE
wr.WriteInt(0);
wr.WriteInt(0)
END;
wr.WriteInt(v.w);
wr.WriteInt(v.h);
wr.WriteSet(v.opts);
END Externalize;
PROCEDURE (v: View) ThisModel(): Models.Model;
BEGIN
RETURN v.view.ThisModel()
END ThisModel;
PROCEDURE (v: View) CopyFromModelView (source: Views.View; model: Models.Model);
BEGIN
WITH source: View DO
IF model = NIL THEN v.view := Views.CopyOf(source.view, Views.deep)
ELSE v.view := Views.CopyWithNewModel(source.view, model)
END;
v.sbW := source.sbW;
v.orgX := source.orgX;
v.orgY := source.orgY;
v.w := source.w;
v.h := source.h;
v.opts := source.opts;
END;
Init(v, FALSE)
END CopyFromModelView;
PROCEDURE (v: View) InitContext (context: Models.Context);
VAR c: Context;
BEGIN
v.InitContext^(context);
IF v.view.context = NIL THEN
NEW(c); c.v := v; c.type := 0; v.view.InitContext(c)
END
END InitContext;
PROCEDURE (v: View) Neutralize;
BEGIN
v.view.Neutralize
END Neutralize;
PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER);
VAR w, h: INTEGER;
BEGIN
v.context.GetSize(w, h);
IF showBorder IN v.opts THEN
v.border := 2 * f.dot;
f.DrawRect(0, f.dot, w, v.border, Ports.fill, Ports.black);
f.DrawRect(f.dot, 0, v.border, h, Ports.fill, Ports.black);
f.DrawRect(0, h - v.border, w, h - f.dot, Ports.fill, Ports.grey25);
f.DrawRect(w - v.border, 0, w - f.dot, h, Ports.fill, Ports.grey25);
f.DrawRect(0, 0, w, f.dot, Ports.fill, Ports.grey50);
f.DrawRect(0, 0, f.dot, h, Ports.fill, Ports.grey50);
f.DrawRect(0, h - f.dot, w, h, Ports.fill, Ports.white);
f.DrawRect(w - f.dot, 0, w, h, Ports.fill, Ports.white)
END;
Views.InstallFrame(f, v.inner, v.border, v.border, 0, TRUE);
IF v.bgap > 0 THEN
Views.InstallFrame(f, v.hor, v.border, h - v.border - v.bgap, 0, FALSE)
END;
IF v.rgap > 0 THEN
Views.InstallFrame(f, v.ver, w - v.border - v.rgap, v.border, 0, FALSE)
END
END Restore;
PROCEDURE (v: View) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View);
VAR w, h, p, n: INTEGER;smsg: Controllers.ScrollMsg; inner: Views.Frame;
BEGIN
WITH msg: Controllers.WheelMsg DO
smsg.focus := FALSE; smsg.op := msg.op;
smsg.pos := 0; smsg.done := FALSE; n := msg.nofLines;
IF (v.rgap > 0) OR (v.bgap > 0) THEN
smsg.vertical := v.rgap > 0;
REPEAT
smsg.done := FALSE;
inner := InnerFrame(v, f);
IF inner # NIL THEN Views.ForwardCtrlMsg(inner, smsg) END;
IF ~smsg.done THEN
Scroll(v, smsg.op, smsg.vertical, 0, p);
Views.ValidateRoot(Views.RootOf(f))
END;
DEC(n)
UNTIL n <= 0;
msg.done := TRUE
ELSE
focus := v.inner
END
| msg: Controllers.CursorMessage DO
v.context.GetSize(w, h);
IF msg.x > w - v.border - v.rgap THEN
IF msg.y <= h - v.border - v.bgap THEN focus := v.ver END
ELSIF msg.y > h - v.border - v.bgap THEN focus := v.hor
ELSE focus := v.inner
END
| msg: Controllers.PollSectionMsg DO
inner := InnerFrame(v, f);
IF inner # NIL THEN Views.ForwardCtrlMsg(inner, msg) END;
IF ~msg.done THEN
PollSection(v, msg.vertical, msg.wholeSize, msg.partSize, msg.partPos);
msg.valid := msg.partSize < msg.wholeSize;
msg.done := TRUE
END
| msg: Controllers.ScrollMsg DO
inner := InnerFrame(v, f);
IF inner # NIL THEN Views.ForwardCtrlMsg(inner, msg) END;
IF ~msg.done THEN
Scroll(v, msg.op, msg.vertical, msg.pos, p);
Views.ValidateRoot(Views.RootOf(f));
msg.done := TRUE
END
ELSE focus := v.inner
END;
(* avoid redundant updates in order to save memory and CPU resources *)
IF ~((msg IS Controllers.TickMsg) OR (msg IS Controllers.PollCursorMsg)
OR (msg IS Controllers.PollOpsMsg) OR (msg IS Controllers.PollFocusMsg)) THEN
Services.DoLater(v.update, Services.now)
END
END HandleCtrlMsg;
PROCEDURE (v: View) HandleViewMsg (f: Views.Frame; VAR msg: Views.Message);
VAR b, r: INTEGER;
BEGIN
WITH msg: UpdateMsg DO
b := v.bgap; r := v.rgap;
Update(v, f);
IF (v.bgap # b) OR (v.rgap # r) THEN msg.changed := TRUE END
ELSE
END
END HandleViewMsg;
PROCEDURE (v: View) HandlePropMsg (VAR msg: Properties.Message);
VAR w, h: INTEGER; p: Properties.Property; prop: Prop; fv: Views.View;
BEGIN
WITH msg: Properties.FocusPref DO
v.context.GetSize(w, h);
Views.HandlePropMsg(v.view, msg);
IF msg.atLocation THEN
IF (msg.x > w - v.border - v.rgap) & (msg.y > h - v.border - v.bgap) THEN
msg.hotFocus := FALSE; msg.setFocus := FALSE
ELSIF ((msg.x > w - v.border - v.rgap) OR (msg.y > h - v.border - v.bgap))
& ~msg.setFocus THEN
msg.hotFocus := TRUE
END
END
| msg: Properties.SizePref DO
IF (v.w > 0) & (v.h > 0) THEN
IF msg.w = Views.undefined THEN msg.w := 50 * Ports.mm END;
IF msg.h = Views.undefined THEN msg.h := 50 * Ports.mm END
ELSE
IF msg.w > v.rgap THEN DEC(msg.w, v.rgap + 2 * v.border) END;
IF msg.h > v.bgap THEN DEC(msg.h, v.bgap + 2 * v.border) END;
Views.HandlePropMsg(v.view, msg);
IF msg.w > 0 THEN INC(msg.w, v.rgap + 2 * v.border) END;
IF msg.h > 0 THEN INC(msg.h, v.bgap + 2 * v.border) END
END;
IF msg.w < 3 * v.sbW THEN msg.w := 3 * v.sbW END;
IF msg.h < 3 * v.sbW THEN msg.h := 3 * v.sbW END
| msg: Properties.ResizePref DO
Views.HandlePropMsg(v.view, msg);
IF v.w > 0 THEN
msg.fixed := FALSE;
msg.horFitToWin := TRUE;
msg.horFitToPage := FALSE
END;
IF v.h > 0 THEN
msg.fixed := FALSE;
msg.verFitToWin := TRUE;
msg.verFitToPage := FALSE
END
| msg: Properties.BoundsPref DO
Views.HandlePropMsg(v.view, msg);
INC(msg.w, 2 * v.border);
INC(msg.h, 2 * v.border);
IF (horBar IN v.opts) & ~(horHide IN v.opts) THEN INC(msg.w, v.sbW) END;
IF (verBar IN v.opts) & ~(verHide IN v.opts) THEN INC(msg.h, v.sbW) END
| msg: Properties.PollMsg DO
Views.HandlePropMsg(v.view, msg);
PollProp(v, prop); Properties.Insert(msg.prop, prop)
| msg: Properties.SetMsg DO
p := msg.prop; WHILE (p # NIL) & ~(p IS Prop) DO p := p.next END;
IF p # NIL THEN SetProp(v, p) END;
Views.HandlePropMsg(v.view, msg);
| msg: Properties.ControlPref DO
fv := msg.focus;
IF fv = v THEN msg.focus := v.view END;
Views.HandlePropMsg(v.view, msg);
msg.focus := fv
ELSE
Views.HandlePropMsg(v.view, msg);
END;
END HandlePropMsg;
PROCEDURE WrappedView* (v: Views.View): Views.View;
BEGIN
WITH v: View DO
RETURN v.view
ELSE
RETURN v
END
END WrappedView;
PROCEDURE WrapView* (view: Views.View): Views.View;
VAR v: View; replace: Controllers.ReplaceViewMsg;
BEGIN
IF (view # NIL) & ~(view IS View) THEN
NEW(v); v.view := view; Init(v, TRUE);
replace.old := view; replace.new := v;
RETURN v
ELSE
RETURN NIL
END;
END WrapView;
(* InnerView *)
PROCEDURE (v: InnerView) GetBackground (VAR color: Ports.Color);
BEGIN
color := Ports.background
END GetBackground;
PROCEDURE (v: InnerView) Restore (f: Views.Frame; l, t, r, b: INTEGER);
BEGIN
Views.InstallFrame(f, v.v.view, -v.v.orgX, -v.v.orgY, 0, TRUE)
END Restore;
PROCEDURE (v: InnerView) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message;
VAR focus: Views.View);
BEGIN
focus := v.v.view
END HandleCtrlMsg;
(* Context *)
PROCEDURE (c: Context) MakeVisible (l, t, r, b: INTEGER);
VAR w, h, x, y: INTEGER;
BEGIN
IF ~(savePos IN c.v.opts) THEN
c.v.context.GetSize(w, h);
x := c.v.orgX; y := c.v.orgY;
IF c.v.w > 0 THEN
DEC(w, c.v.rgap + 2 * c.v.border);
IF r > x + w - Ports.point THEN x := r - w + Ports.point END;
IF l < x + Ports.point THEN x := l - Ports.point END;
END;
IF c.v.h > 0 THEN
DEC(h, c.v.bgap + 2 * c.v.border);
IF b > y + h - Ports.point THEN y := b - h + Ports.point END;
IF t < y + Ports.point THEN y := t - Ports.point END;
END;
IF (x # c.v.orgX) OR (y # c.v.orgY) THEN
CheckPos(c.v, x, y); c.v.orgX := x; c.v.orgY := y;
Views.Update(c.v.view, Views.keepFrames)
END;
Services.DoLater(c.v.update, Services.now)
END
END MakeVisible;
PROCEDURE (c: Context) Consider (VAR p: Models.Proposal);
BEGIN
c.v.context.Consider(p)
END Consider;
PROCEDURE (c: Context) Normalize (): BOOLEAN;
BEGIN
RETURN ~(savePos IN c.v.opts)
END Normalize;
PROCEDURE (c: Context) GetSize (OUT w, h: INTEGER);
BEGIN
c.v.context.GetSize(w, h);
DEC(w, c.v.rgap + 2 * c.v.border);
DEC(h, c.v.bgap + 2 * c.v.border);
IF c.type = 0 THEN
IF c.v.w > 0 THEN w := c.v.w END;
IF c.v.h > 0 THEN h := c.v.h END
ELSIF c.type = 1 THEN
w := c.v.rgap
ELSIF c.type = 2 THEN
h := c.v.bgap
END
END GetSize;
PROCEDURE (c: Context) SetSize (w, h: INTEGER);
VAR w0, h0, w1, h1: INTEGER;
BEGIN
ASSERT(c.type = 0, 100);
c.v.context.GetSize(w0, h0); w1 := w0; h1 := h0;
IF c.v.w > 0 THEN c.v.w := w
ELSE w1 := w + c.v.rgap + 2 * c.v.border
END;
IF c.v.h > 0 THEN c.v.h := h
ELSE h1 := h + c.v.bgap + 2 * c.v.border
END;
IF (w1 # w0) OR (h1 # h0) THEN
c.v.context.SetSize(w1, h1)
END
END SetSize;
PROCEDURE (c: Context) ThisModel (): Models.Model;
BEGIN
RETURN NIL
END ThisModel;
(* dialog *)
PROCEDURE InitDialog*;
VAR p: Properties.Property; u: INTEGER;
BEGIN
Properties.CollectProp(p);
WHILE (p # NIL) & ~(p IS Prop) DO p := p.next END;
IF p # NIL THEN
WITH p: Prop DO
IF Dialog.metricSystem THEN
u := Ports.mm DIV 10
ELSE
u := Ports.inch DIV 100
END;
dialog.valid := p.valid;
dialog.readOnly := p.readOnly;
IF ~p.horBar THEN dialog.horizontal.mode := 0
ELSIF p.horHide THEN dialog.horizontal.mode := 1
ELSE dialog.horizontal.mode := 2
END;
IF ~p.verBar THEN dialog.vertical.mode := 0
ELSIF p.verHide THEN dialog.vertical.mode := 1
ELSE dialog.vertical.mode := 2
END;
dialog.horizontal.size := p.width DIV u / 100;
dialog.vertical.size := p.height DIV u / 100;
dialog.horizontal.adapt := p.width = 0;
dialog.vertical.adapt := p.height = 0;
dialog.showBorder := p.showBorder;
dialog.savePos := p.savePos
END
END
END InitDialog;
PROCEDURE Set*;
VAR p: Prop; u: INTEGER;
BEGIN
IF Dialog.metricSystem THEN u := 10 * Ports.mm ELSE u := Ports.inch END;
NEW(p); p.valid := dialog.valid;
p.horBar := dialog.horizontal.mode # 0;
p.verBar := dialog.vertical.mode # 0;
p.horHide := dialog.horizontal.mode = 1;
p.verHide := dialog.vertical.mode = 1;
IF ~dialog.horizontal.adapt THEN
p.width := SHORT(ENTIER(dialog.horizontal.size * u))
END;
IF ~dialog.vertical.adapt THEN
p.height := SHORT(ENTIER(dialog.vertical.size * u))
END;
p.showBorder := dialog.showBorder;
p.savePos := dialog.savePos;
Properties.EmitProp(NIL, p)
END Set;
PROCEDURE DialogGuard* (VAR par: Dialog.Par);
VAR p: Properties.Property;
BEGIN
Properties.CollectProp(p);
WHILE (p # NIL) & ~(p IS Prop) DO p := p.next END;
IF p = NIL THEN par.disabled := TRUE END
END DialogGuard;
PROCEDURE HorAdaptGuard* (VAR par: Dialog.Par);
BEGIN
IF width IN dialog.readOnly THEN par.readOnly := TRUE END
END HorAdaptGuard;
PROCEDURE VerAdaptGuard* (VAR par: Dialog.Par);
BEGIN
IF height IN dialog.readOnly THEN par.readOnly := TRUE END
END VerAdaptGuard;
PROCEDURE WidthGuard* (VAR par: Dialog.Par);
BEGIN
IF dialog.horizontal.adapt THEN par.disabled := TRUE
ELSIF width IN dialog.readOnly THEN par.readOnly := TRUE
END
END WidthGuard;
PROCEDURE HeightGuard* (VAR par: Dialog.Par);
BEGIN
IF dialog.vertical.adapt THEN par.disabled := TRUE
ELSIF height IN dialog.readOnly THEN par.readOnly := TRUE
END
END HeightGuard;
(* commands *)
PROCEDURE AddScroller*;
VAR poll: Controllers.PollOpsMsg; v: View; replace: Controllers.ReplaceViewMsg;
BEGIN
Controllers.PollOps(poll);
IF (poll.singleton # NIL) & ~(poll.singleton IS View) THEN
NEW(v); v.view := poll.singleton; Init(v, TRUE);
replace.old := poll.singleton; replace.new := v;
Controllers.Forward(replace)
ELSE Dialog.Beep
END
END AddScroller;
PROCEDURE RemoveScroller*;
VAR poll: Controllers.PollOpsMsg; replace: Controllers.ReplaceViewMsg;
BEGIN
Controllers.PollOps(poll);
IF (poll.singleton # NIL) & (poll.singleton IS View) THEN
replace.old := poll.singleton;
replace.new := Views.CopyOf(poll.singleton(View).view, Views.shallow);
Controllers.Forward(replace)
ELSE Dialog.Beep
END
END RemoveScroller;
END StdScrollers.
| Std/Mod/Scrollers.odc |
MODULE StdStamps;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20150617, center #62, Unicode and Internationalization support for StdStamps
- 20151015, center #63, editing of old comments added plus some cleanups
- 20160321, center #110, use mapped strings for labels in all forms
"
issues = "
- ...
"
**)
IMPORT
SYSTEM, (* SYSTEM.ROT only, for fingerprint calculation *)
Dialog, Strings, Dates, StdCmds,
Ports, Models, Stores, Containers, Properties, Views, Controllers, Fonts,
TextModels, TextSetters, TextMappers, TextViews, TextRulers;
CONST
setCommentKey = "#Std:Set Comment";
maxHistoryEntries = 25; (* prepared for future expansion *)
minVersion = 0; origStampVersion = 0; noSnrVersion = 1; snrVersion = 2; wideCommentVersion = 3;
maxVersion = 3;
TYPE
History = POINTER TO ARRAY OF RECORD
fprint, snr: INTEGER; (* fingerprint, sequence number *)
date: INTEGER; (* days since 1/1/1 *)
time: INTEGER; (* min + 64 * hour *)
comment: POINTER TO ARRAY OF CHAR; (* nil if no comment *)
END;
Comment* = ARRAY 64 OF CHAR;
StdView = POINTER TO RECORD (Views.View)
(*--snr: LONGINT; for version 1*)
nentries: INTEGER; (* number of entries in history *)
history: History; (* newest entry in history[0] *)
comment0: Comment; (* comment for new history entry or empty *)
END;
SetCmtOp = POINTER TO RECORD (Stores.Operation)
stamp: StdView;
age: INTEGER;
oldcomment: POINTER TO ARRAY OF CHAR;
END;
VAR
comment*: RECORD
stamp: StdView;
snrList*: Dialog.List;
date-: Dates.Date;
s*: Comment;
END;
PROCEDURE (op: SetCmtOp) Do;
VAR temp: POINTER TO ARRAY OF CHAR;
BEGIN
IF op.age = 0 THEN
NEW(temp, LEN(op.stamp.comment0) + 1); temp^ := op.stamp.comment0$;
op.stamp.comment0 := op.oldcomment^$
ELSE
temp := op.stamp.history[op.age - 1].comment;
op.stamp.history[op.age - 1].comment := op.oldcomment
END;
op.oldcomment := temp;
END Do;
PROCEDURE FontContext (v: StdView): Fonts.Font;
VAR c: Models.Context;
BEGIN
c := v.context;
IF (c # NIL) & (c IS TextModels.Context) THEN
RETURN c(TextModels.Context).Attr().font;
ELSE
RETURN Fonts.dir.Default()
END;
END FontContext;
PROCEDURE CalcFP (t: TextModels.Model): INTEGER;
CONST sglQuote = "'"; dblQuote = '"';
VAR fp: INTEGER; rd: TextModels.Reader; ch, quoteChar: CHAR;
BEGIN
quoteChar := 0X; fp := 0;
rd := t.NewReader(NIL); rd.ReadChar(ch);
WHILE ~rd.eot DO
IF ch = quoteChar THEN quoteChar := 0X;
ELSIF (quoteChar = 0X) & ((ch = dblQuote) OR (ch = sglQuote)) THEN quoteChar := ch;
END;
IF (quoteChar = 0X) & (21X <= ch) & (ch # 8BX) & (ch # 8FX) & (ch # 0A0X) (* not in string literal *)
OR (quoteChar # 0X) & (20X <= ch) (* within string literal *)
THEN
fp := SYSTEM.ROT(fp, 1) + 13 * ORD(ch);
END;
rd.ReadChar(ch);
END;
RETURN fp;
END CalcFP;
PROCEDURE FillComment (v: StdView; age: INTEGER; rebuild: BOOLEAN);
VAR i: INTEGER; s: ARRAY 10 OF CHAR;
BEGIN
comment.stamp := v;
IF rebuild THEN
comment.snrList.SetLen(v.nentries + 1);
comment.snrList.SetItem(0, "#Std:new");
FOR i := 1 TO v.nentries DO
Strings.IntToString(v.history[i - 1].snr, s);
comment.snrList.SetItem(i, s);
END ;
comment.snrList.index := age;
Dialog.UpdateList(comment.snrList)
END;
IF age = 0 THEN
Dates.GetDate(comment.date);
comment.s := v.comment0$
ELSE DEC(age);
Dates.DayToDate(v.history[age].date, comment.date);
IF v.history[age].comment = NIL THEN comment.s := '' ELSE comment.s := v.history[age].comment$ END
END;
Dialog.Update(comment)
END FillComment;
PROCEDURE Update (v: StdView; forcenew: BOOLEAN);
VAR fp, ndays, i: INTEGER; d: Dates.Date; t: Dates.Time;
BEGIN
IF (v.context # NIL) & (v.context IS TextModels.Context) THEN
fp := CalcFP(v.context(TextModels.Context).ThisModel());
IF (fp # v.history[0].fprint) OR forcenew OR (v.comment0 # "") THEN
Dates.GetDate(d); Dates.GetTime(t);
ndays := Dates.Day(d);
IF (ndays # v.history[0].date) OR forcenew THEN
IF v.nentries = LEN(v.history) THEN (* find oldest uncommented entry *)
i := LEN(v.history) - 1;
WHILE (i > 0) & (v.history[i].comment # NIL) & (v.history[i].comment[0] # 0X) DO DEC(i) END;
IF i = 0 THEN i := LEN(v.history) - 1 END
ELSE i := v.nentries; INC(v.nentries)
END;
(* move down entries in history list *)
WHILE i > 0 DO
v.history[i] := v.history[i-1];
DEC(i);
END;
v.history[0].comment := NIL
ELSIF v.nentries = 0 THEN v.nentries := 1
END;
INC(v.history[0].snr);
v.history[0].fprint := fp;
v.history[0].date := ndays;
v.history[0].time := t.minute + t.hour*64;
IF v.comment0 # "" THEN
NEW(v.history[0].comment, LEN(v.comment0$) + 1);
v.history[0].comment^ := v.comment0$; v.comment0 := ""
END;
Views.Update(v, Views.keepFrames);
IF comment.stamp = v THEN FillComment(v, 1, TRUE) END
END;
END;
END Update;
PROCEDURE HasWideChars (IN s: ARRAY OF CHAR): BOOLEAN;
VAR i: INTEGER; ch: CHAR;
BEGIN i := 0; ch := s[0];
WHILE (ch # 0X) & (ch <= 0FFX) DO INC(i); ch := s[i] END;
RETURN ch # 0X
END HasWideChars;
PROCEDURE (v: StdView) Externalize (VAR wr: Stores.Writer);
VAR i, len: INTEGER; version: INTEGER;
BEGIN
Update(v, v.comment0 # "");
v.Externalize^(wr);
i := 0;
WHILE (i < v.nentries) & ~((v.history[i].comment # NIL) & HasWideChars(v.history[i].comment)) DO
INC(i)
END;
IF i < v.nentries THEN version := wideCommentVersion ELSE version := snrVersion END;
wr.WriteVersion(version);
(*--wr.WriteLInt(v.snr);*)
wr.WriteXInt(v.nentries);
FOR i := 0 TO v.nentries-1 DO
wr.WriteInt(v.history[i].fprint);
wr.WriteInt(v.history[i].snr);
wr.WriteInt(v.history[i].date);
wr.WriteXInt(v.history[i].time);
IF (v.history[i].comment # NIL) & (LEN(v.history[i].comment$) > 0) THEN
len := LEN(v.history[i].comment$);
wr.WriteXInt(len);
IF version >= wideCommentVersion THEN
wr.WriteString(v.history[i].comment)
ELSE
wr.WriteXString(v.history[i].comment)
END
ELSE wr.WriteXInt(0);
END
END;
END Externalize;
PROCEDURE (v: StdView) Internalize (VAR rd: Stores.Reader);
VAR version: INTEGER; format: BYTE; k, purge, i, len: INTEGER;
d: Dates.Date; t: Dates.Time;
BEGIN
v.Internalize^(rd);
IF ~rd.cancelled THEN
rd.ReadVersion(minVersion, maxVersion, version);
IF ~rd.cancelled THEN
IF version = origStampVersion THEN (* deal with old StdStamp format *)
(* would like to calculate fingerprint, but hosting model not available at this time *)
NEW(v.history, maxHistoryEntries);
v.history[0].fprint := 0;
v.history[0].snr := 1; v.nentries := 1;
rd.ReadXInt(d.year); rd.ReadXInt(d.month); rd.ReadXInt(d.day);
rd.ReadXInt(t.hour); rd.ReadXInt(t.minute); rd.ReadXInt(t.second);
rd.ReadByte(format); (* format not used anymore *)
v.history[0].date := Dates.Day(d);
v.history[0].time := t.minute + t.hour*64;
ELSE
IF version = noSnrVersion THEN NEW(v.history, maxHistoryEntries); rd.ReadInt(v.history[0].snr) END;
rd.ReadXInt(v.nentries);
IF version > noSnrVersion THEN NEW(v.history, MAX(v.nentries, maxHistoryEntries)) END;
purge := 0;
FOR k := 0 TO v.nentries - 1 DO
i := k - purge;
rd.ReadInt(v.history[i].fprint);
IF version > noSnrVersion THEN rd.ReadInt(v.history[i].snr)
ELSIF (* (version = noSnrVersion) & *) i > 0 THEN v.history[i].snr := v.history[i-1].snr - 1;
END;
rd.ReadInt(v.history[i].date);
rd.ReadXInt(v.history[i].time);
rd.ReadXInt(len);
IF len > 0 THEN
NEW(v.history[i].comment, len + 1);
IF version >= wideCommentVersion THEN
rd.ReadString(v.history[i].comment)
ELSE
rd.ReadXString(v.history[i].comment)
END
ELSE v.history[i].comment := NIL
END;
IF (i > 0) & (v.history[i].date = v.history[i-1].date) THEN
(* purge uncommented entry if another entry for the same date exists *)
IF v.history[i-1].comment = NIL THEN v.history[i-1].comment := v.history[i].comment; INC(purge)
ELSIF v.history[i].comment = NIL THEN INC(purge)
END
END
END;
DEC(v.nentries, purge);
IF version < wideCommentVersion THEN (* cleanup *)
i := v.nentries - 1;
WHILE (i > 0) & (v.history[i].date = 0) DO DEC(i); DEC(v.nentries) END
END
END
END
END
END Internalize;
PROCEDURE (v: StdView) CopyFromSimpleView (source: Views.View);
VAR i: INTEGER;
BEGIN
(* v.CopyFrom^(source); *)
WITH source: StdView DO
(*--v.snr := source.snr;*)
v.nentries := source.nentries;
v.comment0 := source.comment0;
NEW(v.history, LEN(source.history));
FOR i := 0 TO MAX(v.nentries - 1, 1) DO
v.history[i] := source.history[i];
IF source.history[i].comment # NIL THEN
NEW(v.history[i].comment, LEN(source.history[i].comment$) + 1);
v.history[i].comment^ := source.history[i].comment^$;
END
END
END
END CopyFromSimpleView;
PROCEDURE (v: StdView) Restore (f: Views.Frame; l, t, r, b: INTEGER);
VAR a: TextModels.Attributes; color: Ports.Color; c: Models.Context; font: Fonts.Font;
asc, dsc, fw: INTEGER; d: Dates.Date; date: ARRAY 32 OF CHAR; seq: ARRAY 8 OF CHAR;
BEGIN
c := v.context;
IF (c # NIL) & (c IS TextModels.Context) THEN
a := v.context(TextModels.Context).Attr();
font := a.font;
color := a.color
ELSE font := Fonts.dir.Default(); color := Ports.black
END;
font.GetBounds(asc, dsc, fw);
f.DrawLine(f.l, asc + f.dot, f.r, asc + f.dot, 1, Ports.grey25 );
Dates.DayToDate(v.history[0].date, d);
Dates.DateToString(d, Dates.plainAbbreviated, date);
Strings.IntToStringForm(v.history[0].snr, Strings.decimal, 4, "0", FALSE, seq);
f.DrawString(0, asc, color, date + " (" + seq + ")", font)
END Restore;
PROCEDURE SizePref (v: StdView; VAR p: Properties.SizePref);
VAR font: Fonts.Font; asc, dsc, w: INTEGER; d: Dates.Date; s: ARRAY 64 OF CHAR;
BEGIN
font := FontContext(v);
font.GetBounds(asc, dsc, w);
d.day := 28; d.month := 1; d.year := 2222; p.w := 0;
WHILE d.month <= 12 DO
Dates.DateToString(d, Dates.plainAbbreviated, s);
s := s + " (0000)";
w := font.StringWidth(s);
IF w > p.w THEN p.w := w END;
INC(d.month)
END;
p.h := asc + dsc;
END SizePref;
PROCEDURE (v: StdView) HandlePropMsg (VAR msg: Properties.Message);
VAR font: Fonts.Font; asc, w: INTEGER;
BEGIN
WITH msg: Properties.Preference DO
WITH msg: Properties.SizePref DO
SizePref(v, msg)
| msg: Properties.ResizePref DO
msg.fixed := TRUE
| msg: Properties.FocusPref DO
msg.hotFocus := TRUE
| msg: TextSetters.Pref DO
font := FontContext(v);
font.GetBounds(asc, msg.dsc, w);
ELSE
END
ELSE
END
END HandlePropMsg;
PROCEDURE NewRuler (): TextRulers.Ruler;
CONST mm = Ports.mm;
VAR r: TextRulers.Ruler;
BEGIN
r := TextRulers.dir.New(NIL);
TextRulers.SetRight(r, 140 * mm);
TextRulers.AddTab(r, 15 * mm); TextRulers.AddTab(r, 35 * mm); TextRulers.AddTab(r, 75 * mm);
RETURN r
END NewRuler;
PROCEDURE ShowHistory (v: StdView);
VAR text: TextModels.Model; f: TextMappers.Formatter;
i: INTEGER; d: Dates.Date; s: ARRAY 64 OF CHAR;
tv: TextViews.View; attr: TextModels.Attributes;
BEGIN
text := TextModels.dir.New();
f.ConnectTo(text);
attr := f.rider.attr;
f.rider.SetAttr(TextModels.NewStyle(attr, {Fonts.italic}));
Dialog.MapString("#Std:seq nr.", s); f.WriteString(s); f.WriteTab;
Dialog.MapString("#Std:fingerprint", s); f.WriteString(s); f.WriteTab;
Dialog.MapString("#Std:date and time", s); f.WriteString(s); f.WriteTab;
Dialog.MapString("#Std:comment", s); f.WriteString(s); f.WriteLn;
f.rider.SetAttr(attr); f.WriteLn;
(*--n := v.snr;*)
IF v.comment0 # "" THEN
Dialog.MapString("#Std:new", s); f.WriteString(s); f.WriteTab; f.WriteTab;
Dates.GetDate(d); Dates.DateToString(d, Dates.plainAbbreviated, s); f.WriteString(s);
f.WriteTab; f.WriteString(v.comment0); f.WriteLn
END ;
FOR i := 0 TO v.nentries-1 DO
f.WriteIntForm(v.history[i].snr, 10, 4, "0", FALSE);
(*--DEC(n);*)
f.WriteTab;
f.WriteIntForm(v.history[i].fprint, TextMappers.hexadecimal, 8, "0", FALSE);
f.WriteTab;
Dates.DayToDate(v.history[i].date, d);
Dates.DateToString(d, Dates.plainAbbreviated, s);
f.WriteString(s);
f.WriteString(" ");
f.WriteIntForm(v.history[i].time DIV 64, 10, 2, "0", FALSE);
f.WriteString(":");
f.WriteIntForm(v.history[i].time MOD 64, 10, 2, "0", FALSE);
IF v.history[i].comment # NIL THEN
f.WriteTab;
f.WriteString( v.history[i].comment^);
END;
f.WriteLn;
END;
tv := TextViews.dir.New(text);
tv.SetDefaults(NewRuler(), TextViews.dir.defAttr);
tv.ThisController().SetOpts({Containers.noFocus, Containers.noCaret});
Views.OpenAux(tv, "History");
END ShowHistory;
PROCEDURE Track (v: StdView; f: Views.Frame; x, y: INTEGER; buttons: SET);
VAR c: Models.Context; w, h: INTEGER; isDown, in, in0: BOOLEAN; m: SET;
d: Dates.Date; today, age: INTEGER;
BEGIN
c := v.context; c.GetSize(w, h); in0 := FALSE; in := TRUE;
REPEAT
IF in # in0 THEN
f.MarkRect(0, 0, w, h, Ports.fill, Ports.invert, Ports.show); in0 := in
END;
f.Input(x, y, m, isDown);
in := (0 <= x) & (x < w) & (0 <= y) & (y < h)
UNTIL ~isDown;
IF in0 THEN
f.MarkRect(0, 0, w, h, Ports.fill, Ports.invert, Ports.hide);
IF Controllers.modify IN m THEN
Dates.GetDate(d); today := Dates.Day(d);
IF (v.nentries = 0) OR (v.history[0].date # today) OR (v.comment0 # "") THEN age := 0
ELSE age := 1
END;
FillComment(v, age, TRUE);
StdCmds.OpenToolDialog("Std/Rsrc/Stamps", "#Std:Comment");
ELSE ShowHistory(v);
END
END
END Track;
PROCEDURE (v: StdView) HandleCtrlMsg (
f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View);
BEGIN
WITH msg: Controllers.TrackMsg DO
Track(v, f, msg.x, msg.y, msg.modifiers)
| msg: Controllers.PollCursorMsg DO
msg.cursor := Ports.refCursor
ELSE
END
END HandleCtrlMsg;
PROCEDURE GetActiveStamp (): StdView;
VAR context: Models.Context;
BEGIN
IF comment.stamp # NIL THEN
context := comment.stamp.context;
IF context # NIL THEN
IF context.ThisModel() = TextViews.FocusText() THEN RETURN comment.stamp END
END
END;
RETURN NIL
END GetActiveStamp;
(* ------------ programming interface: ---------------------- *)
PROCEDURE GetFirstInText* (t: TextModels.Model): Views.View;
VAR r: TextModels.Reader; v: Views.View;
BEGIN
IF t # NIL THEN
r := t.NewReader(NIL);
REPEAT r.ReadView(v) UNTIL (v = NIL) OR (v IS StdView);
RETURN v;
ELSE RETURN NIL;
END;
END GetFirstInText;
PROCEDURE IsStamp* (v: Views.View): BOOLEAN;
BEGIN
RETURN v IS StdView;
END IsStamp;
PROCEDURE GetInfo* (v: Views.View; OUT historylen: INTEGER);
BEGIN
ASSERT(v IS StdView, 20);
WITH v: StdView DO
historylen := v.nentries;
END
END GetInfo;
PROCEDURE GetData* (v: Views.View; entryno: INTEGER;
OUT snr, fprint: INTEGER; OUT date: Dates.Date; OUT time: Dates.Time;
OUT comment: ARRAY OF CHAR);
BEGIN
ASSERT(v IS StdView, 20);
WITH v: StdView DO
ASSERT(entryno < v.nentries, 21);
snr := v.history[entryno].snr;
fprint := v.history[entryno].fprint;
Dates.DayToDate(v.history[entryno].date, date);
time.hour := v.history[entryno].time DIV 64;
time.minute := v.history[entryno].time MOD 64;
time.second := 0;
IF v.history[entryno].comment # NIL THEN comment := v.history[entryno].comment^$
ELSE comment := ""
END
END
END GetData;
(** Insert new history entry with comment in v. *)
PROCEDURE Stamp* (v: Views.View; IN comment: ARRAY OF CHAR);
BEGIN
ASSERT(v IS StdView, 20);
WITH v: StdView DO
Update(v, TRUE);
NEW(v.history[0].comment, LEN(comment$) + 1);
v.history[0].comment^ := comment$;
END
END Stamp;
PROCEDURE New* (): Views.View;
VAR v: StdView; d: Dates.Date; t: Dates.Time;
BEGIN
NEW(v); NEW(v.history, maxHistoryEntries); v.history[0].snr := 0; v.nentries := 0;
v.history[0].fprint := -1;
Dates.GetDate(d); Dates.GetTime(t);
v.history[0].date := Dates.Day(d);
v.history[0].time := t.minute + t.hour*64;
RETURN v;
END New;
PROCEDURE SetComment*;
VAR v: StdView; op: SetCmtOp;
BEGIN
v := GetActiveStamp();
IF v # NIL THEN
NEW(op); op.stamp := v; op.age := comment.snrList.index;
NEW(op.oldcomment, LEN(comment.s$) + 1);
op.oldcomment^ := comment.s$;
Views.Do(v, setCommentKey, op)
END
END SetComment;
PROCEDURE Deposit*;
BEGIN
Views.Deposit(New())
END Deposit;
PROCEDURE Guard* (VAR par: Dialog.Par);
BEGIN
par.disabled := GetActiveStamp() = NIL
END Guard;
PROCEDURE SnrNotifier* (op, from, to: INTEGER);
VAR v: StdView;
BEGIN
IF op = Dialog.changed THEN
FillComment(comment.stamp, comment.snrList.index, FALSE)
END
END SnrNotifier;
END StdStamps.
| Std/Mod/Stamps.odc |
MODULE StdStdCFrames;
(**
project = "BlackBox 2.0"
organization = "www.oberon.ch, blackbox.oberon.org"
contributors = "Oberon microsystems, Ivan Denisov, Anton Dmitriev, Ketmar Dark"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 20230106, k8, added (rough) SelectionBox implementation
- 20230108, k8, implemented scrolling in Field (text edit control)
- 20230108, k8, reimplemented ListBox (it is not a combo!)
- 20230111, k8, make active ListBox item visible on first show (HACK!)
- 20230112, k8, implemented search-on-type in ListBox
- 20230113, k8, better implementation of ComboBox popup (screen bounds fitting, keyboard navigation)
- 20230113, k8, S-Home and S-End handling in Field
- 20230113, k8, added "stationary" ComboBox popup mode (as in windows version)
- 20230113, k8, implemented very crude (but working) ColorField
- 20230118, k8, completely reworked; removed storages; implemented new look&feel
- 20230121, k8, moved guts out of this module; cosmetic fixes
- 20230126, k8, vertical scrollbar (it is slightly glitchy, but works)
- 20230208, k8, center list cursor on updates
- 20230209, k8, removed `DrawIt()` method
- 20230311, dia, moved k8 realisation to 2.0
- 20230627, dia, multiline fields
"
issues = "
- k8: SelectionBox rendering is not optimal!
"
**)
IMPORT
Dialog, Fonts, Ports, Views, Strings, Controllers, Controls, Services, Stores, Dates,
StdCFrames, StdCmds, TextViews, TextModels, Models, Log, Files,
Documents, StdDocuments, StdRasters;
CONST
DELETE* = 07X; BACKSPACE* = 08X; TAB* = 09X; LTAB* = 0AX;
ENTER* = 0DX; ESC* = 1BX;
PL* = 10X; PR* = 11X; (* ctrl+page up, ctrl+page down *)
PU* = 12X; PD* = 13X; (* page up, page down *)
DL* = 14X; DR* = 15X; (* home, end *)
DU* = 16X; DD* = 17X; (* ctrl+home, ctrl+end *)
AL* = 1CX; AR* = 1DX; AU* = 1EX; AD* = 1FX; (* arrows *)
(* character classes for word searching *)
classBlank* = 0; classWord* = 1; classNonWord* = 2;
(* skin states; "selected" is the selection for an editor, or marked item for a list *)
stNormal* = 0; stFront* = 1; stDisabled* = 2; stReadOnly* = 3;
stSelectedFlag* = 4; stCursorFlag* = 8; stCursorSelectedFlag* = 12;
doubleclickTimeout = 300;
singleLineSize = 1024;
listTabSize = 12; (* for formatted lists *)
maxLayoutColumns = 10;
TYPE
Storage = POINTER TO EXTENSIBLE RECORD
view: Views.View;
next: Storage;
END;
ParamSkin* = POINTER TO RECORD
backPopup*,
textPopup*,
(* control (button, checkbox) *)
back*,
text*,
(* control (button, checkbox) hover *)
backHover*,
textHover*,
(* control (button, checkbox) disabled *)
backDisabled*,
textDisabled*,
(* control (button, checkbox) disabled *)
backReadOnly*,
textReadOnly*,
(* control (button, checkbox) pressed *)
backPressed*,
textPressed*,
(* active editor *)
backEditor*,
textEditor*,
backEditorSelection*,
textEditorSelection*,
(* non-focused editor *)
backEditorBlured*,
textEditorBlured*,
backEditorBluredSelection*,
textEditorBluredSelection*,
(* disabled editor *)
backEditorDisabled*,
textEditorDisabled*,
backEditorDisabledSelection*,
textEditorDisabledSelection*,
(* readonly editor *)
backEditorReadOnly*,
textEditorReadOnly*,
backEditorReadOnlySelection*,
textEditorReadOnlySelection*,
(* list views *)
backList*,
textList*,
(* selected items *)
backSelList*,
textSelList*,
backListCursor*,
textListCursor*,
(* cursor for selected items *)
backSelListCursor*,
textSelListCursor*,
(* disabled list views *)
backListDisabled*,
textListDisabled*,
(* selected items *)
backSelListDisabled*,
textSelListDisabled*,
backListCursorDisabled*,
textListCursorDisabled*,
(* cursor for selected items *)
backSelListCursorDisabled*,
textSelListCursorDisabled*,
(* blured list views *)
backListBlured*,
textListBlured*,
(* selected items *)
backSelListBlured*,
textSelListBlured*,
backListCursorBlured*,
textListCursorBlured*,
(* cursor for selected items *)
backSelListCursorBlured*,
textSelListCursorBlured*,
(* sliders *)
backSlider*, (* -slider-background-color- *)
backPressedSlider*, (* -slider-background-active-color- *)
trackSlider*, (* -slider-track-color- *)
(* frames *)
frame*,
frameFocus*,
frameReadOnly*,
frameDisabled*: Ports.Color;
frameFace*,
frameLight*,
frameDark*,
frameShadow*,
frameSemi*: Ports.Color;
arrowDisabled*,
arrowReadOnly*,
arrow*: Ports.Color;
(* scrollbars *)
backScrollbar*, backScrollbarButtons*, knobScrollbar*, knobScrollbarPressed*: Ports.Color;
scrollbarKnobMargin*: INTEGER;
checkBoxFont: Fonts.Font;
InitDefaults-: PROCEDURE (a: ANYPTR)
END;
(* common tools *)
(* used for margins, if you didn't figured it; in dot counts *)
MarginRect = RECORD
l, t, r, b: INTEGER
END;
SBPosChangedCB = PROCEDURE (sb: ScrollBarCommon; par: ANYPTR);
ScrollBarCommon = POINTER TO ABSTRACT RECORD
min, max, pos, pageSize, contentSize, arrowStep: INTEGER;
(* size along the main dimension; calcucated by the owner *)
length: INTEGER;
(* render position, in pixels; used to fix mouse coords *)
x0, y0: INTEGER
END;
PopupCommon = POINTER TO ABSTRACT RECORD (Views.View)
owner: StdCFrames.Frame; (* listbox or combobox *)
lst: ListCommon; (* shared with the parent *)
dotsize: INTEGER;
starty: INTEGER;
hoveridx: INTEGER;
hideCalled: BOOLEAN;
END;
EditorCommonText = POINTER TO ARRAY OF CHAR;
SingleLine = POINTER TO ARRAY singleLineSize OF CHAR;
EditorCommonExpText = POINTER TO RECORD
str: SingleLine;
num, era: INTEGER;
next: EditorCommonExpText
END;
TextStackItem = POINTER TO RECORD
text: EditorCommonText;
pos, from, to: INTEGER;
next: TextStackItem
END;
(* common editor engine, shared between various input fields *)
(* "not yet deremined" caret position is used after setting the selection.
arrow keys will move the caret to the selection start, or to the selection end respectively. *)
EditorCommon = POINTER TO RECORD
ctl: StdCFrames.Frame;
st: FieldStorage;
text: EditorCommonText; (* 0-terminated, big *)
textExp: EditorCommonExpText; (* exploded `text` *)
textLen: INTEGER; (* cached text length *)
textStars: EditorCommonText; (* used to replace fields with stars for passwords *)
pos: INTEGER; (* caret position; -1 means "not yet determined" *)
from, to: INTEGER; (* selection; from = to means "nothing selected" *)
(* copy of fields from StdCFrames.Field *)
maxLen, caretLine, lineHeight: INTEGER;
left, right, multiLine, password: BOOLEAN;
noMouseSelect: BOOLEAN; (* if TRUE, hold-and-drag mouse selection is disabled *)
xoffs: INTEGER; (* render will start at x-xoffs *)
x0, y0, w, h, pad-: INTEGER; (* render coordinates, don't include margin *)
caretVisible: BOOLEAN; (* current caret state; used in `BlinkCaret` *)
caretLastBlinkTime: LONGINT;
changeCount: INTEGER; (* incremented on each text change; kind of Era *)
outMargin: MarginRect; (* this is used in `Restore()` to clear "outer" margin; dot count *)
lastDblTime: LONGINT; (* last doubleclick time, to detect triple click *)
vsb: VScrollBar;
vsbPressed: BOOLEAN;
yoffs: INTEGER;
END;
TextChain = POINTER TO RECORD
text: EditorCommonText;
next: TextChain
END;
ListCommonItem = RECORD
text: EditorCommonText;
tabbed: TextChain;
marked: BOOLEAN
END;
ListCommonItemArray = POINTER TO ARRAY OF ListCommonItem;
(* list store and renderer, used by ListBox, ComboBox and SelectionBox *)
ListCommon = POINTER TO RECORD
ctl: StdCFrames.Frame;
items: ListCommonItemArray;
map, unmap: POINTER TO ARRAY OF INTEGER;
widths: ARRAY maxLayoutColumns OF INTEGER;
pos: INTEGER; (* cursor position *)
yoffs, xoffs: INTEGER; (* render will start at y-xoffs *)
x0, y0, w, h: INTEGER; (* render coordinates, don't include margin *)
lastSearchTime: LONGINT;
lastSearchPos: INTEGER;
outMargin: MarginRect; (* this is used in `Restore()` to clear "outer" margin; dot count *)
maxWidth, totalHeight: INTEGER; (* cached total width and height *)
vsb: VScrollBar; hsb: HScrollBar;
vsbPressed, hsbPressed, sorted: BOOLEAN
END;
(* handy thing *)
ClipRect = RECORD
ox0, oy0, ox1, oy1: INTEGER; (* saved original *)
f: Views.Frame
END;
(** for calling with Meta.CallWith *)
LenParam = RECORD
i: INTEGER
END;
IndexParam = RECORD
i: INTEGER
END;
Popup = POINTER TO RECORD(PopupCommon) END;
VScrollBar = POINTER TO RECORD (ScrollBarCommon)
trackStartY, trackOfsY, trackSavedPos: INTEGER
END;
HScrollBar = POINTER TO RECORD (ScrollBarCommon)
trackStartX, trackOfsX, trackSavedPos: INTEGER
END;
Directory = POINTER TO RECORD (StdCFrames.Directory) END;
Caption = POINTER TO RECORD (StdCFrames.Caption)
textExp: EditorCommonExpText; (* exploded `text` *)
changeCount: INTEGER;
END;
Group = POINTER TO RECORD (StdCFrames.Group) END;
PushButton = POINTER TO RECORD (StdCFrames.PushButton) END;
CheckBox = POINTER TO RECORD (StdCFrames.CheckBox) END;
RadioButtonStorage = POINTER TO RECORD (Storage)
hasFocus: BOOLEAN;
END;
RadioButton = POINTER TO RECORD (StdCFrames.RadioButton) END;
(* `ctl` in `ed`/`lst` is set on the first update; this is used in the code! *)
ComboBox = POINTER TO RECORD (StdCFrames.ComboBox)
ed: EditorCommon;
lst: ListCommon;
fixCursor: BOOLEAN; (* if TRUE, make the cursor visible on render (and center it) *)
closedTime: LONGINT;
popupOverlay: PopupCommon
END;
FieldStorage = POINTER TO RECORD (Storage)
textStack, forwardStack: TextStackItem;
END;
Field = POINTER TO RECORD (StdCFrames.Field)
ed: EditorCommon
END;
UpDownField = POINTER TO RECORD (StdCFrames.UpDownField)
ed: EditorCommon;
lastval: INTEGER
END;
ListBox = POINTER TO RECORD (StdCFrames.ListBox)
lst: ListCommon;
fixCursor: BOOLEAN; (* if TRUE, make the cursor visible on render (and center it) *)
closedTime: LONGINT;
popupOverlay: PopupCommon
END;
SelectionBox = POINTER TO RECORD (StdCFrames.SelectionBox)
lst: ListCommon;
fixCursor: BOOLEAN (* if TRUE, make the cursor visible on render (and center it) *)
END;
NodeItem = RECORD p: INTEGER; n: Dialog.TreeNode END;
TreeFrame = POINTER TO RECORD (StdCFrames.TreeFrame)
leftMargin, lineHeight, strHeight, totalHeight, maxWidth,
yoffs, xoffs, lines: INTEGER;
vsb: VScrollBar; hsb: HScrollBar;
vsbPressed, hsbPressed: BOOLEAN;
nodesCache: POINTER TO ARRAY OF NodeItem;
END;
ScrollBar = POINTER TO RECORD (StdCFrames.ScrollBar)
vsb: VScrollBar; hsb: HScrollBar;
vsbPressed, hsbPressed: BOOLEAN
END;
TimeField = POINTER TO RECORD (StdCFrames.TimeField)
ed: EditorCommon
END;
DateField = POINTER TO RECORD (StdCFrames.DateField)
ed: EditorCommon;
dateSep: CHAR;
yearPart, monthPart, dayPart: INTEGER; (* first = 1, last = 3 *)
del1, del2: INTEGER (* position of separators *)
END;
ColorField = POINTER TO RECORD (StdCFrames.ColorField) END;
VAR
focusControl*: StdCFrames.Field;
skin*: ParamSkin;
revealPasswords*: BOOLEAN;
inHandleMouse*: BOOLEAN; (* for compatibility with Windows version *)
storages: Storage;
folder, folderopen, leaf: StdRasters.Model;
PROCEDURE (VAR r: MarginRect) SetZero*, NEW;
BEGIN
r.l := 0; r.t := 0; r.r := 0; r.b := 0
END SetZero;
PROCEDURE (VAR r: MarginRect) SetUni* (size: INTEGER), NEW;
BEGIN
r.l := size; r.t := size; r.r := size; r.b := size
END SetUni;
(* doesn't include 0X, newline, paragraph, but includes nbsp and such *)
PROCEDURE IsBlank (ch: CHAR): BOOLEAN;
BEGIN
(* 0DX is line, 0EX is para *)
CASE ch OF
| 01X .. 0CX, 0FX .. 20X
, 08BX (* zwspace *)
, 08FX (* digitspace *)
, 0A0X: (* nbspace *)
RETURN TRUE
ELSE RETURN FALSE
END
END IsBlank;
PROCEDURE ClassifyChar (ch: CHAR): INTEGER;
VAR
res: INTEGER;
BEGIN
CASE ch OF
| 'A' .. 'Z', 'a' .. 'z', '0' .. '9', '_', '$': res := classWord
| 0X .. 20X: res := classBlank
ELSE
IF IsBlank(ch) THEN res := classBlank
ELSIF ch >= 80X THEN res := classWord
ELSE res := classNonWord
END
END;
RETURN res
END ClassifyChar;
(* k8: note that callind this will rebuild frames! *)
PROCEDURE UpdateRoot* (c: StdCFrames.Frame);
VAR
root: Views.RootFrame;
l, t, r, b: INTEGER;
BEGIN
(* this is wrong, because we don't need to update the whole main frame.
besides, sometimes there isn't even one (design mode, for example, is *special*)
(*root := Views.UltimateRootOf(c);*)
root := Views.RootOf(c);
IF root # NIL THEN
l := root.l + root.gx; t := root.t + root.gy; r := root.r + root.gx; b := root.b + root.gy;
Views.RestoreRoot(root, l, t, r, b)
(*Views.ValidateRoot(root) — do not use, this may rebuild frames! *)
END
END UpdateRoot;
PROCEDURE StrStartsWithCI (IN s0, s1: ARRAY OF CHAR; len: INTEGER): BOOLEAN;
VAR
f: INTEGER;
res: BOOLEAN;
BEGIN
res := TRUE;
f := 0; WHILE (f < len) & res DO
IF (s0[f] = 0X) OR (s1[f] = 0X) THEN res := FALSE
ELSE res := (Strings.Upper(s0[f]) = Strings.Upper(s1[f]))
END;
INC(f)
END;
RETURN res
END StrStartsWithCI;
PROCEDURE GetLen (VAR rec, par: ANYREC);
BEGIN
WITH rec: Dialog.Combo DO
WITH par: LenParam DO par.i := rec.len END
| rec: Dialog.List DO
WITH par: LenParam DO par.i := rec.len END
| rec: Dialog.Selection DO
WITH par: LenParam DO par.i := rec.len END
END
END GetLen;
PROCEDURE Update* (VAR cb, par: ANYREC);
BEGIN Dialog.Update(cb)
END Update;
PROCEDURE GetSortedInfo (c: StdCFrames.Frame): BOOLEAN;
VAR res: BOOLEAN;
BEGIN
res := FALSE;
IF c.view # NIL THEN
WITH c: StdCFrames.ListBox DO res := c(StdCFrames.ListBox).sorted
| c: StdCFrames.SelectionBox DO res := c(StdCFrames.SelectionBox).sorted
| c: StdCFrames.ComboBox DO res := c(StdCFrames.ComboBox).sorted
END
END;
RETURN res
END GetSortedInfo;
PROCEDURE GetListLength (c: StdCFrames.Frame): INTEGER;
VAR par: LenParam; con: Controls.Control; doit: BOOLEAN; res: INTEGER;
BEGIN
ASSERT(c # NIL, 20);
res := 0;
IF c.view # NIL THEN
WITH c: StdCFrames.ListBox DO doit := TRUE
| c: StdCFrames.SelectionBox DO doit := TRUE
| c: StdCFrames.ComboBox DO doit := TRUE
ELSE doit := FALSE
END;
IF doit THEN
con := c.view(Controls.Control);
ASSERT(con # NIL);
IF con.item.Valid() THEN
con.item.CallWith(GetLen, par);
res := MAX(0, par.i)
END
END
END;
RETURN res
END GetListLength;
PROCEDURE ThisIndex (VAR rec, par: ANYREC);
VAR
res, i: INTEGER;
s: Dialog.String;
BEGIN
WITH par: IndexParam DO
WITH rec: Dialog.Combo DO
res := -1; i := 0;
WHILE (res < 0) & (i < rec.len) DO
rec.GetItem(i, s);
IF s$ = rec.item$ THEN res := i END;
INC(i)
END;
par.i := res
END
END
END ThisIndex;
PROCEDURE GetCursorIndex (c: StdCFrames.Frame): INTEGER;
VAR
con: Controls.Control;
par: IndexParam;
res: INTEGER;
BEGIN
res := -1;
IF (c # NIL) & (c.view # NIL) THEN
WITH c: StdCFrames.ListBox DO c.Get(c, res)
| c: SelectionBox DO
res := c.lst.pos
| c: StdCFrames.ComboBox DO
con := c.view(Controls.Control);
ASSERT(con # NIL);
IF con.item.Valid() THEN
con.item.CallWith(ThisIndex, par);
res := par.i
END
ELSE END
END;
RETURN res
END GetCursorIndex;
PROCEDURE GetItemText* (c: StdCFrames.Frame; idx: INTEGER; OUT s: ARRAY OF CHAR);
BEGIN
s := "";
IF (c # NIL) & (c.view # NIL) THEN
WITH c: StdCFrames.ListBox DO c.GetName(c, idx, s)
| c: StdCFrames.SelectionBox DO c.GetName(c, idx, s)
| c: StdCFrames.ComboBox DO c.GetName(c, idx, s)
ELSE END
END
END GetItemText;
(** **************** ClipRect **************** **)
PROCEDURE (VAR c: ClipRect) Init* (f: Views.Frame), NEW;
BEGIN
IF (f # NIL) & (f.rider # NIL) THEN
c.f := f;
f.rider.GetRect(c.ox0, c.oy0, c.ox1, c.oy1)
ELSE c.f := NIL
END
END Init;
PROCEDURE (VAR c: ClipRect) Close*, NEW;
BEGIN
IF (c.f # NIL) & (c.f.rider # NIL) THEN
c.f.rider.SetRect(c.ox0, c.oy0, c.ox1, c.oy1)
END;
c.f := NIL
END Close;
(* `x1` and `y1` are NOT included *)
PROCEDURE (VAR c: ClipRect) ShrinkToXY* (x0, y0, x1, y1: INTEGER): BOOLEAN, NEW;
VAR
cx0, cy0, cx1, cy1: INTEGER;
res: BOOLEAN;
BEGIN
res := FALSE;
IF (c.f # NIL) & (c.f.rider # NIL) & (x0 <= x1) & (y0 <= y1) THEN
(* transform selection rectangle to pixel coords *)
x0 := (c.f.gx + x0) DIV c.f.unit;
y0 := (c.f.gy + y0) DIV c.f.unit;
x1 := (c.f.gx + x1) DIV c.f.unit;
y1 := (c.f.gy + y1) DIV c.f.unit;
c.f.rider.GetRect(cx0, cy0, cx1, cy1);
IF (cx0 < cx1) & (cy0 < cy1) THEN
IF (x1 <= cx0) OR (y1 <= cy0) OR
(x0 >= cx1) OR (y0 >= cy1) THEN
(* nothing to do *)
ELSE (* rectangles intersects *)
cx0 := MAX(cx0, x0);
cy0 := MAX(cy0, y0);
cx1 := MIN(cx1, x1);
cy1 := MIN(cy1, y1);
IF (cx0 < cx1) & (cy0 < cy1) THEN
res := TRUE; c.f.rider.SetRect(cx0, cy0, cx1, cy1)
ELSE
c.f.rider.SetRect(cx0, cy0, cx0, cy0)
END
END
END
END;
RETURN res
END ShrinkToXY;
PROCEDURE (VAR c: ClipRect) ShrinkToWH* (x0, y0, w, h: INTEGER): BOOLEAN, NEW;
VAR
res: BOOLEAN;
BEGIN
IF c.f # NIL THEN
res := c.ShrinkToXY(x0, y0, x0 + w, y0 + h)
ELSE res := FALSE
END;
RETURN res
END ShrinkToWH;
(** **************** common "onpress" code for buttons **************** **)
PROCEDURE TrackMouseDown* (c: StdCFrames.Frame): BOOLEAN;
VAR
w, h, x, y: INTEGER;
isDown: BOOLEAN;
modifiers: SET;
res: BOOLEAN;
BEGIN
res := FALSE;
IF c.rider # NIL THEN
(* k8: this hack repaints other controls, so they could indicate focus loss *)
UpdateRoot(c);
c.view.context.GetSize(w, h);
c.pressed := TRUE;
c.ForceUpdate;
REPEAT
c.Input(x, y, modifiers, isDown);
IF c.pressed # ((x >= 0) & (y >= 0) & (x < w) & (y < h)) THEN
c.pressed := ~c.pressed;
c.ForceUpdate
END
UNTIL ~isDown;
res := c.pressed;
IF c.pressed THEN c.pressed := FALSE; c.ForceUpdate END
END;
RETURN res
END TrackMouseDown;
(** **************** ScrollBarCommon **************** **)
PROCEDURE (sb: ScrollBarCommon) Init, NEW, EMPTY;
PROCEDURE (sb: ScrollBarCommon) Draw (frm: Views.Frame; x, y, dim: INTEGER; pressed: BOOLEAN), NEW, ABSTRACT;
PROCEDURE (sb: ScrollBarCommon) SBMouseDown (x, y: INTEGER): BOOLEAN, NEW, ABSTRACT;
PROCEDURE (sb: ScrollBarCommon) SBMouseTrack (x, y: INTEGER), NEW, ABSTRACT;
PROCEDURE (sb: ScrollBarCommon) Width(): INTEGER, NEW;
BEGIN
RETURN 12 * Ports.point
END Width;
PROCEDURE (sb: ScrollBarCommon) GetMinKnobSize (): INTEGER, NEW;
BEGIN
RETURN sb.Width()
END GetMinKnobSize;
PROCEDURE (sb: ScrollBarCommon) GetTotalSize (): INTEGER, NEW;
BEGIN
RETURN MAX(0, sb.max - sb.min + 1)
END GetTotalSize;
PROCEDURE (sb: ScrollBarCommon) CanFit (): BOOLEAN, NEW;
BEGIN
RETURN sb.length - sb.Width() * 2 - sb.GetMinKnobSize() > 0
END CanFit;
PROCEDURE (sb: ScrollBarCommon) CalcKnobSize (): INTEGER, NEW;
VAR res, length: INTEGER;
BEGIN
length := sb.length - sb.Width() * 2;
IF (length > 0) & (sb.pageSize > 0) THEN
(*
knob size shows how much of the total is visible
i.e. if total is 20, visible is 5 and the main dim is 60, then
knob size is 5/20*60
*)
res := SHORT((LONG(sb.pageSize) * LONG(length)) DIV LONG(sb.contentSize))
END;
IF res < sb.GetMinKnobSize() THEN
res := sb.GetMinKnobSize()
END;
RETURN res
END CalcKnobSize;
(* in pixels, inside the main bar *)
PROCEDURE (sb: ScrollBarCommon) CalcKnobPos (pos: INTEGER): INTEGER, NEW;
VAR res, sz, kSize, scrollSize: INTEGER;
BEGIN
scrollSize := sb.length - sb.Width() * 2;
IF (scrollSize < 1) OR (sb.min >= sb.max) THEN
res := 0
ELSE
kSize := sb.CalcKnobSize();
IF kSize > scrollSize THEN
res := 0
ELSE
sz := sb.GetTotalSize();
(* knob position is current visible page position on the length minus knob size *)
pos := MAX(sb.min, MIN(sb.max, pos));
res := SHORT((LONG(scrollSize - kSize) * LONG(pos)) DIV LONG(sz))
END
END;
RETURN res
END CalcKnobPos;
(** **************** EditorCommon (engine) **************** **)
PROCEDURE (ed: EditorCommon) KeepText, NEW;
VAR item: TextStackItem; i: INTEGER;
BEGIN
IF ed.st # NIL THEN
NEW(item);
NEW(item.text, LEN(ed.text));
item.pos := ed.pos;
item.from := ed.from;
item.to := ed.to;
FOR i := 0 TO LEN(ed.text$) - 1 DO
item.text[i] := ed.text[i]
END;
IF ed.st.textStack = NIL THEN
ed.st.textStack := item
ELSE
item.next := ed.st.textStack;
ed.st.textStack := item
END;
ed.st.forwardStack := NIL;
END
END KeepText;
PROCEDURE (ed: EditorCommon) Init, NEW;
BEGIN
ed.ctl := NIL;
NEW(ed.text, 256);
ed.text[0] := 0X; ed.textLen := 0;
ed.textStars := NIL;
ed.pos := -1; ed.from := 0; ed.to := MAX(INTEGER);
ed.xoffs := 0; ed.x0 := 0; ed.y0 := 0; ed.w := 0; ed.h := 0;
ed.maxLen := 255;
ed.password := FALSE; ed.left := TRUE; ed.right := FALSE;
ed.multiLine := FALSE;
ed.caretLine := 1;
ed.lineHeight := 12 * Ports.point;
ed.caretVisible := TRUE; (* why not? ;-) *)
ed.caretLastBlinkTime := Services.Ticks();
ed.changeCount := 0; ed.outMargin.SetZero;
ed.lastDblTime := 0;
ed.noMouseSelect := FALSE
END Init;
PROCEDURE (ed: EditorCommon) SetupCtl (ctl: StdCFrames.Frame), NEW;
BEGIN
ed.ctl := ctl
END SetupCtl;
PROCEDURE (ed: EditorCommon) Setup (ctl: StdCFrames.Frame; x0, y0, w, h: INTEGER), NEW;
BEGIN
ed.x0 := x0; ed.y0 := y0; ed.w := w; ed.h := h;
ed.SetupCtl(ctl)
END Setup;
PROCEDURE (ed: EditorCommon) IsValid (): BOOLEAN, NEW;
BEGIN
RETURN (ed.ctl # NIL) & (ed.w > 0) & (ed.h > 0)
END IsValid;
PROCEDURE (ed: EditorCommon) NeedCaret (): BOOLEAN, NEW;
BEGIN
RETURN (ed.ctl # NIL) & ~ed.ctl.disabled & ~ed.ctl.readOnly
END NeedCaret;
(* return TRUE if the text was changed *)
PROCEDURE (ed: EditorCommon) SetText (IN s: ARRAY OF CHAR): BOOLEAN, NEW;
VAR
res: BOOLEAN;
slen, f, nsz: INTEGER;
nt: EditorCommonText;
wasAllSelected: BOOLEAN;
BEGIN
IF LEN(s) = 0 THEN
IF ed.textLen # 0 THEN
IF LEN(ed.text) > 256 THEN NEW(ed.text, 256) END;
ed.text[0] := 0X; ed.textLen := 0; res := TRUE
END
ELSE
slen := MIN(ed.maxLen, LEN(s$));
res := (slen # ed.textLen);
IF ~res THEN (* same length *)
(* `s` can be longer than allowed, so use the loop instead of `s$ # ed.text$` *)
f := 0; WHILE ~res & (f < slen) DO res := (s[f] # ed.text[f]); INC(f) END
END;
IF res THEN
(* need to reallocate the text storage? *)
IF slen > LEN(ed.text) + 1 THEN
ASSERT(slen < 020000000H); (* just in case *)
nsz := MAX(256, MIN(slen * 2 + 1, ed.maxLen + 1));
NEW(nt, nsz);
ed.text := nt;
ed.text[0] := 0X (* just in case *)
END;
(* `s` can be longer than allowed, so use the loop instead of `ed.text^ := s$` *)
f := 0;
FOR f := 0 TO LEN(ed.text) - 1 DO
ed.text[f] := s[f]
END;
IF slen < LEN(ed.text) - 1 THEN
ed.text[slen] := 0X
ELSE
ed.text[LEN(ed.text) - 1] := 0X
END;
wasAllSelected := (ed.from = 0) & (ed.to >= ed.textLen) & ed.NeedCaret();
ed.textLen := slen;
IF wasAllSelected OR ed.ctl.readOnly THEN ed.pos := -1; ed.from := 0; ed.to := slen
ELSE ed.pos := slen; ed.from := slen; ed.to := slen
END
END
END;
RETURN res
END SetText;
PROCEDURE (ed: EditorCommon) FixSelection, NEW;
VAR
slen: INTEGER;
BEGIN
IF ed.textLen # 0 THEN
slen := ed.textLen;
ed.from := MAX(0, MIN(slen, ed.from));
IF (ed.to < 0) OR (ed.to > slen) THEN ed.to := slen END;
IF ed.to < ed.from THEN slen := ed.from; ed.from := ed.to; ed.to := slen END
ELSE ed.from := 0; ed.to := 0
END
END FixSelection;
PROCEDURE (ed: EditorCommon) Select (from, to: INTEGER), NEW;
BEGIN
ed.from := from; ed.to := to; ed.pos := to;
ed.FixSelection
END Select;
PROCEDURE (ed: EditorCommon) GetSelection (OUT from, to: INTEGER), NEW;
BEGIN
ed.FixSelection;
from := ed.from; to := ed.to
END GetSelection;
PROCEDURE (ed: EditorCommon) GetVisText (): EditorCommonText, NEW;
VAR
res: EditorCommonText;
f: INTEGER;
BEGIN
IF (ed.textLen = 0) OR ~ed.password THEN res := ed.text
ELSE
IF (ed.textStars = NIL) OR (LEN(ed.textStars) < LEN(ed.text)) THEN
NEW(ed.textStars, LEN(ed.text))
END;
FOR f := 0 TO ed.textLen - 1 DO ed.textStars[f] := '*' END;
ed.textStars[ed.textLen] := 0X;
res := ed.textStars
END;
RETURN res
END GetVisText;
(* this doesn't change `ed.pos`, but returns suitable `pos` for rendering *)
PROCEDURE (ed: EditorCommon) FixSelectionPos (): INTEGER, NEW;
VAR
pos, res: INTEGER;
v: REAL;
BEGIN
IF ed.textLen # 0 THEN
ed.FixSelection;
IF ed.multiLine THEN
pos := ed.pos;
IF pos < 0 THEN
IF ed.from = ed.to THEN pos := ed.textLen ELSE pos := ed.to END
ELSE pos := MIN(pos, ed.textLen) (* sanitise it, just in case *)
END;
(* hack for numeric fields *)
IF (ed.from <= 0) & (ed.to >= ed.textLen) THEN
Strings.StringToReal(ed.text, v, res);
IF res = 0 THEN pos := 0 END
END
ELSE
pos := ed.pos;
IF pos < 0 THEN
IF ed.from = ed.to THEN pos := ed.textLen ELSE pos := ed.to END
ELSE pos := MIN(pos, ed.textLen) (* sanitise it, just in case *)
END;
(* hack for numeric fields *)
IF (ed.from <= 0) & (ed.to >= ed.textLen) THEN
Strings.StringToReal(ed.text, v, res);
IF res = 0 THEN pos := 0 END
END
END
ELSE
pos := 0; ed.from := 0; ed.to := 0
END;
RETURN pos
END FixSelectionPos;
PROCEDURE (ed: EditorCommon) RetainCaret, NEW;
BEGIN
ed.caretLastBlinkTime := Services.Ticks();
ed.caretVisible := TRUE
END RetainCaret;
PROCEDURE (ed: EditorCommon) CalcCaretWidth (): INTEGER, NEW;
VAR
sw: INTEGER;
BEGIN
IF ed.ctl # NIL THEN
IF Dialog.thickCaret THEN sw := ed.ctl.dot * 2 ELSE sw := ed.ctl.dot END
ELSE
sw := 1
END;
RETURN sw
END CalcCaretWidth;
PROCEDURE (ed: EditorCommon) CalcTextWidth (): INTEGER, NEW;
VAR sw, maxWidth: INTEGER; tmp: EditorCommonExpText;
BEGIN
sw := 0;
IF (ed.textLen # 0) & ed.IsValid() THEN
IF ed.multiLine THEN
maxWidth := 0;
tmp := ed.textExp;
WHILE tmp # NIL DO
sw := ed.ctl.font.StringWidth(tmp.str);
IF sw > maxWidth THEN maxWidth := sw END;
tmp := tmp.next
END;
sw := maxWidth
ELSE
sw := ed.ctl.font.StringWidth(ed.GetVisText())
END
END;
RETURN sw + ed.CalcCaretWidth()
END CalcTextWidth;
PROCEDURE (ed: EditorCommon) CalcXPos (): INTEGER, NEW;
VAR
x, sw: INTEGER;
BEGIN
IF ed.IsValid() THEN
sw := ed.CalcTextWidth();
IF ed.left THEN
x := ed.pad;
ELSIF ed.right THEN
x := (ed.w - sw) - ed.pad;
ELSE
x := (ed.w - sw) DIV 2
END
ELSE x := 0
END;
RETURN x
END CalcXPos;
PROCEDURE (ed: EditorCommon) MakeCaretVisible, NEW;
VAR
pos, sw, x, addwdt: INTEGER;
BEGIN
pos := ed.FixSelectionPos();
IF (ed.textLen # 0) & ed.IsValid() THEN
IF pos = 0 THEN ed.xoffs := 0
ELSE
sw := ed.CalcTextWidth();
IF sw < ed.w THEN
ed.xoffs := 0
ELSE
addwdt := ed.pad * 2;
x := ed.CalcXPos();
x := ed.ctl.CharPos(x, pos, ed.GetVisText(), ed.ctl.font);
DEC(x, ed.xoffs);
(* now check if the caret is visible *)
IF x - addwdt < 0 THEN
INC(ed.xoffs, x - addwdt)
ELSE
INC(x, ed.CalcCaretWidth() + addwdt);
IF x > ed.w THEN
INC(ed.xoffs, x - ed.w)
END
END;
ed.xoffs := MIN(ed.xoffs, sw - ed.w + addwdt);
ed.xoffs := MAX(ed.xoffs, 0)
END
END
ELSE ed.xoffs := 0
END
END MakeCaretVisible;
PROCEDURE (ed: EditorCommon) NormaliseXOffs, NEW;
VAR
pos, sw: INTEGER;
BEGIN
pos := ed.FixSelectionPos();
IF (ed.textLen # 0) & ed.IsValid() THEN
IF pos = 0 THEN ed.xoffs := 0
ELSE
sw := ed.CalcTextWidth();
IF sw < ed.w THEN ed.xoffs := 0
ELSE
ed.xoffs := MIN(ed.xoffs, sw - ed.w);
ed.xoffs := MAX(ed.xoffs, 0)
END
END
ELSE ed.xoffs := 0
END
END NormaliseXOffs;
PROCEDURE (ed: EditorCommon) PrepareExplodedText, NEW;
VAR
pos, pos2, width, lastSpacePos, lastSpacePos2, line, vsbSize: INTEGER;
str: SingleLine; lineBreak: BOOLEAN;
tx: EditorCommonText; tmp: EditorCommonExpText;
PROCEDURE AddStringToList (str: SingleLine);
VAR n: INTEGER;
BEGIN
IF ed.textExp = NIL THEN
NEW(ed.textExp);
ed.textExp.era := ed.changeCount;
ed.textExp.str := str;
ed.textExp.num := 1;
ELSE
n := 2;
tmp := ed.textExp;
WHILE tmp.next # NIL DO
INC(n);
tmp := tmp.next;
END;
NEW(tmp.next);
tmp.next.str := str;
tmp.next.num := n;
END
END AddStringToList;
BEGIN
IF (ed.textExp # NIL) & (ed.textExp.era = ed.changeCount) THEN RETURN END;
ed.textExp := NIL;
tx := ed.GetVisText();
IF ed.vsb # NIL THEN
vsbSize := MAX(0, ed.vsb.Width())
ELSE
vsbSize := 0
END;
pos := 0;
line := 0;
WHILE (tx[pos] # 0X) & (line < 1024) DO (* prevent hanging in case of trubles with parsing *)
pos2 := 0;
NEW(str);
width := 0; lineBreak := FALSE;
lastSpacePos := 0; lastSpacePos2 := 0;
WHILE (tx[pos] # 0X) & (~lineBreak) DO
IF tx[pos] = " " THEN
lastSpacePos := pos;
lastSpacePos2 := pos2;
END;
str[pos2] := tx[pos];
str[pos2+1] := 0X;
width := ed.ctl.font.StringWidth(str);
IF (width > ed.w - vsbSize - ed.x0 - ed.pad * 2 ) THEN
lineBreak := TRUE;
IF lastSpacePos # 0 THEN
(* forward count untill space *)
pos := lastSpacePos + 1;
pos2 := lastSpacePos2 + 1
END
ELSIF tx[pos] = ENTER THEN
lineBreak := TRUE;
INC(pos); INC(pos2)
ELSE
INC(pos); INC(pos2)
END
END;
str[pos2] := 0X;
AddStringToList(str);
INC(line)
END;
IF (pos >= 1) & (tx[pos-1] = ENTER) THEN
NEW(str);
str[0] := 0X;
AddStringToList(str)
END
END PrepareExplodedText;
(* returns active string and position of caret in it *)
PROCEDURE (ed: EditorCommon) GetStr (atPos: INTEGER;
OUT str: EditorCommonExpText; OUT pos: INTEGER), NEW;
VAR tmp: EditorCommonExpText; len, lenPrev (* , state *) : INTEGER;
BEGIN
ed.PrepareExplodedText;
(* state := -1; *)
tmp := ed.textExp;
len := 0; lenPrev := 0;
WHILE tmp # NIL DO
lenPrev := len;
len := len + LEN(tmp.str$);
IF (len = atPos) & (ed.text[atPos-1] # ENTER) THEN
(* end of line without return *)
(* state := 1; *)
str := tmp;
pos := LEN(tmp.str$);
tmp := NIL
ELSIF (len = atPos) & (ed.text[atPos-1] = ENTER) THEN
(* end of line with return *)
(* state := 2; *)
ASSERT(tmp.next # NIL, 61);
str := tmp.next;
pos := 0;
tmp := NIL
ELSIF atPos < len THEN
(* state := 3; *)
str := tmp;
pos := atPos - lenPrev;
tmp := NIL
ELSE
(* state := 4; *)
tmp := tmp.next
END
END;
ASSERT(str # NIL, 61);
END GetStr;
PROCEDURE (ed: EditorCommon) DefineCaretLine, NEW;
VAR tmp: EditorCommonExpText; pos: INTEGER;
BEGIN
IF ed.textExp = NIL THEN
ed.caretLine := 1
ELSE
ed.GetStr(ed.pos, tmp, pos);
ed.caretLine := tmp.num
END
END DefineCaretLine;
(* this must remove caret if called second time;
caret visibility flag is changed accordingly *)
PROCEDURE (ed: EditorCommon) DrawCaret, NEW;
VAR
asc, dsc, sw, dot, pos, vsbSize, x, y0, y1: INTEGER;
clip: ClipRect; str: EditorCommonExpText;
BEGIN
ed.caretVisible := ~ed.caretVisible;
ed.ctl.font.GetBounds(asc, dsc, sw);
dot := ed.ctl.dot;
IF ed.vsb # NIL THEN
vsbSize := MAX(0, ed.vsb.Width())
ELSE
vsbSize := 0
END;
sw := ed.CalcTextWidth();
x := ed.CalcXPos();
DEC(x, ed.xoffs);
IF ed.multiLine THEN
y0 := ed.pad + (dsc + asc) + (ed.caretLine - 1) * ed.lineHeight;
IF ed.vsb # NIL THEN
y0 := y0 - ed.vsb.pos
END
ELSE
y0 := ed.y0 + (ed.h - dsc + asc) DIV 2
END;
DEC(y0, asc);
y1 := y0 + asc + dsc;
y0 := MAX(ed.y0, y0);
y1 := MIN(ed.y0 + ed.h - 2 * dot, y1);
IF y0 < y1 THEN
(* caret *)
clip.Init(ed.ctl);
IF clip.ShrinkToWH(ed.x0, ed.y0, ed.w - vsbSize, ed.h) THEN
pos := ed.FixSelectionPos();
IF pos # 0 THEN
IF ed.multiLine THEN
ed.GetStr(ed.pos, str, pos);
x := ed.ctl.CharPos(x, pos, str.str, ed.ctl.font)
ELSE
x := ed.ctl.CharPos(x, pos, ed.GetVisText(), ed.ctl.font)
END
END;
sw := ed.CalcCaretWidth();
ed.ctl.MarkRect(ed.x0+x, y0, ed.x0+x+sw, y1, Ports.fill, Ports.invert, ed.caretVisible)
END;
clip.Close
END
END DrawCaret;
(* background should be already painted by the owner *)
PROCEDURE (ed: EditorCommon) Restore, NEW;
VAR
c: StdCFrames.Frame;
clip: ClipRect;
dot, asc, dsc, sw, sl, sr, textCol, bgCol, selTextCol, selBgCol: INTEGER;
skidx, x, y: INTEGER;
ch: CHAR;
px0, py0, px1, py1: INTEGER;
tx: EditorCommonText;
vsb: VScrollBar;
tmp, strFrom, strTo: EditorCommonExpText;
str1, str2: ARRAY 16 OF CHAR; replaced: CHAR;
lineNum, posFrom, posTo, liHei, n, len, vsbSize: INTEGER;
BEGIN
IF ed.IsValid() THEN
IF ed.multiLine THEN
ed.PrepareExplodedText;
tmp := ed.textExp; n := 0;
WHILE tmp # NIL DO
INC(n); tmp := tmp.next
END
END;
ed.MakeCaretVisible;
c := ed.ctl;
c.font.GetBounds(asc, dsc, sw);
(* check if we need a scrollbar, and prepare it *)
IF n * ed.lineHeight > ed.h THEN
IF ed.vsb = NIL THEN
NEW(vsb);
vsb.Init;
ed.vsb := vsb
ELSE
vsb := ed.vsb
END;
IF vsb # NIL THEN
vsb.min := 0;
vsb.max := (n * ed.lineHeight - ed.h) ;
vsb.contentSize := (n * ed.lineHeight);
vsb.pos := ed.yoffs;
vsb.pageSize := ed.h;
vsb.arrowStep := ed.lineHeight;
vsb.length := ed.h;
IF ~vsb.CanFit() THEN vsb := NIL END
END;
IF vsb # NIL THEN
vsbSize := MAX(0, vsb.Width());
IF (vsbSize = 0) OR ((vsbSize + 4 * Ports.point) >= ed.w) THEN
vsbSize := 0; vsb := NIL
END
END
ELSE
ed.vsb := NIL; vsb := NIL; vsbSize := 0
END;
IF ed.vsb # NIL THEN ed.vsb.length := ed.h END;
sw := ed.CalcTextWidth();
x := ed.CalcXPos();
DEC(x, ed.xoffs);
IF ed.multiLine THEN
y := ed.pad + (dsc + asc) - ed.yoffs
ELSE
y := ed.y0 + (ed.h - dsc + asc) DIV 2
END;
(* map skin according coltrol state *)
IF ed.ctl.disabled THEN
textCol := skin.textEditorDisabled;
bgCol := skin.backEditorDisabled;
selTextCol := skin.textEditorDisabledSelection;
selBgCol := skin.backEditorDisabledSelection;
ELSIF ed.ctl.readOnly THEN
textCol := skin.textEditorReadOnly;
bgCol := skin.backEditorReadOnly;
selTextCol := skin.textEditorReadOnlySelection;
selBgCol := skin.backEditorReadOnlySelection;
ELSIF ed.ctl.mark THEN
textCol := skin.textEditor;
bgCol := skin.backEditor;
selTextCol := skin.textEditorSelection;
selBgCol := skin.backEditorSelection;
ELSE
textCol := skin.textEditorBlured;
bgCol := skin.backEditorBlured;
selTextCol := skin.textEditorBluredSelection;
selBgCol := skin.backEditorBluredSelection;
END;
dot := ed.ctl.dot;
ed.ctl.DrawRect(ed.x0 - ed.outMargin.l * dot, ed.y0 - ed.outMargin.t * dot,
ed.x0 + ed.w + ed.outMargin.r * dot, ed.y0 + ed.h + ed.outMargin.b * dot,
Ports.fill, bgCol);
tx := ed.GetVisText();
clip.Init(ed.ctl);
IF clip.ShrinkToWH(ed.x0, ed.y0, ed.w, ed.h) THEN
IF ed.multiLine THEN
n := y;
tmp := ed.textExp;
WHILE tmp # NIL DO
IF tmp.str$ # "" THEN
len := LEN(tmp.str$)-1;
IF tmp.str[len] = 0DX THEN
tmp.str[len] := 0X;
c.DrawString(ed.x0 + x, n, textCol, tmp.str, c.font);
tmp.str[len] := 0DX
ELSE
c.DrawString(ed.x0 + x, n, textCol, tmp.str, c.font)
END
END;
INC(n, ed.lineHeight);
tmp := tmp.next
END
ELSE
c.DrawString(ed.x0 + x, y, textCol, tx, c.font)
END
END;
clip.Close;
(* selection *)
IF c.front & ~c.disabled & (ed.from # ed.to) & (c.rider # NIL) THEN
IF ed.multiLine THEN
ed.GetStr(ed.from, strFrom, posFrom);
ed.GetStr(ed.to, strTo, posTo);
IF strFrom = strTo THEN
tmp := strFrom;
IF tmp.str$ # "" THEN
len := LEN(tmp.str$) - 1;
IF tmp.str[len] = 0DX THEN
replaced := 0DX;
tmp.str[len] := 0X
ELSE
replaced := 0X
END;
ch := tmp.str[posFrom];
tmp.str[posFrom] := 0X;
sl := c.font.StringWidth(tmp.str);
tmp.str[posFrom] := ch;
(* text length with the selection *)
ch := tmp.str[posTo];
tmp.str[posTo] := 0X;
sr := c.font.StringWidth(tmp.str);
tmp.str[posTo] := ch;
IF sr > sl THEN
clip.Init(c);
(* transform selection rectangle to the actual coords*)
px0 := ed.x0 + x + sl;
px1 := ed.x0 + x + sr + c.dot;
liHei := (tmp.num - 1) * ed.lineHeight;
py0 := y + liHei - asc;
py1 := y + liHei + dsc;
IF clip.ShrinkToXY(px0, py0, px1, py1) THEN
(* draw selection bar *)
c.DrawRect(px0, py0, px1, py1, Ports.fill, selBgCol);
(* and the text again, with the proper color *)
c.DrawString(ed.x0 + x, y + liHei, selTextCol, tmp.str, c.font);
END;
(* restore old clip rectangle *)
clip.Close
END;
IF replaced = 0DX THEN
tmp.str[len] := 0DX
END
END
ELSIF strFrom.num < strTo.num THEN
tmp := strFrom;
IF tmp.str$ # "" THEN
len := LEN(tmp.str$) - 1;
IF tmp.str[len] = 0DX THEN
replaced := 0DX;
tmp.str[len] := 0X
ELSE
replaced := 0X
END;
ch := tmp.str[posFrom];
tmp.str[posFrom] := 0X;
sl := c.font.StringWidth(strFrom.str);
tmp.str[posFrom] := ch;
sr := c.font.StringWidth(strFrom.str);
IF sr > sl THEN
clip.Init(c);
(* transform selection rectangle to the actual coords*)
px0 := ed.x0 + x + sl;
px1 := ed.x0 + x + sr + c.dot;
liHei := (tmp.num - 1) * ed.lineHeight;
py0 := y + liHei - asc;
py1 := y + liHei + dsc;
IF clip.ShrinkToXY(px0, py0, px1, py1) THEN
c.DrawRect(px0, py0, px1, py1, Ports.fill, selBgCol);
c.DrawString(ed.x0 + x, y + liHei, selTextCol, tmp.str, c.font);
END;
(* restore old clip rectangle *)
clip.Close
END;
IF replaced = 0DX THEN
tmp.str[len] := 0DX
END
END;
tmp := strFrom.next;
FOR n := strFrom.num + 1 TO strTo.num - 1 DO
IF tmp.str$ # "" THEN
len := LEN(tmp.str$) - 1;
IF tmp.str[len] = 0DX THEN
replaced := 0DX;
tmp.str[len] := 0X
ELSE
replaced := 0X
END;
sl := 0;
sr := c.font.StringWidth(tmp.str);
IF sr > sl THEN
clip.Init(c);
(* transform selection rectangle to the actual coords*)
px0 := ed.x0 + x + sl;
px1 := ed.x0 + x + sr + c.dot;
liHei := (tmp.num - 1) * ed.lineHeight;
py0 := y + liHei - asc;
py1 := y + liHei + dsc;
IF clip.ShrinkToXY(px0, py0, px1, py1) THEN
c.DrawRect(px0, py0, px1, py1, Ports.fill, selBgCol);
c.DrawString(ed.x0 + x, y + liHei, selTextCol, tmp.str, c.font);
END;
(* restore old clip rectangle *)
clip.Close
END;
IF replaced = 0DX THEN
tmp.str[len] := 0DX
END
END;
tmp := tmp.next
END;
tmp := strTo;
IF tmp.str$ # "" THEN
len := LEN(tmp.str$) - 1;
IF tmp.str[len] = 0DX THEN
replaced := 0DX;
tmp.str[len] := 0X
ELSE
replaced := 0X
END;
sl := 0;
ch := tmp.str[posTo];
tmp.str[posTo] := 0X;
sr := c.font.StringWidth(tmp.str);
tmp.str[posTo] := ch;
IF sr > sl THEN
clip.Init(c);
(* transform selection rectangle to the actual coords*)
px0 := ed.x0 + x + sl;
px1 := ed.x0 + x + sr + c.dot;
liHei := (tmp.num - 1) * ed.lineHeight;
py0 := y + liHei - asc;
py1 := y + liHei + dsc;
IF clip.ShrinkToXY(px0, py0, px1, py1) THEN
c.DrawRect(px0, py0, px1, py1, Ports.fill, selBgCol);
c.DrawString(ed.x0 + x, y + liHei, selTextCol, tmp.str, c.font);
END;
(* restore old clip rectangle *)
clip.Close
END;
IF replaced = 0DX THEN
tmp.str[len] := 0DX
END
END
END;
ELSE
(* single line *)
(* text length before the selection *)
ch := tx[ed.from];
tx[ed.from] := 0X;
sl := c.font.StringWidth(tx);
tx[ed.from] := ch;
(* text length with the selection *)
ch := tx[ed.to];
tx[ed.to] := 0X;
sr := c.font.StringWidth(tx);
tx[ed.to] := ch;
IF sr > sl THEN
clip.Init(c);
(* transform selection rectangle to the actual coords*)
px0 := ed.x0 + x + sl;
px1 := ed.x0 + x + sr + c.dot;
py0 := y - asc;
py1 := y + dsc;
IF clip.ShrinkToXY(px0, py0, px1, py1) THEN
(* draw selection bar *)
c.DrawRect(px0, py0, px1, py1, Ports.fill, selBgCol);
(* and the text again, with the proper color *)
c.DrawString(ed.x0 + x, y, selTextCol, tx, c.font);
END;
(* restore old clip rectangle *)
clip.Close
END
END
END;
(* caret *)
IF c.front & (ed.from = ed.to) & ed.NeedCaret() THEN
IF ed.caretVisible THEN
ed.caretVisible := FALSE; (* hack, because it is changed in `DrawCaret()` *)
ed.DefineCaretLine;
ed.DrawCaret
END
ELSE
ed.caretVisible := FALSE;
ed.caretLastBlinkTime := 0
END;
IF vsb # NIL THEN
vsb.Draw(c, ed.x0 + ed.w - vsbSize, ed.y0, ed.h, ed.vsbPressed);
vsb.x0 := ed.x0 + ed.w - vsbSize;
vsb.y0 := ed.y0
END
END
END Restore;
PROCEDURE (ed: EditorCommon) BlinkCaret, NEW;
VAR
newTime: LONGINT;
BEGIN
ed.FixSelection;
IF ed.IsValid() & (ed.from = ed.to) & ed.ctl.front & ed.NeedCaret() THEN
newTime := Services.Ticks();
IF newTime > ed.caretLastBlinkTime + Dialog.caretPeriod THEN
ed.DrawCaret;
ed.caretLastBlinkTime := newTime
END
ELSE
ed.caretVisible := ed.NeedCaret();
ed.caretLastBlinkTime := 0
END
END BlinkCaret;
PROCEDURE (ed: EditorCommon) GetSelectedText (): EditorCommonText, NEW;
VAR
res: EditorCommonText;
f: INTEGER;
BEGIN
IF ed.textLen # 0 THEN
ed.FixSelection;
IF ed.from = ed.to THEN
NEW(res, ed.textLen + 1);
res^ := ed.text$
ELSE
NEW(res, ed.to - ed.from + 1);
f := 0; WHILE ed.from + f < ed.to DO
res[f] := ed.text[ed.from + f]; INC(f)
END;
res[f] := 0X
END
ELSE
NEW(res, 1);
res[0] := 0X
END;
RETURN res
END GetSelectedText;
PROCEDURE (ed: EditorCommon) RemoveSelectedText, NEW;
VAR
f, e: INTEGER;
BEGIN
IF ed.textLen # 0 THEN
ed.FixSelection;
f := ed.from; e := ed.to;
IF f # e THEN
WHILE ed.text[e] # 0X DO
ed.text[f] := ed.text[e];
INC(f); INC(e)
END;
ed.text[f] := 0X;
ed.to := ed.from;
ASSERT(f = LEN(ed.text$));
ed.textLen := f;
ed.pos := ed.from;
(* set update flag *)
INC(ed.changeCount)
END
END
END RemoveSelectedText;
(* return FALSE if there is no room *)
PROCEDURE (ed: EditorCommon) InsertChar (ch: CHAR): BOOLEAN, NEW;
VAR
nt: EditorCommonText;
slen, newlen, pos, f: INTEGER;
res: BOOLEAN;
BEGIN
res := TRUE;
IF (ch # 0X) THEN
slen := ed.textLen;
IF slen < ed.maxLen THEN
(* grow the buffer *)
IF slen + 1 >= LEN(ed.text) THEN
ASSERT(slen + 1 < 020000000H); (* just in case *)
newlen := MIN(LEN(ed.text) * 2, ed.maxLen + 1);
NEW(nt, newlen);
nt^ := ed.text$;
ed.text := nt
END;
pos := ed.FixSelectionPos();
(* insert the char *)
ed.text[slen + 1] := 0X;
f := slen; WHILE f > pos DO ed.text[f] := ed.text[f - 1]; DEC(f) END;
ed.text[pos] := ch;
INC(ed.textLen);
(* fix selection *)
IF ed.from # ed.to THEN
IF (pos >= ed.from) & (pos < ed.to) THEN INC(ed.to) END
END;
(* fix position *)
ed.pos := pos + 1;
(* set update flag *)
INC(ed.changeCount)
ELSE res := FALSE
END
END;
RETURN res
END InsertChar;
PROCEDURE (ed: EditorCommon) Edit (op: INTEGER; VAR v: Views.View; VAR clipboard: BOOLEAN), NEW;
VAR
rd: TextModels.Reader;
seltext: EditorCommonText;
insok: BOOLEAN;
BEGIN
IF clipboard THEN
CASE op OF
| Controllers.copy:
IF ~ed.password THEN
seltext := ed.GetSelectedText();
StdCmds.clipboardHook.Register(
TextViews.dir.New(TextModels.dir.NewFromString(seltext)), 0, 0, FALSE);
seltext := NIL
END
| Controllers.cut:
IF (ed.from # ed.to) & ~ed.password THEN
seltext := ed.GetSelectedText();
StdCmds.clipboardHook.Register(
TextViews.dir.New(TextModels.dir.NewFromString(seltext)), 0, 0, FALSE);
seltext := NIL;
ed.RemoveSelectedText
END
| Controllers.paste:
IF v # NIL THEN
WITH v: TextViews.View DO
ed.KeepText;
rd := v.ThisModel().NewReader(NIL); rd.SetPos(0);
ed.RemoveSelectedText; insok := TRUE;
REPEAT
rd.Read;
IF rd.view = NIL THEN
IF (rd.char = TextModels.line) OR (rd.char = TextModels.para) THEN
insok := ed.InsertChar(rd.char)
ELSIF rd.char = TAB THEN
insok := ed.InsertChar(" ");
insok := ed.InsertChar(" ");
insok := ed.InsertChar(" ");
ELSE
insok := ed.InsertChar(rd.char)
END
END
UNTIL insok & rd.eot;
IF ~insok THEN Dialog.Beep END
ELSE END
END
ELSE END
END
END Edit;
(* return position of the first char of the word *)
PROCEDURE (ed: EditorCommon) WordBack (pos: INTEGER): INTEGER, NEW;
VAR
cc: INTEGER;
BEGIN
pos := MAX(0, MIN(pos, ed.textLen));
IF pos > 0 THEN
IF ed.password THEN DEC(pos)
ELSE
cc := ClassifyChar(ed.text[pos - 1]);
DEC(pos);
WHILE (pos > 0) & (cc = ClassifyChar(ed.text[pos - 1])) DO
DEC(pos)
END
END
END;
RETURN pos
END WordBack;
(* return position after the last char of the word *)
PROCEDURE (ed: EditorCommon) WordForward (pos: INTEGER): INTEGER, NEW;
VAR
cc: INTEGER;
BEGIN
pos := MAX(0, MIN(pos, ed.textLen));
IF pos < ed.textLen THEN
IF ed.password THEN
INC(pos)
ELSE
cc := ClassifyChar(ed.text[pos]);
INC(pos);
WHILE (pos < ed.textLen) & (cc = ClassifyChar(ed.text[pos])) DO
INC(pos)
END
END
END;
RETURN pos
END WordForward;
PROCEDURE SelectAll*;
VAR ed: EditorCommon;
BEGIN
IF focusControl # NIL THEN
WITH focusControl: Field DO
ed := focusControl.ed;
IF (ed.from # 0) OR (ed.to # ed.textLen) THEN
INC(ed.changeCount);
ed.from := 0; ed.to := ed.textLen;
focusControl.Update
END
ELSE
END
END
END SelectAll;
PROCEDURE Cut*;
VAR ed: EditorCommon; seltext: EditorCommonText;
BEGIN
IF focusControl # NIL THEN
WITH focusControl: Field DO
ed := focusControl.ed;
IF (ed.from # ed.to) & ~ed.password THEN
seltext := ed.GetSelectedText();
StdCmds.clipboardHook.Register(
TextViews.dir.New(TextModels.dir.NewFromString(seltext)), 0, 0, FALSE);
seltext := NIL;
ed.RemoveSelectedText;
focusControl.Set(focusControl, ed.text);
focusControl.Update
END
ELSE
END
END
END Cut;
PROCEDURE Copy*;
VAR ed: EditorCommon; seltext: EditorCommonText;
BEGIN
IF focusControl # NIL THEN
WITH focusControl: Field DO
ed := focusControl.ed;
IF (ed.from # ed.to) & ~ed.password THEN
seltext := ed.GetSelectedText();
StdCmds.clipboardHook.Register(
TextViews.dir.New(TextModels.dir.NewFromString(seltext)), 0, 0, FALSE);
seltext := NIL
END
ELSE
END
END
END Copy;
PROCEDURE Paste*;
VAR ed: EditorCommon; type: Stores.TypeName; v: Views.View; w, h: INTEGER; s: BOOLEAN;
rd: TextModels.Reader; seltext: EditorCommonText; insok: BOOLEAN;
oldChangeCount: INTEGER;
BEGIN
(*
IF focusControl # NIL THEN
WITH focusControl: Field DO
ed := focusControl.ed;
WinClipboard.GetClipView(type, v, w, h, s);
IF v # NIL THEN
WITH v: TextViews.View DO
rd := v.ThisModel().NewReader(NIL); rd.SetPos(0);
oldChangeCount := ed.changeCount;
ed.RemoveSelectedText; insok := TRUE;
ed.KeepText;
REPEAT
rd.Read;
IF rd.view = NIL THEN
IF (rd.char = TextModels.line) OR (rd.char = TextModels.para) THEN
insok := ed.InsertChar(rd.char)
ELSIF rd.char = TAB THEN
insok := ed.InsertChar(" ");
insok := ed.InsertChar(" ");
insok := ed.InsertChar(" ");
ELSE
insok := ed.InsertChar(rd.char)
END
END
UNTIL insok & rd.eot;
IF ~insok THEN Dialog.Beep END;
IF ed.changeCount # oldChangeCount THEN
focusControl.Set(focusControl, ed.text)
END;
ed.RetainCaret;
focusControl.Update
ELSE END
END
END
END
*)
END Paste;
PROCEDURE Delete*;
VAR ed: EditorCommon;
BEGIN
IF focusControl # NIL THEN
WITH focusControl: Field DO
ed := focusControl.ed;
IF ed.from # ed.to THEN
ed.RemoveSelectedText;
focusControl.Set(focusControl, ed.text);
ed.RetainCaret;
focusControl.Update
END
ELSE
END
END
END Delete;
PROCEDURE SelectAllGuard* (VAR par: Dialog.Par);
VAR ops: Controllers.PollOpsMsg;
BEGIN
par.disabled := TRUE;
IF focusControl # NIL THEN
par.disabled := ~ (focusControl IS Field)
END;
END SelectAllGuard;
PROCEDURE CutGuard* (VAR par: Dialog.Par);
VAR ops: Controllers.PollOpsMsg;
BEGIN
par.disabled := TRUE;
IF (focusControl # NIL) & ~focusControl.readOnly & ~focusControl.disabled THEN
par.disabled := ~ (focusControl IS Field) & ~ focusControl(Field).password
END;
END CutGuard;
PROCEDURE CopyGuard* (VAR par: Dialog.Par);
VAR ops: Controllers.PollOpsMsg;
BEGIN
par.disabled := TRUE;
IF focusControl # NIL THEN
par.disabled := ~ (focusControl IS Field) & ~ focusControl(Field).password
END;
END CopyGuard;
PROCEDURE PasteGuard* (VAR par: Dialog.Par);
VAR ops: Controllers.PollOpsMsg;
BEGIN
par.disabled := TRUE;
IF (focusControl # NIL) & ~focusControl.readOnly & ~focusControl.disabled THEN
par.disabled := ~ (focusControl IS Field)
END;
END PasteGuard;
PROCEDURE (ed: EditorCommon) KeepTextToForwardStack, NEW;
VAR item: TextStackItem; i: INTEGER;
BEGIN
IF ed.st # NIL THEN
NEW(item);
NEW(item.text, LEN(ed.text));
item.pos := ed.pos;
item.from := ed.from;
item.to := ed.to;
FOR i := 0 TO LEN(ed.text$) - 1 DO
item.text[i] := ed.text[i]
END;
IF ed.st.forwardStack = NIL THEN
ed.st.forwardStack := item
ELSE
item.next := ed.st.forwardStack;
ed.st.forwardStack := item
END
END
END KeepTextToForwardStack;
PROCEDURE (ed: EditorCommon) TimeBack, NEW;
BEGIN
IF ed.st # NIL THEN
IF ed.st.textStack # NIL THEN
ed.KeepTextToForwardStack;
ed.text := ed.st.textStack.text;
ed.textLen := LEN(ed.text$);
INC(ed.changeCount);
ed.pos := ed.st.textStack.pos;
ed.from := ed.st.textStack.from;
ed.to := ed.st.textStack.to;
ed.st.textStack := ed.st.textStack.next
END
END
END TimeBack;
PROCEDURE (ed: EditorCommon) TimeForward, NEW;
BEGIN
IF ed.st # NIL THEN
IF ed.st.forwardStack # NIL THEN
ed.text := ed.st.forwardStack.text;
ed.textLen := LEN(ed.text$);
INC(ed.changeCount);
ed.pos := ed.st.forwardStack.pos;
ed.from := ed.st.forwardStack.from;
ed.to := ed.st.forwardStack.to;
ed.st.forwardStack := ed.st.forwardStack.next
END
END
END TimeForward;
PROCEDURE (ed: EditorCommon) KeyDown (ch: CHAR; modifiers: SET), NEW;
VAR
pos, npos, p1, p2: INTEGER; tx: EditorCommonText;
tmp: EditorCommonExpText; ok: BOOLEAN;
BEGIN
pos := ed.FixSelectionPos();
CASE ch OF
CHR(64977): (* Ctrl + Z *)
ed.TimeBack
| 019X: (* Ctrl + Y *)
ed.TimeForward
| CHR(64978): (* Ctrl + A *)
IF (ed.from # 0) OR (ed.to # ed.textLen) THEN
INC(ed.changeCount);
ed.from := 0; ed.to := ed.textLen;
END
| BACKSPACE: (* backspace *)
IF ed.from = ed.to THEN
IF pos > 0 THEN
ed.to := pos;
IF Controllers.modify IN modifiers THEN (* Ctrl *)
(* word *)
ed.from := ed.WordBack(pos)
ELSE ed.from := pos - 1
END
END
END;
ed.RemoveSelectedText
| DELETE: (* delete *)
IF ed.from = ed.to THEN
IF pos < ed.textLen THEN ed.to := pos + 1; ed.from := pos END
END;
ed.RemoveSelectedText
| DL: (* home *)
IF Controllers.extend IN modifiers THEN (* Shift *)
IF ed.from = ed.to THEN ed.to := pos END
ELSE ed.to := 0
END;
ed.pos := 0; ed.from := 0
| DR: (* end *)
IF ed.multiLine THEN
IF Controllers.extend IN modifiers THEN (* Shift *)
IF ed.from = ed.to THEN ed.from := ed.pos END;
tx := ed.GetVisText();
WHILE (tx[ed.pos] # ENTER) & (tx[ed.pos] # 0X) DO
INC(ed.pos)
END;
ed.to := ed.pos;
ELSE
tx := ed.GetVisText();
WHILE (tx[ed.pos] # ENTER) & (tx[ed.pos] # 0X) DO
INC(ed.pos)
END;
ed.from := ed.pos; ed.to := ed.pos
END;
ELSE
IF Controllers.extend IN modifiers THEN (* Shift *)
IF ed.from = ed.to THEN ed.from := pos END
ELSE
ed.from := ed.textLen
END;
ed.pos := ed.textLen; ed.to := ed.pos
END
| AU: (* arrow up *)
IF ed.multiLine THEN
IF ed.caretLine > 1 THEN
ed.GetStr(ed.pos, tmp, p1);
ed.pos := ed.pos - p1 - 1;
tx := ed.GetVisText();
ed.GetStr(ed.pos, tmp, p2);
IF p1 > LEN(tmp.str$) THEN
ed.pos := ed.pos
ELSE
ed.pos := ed.pos - LEN(tmp.str$) + p1 + 1
END;
ed.DefineCaretLine
END
END
| AD: (* arrow down *)
IF ed.multiLine THEN
tx := ed.GetVisText();
IF tx[0] # 0X THEN
ed.GetStr(ed.pos, tmp, p1);
IF tx[ed.pos + LEN(tmp.str$)] # 0X THEN
ed.pos := ed.pos - p1 + LEN(tmp.str$);
ed.GetStr(ed.pos, tmp, p2);
IF LEN(tmp.str$) > p1 THEN
ed.pos := ed.pos + p1
ELSE
ed.pos := ed.pos + LEN(tmp.str$) - 1
END;
END;
IF ed.pos > ed.textLen THEN ed.pos := ed.textLen END;
ed.DefineCaretLine
END
END
| AL: (* arrow left *)
IF (ed.textLen = 0) OR (pos = 0) THEN
IF ~(Controllers.extend IN modifiers) THEN
ed.from := 0; ed.to := 0
END;
ed.pos := 0
ELSE
IF ed.from = ed.to THEN ed.from := pos; ed.to := pos END;
(* calculate new cursor position *)
IF Controllers.modify IN modifiers THEN
npos := ed.WordBack(pos);
ELSE
npos := MAX(0, pos - 1)
END;
(* extend selection *)
IF Controllers.extend IN modifiers THEN
ed.from := npos
ELSE
IF ed.from # ed.to THEN
npos := ed.from
END;
ed.from := ed.to
END;
ed.pos := npos
END;
ed.DefineCaretLine
| AR: (* arrow right *)
IF (ed.textLen = 0) OR (pos >= ed.textLen) THEN
IF ~(Controllers.extend IN modifiers) THEN
ed.from := ed.textLen;
ed.to := ed.textLen
END;
ed.pos := ed.textLen
ELSE
IF ed.from = ed.to THEN
ed.from := pos;
ed.to := pos
END;
(* calculate new cursor position *)
IF Controllers.modify IN modifiers THEN
npos := ed.WordForward(pos)
ELSE
npos := MIN(ed.textLen, pos + 1)
END;
(* extend selection *)
IF Controllers.extend IN modifiers THEN
ed.to := npos
ELSE
IF (ed.from # ed.to) & (ed.to # MAX(INTEGER)) & (ed.to # 0) THEN
npos := ed.to
END;
ed.from := ed.to
END;
ed.pos := npos
END;
IF ed.pos > ed.textLen THEN ed.pos := ed.textLen END;
ed.DefineCaretLine
ELSE (* insert char *)
IF ch = TAB THEN
ed.KeepText;
ed.RemoveSelectedText;
ok := ed.InsertChar(" ");
ok := ed.InsertChar(" ");
ok := ed.InsertChar(" ");
IF ~ok THEN Dialog.Beep END;
ed.DefineCaretLine
ELSIF ed.multiLine & (ch = ENTER) THEN
tx := ed.GetVisText();
ed.KeepText;
ed.RemoveSelectedText;
npos := ed.pos;
WHILE (npos > 0) & (tx[npos] # ENTER) DO
DEC(npos)
END;
p1 := 0;
INC(npos);
WHILE tx[npos] = " " DO
INC(p1);
INC(npos);
END;
ok := ed.InsertChar(ch);
IF ok & (p1 > 0) THEN
FOR npos := 0 TO p1 - 1 DO
ok := ed.InsertChar(" ")
END
END;
IF ~ok THEN Dialog.Beep END;
ed.DefineCaretLine
ELSIF ((ch >= 20X) & (ch # 07FX)) THEN
ed.KeepText;
ed.RemoveSelectedText;
IF ~ed.InsertChar(ch) THEN Dialog.Beep END;
ed.DefineCaretLine
END
END
END KeyDown;
(* `x` is in global ctl coords, not in editor coords *)
PROCEDURE (ed: EditorCommon) CharAtXY (x, y: INTEGER): INTEGER, NEW;
VAR
sx, sw, pos, sl, sr: INTEGER;
tx: EditorCommonText;
str: EditorCommonExpText; lineNum, len: INTEGER; tmp: EditorCommonExpText;
BEGIN
IF ed.textLen # 0 THEN
(* convert `x` to editor coords *)
DEC(x, ed.x0);
sw := ed.CalcTextWidth() - ed.CalcCaretWidth();
sx := ed.CalcXPos();
DEC(sx, ed.xoffs);
IF ed.multiLine THEN
lineNum := 0; len := 0;
tmp := ed.textExp;
WHILE (tmp # NIL) & (lineNum < (y + ed.yoffs - ed.lineHeight DIV 2) DIV ed.lineHeight) DO
INC(lineNum);
INC(len, LEN(tmp.str$));
tmp := tmp.next
END;
IF tmp = NIL THEN
pos := ed.textLen
ELSE
sx := ed.ctl.CharIndex(sx, x, tmp.str, ed.ctl.font);
IF (sx > 0) & (tmp.str[sx - 1] = 0DX) THEN
pos := len + sx - 1
ELSE
pos := len + sx
END
END
ELSE
IF x <= 0 THEN pos := 0
ELSIF x >= sw THEN
pos := ed.textLen
ELSE
tx := ed.GetVisText();
pos := ed.ctl.CharIndex(sx, x, tx, ed.ctl.font);
sl := ed.ctl.CharPos(sx, pos, tx, ed.ctl.font);
sr := ed.ctl.CharPos(sx, pos + 1, tx, ed.ctl.font);
IF x >= sl + (sr - sl) DIV 2 THEN INC(pos) END;
pos := MAX(0, MIN(pos, ed.textLen))
END
END
ELSE pos := 0
END;
RETURN pos
END CharAtXY;
PROCEDURE (ed: EditorCommon) NormaliseYOffs, NEW;
VAR lineNum: INTEGER; tmp: EditorCommonExpText; textHeight: INTEGER;
BEGIN
IF ed.yoffs > 0 THEN
lineNum := 0;
tmp := ed.textExp;
WHILE tmp # NIL DO
INC(lineNum);
tmp := tmp.next
END;
textHeight := (lineNum - 1) * ed.lineHeight;
IF textHeight < ed.yoffs THEN
ed.yoffs := textHeight
END
ELSE
ed.yoffs := 0
END
END NormaliseYOffs;
PROCEDURE (ed: EditorCommon) WheelMove (x, y, op, nofLines: INTEGER; VAR done: BOOLEAN), NEW;
VAR asc, dsc, sw: INTEGER;
BEGIN
IF ed.IsValid() & (x >= ed.x0) & (y >= ed.y0)
& (x < ed.x0 + ed.w) & (y < ed.y0 + ed.h) THEN
done := TRUE;
IF op = Controllers.decLine THEN nofLines := -nofLines END;
ed.ctl.font.GetBounds(asc, dsc, sw);
IF ed.multiLine THEN
INC(ed.yoffs, (asc + dsc) * nofLines);
ed.NormaliseYOffs
ELSE
INC(ed.xoffs, sw * nofLines);
ed.NormaliseXOffs
END
END
END WheelMove;
PROCEDURE (l: EditorCommon) EdTrackVSBMouse (), NEW;
VAR
c: StdCFrames.Frame;
x, y, ox, oy: INTEGER;
isDown: BOOLEAN;
modifiers: SET;
opos: INTEGER;
BEGIN
c := l.ctl;
IF c.rider # NIL THEN
(* k8: this hack repaints other controls, so they could indicate focus loss *)
UpdateRoot(c);
l.vsbPressed := TRUE;
l.ctl.ForceUpdate;
opos := l.vsb.pos;
ox := MIN(INTEGER); oy := MIN(INTEGER);
REPEAT
c.Input(x, y, modifiers, isDown);
x := (x - l.x0) - l.vsb.x0;
y := (y - l.y0) - l.vsb.y0;
IF ox = MIN(INTEGER) THEN ox := x END;
IF oy = MIN(INTEGER) THEN oy := y END;
IF (ox # x) OR (oy # y) THEN
ox := x; oy := y;
l.vsb.SBMouseTrack(x, y);
IF opos # l.vsb.pos THEN
opos := l.vsb.pos;
l.yoffs := opos;
l.ctl.ForceUpdate
END
END
UNTIL ~isDown;
l.vsbPressed := FALSE;
l.ctl.ForceUpdate
END
END EdTrackVSBMouse;
PROCEDURE (ed: EditorCommon) MouseDown (x, y: INTEGER; buttons: SET), NEW;
VAR
isDown, triple: BOOLEAN; modifiers: SET; tstart: LONGINT;
movedto, sx, pos, cc, dot, ox, oy: INTEGER;
BEGIN
IF (ed.vsb # NIL) & (ed.vsb.length > 0) & (ed.x0 + ed.w - x < ed.vsb.Width()) THEN
IF ed.vsb.SBMouseDown((x - ed.x0) - ed.vsb.x0, (y - ed.y0) - ed.vsb.y0) THEN
ed.EdTrackVSBMouse
ELSE
ed.yoffs := ed.vsb.pos
(* the caller will repaint us *)
END
ELSIF (ed.textLen # 0) & ed.IsValid() &
(x >= ed.x0) & (y >= ed.y0) & (x < ed.x0 + ed.w) & (y < ed.y0 + ed.h) THEN
(*sw := ed.CalcTextWidth();*)
sx := ed.CalcXPos();
DEC(sx, ed.xoffs);
ed.pos := ed.CharAtXY(x, y);
IF ed.multiLine THEN ed.DefineCaretLine END;
ed.from := ed.pos; ed.to := ed.pos;
pos := ed.FixSelectionPos();
IF ~ed.noMouseSelect THEN
(* select word with double click *)
IF Controllers.doubleClick IN buttons THEN
ASSERT(pos <= ed.textLen);
IF (ed.textLen # 0) & ~ed.password THEN
IF pos = ed.textLen THEN
(* from the end of the text *)
ed.to := pos;
cc := ClassifyChar(ed.text[pos - 1]);
DEC(pos);
WHILE (pos > 0) & (cc = ClassifyChar(ed.text[pos - 1])) DO
DEC(pos)
END;
ed.from := pos; ed.pos := pos
ELSE (* inside a word or a blank span *)
ed.from := pos; cc := ClassifyChar(ed.text[pos]);
WHILE (ed.from > 0) & (cc = ClassifyChar(ed.text[ed.from - 1])) DO
DEC(ed.from)
END;
WHILE (pos < ed.textLen) & (cc = ClassifyChar(ed.text[pos])) DO
INC(pos)
END;
ed.to := pos; ed.pos := pos
END
END;
ed.lastDblTime := Services.Ticks()
ELSIF ed.ctl.rider # NIL THEN
(*Views.ValidateRoot(Views.RootOf(ed.ctl));*)
(* k8: this hack repaints other controls, so they could indicate focus loss *)
UpdateRoot(ed.ctl);
ed.pos := pos;
dot := ed.ctl.dot;
pos := ed.pos; ox := x - 1; oy := y - 1;
tstart := Services.Ticks();
triple := (tstart - ed.lastDblTime <= doubleclickTimeout);
IF triple THEN
(* select all *)
ed.from := 0; ed.to := ed.textLen
END;
ed.lastDblTime := 0;
REPEAT
ed.ctl.Input(x, y, modifiers, isDown);
IF (x # ox) OR (y # oy) THEN
ox := x; oy := y;
movedto := ed.CharAtXY(x, y);
IF (movedto = pos) OR (Services.Ticks() - tstart < 150) THEN
IF ~triple THEN ed.from := 0; ed.to := 0 END
ELSE
IF movedto > pos THEN
ed.from := pos;
ed.to := movedto;
IF ed.to > ed.textLen THEN ed.to := ed.textLen END
ELSE
ed.from := movedto;
IF ed.from < 0 THEN ed.from := 0 END;
ed.to := pos
END
END;
ed.pos := movedto;
ed.RetainCaret;
ed.ctl.ForceUpdate
END
UNTIL (ed.ctl.rider = NIL) OR ~isDown;
END
END
END
END MouseDown;
(** **************** ListCommon (engine) **************** **)
PROCEDURE (l: ListCommon) Init, NEW;
BEGIN
l.ctl := NIL;
l.items := NIL;
l.pos := 0;
l.yoffs := 0; l.x0 := 0; l.y0 := 0; l.w := 0; l.h := 0;
l.lastSearchTime := 0;
l.lastSearchPos := 0;
l.outMargin.SetZero;
l.maxWidth := 0; l.totalHeight := 0;
l.vsb := NIL;
l.sorted := FALSE;
END Init;
PROCEDURE (l: ListCommon) Idx (i: INTEGER): INTEGER, NEW;
BEGIN
IF l.sorted & (l.map # NIL) THEN
RETURN l.map[i]
ELSE
RETURN i
END
END Idx;
PROCEDURE (l: ListCommon) IdxBack (i: INTEGER): INTEGER, NEW;
BEGIN
IF l.sorted & (l.unmap # NIL) THEN
RETURN l.unmap[i]
ELSE
RETURN i
END
END IdxBack;
PROCEDURE (l: ListCommon) GetSelectionBox (): StdCFrames.SelectionBox, NEW;
VAR
sb: StdCFrames.SelectionBox;
BEGIN
IF (l.ctl # NIL) & (l.ctl IS StdCFrames.SelectionBox) THEN sb := l.ctl(StdCFrames.SelectionBox)
ELSE sb := NIL
END;
RETURN sb
END GetSelectionBox;
PROCEDURE (l: ListCommon) GetLength (): INTEGER, NEW;
VAR
len: INTEGER;
BEGIN
IF l.items # NIL THEN len := LEN(l.items) ELSE len := 0 END;
RETURN len
END GetLength;
PROCEDURE (l: ListCommon) RecalcCachedSizes, NEW;
VAR asc, dsc, sw, f, col: INTEGER; tmp: TextChain;
BEGIN
IF (l.ctl # NIL) & (l.ctl.font # NIL) THEN
l.maxWidth := 0;
FOR f := 0 TO l.GetLength() - 1 DO
IF l.items[f].tabbed # NIL THEN
sw := 0;
col := 0;
tmp := l.items[f].tabbed;
WHILE tmp # NIL DO
sw := sw + l.widths[col];
IF tmp.next # NIL THEN
sw := sw + listTabSize * Ports.point
END;
tmp := tmp.next;
INC(col)
END
ELSE
sw := l.ctl.font.StringWidth(l.items[f].text);
END;
IF sw > l.maxWidth THEN
l.maxWidth := sw
END
END;
l.ctl.font.GetBounds(asc, dsc, sw);
l.totalHeight := (asc + dsc) * l.GetLength()
ELSE
l.maxWidth := 0;
l.totalHeight := 0;
END
END RecalcCachedSizes;
PROCEDURE (l: ListCommon) SetupCtl (ctl: StdCFrames.Frame), NEW;
BEGIN
IF l.ctl # ctl THEN
l.ctl := ctl;
IF ctl # NIL THEN l.RecalcCachedSizes END
END
END SetupCtl;
PROCEDURE (l: ListCommon) Setup (ctl: StdCFrames.Frame; x0, y0, w, h: INTEGER), NEW;
BEGIN
l.x0 := x0; l.y0 := y0; l.w := w; l.h := h;
l.SetupCtl(ctl)
END Setup;
PROCEDURE (l: ListCommon) IsValid (): BOOLEAN, NEW;
BEGIN
RETURN (l.ctl # NIL) & (l.w > 0) & (l.h > 0)
END IsValid;
PROCEDURE (l: ListCommon) QuickSort, NEW;
PROCEDURE LessThan (ai, bi: INTEGER): BOOLEAN;
VAR res, equal: BOOLEAN; i: INTEGER; a, b: ListCommonItem;
BEGIN
a := l.items[ai];
b := l.items[bi];
res := FALSE;
equal := TRUE;
i := 0;
WHILE equal & (i < LEN(a.text$)) & (i < LEN(b.text$)) DO
IF ORD(CAP(a.text[i])) = ORD(CAP(b.text[i])) THEN
(* pass *)
ELSIF ORD(CAP(a.text[i])) < ORD(CAP(b.text[i])) THEN
res := TRUE;
equal := FALSE
ELSE
equal := FALSE
END;
INC(i)
END;
RETURN res
END LessThan;
PROCEDURE Sort(L, R: INTEGER);
VAR i, j: INTEGER; w, x: INTEGER;
BEGIN
i := L; j := R;
x := l.map[(L+R) DIV 2];
REPEAT
WHILE LessThan(l.map[i], x) DO i := i + 1; END;
WHILE LessThan(x, l.map[j]) DO j := j - 1; END;
IF i <= j THEN
w := l.map[i];
l.map[i] := l.map[j];
l.map[j] := w;
i := i + 1;
j := j -1;
END;
UNTIL i > j;
IF L < j THEN Sort(L, j); END;
IF i < R THEN Sort(i, R); END
END Sort;
BEGIN
Sort(0, LEN(l.map) - 1);
END QuickSort;
PROCEDURE (l: ListCommon) UpdateFromCtl (): BOOLEAN, NEW;
VAR
f, oldlen, newlen, tmp, n: INTEGER;
s: Dialog.String; res, needup, markup, mark, newSorted: BOOLEAN;
sb: StdCFrames.SelectionBox; t: LONGINT;
BEGIN
res := FALSE;
IF l.ctl # NIL THEN
sb := l.GetSelectionBox();
newSorted := GetSortedInfo(l.ctl);
newlen := GetListLength(l.ctl);
oldlen := l.GetLength();
needup := (oldlen # newlen) OR (newSorted # l.sorted);
l.sorted := newSorted;
markup := FALSE;
IF ~needup THEN
f := 0; WHILE ~needup & (f < newlen) DO
ASSERT(f < oldlen);
GetItemText(l.ctl, f, s);
Dialog.MapString(s, s);
needup := (l.items[f].text$ # s$);
IF ~needup & ~markup & (sb # NIL) THEN
sb.Get(sb, f, mark);
markup := (l.items[f].marked # mark)
END;
INC(f)
END
END;
IF needup OR (newlen # oldlen) THEN
IF newlen # oldlen THEN
IF newlen # 0 THEN NEW(l.items, newlen) ELSE l.items := NIL END
END;
FOR f := 0 TO newlen - 1 DO
GetItemText(l.ctl, f, s);
Dialog.MapString(s, s);
NEW(l.items[f].text, LEN(s$) + 1);
l.items[f].text^ := s$;
IF sb # NIL THEN sb.Get(sb, f, mark)
ELSE mark := FALSE
END;
l.items[f].marked := mark
END;
IF l.sorted & (newlen # 0) THEN
IF (l.map = NIL) OR (LEN(l.map) # LEN(l.items)) THEN
NEW(l.map, LEN(l.items));
NEW(l.unmap, LEN(l.items))
END;
FOR f := 0 TO newlen - 1 DO
l.map[f] := f
END;
l.QuickSort;
FOR n := 0 TO newlen - 1 DO
l.unmap[l.map[n]] := n
END
END;
l.pos := GetCursorIndex(l.ctl);
l.pos := MAX(-1, MIN(l.pos, newlen - 1));
l.RecalcCachedSizes;
res := TRUE
ELSE
IF markup THEN
ASSERT(sb # NIL);
FOR f := 0 TO oldlen - 1 DO
sb.Get(sb, f, mark);
l.items[f].marked := mark
END
END;
f := GetCursorIndex(l.ctl);
IF f # l.pos THEN
l.pos := MAX(0, MIN(f, newlen - 1));
res := TRUE
END
END
END;
RETURN res
END UpdateFromCtl;
PROCEDURE (l: ListCommon) GetItemHeight (): INTEGER, NEW;
VAR asc, dsc, sw: INTEGER;
BEGIN
IF (l.GetLength() # 0) & (l.ctl # NIL) THEN
l.ctl.font.GetBounds(asc, dsc, sw);
sw := asc + dsc
ELSE sw := 1
END;
RETURN sw
END GetItemHeight;
PROCEDURE (l: ListCommon) GetItemsPerPage (): INTEGER, NEW;
VAR ih, res: INTEGER;
BEGIN
res := 1;
IF (l.GetLength() # 0) & l.IsValid() THEN
ih := l.GetItemHeight();
res := l.h DIV ih;
IF res = 0 THEN res := 1 END
END;
RETURN res
END GetItemsPerPage;
PROCEDURE (l: ListCommon) GetFirstPageItem (): INTEGER, NEW;
VAR y, ih, res: INTEGER;
BEGIN
res := 0;
IF (l.GetLength() # 0) & l.IsValid() THEN
y := 0 - l.yoffs;
ih := l.GetItemHeight();
res := l.yoffs DIV ih;
INC(y, res * ih);
IF y < 0 THEN INC(res) END;
res := MAX(0, MIN(l.GetLength() - 1, res))
END;
RETURN res
END GetFirstPageItem;
PROCEDURE (l: ListCommon) GetItemYOfs (): INTEGER, NEW;
VAR asc, dsc, sw: INTEGER;
BEGIN
IF (l.GetLength() # 0) & l.IsValid() THEN
l.ctl.font.GetBounds(asc, dsc, sw);
sw := l.GetItemHeight();
IF asc + dsc > sw THEN sw := (sw - asc - dsc) DIV 2
ELSE sw := 0
END;
INC(sw, asc)
ELSE sw := 0
END;
RETURN sw
END GetItemYOfs;
PROCEDURE (l: ListCommon) NormaliseYOffs, NEW;
VAR ih: INTEGER;
BEGIN
IF (l.GetLength() # 0) & l.IsValid() THEN
IF (l.pos < 0) OR (l.totalHeight <= l.h) THEN
l.yoffs := 0
ELSE
ih := l.GetItemHeight();
IF l.h < ih * 2 THEN
l.yoffs := ih * l.pos
ELSE
IF l.hsb # NIL THEN
l.yoffs := MIN(l.yoffs, l.totalHeight - (l.h - l.hsb.Width()))
ELSE
l.yoffs := MIN(l.yoffs, l.totalHeight - l.h)
END;
l.yoffs := MAX(l.yoffs, 0)
END
END
ELSE l.yoffs := 0
END
END NormaliseYOffs;
PROCEDURE (l: ListCommon) MakeCursorVisibleWorker (doCenter: BOOLEAN), NEW;
VAR y, ih, pos, hsbSize: INTEGER;
BEGIN
IF (l.GetLength() # 0) & l.IsValid() & (l.pos > -1) THEN
IF l.totalHeight = 0 THEN l.RecalcCachedSizes END;
pos := l.IdxBack(l.pos);
IF (pos <= 0) OR (l.totalHeight <= l.h) THEN
l.yoffs := 0
ELSE
ih := l.GetItemHeight();
y := ih * pos;
hsbSize := 0;
IF l.hsb # NIL THEN
hsbSize := l.hsb.Width()
END;
IF l.h < ih * 2 THEN
l.yoffs := y
ELSE
DEC(y, l.yoffs);
(* now check if the cursor is visible *)
IF y < 0 THEN
INC(l.yoffs, y);
IF doCenter & (l.h > ih * 4) THEN DEC(l.yoffs, ((l.h - hsbSize) - ih) DIV 2) END;
ELSIF y + ih > (l.h - hsbSize) THEN
INC(l.yoffs, y + ih - (l.h - hsbSize));
IF doCenter & (l.h > ih * 4) THEN INC(l.yoffs, ((l.h - hsbSize) - ih) DIV 2) END
END
END;
l.NormaliseYOffs;
END
ELSE
l.yoffs := 0
END
END MakeCursorVisibleWorker;
(* should be called from owner's `Restore()` *)
PROCEDURE (l: ListCommon) MakeCursorVisible, NEW;
BEGIN l.MakeCursorVisibleWorker(FALSE)
END MakeCursorVisible;
(* should be called from owner's `Restore()` *)
PROCEDURE (l: ListCommon) MakeCursorVisibleCentered, NEW;
BEGIN l.MakeCursorVisibleWorker(TRUE)
END MakeCursorVisibleCentered;
PROCEDURE (l: ListCommon) ResetCharSearch, NEW;
BEGIN
l.lastSearchPos := 0
END ResetCharSearch;
PROCEDURE (l: ListCommon) CharSearch (ch: CHAR), NEW;
VAR ctime: LONGINT; curpos, idx, spos, found: INTEGER;
BEGIN
IF l.GetLength() > 0 THEN
ch := Strings.Upper(ch);
ctime := Services.Ticks();
IF ctime - l.lastSearchTime > 600 THEN l.lastSearchPos := 0 END;
l.lastSearchTime := ctime;
curpos := l.pos;
spos := l.lastSearchPos;
IF spos = 0 THEN INC(curpos) END;
idx := l.GetLength(); found := -1;
WHILE (idx > 0) & (found < 0) DO
DEC(idx);
IF curpos >= l.GetLength() THEN curpos := 0 END;
IF (spos = 0) OR StrStartsWithCI(l.items[curpos].text, l.items[l.pos].text, spos) THEN
IF Strings.Upper(l.items[curpos].text[spos]) = ch THEN
found := curpos;
INC(l.lastSearchPos)
END
END;
INC(curpos)
END;
IF (found # -1) & (found # l.pos) THEN l.pos := found END
END
END CharSearch;
PROCEDURE (l: ListCommon) GetBackgroundColor (): Ports.Color, NEW;
VAR bkcol: Ports.Color;
BEGIN
IF l.ctl.disabled OR l.ctl.readOnly THEN
bkcol := skin.backListDisabled
ELSIF l.ctl.mark THEN
bkcol := skin.backList
ELSE
bkcol := skin.backListBlured
END;
RETURN bkcol
END GetBackgroundColor;
PROCEDURE (l: ListCommon) DefineColors (ff: INTEGER; OUT col, bcol: Ports.Color; OUT mark: BOOLEAN), NEW;
VAR c: StdCFrames.Frame; f: INTEGER;
BEGIN
c := l.ctl;
f := l.Idx(ff);
mark := FALSE;
IF c.disabled OR c.readOnly THEN (* Disabled *)
IF ~c.readOnly & (f = l.pos) THEN
IF l.items[f].marked THEN (* Selected + Cursored *)
bcol := skin.backSelListCursorDisabled;
col := skin.textSelListCursorDisabled;
ELSE (* Cursored *)
bcol := skin.backListCursorDisabled;
col := skin.textListCursorDisabled;
END
ELSE
IF l.items[f].marked THEN (* Selected *)
bcol := skin.backSelListDisabled;
col := skin.textSelListDisabled;
ELSE
bcol := skin.backListDisabled;
col := skin.textListDisabled;
END
END
ELSIF c.mark THEN
IF ~c.readOnly & (f = l.pos) THEN
IF l.items[f].marked THEN (* Selected + Cursored *)
bcol := skin.backSelListCursor;
col := skin.textSelListCursor;
ELSE (* Cursored *)
IF l.GetSelectionBox() # NIL THEN
bcol := skin.backList;
col := skin.textList;
ELSE
bcol := skin.backListCursor;
col := skin.textListCursor;
END
END;
mark := l.pos >= 0
ELSE
IF l.items[f].marked THEN (* Selected *)
bcol := skin.backSelList;
col := skin.textSelList;
ELSE
bcol := skin.backList;
col := skin.textList;
END
END
ELSE (* Blured *)
IF ~c.readOnly & (f = l.pos) THEN
IF l.items[f].marked THEN (* Selected + Cursored *)
bcol := skin.backSelListCursorBlured;
col := skin.textSelListCursorBlured;
ELSE (* Cursored *)
bcol := skin.backListCursorBlured;
col := skin.textListCursorBlured;
END
ELSE
IF l.items[f].marked THEN (* Selected *)
bcol := skin.backSelListBlured;
col := skin.textSelListBlured;
ELSE
bcol := skin.backListBlured;
col := skin.textListBlured;
END
END
END;
END DefineColors;
PROCEDURE (l: ListCommon) Restore, NEW;
VAR
c: StdCFrames.Frame;
bkcol, col, bcol: Ports.Color;
ih, iofs, len, y, f, xoffs, asc, dsc, sw, i, pos, column, colWidth: INTEGER;
vsb: VScrollBar; vsbSize: INTEGER;
hsb: HScrollBar; hsbSize: INTEGER;
item, tmp: TextChain;
clip: ClipRect; marked, tabbed: BOOLEAN;
BEGIN
IF l.IsValid() THEN
IF l.totalHeight = 0 THEN
l.RecalcCachedSizes
END;
c := l.ctl;
(* check if we need a scrollbar, and prepare it *)
IF l.totalHeight > l.h THEN
IF l.vsb = NIL THEN
NEW(vsb);
vsb.Init;
l.vsb := vsb
ELSE
vsb := l.vsb
END;
vsb.min := 0;
vsb.max := l.totalHeight - l.h;
vsb.contentSize := l.totalHeight;
vsb.pos := l.yoffs;
vsb.pageSize := l.h;
vsb.arrowStep := l.GetItemHeight();
vsb.length := l.h;
IF ~vsb.CanFit() THEN
vsb := NIL
ELSE
vsbSize := MAX(0, vsb.Width());
vsb.length := l.h - vsb.Width();
IF (vsbSize = 0) OR ((vsbSize + 4 * Ports.point) >= l.w) THEN
vsb := NIL
END
END
ELSE
vsb := NIL
END;
IF vsb = NIL THEN vsbSize := 0; l.vsb := NIL END;
bkcol := l.GetBackgroundColor();
c.DrawRect(l.x0 - l.outMargin.l * c.dot, l.y0 - l.outMargin.t * c.dot,
l.x0 + l.w + l.outMargin.r * c.dot, l.y0 + l.h + l.outMargin.b * c.dot,
Ports.fill, bkcol);
(* analyze list for tabs *)
len := l.GetLength();
f := 0; tabbed := FALSE;
WHILE f < len DO
i := 0; column := 0;
l.items[f].tabbed := NIL;
REPEAT
Strings.Find(l.items[f].text, TAB, i, pos);
IF pos >= 1 THEN
tabbed := TRUE;
NEW(item);
NEW(item.text, pos - i + 1);
Strings.Extract(l.items[f].text, i, pos - i, item.text);
IF l.items[f].tabbed = NIL THEN
l.items[f].tabbed := item
ELSE
tmp := l.items[f].tabbed;
WHILE tmp.next # NIL DO
tmp := tmp.next
END;
tmp.next := item
END;
colWidth := c.font.StringWidth(item.text);
IF l.widths[column] < colWidth THEN l.widths[column] := colWidth END;
INC(column)
ELSIF l.items[f].tabbed # NIL THEN
pos := LEN(l.items[f].text$);
NEW(item);
NEW(item.text, pos - i + 1);
Strings.Extract(l.items[f].text, i, pos - i, item.text);
IF l.items[f].tabbed = NIL THEN
l.items[f].tabbed := item
ELSE
tmp := l.items[f].tabbed;
WHILE tmp.next # NIL DO
tmp := tmp.next
END;
tmp.next := item
END;
colWidth := c.font.StringWidth(item.text);
IF l.widths[column] < colWidth THEN l.widths[column] := colWidth END;
INC(column)
END;
i := pos + 1
UNTIL ( pos = -1 ) OR ( pos >= LEN(l.items[f].text$) );
INC(f)
END;
IF tabbed THEN
l.RecalcCachedSizes;
END;
(* check if we need a horisontal scrollbar, and prepare it *)
IF (l.maxWidth > (l.w - vsbSize)) & (l.h > l.GetItemHeight() * 2) THEN
IF l.hsb = NIL THEN
NEW(hsb);
hsb.Init;
l.hsb := hsb
ELSE
hsb := l.hsb
END;
hsb.min := 0;
hsb.max := (l.maxWidth - l.w + vsbSize + l.x0 + Ports.mm);
hsb.contentSize := l.maxWidth;
hsb.pos := l.xoffs;
hsb.pageSize := l.w;
hsb.arrowStep := Ports.mm;
hsb.length := l.w;
IF ~hsb.CanFit() THEN
hsb := NIL
ELSE
hsbSize := MAX(0, hsb.Width());
hsb.length := l.w;
IF vsb # NIL THEN
DEC(hsb.length, vsbSize);
DEC(vsb.length, hsbSize)
END;
IF (hsbSize = 0) OR ((hsbSize + 4 * Ports.point) >= l.h) THEN
hsbSize := 0; hsb := NIL
END
END;
IF vsb # NIL THEN
INC(vsb.max, hsbSize);
INC(hsb.max, vsbSize);
END;
ELSE
l.hsb := NIL; hsbSize := 0; hsb := NIL;
END;
clip.Init(l.ctl);
IF clip.ShrinkToWH(l.x0, l.y0, l.w, l.h) THEN
y := 0 - l.yoffs;
ih := l.GetItemHeight();
iofs := l.GetItemYOfs();
f := l.yoffs DIV ih;
len := l.GetLength();
IF f < len THEN
IF (hsb # NIL) THEN
xoffs := - l.xoffs
END;
INC(y, f * ih);
IF 2 * ih > l.h THEN
IF (f >= 0) & (l.pos # -1) THEN f := l.pos END;
l.DefineColors(f, col, bcol, marked);
IF bcol # bkcol THEN
c.DrawRect(l.x0, l.y0, l.x0 + l.w, l.y0 + l.h, Ports.fill, bcol)
END;
IF marked THEN
c.MarkRect(l.x0 + 2*c.dot, l.y0 + 2*c.dot, l.x0 + l.w - 2*c.dot, l.y0 + l.h - 2*c.dot, c.dot, Ports.dim50, Ports.show)
END;
c.font.GetBounds(asc, dsc, sw);
iofs := (l.h - asc - dsc) DIV 2 - c.dot;
IF (l.items[f].tabbed = NIL) THEN
c.DrawString(l.x0 + xoffs + 2*c.dot, l.y0 + asc + iofs, col, l.items[f].text, c.font)
ELSE
tmp := l.items[f].tabbed;
column := 0;
pos := 0;
WHILE tmp # NIL DO
c.DrawString(l.x0 + xoffs + pos + 2*c.dot, l.y0 + asc + iofs, col, tmp.text, c.font);
tmp := tmp.next;
INC(column);
pos := pos + l.widths[column-1] + listTabSize * Ports.point;
END
END
ELSE
WHILE (f < len) & (y < l.h) DO
l.DefineColors(f, col, bcol, marked);
IF bcol # bkcol THEN
c.DrawRect(l.x0, l.y0 + y, l.x0 + l.w, l.y0 + y + ih, Ports.fill, bcol)
END;
IF marked THEN
c.MarkRect(l.x0 + c.dot, l.y0 + y + c.dot, l.x0 + l.w - c.dot, l.y0 + y + ih - c.dot, c.dot, Ports.dim50, Ports.show)
END;
IF l.items[l.Idx(f)].tabbed = NIL THEN
c.DrawString(l.x0 + xoffs+ 2*c.dot, l.y0 + y + iofs, col, l.items[l.Idx(f)].text, c.font)
ELSE
tmp := l.items[l.Idx(f)].tabbed;
column := 0;
pos := 0;
WHILE tmp # NIL DO
c.DrawString(l.x0 + xoffs + pos+ 2*c.dot, l.y0 + y + iofs, col, tmp.text, c.font);
tmp := tmp.next;
INC(column);
pos := pos + l.widths[column-1] + listTabSize * c.dot
END
END;
INC(y, ih);
INC(f)
END
END
END
END;
IF vsb # NIL THEN
vsb.Draw(c, l.x0 + l.w - vsbSize, l.y0, l.h - hsbSize, l.vsbPressed);
vsb.x0 := l.x0 + l.w - vsbSize;
vsb.y0 := l.y0
END;
IF hsb # NIL THEN
hsb.Draw(c, l.x0, l.y0 + l.h - hsbSize, l.w - vsbSize, l.hsbPressed);
hsb.x0 := l.x0;
hsb.y0 := l.y0 + l.h - hsbSize
END;
IF (hsbSize > 0) & (vsbSize > 0) THEN
c.DrawRect(l.x0 + l.w - vsbSize, l.y0 + l.h - hsbSize, l.w + 2*c.dot, l.h+ 2*c.dot, Ports.fill, skin.backScrollbar)
END;
clip.Close
END
END Restore;
PROCEDURE (l: ListCommon) KeyDown (ch: CHAR; modifiers: SET), NEW;
VAR
f, pos, i: INTEGER; mark, doCenter: BOOLEAN; sb: StdCFrames.SelectionBox;
BEGIN
IF l.GetLength() > 0 THEN
doCenter := FALSE;
sb := l.GetSelectionBox();
CASE ch OF
| DL: (* home *)
IF l.unmap # NIL THEN
pos := l.unmap[l.pos];
IF (Controllers.extend IN modifiers) & (sb # NIL) THEN (* Shift *)
IF pos > 0 THEN
mark := ~l.items[pos].marked;
FOR f := 0 TO pos DO l.items[f].marked := mark END;
IF mark THEN sb.Incl(sb, 0, pos) ELSE sb.Excl(sb, 0, pos) END
END
END;
l.pos := l.Idx(0)
ELSE
IF (Controllers.extend IN modifiers) & (sb # NIL) THEN (* Shift *)
IF l.pos > 0 THEN
mark := ~l.items[l.pos].marked;
FOR f := 0 TO l.pos DO l.items[f].marked := mark END;
IF mark THEN sb.Incl(sb, 0, l.pos) ELSE sb.Excl(sb, 0, l.pos) END
END
END;
l.pos := 0
END
| DR: (* end *)
IF l.unmap # NIL THEN
pos := l.unmap[l.pos];
IF (Controllers.extend IN modifiers) & (sb # NIL) THEN (* Shift *)
IF pos < l.GetLength() - 1 THEN
mark := ~l.items[pos].marked;
FOR f := pos TO l.GetLength() - 1 DO l.items[f].marked := mark END;
IF mark THEN
sb.Incl(sb, pos, l.GetLength() - 1)
ELSE
sb.Excl(sb, pos, l.GetLength() - 1)
END
END
END;
l.pos := MAX(0, l.Idx(l.GetLength() - 1))
ELSE
IF (Controllers.extend IN modifiers) & (sb # NIL) THEN (* Shift *)
IF l.pos < l.GetLength() - 1 THEN
mark := ~l.items[l.pos].marked;
FOR f := l.pos TO l.GetLength() - 1 DO l.items[f].marked := mark END;
IF mark THEN
sb.Incl(sb, l.pos, l.GetLength() - 1)
ELSE
sb.Excl(sb, l.pos, l.GetLength() - 1)
END
END
END;
l.pos := MAX(0, l.GetLength() - 1)
END
| AU: (* arrow up *)
IF l.unmap # NIL THEN
pos := l.unmap[l.pos]
ELSE
pos := l.pos
END;
IF pos > 0 THEN
IF (Controllers.extend IN modifiers) & (sb # NIL) THEN (* Shift *)
IF l.items[l.Idx(pos - 1)].marked THEN
l.items[l.Idx(pos)].marked := FALSE;
sb.Excl(sb, l.Idx(pos), l.Idx(pos))
ELSE
l.items[l.Idx(pos - 1)].marked := TRUE;
sb.Incl(sb, l.Idx(pos - 1), l.Idx(pos-1))
END
ELSIF sb # NIL THEN
FOR i := 0 TO l.GetLength() - 1 DO
IF l.items[i].marked & (i # l.Idx(pos - 1)) THEN
sb.Excl(sb, i, i);
l.items[i].marked := FALSE
END
END;
i := l.Idx(pos - 1);
IF ~l.items[i].marked THEN
sb.Incl(sb, i, i);
l.items[i].marked := TRUE
END;
END;
DEC(pos);
l.pos := l.Idx(pos)
END
| AD: (* arrow down *)
IF l.unmap # NIL THEN
pos := l.unmap[l.pos]
ELSE
pos := l.pos
END;
IF pos < l.GetLength() - 1 THEN
IF (Controllers.extend IN modifiers) & (sb # NIL) THEN (* Shift *)
IF l.items[l.Idx(pos + 1)].marked THEN
l.items[l.Idx(pos)].marked := FALSE;
sb.Excl(sb, l.Idx(pos), l.Idx(pos))
ELSE
l.items[l.Idx(pos + 1)].marked := TRUE;
sb.Incl(sb, l.Idx(pos + 1), l.Idx(pos + 1))
END
ELSIF sb # NIL THEN
FOR i := 0 TO l.GetLength() - 1 DO
IF l.items[i].marked & (i # l.Idx(pos + 1)) THEN
sb.Excl(sb, i, i);
l.items[i].marked := FALSE
END
END;
i := l.Idx(pos + 1);
IF ~l.items[i].marked THEN
sb.Incl(sb, i, i);
l.items[i].marked := TRUE
END;
END;
INC(pos);
l.pos := l.Idx(pos)
END
| AL: (* arrow left *)
IF l.xoffs > 8 * Ports.point THEN
l.xoffs := l.xoffs - 8 * Ports.point
ELSE
l.xoffs := 0
END
| AR: (* arrow right *)
l.xoffs := l.xoffs + 8 * Ports.point;
IF l.xoffs > l.maxWidth THEN (* does not work somehow, TO CHECK *)
l.xoffs := l.maxWidth
END
| PU: (* page up *)
IF l.pos > l.GetFirstPageItem() THEN
l.pos := l.GetFirstPageItem()
ELSE
DEC(l.pos, l.GetItemsPerPage())
END;
l.pos := MAX(0, MIN(l.GetLength() - 1, l.pos))
| PD: (* page down *)
IF l.pos < l.GetFirstPageItem() + l.GetItemsPerPage() - 1 THEN
l.pos := l.GetFirstPageItem() + l.GetItemsPerPage() - 1
ELSE
INC(l.pos, l.GetItemsPerPage())
END;
l.pos := MAX(0, MIN(l.GetLength() - 1, l.pos))
| 20X: (* toggle mark *)
IF sb # NIL THEN
mark := ~l.items[l.pos].marked;
l.items[l.pos].marked := mark;
IF mark THEN sb.Incl(sb, l.pos, l.pos) ELSE sb.Excl(sb, l.pos, l.pos) END;
IF l.pos < l.GetLength() - 1 THEN INC(l.pos) END
ELSE l.CharSearch(ch); doCenter := TRUE
END
ELSE
IF (ch >= 20X) & (ch # 7FX) THEN l.CharSearch(ch); doCenter := TRUE END
END;
l.MakeCursorVisibleWorker(doCenter)
END
END KeyDown;
PROCEDURE (l: ListCommon) WheelMove (x, y: INTEGER; op, nofLines: INTEGER; VAR done: BOOLEAN), NEW;
VAR
asc, dsc, sw: INTEGER;
BEGIN
IF l.IsValid() & (x >= l.x0) & (y >= l.y0) & (x < l.x0 + l.w) & (y < l.y0 + l.h) THEN
done := TRUE; (* eat it! *)
IF op = Controllers.decLine THEN nofLines := -nofLines END;
l.ctl.font.GetBounds(asc, dsc, sw);
INC(l.yoffs, (asc + dsc) * nofLines);
l.NormaliseYOffs
END
END WheelMove;
PROCEDURE (l: ListCommon) LstTrackVSBMouse (), NEW;
VAR c: StdCFrames.Frame;
x, y, ox, oy, opos: INTEGER; isDown: BOOLEAN; modifiers: SET;
BEGIN
c := l.ctl;
IF c.rider # NIL THEN
(* k8: this hack repaints other controls, so they could indicate focus loss *)
l.vsbPressed := TRUE;
UpdateRoot(c);
l.ctl.ForceUpdate;
opos := l.vsb.pos;
ox := MIN(INTEGER); oy := MIN(INTEGER);
REPEAT
c.Input(x, y, modifiers, isDown);
x := (x - l.x0) - l.vsb.x0;
y := (y - l.y0) - l.vsb.y0;
IF ox = MIN(INTEGER) THEN ox := x END;
IF oy = MIN(INTEGER) THEN oy := y END;
IF (ox # x) OR (oy # y) THEN
ox := x; oy := y;
l.vsb.SBMouseTrack(x, y);
IF opos # l.vsb.pos THEN
opos := l.vsb.pos;
l.yoffs := opos;
l.ctl.ForceUpdate
END
END
UNTIL ~isDown;
l.vsbPressed := FALSE;
l.ctl.ForceUpdate
END
END LstTrackVSBMouse;
PROCEDURE (l: ListCommon) LstTrackHSBMouse (), NEW;
VAR c: StdCFrames.Frame; x, y, ox, oy, opos: INTEGER; isDown: BOOLEAN; modifiers: SET;
BEGIN
c := l.ctl;
IF c.rider # NIL THEN
(* k8: this hack repaints other controls, so they could indicate focus loss *)
l.hsbPressed := TRUE;
UpdateRoot(c);
l.ctl.ForceUpdate;
opos := l.hsb.pos;
ox := MIN(INTEGER); oy := MIN(INTEGER);
REPEAT
c.Input(x, y, modifiers, isDown);
x := (x - l.x0) - l.hsb.x0;
y := (y - l.y0) - l.hsb.y0;
IF ox = MIN(INTEGER) THEN ox := x END;
IF oy = MIN(INTEGER) THEN oy := y END;
IF (ox # x) OR (oy # y) THEN
ox := x; oy := y;
l.hsb.SBMouseTrack(x, y);
IF opos # l.hsb.pos THEN
opos := l.hsb.pos;
l.xoffs := opos;
l.ctl.ForceUpdate
END
END
UNTIL ~isDown;
l.hsbPressed := FALSE;
l.ctl.ForceUpdate
END
END LstTrackHSBMouse;
PROCEDURE (l: ListCommon) MouseDown (x, y: INTEGER; buttons: SET), NEW;
VAR id, ff, idx, asc, pos, dsc, sw, f, i, initPos: INTEGER;
mark, makeCursorVisible, isDown, changed, selected: BOOLEAN;
sb: StdCFrames.SelectionBox; modifiers: SET;
BEGIN
makeCursorVisible := TRUE;
IF (l.GetLength() # 0) & l.IsValid() & (x >= l.x0) & (y >= l.y0) & (x < l.x0+l.w) & (y < l.y0+l.h) THEN
IF (l.vsb # NIL) & (l.vsb.length > 0) & (l.x0+l.w - x < l.vsb.Width()) THEN
makeCursorVisible := FALSE;
IF l.vsb.SBMouseDown((x - l.x0) - l.vsb.x0, (y - l.y0) - l.vsb.y0) THEN
l.LstTrackVSBMouse
ELSE
l.yoffs := l.vsb.pos
(* the caller will repaint us *)
END
ELSIF (l.hsb # NIL) & (l.hsb.length > 0) & (l.y0 + l.h - y < l.hsb.Width()) THEN
makeCursorVisible := FALSE;
IF l.hsb.SBMouseDown((x - l.x0) - l.hsb.x0, (y - l.y0) - l.hsb.y0) THEN
l.LstTrackHSBMouse
ELSE
l.xoffs := l.hsb.pos
(* the caller will repaint us *)
END
ELSIF ~ l.ctl.readOnly THEN
changed := FALSE;
selected := FALSE;
initPos := -777;
REPEAT
l.ctl.Input(x, y, modifiers, isDown);
DEC(y, l.y0);
l.ctl.font.GetBounds(asc, dsc, sw);
id := (y + l.yoffs) DIV (asc + dsc) ;
id := MAX(0, MIN(id, l.GetLength() - 1) );
idx := l.Idx(id);
IF initPos = -777 THEN initPos := id END;
sb := l.GetSelectionBox();
IF (sb # NIL) & ~selected THEN
IF id # initPos THEN
pos := initPos;
IF id < pos THEN
REPEAT
IF ~l.items[l.Idx(pos - 1)].marked THEN
l.items[l.Idx(pos - 1)].marked := TRUE;
sb.Incl(sb, l.Idx(pos - 1), l.Idx(pos-1));
END;
DEC(pos)
UNTIL pos = id
ELSIF id > pos THEN
REPEAT
IF ~l.items[l.Idx(pos + 1)].marked THEN
l.items[l.Idx(pos + 1)].marked := TRUE;
sb.Incl(sb, l.Idx(pos + 1), l.Idx(pos + 1));
END;
INC(pos)
UNTIL pos = id;
END;
changed := TRUE;
ELSIF idx # l.pos THEN
IF (Controllers.extend IN buttons) THEN (* Shift *)
pos := l.IdxBack(l.pos);
IF id < pos THEN
REPEAT
IF ~l.items[l.Idx(pos - 1)].marked THEN
l.items[l.Idx(pos - 1)].marked := TRUE;
sb.Incl(sb, l.Idx(pos - 1), l.Idx(pos-1));
END;
DEC(pos)
UNTIL pos = id
ELSIF id > pos THEN
REPEAT
IF ~l.items[l.Idx(pos + 1)].marked THEN
l.items[l.Idx(pos + 1)].marked := TRUE;
sb.Incl(sb, l.Idx(pos + 1), l.Idx(pos + 1));
END;
INC(pos)
UNTIL pos = id;
END;
changed := TRUE;
selected := TRUE
ELSIF Controllers.modify IN buttons THEN (* Ctrl *)
IF ~l.items[idx].marked THEN
sb.Incl(sb, idx, idx);
l.items[idx].marked := TRUE;
changed := TRUE;
selected := TRUE
ELSE
sb.Excl(sb, idx, idx);
l.items[idx].marked := FALSE;
changed := TRUE;
selected := TRUE
END
ELSE
FOR i := 0 TO l.GetLength() - 1 DO
IF l.items[i].marked & (i # idx) THEN
sb.Excl(sb, i, i);
l.items[i].marked := FALSE;
changed := TRUE;
END
END;
IF ~ l.items[idx].marked THEN
sb.Incl(sb, idx, idx);
l.items[idx].marked := TRUE;
changed := TRUE;
END
END
ELSE
IF Controllers.modify IN buttons THEN (* Ctrl *)
IF ~l.items[idx].marked THEN
sb.Incl(sb, idx, idx);
l.items[idx].marked := TRUE;
changed := TRUE;
selected := TRUE
ELSE
sb.Excl(sb, idx, idx);
l.items[idx].marked := FALSE;
changed := TRUE;
selected := TRUE
END
ELSE
FOR i := 0 TO l.GetLength() - 1 DO
IF l.items[i].marked & (i # idx) THEN
sb.Excl(sb, i, i);
l.items[i].marked := FALSE;
changed := TRUE;
END
END;
IF ~ l.items[idx].marked THEN
sb.Incl(sb, idx, idx);
l.items[idx].marked := TRUE;
changed := TRUE
END
END
END
END;
IF l.pos # idx THEN
l.pos := idx;
changed := TRUE;
END;
IF changed THEN
l.ctl.ForceUpdate;
changed := FALSE;
END;
UNTIL ~isDown;
END
END;
IF makeCursorVisible THEN l.MakeCursorVisible END
END MouseDown;
(** **************** PopupCommon for ComboBox **************** **)
PROCEDURE (p: PopupCommon) DrawFrame (c: Views.Frame; w, h: INTEGER), NEW, ABSTRACT;
(* margins are in pixels *)
PROCEDURE (p: PopupCommon) GetFrameMargins (OUT l, t, r, b: INTEGER), NEW, ABSTRACT;
PROCEDURE (p: PopupCommon) GetBackground (VAR col: Ports.Color);
BEGIN
col := skin.backList
END GetBackground;
PROCEDURE (p: PopupCommon) GetItemHeight (): INTEGER, NEW;
VAR
asc, dsc, sw: INTEGER;
BEGIN
ASSERT(p.owner # NIL);
p.owner.font.GetBounds(asc, dsc, sw);
RETURN asc + dsc + 2 * p.owner.dot
END GetItemHeight;
PROCEDURE (p: PopupCommon) ForceUpdate, NEW;
BEGIN
Views.Update(p, Views.keepFrames)
(*
IF (p.owner # NIL) & (p.owner.view # NIL) THEN
Views.Update(p.owner.view, Views.keepFrames)
END
*)
END ForceUpdate;
PROCEDURE (p: PopupCommon) GetItemCount (): INTEGER, NEW;
BEGIN
RETURN p.lst.GetLength()
END GetItemCount;
PROCEDURE (p: PopupCommon) GetCurrent (): INTEGER, NEW;
BEGIN
RETURN p.lst.pos
END GetCurrent;
PROCEDURE (p: PopupCommon) GetItemsPerPage (): INTEGER, NEW;
VAR w, h, ih, res: INTEGER;
BEGIN
res := 1;
IF (p.owner # NIL) & (p.context # NIL) THEN
p.context.GetSize(w, h);
IF h > 0 THEN
ih := p.GetItemHeight();
res := MAX(1, h DIV ih)
END
END;
RETURN res
END GetItemsPerPage;
PROCEDURE^ (p: PopupCommon) MakeCursorVisible (doCenter: BOOLEAN), NEW;
PROCEDURE (p: PopupCommon) NormaliseYOfs, NEW;
VAR
w, h, ih, ph: INTEGER;
BEGIN
IF p.starty = MIN(INTEGER) THEN p.MakeCursorVisible(TRUE) END;
p.starty := MAX(0, p.starty);
IF (p.owner # NIL) & (p.context # NIL) THEN
p.context.GetSize(w, h);
ih := p.GetItemHeight();
ph := ih * p.GetItemCount();
IF ph <= h THEN p.starty := 0
ELSE p.starty := MIN(p.starty, h - ph)
END
END
END NormaliseYOfs;
PROCEDURE (p: PopupCommon) MakeCursorVisible (doCenter: BOOLEAN), NEW;
VAR
w, h, cy, ih, len, curidx: INTEGER;
BEGIN
IF p.starty = MIN(INTEGER) THEN p.starty := 0; doCenter := TRUE END;
IF (p.owner # NIL) & (p.context # NIL) THEN
curidx := p.GetCurrent();
len := p.GetItemCount();
IF (curidx >= 0) & (curidx < len) THEN
p.context.GetSize(w, h);
ih := p.GetItemHeight();
cy := ih * curidx;
DEC(cy, p.starty);
IF cy < 0 THEN
INC(p.starty, cy);
IF doCenter THEN DEC(p.starty, (h - ih) DIV 2) END
ELSIF cy + p.GetItemHeight() > h THEN
INC(p.starty, cy + p.GetItemHeight() - h);
IF doCenter THEN INC(p.starty, (h - ih) DIV 2) END
END
END;
p.NormaliseYOfs
ELSE p.starty := 0
END
END MakeCursorVisible;
PROCEDURE (p: PopupCommon) SetCurrent (idx: INTEGER; doCenter: BOOLEAN), NEW;
BEGIN
IF (idx >= 0) & (idx < p.GetItemCount()) & (idx # p.lst.pos) THEN
p.lst.pos := p.lst.Idx(idx);
p.MakeCursorVisible(doCenter);
p.ForceUpdate
END
END SetCurrent;
PROCEDURE (p: PopupCommon) Restore (c: Views.Frame; left, top, right, bottom: INTEGER);
VAR fnt: Fonts.Font; col: Ports.Color; l: ListCommon; tmp: TextChain;
w, h, ih, iofs, asc, dsc, sw,
f, x, y, curidx, len, ml, mt, mr, mb, pos, column: INTEGER;
BEGIN
p.GetFrameMargins(ml, mt, mr, mb);
IF p.starty = MIN(INTEGER)THEN p.MakeCursorVisible(TRUE) END;
p.dotsize := c.dot;
p.NormaliseYOfs;
p.context.GetSize(w, h);
p.GetBackground(col);
c.DrawRect(left, top, right, bottom, Ports.fill, col);
fnt := p.owner.font;
len := p.GetItemCount();
curidx := p.GetCurrent();
ih := p.GetItemHeight();
fnt.GetBounds(asc, dsc, sw);
iofs := asc + (ih - asc - dsc) DIV 2;
x := (ml + 2) * c.dot;
y := 0 - p.starty + mt * c.dot;
f := 0; WHILE (f < len) & (y <= bottom) DO
IF y + ih >= top THEN
IF p.lst.Idx(f) = curidx THEN
c.DrawRect(c.dot, y, w - c.dot, y + ih, Ports.fill, skin.backSelList);
col := skin.textSelList
ELSIF f = p.hoveridx THEN
c.DrawRect(c.dot, y, w - c.dot, y + ih, Ports.fill, skin.backHover);
col := skin.textHover
ELSE
col := skin.text
END;
l := p.lst;
IF l.items[l.Idx(f)].tabbed = NIL THEN
c.DrawString(x, y + iofs, col, p.lst.items[p.lst.Idx(f)].text^, fnt)
ELSE
tmp := l.items[l.Idx(f)].tabbed;
column := 0;
pos := 0;
WHILE tmp # NIL DO
c.DrawString(x + pos, y + iofs, col, tmp.text, fnt);
tmp := tmp.next;
INC(column);
pos := pos + l.widths[column-1] + listTabSize * c.dot
END
END
END;
INC(y, ih);
INC(f)
END;
p.DrawFrame(c, w, h)
END Restore;
PROCEDURE (p: PopupCommon) ClosePopup, NEW;
VAR
op: StdDocuments.OverlayProposal;
BEGIN
IF ~p.hideCalled THEN
p.hideCalled := TRUE;
op.op := StdDocuments.hide; p.context.Consider(op)
END
END ClosePopup;
PROCEDURE (p: PopupCommon) CopyFromModelView- (source: Views.View; model: Models.Model);
BEGIN
WITH source: PopupCommon DO
p.owner := source.owner;
p.lst := source.lst;
p.starty := source.starty;
p.hoveridx := -1
ELSE END
END CopyFromModelView;
PROCEDURE (p: PopupCommon) Internalize- (VAR rd: Stores.Reader);
BEGIN
END Internalize;
PROCEDURE (p: PopupCommon) Externalize- (VAR wr: Stores.Writer);
BEGIN
END Externalize;
PROCEDURE (p: PopupCommon) WheelMove (x, y, op, nofLines: INTEGER; VAR done: BOOLEAN), NEW;
VAR
w, h, ih: INTEGER;
BEGIN
IF (p.owner # NIL) & (p.context # NIL) THEN
p.context.GetSize(w, h);
IF (x >= 0) & (y >= 0) & (x < w) & (y < h) THEN
done := TRUE; (* eat it! *)
IF op = Controllers.decLine THEN nofLines := -nofLines END;
ih := p.GetItemHeight();
INC(p.starty, nofLines * ih);
p.NormaliseYOfs;
p.ForceUpdate
END
END
END WheelMove;
PROCEDURE (p: PopupCommon) ItemAtY (y: INTEGER): INTEGER, NEW;
BEGIN
RETURN (y + p.starty + 1 * p.dotsize) DIV p.GetItemHeight()
END ItemAtY;
PROCEDURE (p: PopupCommon) MouseDown (x, y: INTEGER; buttons: SET), NEW;
BEGIN
IF (p.owner # NIL) & (p.context # NIL) THEN
p.SetCurrent(p.ItemAtY(y), FALSE);
p.ClosePopup
END
END MouseDown;
PROCEDURE (p: PopupCommon) MouseMoved (x, y: INTEGER; buttons: SET), NEW;
VAR
hidx: INTEGER;
BEGIN
IF (p.owner # NIL) & (p.context # NIL) THEN
hidx := p.ItemAtY(y);
IF hidx # p.hoveridx THEN
p.hoveridx := hidx;
p.ForceUpdate
END
END
END MouseMoved;
PROCEDURE (p: PopupCommon) KeyDown (ch: CHAR; mods: SET): BOOLEAN, NEW;
VAR
idx, len: INTEGER;
res: BOOLEAN;
BEGIN
res := TRUE;
CASE ch OF
| PU: (* page up *)
len := p.GetItemCount();
IF len > 0 THEN
idx := MAX(0, p.GetCurrent()-p.GetItemsPerPage());
p.SetCurrent(idx, FALSE)
END
| PD: (* page down *)
len := p.GetItemCount();
IF len > 0 THEN
idx := MIN(len - 1, p.GetCurrent()+p.GetItemsPerPage());
p.SetCurrent(idx, FALSE)
END
| DL: (* home *)
p.SetCurrent(0, FALSE)
| DR: (* end *)
p.SetCurrent(p.GetItemCount() - 1, FALSE)
| AU: (* arrow up *)
p.SetCurrent(p.GetCurrent() - 1, FALSE)
| AD: (* arrow down *)
p.SetCurrent(p.GetCurrent() + 1, FALSE)
| ENTER:
p.SetCurrent(p.GetCurrent(), FALSE);
p.ClosePopup
| ESC, PL, PR:
p.ClosePopup
ELSE res := FALSE
END;
RETURN res
END KeyDown;
PROCEDURE (p: PopupCommon) HandleCtrlMsg* (c_: Views.Frame; VAR msg: Views.CtrlMessage;
VAR focus: Views.View);
BEGIN
WITH msg: Controllers.TrackMsg DO
p.MouseDown(msg.x, msg.y, msg.modifiers)
|msg: Controllers.WheelMsg DO
p.WheelMove(msg.x, msg.y, msg.op, msg.nofLines, msg.done)
| msg: Controllers.EditMsg DO
IF msg.modifiers * {0..7} = {} THEN
IF p.KeyDown(msg.char, msg.modifiers) THEN END
ELSIF Controllers.pick IN msg.modifiers THEN
IF msg.char = AU THEN p.ClosePopup END
END
| msg: Controllers.PollCursorMsg DO
p.MouseMoved(msg.x, msg.y, msg.modifiers)
ELSE END
END HandleCtrlMsg;
PROCEDURE (p: PopupCommon) HandleViewMsg- (c_: Views.Frame; VAR msg: Views.Message);
VAR
c: StdCFrames.Frame;
BEGIN
WITH msg: StdDocuments.RemoveOverlayMsg DO
c := p.owner;
IF c # NIL THEN c.PopupClosed(p) END
(* | msg: Documents.RemoveOverlayMsg DO
c := p.owner;
IF c # NIL THEN c.PopupClosed(p) END *)
ELSE END
END HandleViewMsg;
PROCEDURE (p: PopupCommon) SetupOwner (owner: StdCFrames.Frame; lst: ListCommon), NEW;
BEGIN
p.owner := owner;
p.lst := lst;
p.dotsize := 0;
p.starty := MIN(INTEGER);
p.hoveridx := -1;
p.hideCalled := FALSE
END SetupOwner;
PROCEDURE (l: ListCommon) NewPopup(): PopupCommon, NEW;
VAR
p: Popup;
BEGIN
NEW(p);
RETURN p
END NewPopup;
PROCEDURE (l: ListCommon) ShowPopup (yofs: INTEGER): PopupCommon, NEW;
VAR
popup: PopupCommon; doc: Views.View; root: Views.Frame;
w, h, len, f, px, py, pw, ph, ml, mt, mr, mb, fw, fh: INTEGER;
str: ARRAY 256 OF CHAR;
BEGIN
popup := NIL;
IF (l.ctl # NIL) & ~l.ctl.readOnly & ~l.ctl.disabled & (l.ctl.rider # NIL) THEN
len := l.GetLength();
IF len > 0 THEN
popup := l.NewPopup();
popup.SetupOwner(l.ctl, l);
root := Views.UltimateRootOf(l.ctl); ASSERT(root # NIL);
ASSERT(root.view # NIL); doc := root.view;
popup.GetFrameMargins(ml, mt, mr, mb);
fw := MAX(0, (ml + mr) * l.ctl.dot);
fh := MAX(0, (mt + mb) * l.ctl.dot);
l.ctl.view.context.GetSize(w, h);
FOR f := 0 TO len - 1 DO
w := MAX(w, l.ctl.font.StringWidth(l.items[f].text) + fw)
END;
px := l.ctl.gx - root.gx; py := l.ctl.gy - root.gy + yofs;
pw := MIN(w, root.r - root.l);
ph := popup.GetItemHeight() * len + fh;
ph := MIN(ph, root.b - root.t);
px := MAX(0, MIN(px, root.r-pw));
py := MAX(0, MIN(py, root.b-ph));
WITH doc: StdDocuments.Document DO
StdDocuments.InsertOverlaid(popup, popup, doc, px, py, pw, ph, NIL)
| doc: Documents.Document DO
(*
Documents.InsertOverlay(doc, popup, px, py, pw, ph);
Views.Update(root.view, Views.keepFrames);
*)
ELSE HALT(20)
END
END
END;
RETURN popup
END ShowPopup;
PROCEDURE GetStorage (v: Views.View): Storage;
VAR st: Storage;
BEGIN
st := storages;
WHILE (st # NIL) & (st.view # v) DO st := st.next END;
RETURN st
END GetStorage;
PROCEDURE AddStorage (new: Storage);
VAR st: Storage;
BEGIN
IF storages = NIL THEN storages := new ELSE
st := storages;
WHILE (st.next # NIL) & (st.view # new.view) DO
st := st.next
END;
IF st.next = NIL THEN
st.next := new
END
END
END AddStorage;
(* our skin system implies the correct color of dialog background *)
PROCEDURE SetupDialogBackground* (c: StdCFrames.Frame);
VAR root: Views.RootFrame;
BEGIN
(*
IF Ports.dialogBackground # skin.back THEN
Ports.dialogBackground := skin.back;
(*root := Views.UltimateRootOf(c);*)
root := Views.RootOf(c);
IF root # NIL THEN
Views.UpdateRoot(root, root.l, root.t, root.r, root.b, Views.keepFrames)
END
END
*)
END SetupDialogBackground;
PROCEDURE (p: Popup) DrawFrame (c: Views.Frame; w, h: INTEGER);
VAR
x0, y0, x1, y1: INTEGER;
BEGIN
IF (w > 2 * c.dot) & (h > 2 * c.dot) THEN
x1 := w - c.dot;
y1 := h - c.dot;
x0 := 0; y0 := 0;
IF (x1 - x0 > 2 * c.dot) & (y1 - y0 > 2 * c.dot) THEN
c.DrawLine(x0, y0, x1, y0, 0, skin.frameDark);
c.DrawLine(x0, y0, x0, y1, 0, skin.frameDark);
c.DrawLine(x0, y1, x1 + c.dot, y1, 0, skin.frameDark);
c.DrawLine(x1, y0, x1, y1, 0, skin.frameDark);
c.DrawLine(x0 + 1 * c.dot, y1 - 1 * c.dot, x1, y1 - 1 * c.dot, 0, skin.frameShadow);
c.DrawLine(x1 - 1 * c.dot, y0 + 1 * c.dot, x1 - 1 * c.dot, y1 - 1 * c.dot, 0, skin.frameShadow)
END
END
END DrawFrame;
(* margins are in pixels *)
PROCEDURE (p: Popup) GetFrameMargins (OUT l, t, r, b: INTEGER);
BEGIN
l := 2; t := 1;
r := 2; b := 2
END GetFrameMargins;
PROCEDURE DrawArrowUpDown (c: StdCFrames.Frame; x, y: INTEGER; invert: BOOLEAN);
VAR path: ARRAY 3 OF Ports.Point; pathCount: INTEGER; pathColor: Ports.Color;
PROCEDURE AddPoint (px, py: INTEGER);
BEGIN
IF invert THEN py := 6 - py END;
path[pathCount].x := x + px * Ports.point;
path[pathCount].y := y + py * Ports.point;
INC(pathCount)
END AddPoint;
BEGIN
IF c.disabled THEN
pathColor := skin.arrowDisabled
ELSIF c.readOnly THEN
pathColor := skin.arrowReadOnly
ELSE
pathColor := skin.arrow
END;
pathCount := 0;
AddPoint(0, 6); AddPoint(3, 0); AddPoint(6, 6);
c.DrawPath(path, pathCount, Ports.fill, pathColor, Ports.closedPoly);
END DrawArrowUpDown;
PROCEDURE DrawArrowUp (c: StdCFrames.Frame; x, y: INTEGER);
BEGIN
DrawArrowUpDown(c, x, y, FALSE)
END DrawArrowUp;
PROCEDURE DrawArrowDown (c: StdCFrames.Frame; x, y: INTEGER);
BEGIN
DrawArrowUpDown(c, x, y, TRUE)
END DrawArrowDown;
PROCEDURE DrawArrowLeftRight (c: StdCFrames.Frame; x, y: INTEGER; invert: BOOLEAN);
VAR path: ARRAY 3 OF Ports.Point; pathCount: INTEGER; pathColor: Ports.Color;
PROCEDURE AddPoint (px, py: INTEGER);
BEGIN
IF invert THEN px := 6 - px END;
path[pathCount].x := x + px * Ports.point;
path[pathCount].y := y + py * Ports.point;
INC(pathCount)
END AddPoint;
BEGIN
IF c.disabled THEN
pathColor := skin.arrowDisabled
ELSIF c.readOnly THEN
pathColor := skin.arrowReadOnly
ELSE
pathColor := skin.arrow
END;
pathCount := 0;
AddPoint(0, 0); AddPoint(6, 3); AddPoint(0, 6);
c.DrawPath(path, pathCount, Ports.fill, pathColor, Ports.closedPoly)
END DrawArrowLeftRight;
PROCEDURE DrawArrowLeft (c: StdCFrames.Frame; x, y: INTEGER);
BEGIN
DrawArrowLeftRight(c, x, y, TRUE)
END DrawArrowLeft;
PROCEDURE DrawArrowRight (c: StdCFrames.Frame; x, y: INTEGER);
BEGIN
DrawArrowLeftRight(c, x, y, FALSE)
END DrawArrowRight;
(* processing '&' and "&&"; return amp position and width *)
PROCEDURE CleanAmp (VAR s: ARRAY OF CHAR; font: Fonts.Font; OUT awdt: INTEGER): INTEGER;
VAR
tmp: ARRAY 2 OF CHAR;
i, j: INTEGER;
apos: INTEGER;
BEGIN
apos := -1; awdt := -1; i := 0; j := 0;
WHILE s[i] # 0X DO
IF (s[i] = '&') & (s[i + 1] # 0X) THEN
INC(i);
IF (apos < 0) & (s[i] # '&') THEN apos := j END
END;
s[j] := s[i]; INC(i); INC(j)
END;
s[j] := 0X;
IF apos >= 0 THEN
ASSERT(apos < LEN(s$));
i := apos;
tmp[0] := s[i]; tmp[1] := 0X;
s[apos] := 0X; apos := font.StringWidth(s); s[i] := tmp[0];
awdt := font.StringWidth(tmp)
END;
awdt := MAX(0, awdt);
RETURN apos
END CleanAmp;
PROCEDURE DrawAmpString (c: StdCFrames.Frame; x, y: INTEGER; col: Ports.Color; IN s: ARRAY OF CHAR;
apos, awdt: INTEGER);
BEGIN
IF (LEN(s) > 0) & (s[0] # 0X) THEN
c.DrawString(x, y, col, s, c.font);
IF awdt > c.dot THEN
INC(y, 1 * c.dot);
c.DrawRect(x + apos, y, x + apos + awdt, y + c.dot, Ports.fill, col)
END
END
END DrawAmpString;
PROCEDURE DummyRestore (c: StdCFrames.Frame; lbl: Dialog.String; l_, t_, r_, b_: INTEGER);
VAR w, h, mx, my, dw, dh, asc, dsc: INTEGER;
BEGIN
c.view.context.GetSize(w, h);
mx := w DIV 2; my := h DIV 2;
dw := StdCFrames.defaultFont.StringWidth(lbl) DIV 2;
StdCFrames.defaultFont.GetBounds(asc, dsc, dh); dh := (asc + dsc) DIV 2;
c.DrawRect(0, 0, w, h, Ports.fill, Ports.grey50);
c.DrawRect(0, 0, w, h, 1, Ports.black);
c.DrawString(mx - dw, my + dh, Ports.white, lbl, StdCFrames.defaultFont)
END DummyRestore;
(** **************** Caption **************** **)
PROCEDURE (ed: Caption) PrepareExplodedCaption (width: INTEGER), NEW;
VAR
lastSpacePosInText, lastSpacePosInLine, textPos, linePos: INTEGER;
str: SingleLine; tx: ARRAY 2048 OF CHAR;
PROCEDURE AddStringToList (str: SingleLine);
VAR n: INTEGER; tmp: EditorCommonExpText;
BEGIN
(* add string to list *)
IF ed.textExp = NIL THEN
NEW(ed.textExp);
ed.textExp.era := ed.changeCount;
ed.textExp.str := str;
ed.textExp.num := 1;
ELSE
n := 2;
tmp := ed.textExp;
WHILE tmp.next # NIL DO
INC(n);
tmp := tmp.next;
END;
NEW(tmp.next);
tmp.next.str := str;
tmp.next.num := n;
END
END AddStringToList;
BEGIN
IF (ed.textExp # NIL) & (ed.textExp.era = ed.changeCount) THEN RETURN END;
ed.textExp := NIL;
Dialog.MapString(ed.label, tx);
textPos := 0; linePos := 0;
WHILE tx[textPos] # 0X DO
IF linePos = 0 THEN
NEW(str);
lastSpacePosInLine := 0;
lastSpacePosInText := 0;
END;
IF tx[textPos] = " " THEN
lastSpacePosInText := textPos;
lastSpacePosInLine := linePos
END;
IF tx[textPos] = ENTER THEN
str[linePos] := 0X;
AddStringToList(str);
linePos := 0
ELSE
str[linePos] := tx[textPos];
str[linePos+1] := 0X;
INC(linePos);
IF ed.font.StringWidth(str) > width THEN
IF lastSpacePosInLine # 0 THEN
textPos := lastSpacePosInText + 1;
str[lastSpacePosInLine+1] := 0X;
AddStringToList(str);
linePos := 0
ELSE
INC(textPos)
END;
ELSE
INC(textPos)
END;
END;
END;
IF linePos > 0 THEN
str[linePos] := 0X;
AddStringToList(str)
END
END PrepareExplodedCaption;
PROCEDURE (c: Caption) Restore (l_, t_, r_, b_: INTEGER);
VAR
x, w, h, col, asc, dsc, sw, apos, awdt, len, n: INTEGER;
s: Dialog.String; i: INTEGER; find: BOOLEAN;
str: ARRAY 1024 OF CHAR;
tmp: EditorCommonExpText;
BEGIN
SetupDialogBackground(c);
c.view.context.GetSize(w, h);
IF c.disabled THEN col := skin.textDisabled
ELSE col := skin.text
END;
c.font.GetBounds(asc, dsc, sw);
Dialog.MapString(c.label, s);
IF c.font.StringWidth(s) > w THEN
c.PrepareExplodedCaption(w);
tmp := c.textExp;
n := asc - dsc;
tmp := c.textExp;
WHILE tmp # NIL DO
IF tmp.str$ # "" THEN
len := LEN(tmp.str$) - 1;
IF tmp.str[len] = 0DX THEN
tmp.str[len] := 0X;
IF c.left THEN x := c.dot
ELSIF c.right THEN x := w - c.dot - c.font.StringWidth(tmp.str)
ELSE x := (w - c.font.StringWidth(tmp.str)) DIV 2
END;
c.DrawString(x, n, col, tmp.str, c.font);
tmp.str[len] := 0DX
ELSE
IF c.left THEN x := c.dot
ELSIF c.right THEN x := w - c.dot - c.font.StringWidth(tmp.str)
ELSE x := (w - c.font.StringWidth(tmp.str)) DIV 2
END;
c.DrawString(x, n, col, tmp.str, c.font)
END
END;
INC(n, dsc + asc);
tmp := tmp.next
END
ELSE
apos := CleanAmp(s, c.font, awdt);
IF c.left THEN x := c.dot
ELSIF c.right THEN x := w - c.dot - c.font.StringWidth(s)
ELSE x := (w - c.font.StringWidth(s)) DIV 2
END;
DrawAmpString(c, x, (h - dsc + asc) DIV 2, col, s, apos, awdt)
END
END Restore;
PROCEDURE (c: Caption) DblClickOk (x, y: INTEGER): BOOLEAN;
BEGIN
RETURN FALSE
END DblClickOk;
PROCEDURE (f: Caption) Update;
BEGIN
f.Update^
END Update;
(** **************** Group **************** **)
PROCEDURE (c: Group) Restore (l_, t_, r_, b_: INTEGER);
VAR w, h, asc, dsc, sw, tw, apos, awdt, col: INTEGER; s: Dialog.String;
BEGIN
IF c.view # NIL THEN
SetupDialogBackground(c);
c.view.context.GetSize(w, h);
Dialog.MapString(c.label, s);
apos := CleanAmp(s, c.font, awdt);
c.font.GetBounds(asc, dsc, sw);
tw := c.font.StringWidth(s);
IF c.disabled THEN
col := skin.frameDisabled
ELSIF c.readOnly THEN
col := skin.frameReadOnly
ELSE
col := skin.frame
END;
IF h - Ports.point > (asc + dsc) * 2 DIV 3 THEN
h := h - Ports.point
ELSE
h := (asc + dsc) * 2 DIV 3 + Ports.point
END;
c.DrawRect(
Ports.point, (asc + dsc) * 2 DIV 3, w - Ports.point, h, Ports.point, col);
IF LEN(s$) > 0 THEN
c.DrawRect(Ports.mm * 3 DIV 2, 0, Ports.mm * 3 + tw, asc + dsc, Ports.fill, Ports.dialogBackground);
IF c.disabled THEN col := skin.textDisabled ELSE col := skin.text END;
DrawAmpString(c, Ports.mm * 2 , asc + dsc, col, s, apos, awdt)
END
END
END Restore;
PROCEDURE (c: Group) DblClickOk (x, y: INTEGER): BOOLEAN;
BEGIN
RETURN FALSE
END DblClickOk;
PROCEDURE (c: Group) Update;
BEGIN
c.Update^
END Update;
(** **************** PushButton **************** **)
PROCEDURE Execute (c: PushButton);
BEGIN
IF c.Do # NIL THEN
Dialog.ShowStatus("");
c.Do(c)
END
END Execute;
PROCEDURE (c: PushButton) Restore (l_, t_, r_, b_: INTEGER);
VAR
w, h, res, asc, dsc, sw, x, y, apos, awdt, yofs, col: INTEGER;
s: Dialog.String;
BEGIN
SetupDialogBackground(c);
c.view.context.GetSize(w, h);
Dialog.MapString(c.label, s);
apos := CleanAmp(s, c.font, awdt);
c.font.GetBounds(asc, dsc, sw);
(* for text *)
res := c.font.StringWidth(s);
y := (h - 3 * c.dot - dsc + asc) DIV 2 + c.dot (* h DIV 2 + (asc - dsc) DIV 2 *);
x := (w - res) DIV 2;
IF c.disabled THEN
c.DrawRect(0, 0, w, h, Ports.fill, skin.backDisabled);
c.DrawString(x, y, skin.textDisabled, s, c.font);
c.DrawRect(0, 0, w, h, c.dot, skin.frameDisabled);
ELSIF c.readOnly THEN
c.DrawRect(0, 0, w, h, Ports.fill, skin.backReadOnly);
c.DrawString(x, y, skin.textReadOnly, s, c.font);
c.DrawRect(0, 0, w, h, c.dot, skin.frameReadOnly);
ELSE
IF c.pressed THEN col := skin.backPressed ELSE col := skin.back END;
c.DrawRect(0, 0, w, h, Ports.fill, col);
IF c.pressed THEN col := skin.textPressed ELSE col := skin.text END;
DrawAmpString(c, x, y, col, s, apos, awdt);
IF c.default THEN
c.DrawRect(0, 0, w, h, 2 * c.dot, Ports.RGBColor(51, 153, 255))
ELSIF c.mark THEN
c.DrawRect(0, 0, w, h, c.dot , skin.frameFocus)
ELSE
c.DrawRect(0, 0, w, h, c.dot, skin.frame)
END;
IF c.mark THEN
c.MarkRect(2 * c.dot, 2 * c.dot, w - 2 * c.dot, h - 2 * c.dot, c.dot, Ports.dim50, Ports.show)
END
END
END Restore;
PROCEDURE (c: PushButton) MouseDown (x, y: INTEGER; buttons: SET);
BEGIN
ASSERT(~c.disabled, 100);
IF TrackMouseDown(c) THEN Execute(c) END
END MouseDown;
PROCEDURE (c: PushButton) KeyDown (ch_: CHAR; modifiers: SET);
BEGIN
ASSERT(~c.disabled, 100);
Execute(c)
END KeyDown;
PROCEDURE (c: PushButton) Mark (on_, focus_: BOOLEAN);
BEGIN
c.Update^
END Mark;
PROCEDURE (c: PushButton) DblClickOk (x, y: INTEGER): BOOLEAN;
BEGIN
RETURN FALSE
END DblClickOk;
PROCEDURE (c: PushButton) Update;
BEGIN
c.Update^
END Update;
(** **************** CheckBox **************** **)
PROCEDURE (c: CheckBox) Restore (l_, t_, r_, b_: INTEGER);
VAR w, h, h2, res, asc, dsc, sw, awdt, apos, sz, ss: INTEGER;
col: Ports.Color; s: Dialog.String; active: BOOLEAN; root: Views.Frame;
BEGIN
c.noRedraw := FALSE;
IF c # NIL THEN
c.Get(c, active);
c.view.context.GetSize(w, h);
IF c.disabled THEN col := skin.frameDisabled ELSE col := skin.frame END;
h2 := h DIV 2;
skin.checkBoxFont.GetBounds(asc, dsc, sw);
sz := asc + dsc - c.dot;
c.font.GetBounds(asc, dsc, sw);
IF asc + dsc - c.dot > sz THEN sz := asc + dsc - c.dot END;
IF sz > h THEN sz := h - c.dot END;
ss := sz DIV 2;
IF c.disabled THEN
col := skin.textDisabled
ELSIF c.readOnly THEN
col := skin.textReadOnly
ELSE
col := skin.text
END;
c.DrawRect(c.dot, h2 - ss, sz+c.dot, h2 + ss, c.dot, col);
Dialog.MapString(c.label, s);
apos := CleanAmp(s, c.font, awdt);
DrawAmpString(c, sz + 5 * c.dot, (h - dsc + asc) DIV 2, col, s, apos, awdt);
IF active & ~ c.disabled THEN
res := skin.checkBoxFont.StringWidth("V");
c.DrawString((sz - res) DIV 2, (h + asc) DIV 2 - 1 * c.dot, col, "V", skin.checkBoxFont);
root := Views.HostOf(c);
IF root.view IS TextViews.View THEN
col := Ports.background
ELSE
col := Ports.dialogBackground
END;
c.DrawRect(2 * c.dot, h2-ss+c.dot, sz DIV 2, (h2-ss)+ss-c.dot, Ports.fill, col);
c.DrawRect(2 * c.dot, h2 - ss + c.dot, sz, h2 + ss - c.dot, c.dot, col);
END;
IF c.mark & ~ c.disabled THEN
res := c.font.StringWidth(s);
asc := c.dot;
IF asc < h2 - ss THEN asc := h2 - ss END;
dsc := h - c.dot;
IF dsc > h2 + ss THEN dsc := h2 + ss END;
c.MarkRect(
sz + 4 * c.dot, asc,
sz + 7 * c.dot + res, dsc,
c.dot, Ports.dim50, Ports.show);
END
END
END Restore;
PROCEDURE (c: CheckBox) MouseDown (x, y: INTEGER; buttons: SET);
VAR
state: BOOLEAN;
BEGIN
ASSERT(~c.disabled, 100);
IF TrackMouseDown(c) THEN
c.Get(c, state); c.Set(c, ~state); c.Update
END
END MouseDown;
(* `Controls` module guarantees that we'll get only hotkeys and space here *)
PROCEDURE (c: CheckBox) KeyDown (ch: CHAR; modifiers: SET);
VAR state: BOOLEAN;
BEGIN
ASSERT(~c.disabled, 100);
c.Get(c, state); c.Set(c, ~state); c.Update
END KeyDown;
PROCEDURE (c: CheckBox) Mark (on, focus: BOOLEAN);
BEGIN
c.Update
END Mark;
PROCEDURE (c: CheckBox) DblClickOk (x, y: INTEGER): BOOLEAN;
BEGIN
RETURN FALSE
END DblClickOk;
(** **************** RadioButton **************** **)
PROCEDURE (c: RadioButton) Add(): Storage, NEW;
VAR nst: RadioButtonStorage;
BEGIN
NEW(nst);
nst.view := c.view;
nst.hasFocus := FALSE;
AddStorage(nst);
RETURN nst
END Add;
PROCEDURE (c: RadioButton) Restore (l_, t_, r_, b_: INTEGER);
VAR
w, h, asc, dsc, sw, res, h2, apos, awdt, rad1, rad2: INTEGER;
col: Ports.Color; s: Dialog.String;
active, drawBack: BOOLEAN;
st: Storage;
BEGIN
st := GetStorage(c.view);
IF (st = NIL) & (c.view # NIL) THEN st := c.Add() END;
WITH st : RadioButtonStorage DO
SetupDialogBackground(c);
c.Get(c, active);
c.view.context.GetSize(w, h);
IF c.disabled THEN
col := skin.textDisabled
ELSIF c.readOnly THEN
col := skin.textReadOnly
ELSE
col := skin.text
END;
h2 := h DIV 2;
rad1 := 5 * Ports.point - (5 * Ports.point) MOD c.unit;
rad2 := 3 * Ports.point - (3 * Ports.point) MOD c.unit;
c.DrawOval(c.unit, h2 - rad1, rad1 + c.unit + rad1, h2 + rad1, c.dot, col);
IF active THEN
c.DrawOval(rad1 + c.unit - rad2, h2 - rad2, rad1 + c.unit + rad2, h2 + rad2, Ports.fill , col)
END;
Dialog.MapString(c.label, s);
apos := CleanAmp(s, c.font, awdt);
c.font.GetBounds(asc, dsc, sw);
DrawAmpString(c, 16 * Ports.point, (h - dsc + asc) DIV 2, col, s, apos, awdt);
(*
IF c.mark OR st.hasFocus THEN
res := c.font.StringWidth(s);
c.DrawLine(
16 * Ports.point, h DIV 2 + asc DIV 2 + 2 * c.dot,
16 * Ports.point + res, h DIV 2 + asc DIV 2 + 2 * c.dot, c.dot, col)
END
*)
END
END Restore;
PROCEDURE (c: RadioButton) MouseDown (x, y: INTEGER; buttons: SET);
VAR
state: BOOLEAN;
BEGIN
ASSERT(~c.disabled, 100);
IF TrackMouseDown(c) THEN
c.Get(c, state);
IF ~state THEN c.Set(c, TRUE) END
END
END MouseDown;
(* `Controls` module guarantees that we'll get only hotkeys and space here *)
PROCEDURE (c: RadioButton) KeyDown (ch: CHAR; modifiers: SET);
VAR
state: BOOLEAN;
BEGIN
ASSERT(~c.disabled, 100);
c.Get(c, state);
IF ~state THEN c.Set(c, TRUE) END
END KeyDown;
PROCEDURE (c: RadioButton) Mark (on, focus: BOOLEAN);
VAR st: Storage;
BEGIN
st := GetStorage(c.view);
IF (st = NIL) & (c.view # NIL) THEN st := c.Add(); END;
WITH st : RadioButtonStorage DO
IF focus THEN
IF on THEN IF ~ st.hasFocus THEN st.hasFocus := TRUE END
ELSE IF st.hasFocus THEN st.hasFocus := FALSE END END
END
END;
c.Update^
END Mark;
PROCEDURE (c: RadioButton) DblClickOk (x, y: INTEGER): BOOLEAN;
BEGIN
RETURN FALSE
END DblClickOk;
PROCEDURE (c: RadioButton) Update;
BEGIN
c.Update^
END Update;
(** **************** Field **************** **)
PROCEDURE (c: Field) UpdateEd, NEW;
VAR
s: Dialog.String;
ps: EditorCommonText;
BEGIN
c.ed.SetupCtl(c);
(* INC(c.ed.changeCount); c.ed.changeCount := 0; *)
c.ed.maxLen := c.maxLen;
IF c.maxLen > 255 THEN
ASSERT(c.maxLen < 1024*1024*32);
NEW(ps, c.maxLen + 1);
c.Get(c, ps^);
IF c.ed.SetText(ps) THEN INC(c.ed.changeCount) END
ELSE
c.Get(c, s);
IF c.ed.SetText(s) THEN INC(c.ed.changeCount) END
END
END UpdateEd;
PROCEDURE (c: Field) Add(): Storage, NEW;
VAR nst: FieldStorage;
BEGIN
NEW(nst);
nst.view := c.view;
AddStorage(nst);
RETURN nst
END Add;
PROCEDURE (c: Field) Restore (l_, t_, r_, b_: INTEGER);
VAR asc, dsc, sw, w, h: INTEGER; st: Storage;
BEGIN
st := GetStorage(c.view);
IF (st = NIL) & (c.view # NIL) THEN
st := c.Add()
END;
WITH st : FieldStorage DO
c.ed.st := st;
SetupDialogBackground(c);
c.view.context.GetSize(w, h);
IF c.disabled THEN
c.DrawRect(0, 0, w, h, Ports.fill, skin.backEditorDisabled);
c.DrawRect(0, 0, w, h, c.dot, skin.frameDisabled);
ELSE
IF c.ed.ctl = NIL THEN
c.UpdateEd;
END;
c.ed.Setup(c, c.dot, c.dot, w - 2 * c.dot, h - 2 * c.dot);
IF ~c.readOnly & c.mark THEN
c.ed.outMargin.SetUni(1)
ELSE
c.ed.outMargin.SetUni(2)
END;
c.ed.ctl.font.GetBounds(asc, dsc, sw);
IF c.multiLine THEN
c.ed.pad := Ports.mm
ELSE
c.ed.pad := (h - (asc + dsc)) DIV 3
END;
IF c.ed.pad < 2 * Ports.point THEN c.ed.pad := 2 * Ports.point END;
c.ed.maxLen := c.maxLen;
c.ed.multiLine := c.multiLine;
c.ed.password := c.password & ~revealPasswords;
c.ed.left := c.left;
c.ed.right := c.right;
c.ed.Restore;
IF c.readOnly THEN
c.DrawRect(0, 0, w, h, c.dot, skin.frameReadOnly)
ELSE
IF c.mark THEN
c.DrawRect(0, 0, w, h, c.dot * 2, skin.frameFocus)
ELSE
c.DrawRect(0, 0, w, h, c.dot, skin.frame)
END
END
END
END
END Restore;
PROCEDURE (c: Field) GetCursor (x, y: INTEGER; modifiers: SET; VAR cursor: INTEGER);
VAR w, h: INTEGER;
BEGIN
c.view.context.GetSize(w, h);
IF (c.ed.vsb # NIL) & (x > w - c.ed.vsb.Width())THEN
cursor := Ports.arrowCursor
ELSE
cursor := Ports.textCursor
END
END GetCursor;
PROCEDURE (c: Field) Edit (op: INTEGER; VAR v: Views.View; VAR w, h: INTEGER;
VAR singleton, clipboard: BOOLEAN);
VAR oldChangeCount: INTEGER;
BEGIN
IF c.ed.ctl # NIL THEN
IF (~c.disabled & ~c.readOnly) OR (c.readOnly & (op = Controllers.copy)) THEN
oldChangeCount := c.ed.changeCount;
c.ed.Edit(op, v, clipboard);
IF c.ed.changeCount # oldChangeCount THEN c.Set(c, c.ed.text) END;
c.Update^
END
END
END Edit;
PROCEDURE (c: Field) WheelMove (x, y, op, nofLines: INTEGER; VAR done: BOOLEAN);
VAR oldChangeCount: INTEGER;
BEGIN
IF c.ed.ctl # NIL THEN
oldChangeCount := c.ed.changeCount;
c.ed.WheelMove(x, y, op, nofLines, done);
IF c.ed.changeCount # oldChangeCount THEN c.Set(c, c.ed.text) END;
IF done OR (c.ed.changeCount # oldChangeCount) THEN
c.Update^
END
END
END WheelMove;
PROCEDURE (c: Field) MouseDown (x, y: INTEGER; buttons: SET);
VAR oldChangeCount, res: INTEGER;
BEGIN
IF c.ed.ctl # NIL THEN
IF ~c.disabled THEN
IF Controllers.popup IN buttons THEN
focusControl := c;
(* Dialog.Call(" show popup menu TODO ", 'error', res); *)
ELSE
oldChangeCount := c.ed.changeCount;
c.ed.MouseDown(x, y, buttons);
IF c.ed.changeCount # oldChangeCount THEN c.Set(c, c.ed.text) END;
c.Update^
END
END
END
END MouseDown;
PROCEDURE (c: Field) KeyDown (ch: CHAR; modifiers: SET);
VAR oldChangeCount: INTEGER;
BEGIN
IF c.ed.ctl # NIL THEN
IF ~c.disabled & ~c.readOnly THEN
oldChangeCount := c.ed.changeCount;
c.ed.KeyDown(ch, modifiers);
IF c.ed.changeCount # oldChangeCount THEN c.Set(c, c.ed.text) END;
c.ed.RetainCaret;
c.Update^
END
END
END KeyDown;
PROCEDURE (c: Field) Select (from, to: INTEGER);
BEGIN
IF c.ed.ctl # NIL THEN
IF ~c.disabled THEN
c.ed.Select(from, to);
c.Update^
END
END
END Select;
PROCEDURE (c: Field) GetSelection (OUT from, to: INTEGER);
BEGIN
IF c.ed.ctl # NIL THEN c.ed.GetSelection(from, to)
ELSE from := 0; to := MAX(INTEGER)
END
END GetSelection;
PROCEDURE (c: Field) Idle;
BEGIN
c.ed.BlinkCaret
END Idle;
PROCEDURE (c: Field) Length (): INTEGER;
BEGIN
RETURN c.ed.textLen
END Length;
PROCEDURE (c: Field) Mark (on_, focus_: BOOLEAN);
BEGIN
c.Update^
END Mark;
PROCEDURE (c: Field) DblClickOk (x, y: INTEGER): BOOLEAN;
BEGIN
RETURN TRUE
END DblClickOk;
(* called when the text is updated by the external actor *)
PROCEDURE (c: Field) Update;
BEGIN
c.UpdateEd;
IF c.ed.changeCount # 0 THEN
c.ed.RetainCaret;
c.Update^
END
END Update;
(** **************** ListBox **************** **)
PROCEDURE (c: ListBox) UpdateLCtl, NEW;
BEGIN
c.lst.SetupCtl(c);
IF c.lst.UpdateFromCtl() THEN c.fixCursor := TRUE END
END UpdateLCtl;
PROCEDURE (c: ListBox) NeedPopup (): BOOLEAN, NEW;
VAR w, h, strHeight: INTEGER;
BEGIN
c.view.context.GetSize(w, h);
strHeight := c.lst.GetItemHeight();
RETURN (w > 6 * Ports.point) & (h > 6 * Ports.point) & (h < strHeight * 2)
END NeedPopup;
PROCEDURE (c: ListBox) Restore (l_, t_, r_, b_: INTEGER);
VAR w, h, y: INTEGER;
BEGIN
IF c.view # NIL THEN
SetupDialogBackground(c);
IF c.lst.ctl = NIL THEN c.UpdateLCtl END;
c.view.context.GetSize(w, h);
c.lst.outMargin.SetUni(0);
IF c.fixCursor THEN
c.fixCursor := FALSE;
c.lst.MakeCursorVisibleCentered
END;
(* draw arrow *)
IF c.NeedPopup() THEN
c.lst.Setup(c, 2 * c.dot, 2 * c.dot, w - 3 * c.dot - h, h - 4 * c.dot);
c.DrawRect(w - h, 0, w, h, Ports.fill, skin.backScrollbar);
IF h > 3 * Ports.point THEN
y := h DIV 2 - 2 * Ports.point;
ELSE
y := h DIV 2
END;
DrawArrowDown(c, w - h DIV 2 - 3 * Ports.point, y)
ELSE
c.lst.Setup(c, 2 * c.dot, 2 * c.dot, w - 4 * c.dot, h - 4 * c.dot)
END;
c.lst.Restore;
IF c.readOnly THEN
c.DrawRect(0, 0, w, h, c.dot, skin.frameReadOnly)
ELSE
IF c.mark THEN
c.DrawRect(0, 0, w, h, c.dot * 2, skin.frameFocus)
ELSE
c.DrawRect(0, 0, w, h, c.dot, skin.frame)
END
END
END
END Restore;
PROCEDURE (c: ListBox) Mark (on_, focus_: BOOLEAN);
BEGIN
c.Update^
END Mark;
PROCEDURE (c: ListBox) FixModelCursorPos, NEW;
VAR
idx: INTEGER;
BEGIN
IF c.view # NIL THEN
c.Get(c, idx);
IF c.lst.GetLength() # 0 THEN
IF idx # c.lst.pos THEN c.Set(c, c.lst.pos) END
ELSIF idx # -1 THEN c.Set(c, -1)
END
END
END FixModelCursorPos;
PROCEDURE (c: ListBox) PopupClosed (popup: ANYPTR);
BEGIN
c.closedTime := Services.Ticks();
c.popupOverlay := NIL;
c.FixModelCursorPos;
c.fixCursor := TRUE;
c.Update
END PopupClosed;
PROCEDURE (c: ListBox) ShowPopup, NEW;
VAR
w, h: INTEGER;
BEGIN
IF (c.lst.ctl # NIL) & ~c.readOnly & ~c.disabled & (c.rider # NIL) & c.NeedPopup() THEN
IF (c.popupOverlay = NIL) & (Services.Ticks() - c.closedTime > 100) THEN
c.view.context.GetSize(w, h);
c.popupOverlay := c.lst.ShowPopup(h - c.dot)
END
END
END ShowPopup;
PROCEDURE (c: ListBox) WheelMove (x, y, op, nofLines: INTEGER; VAR done: BOOLEAN);
BEGIN
IF c.lst.ctl # NIL THEN
c.lst.WheelMove(x, y, op, nofLines, done);
IF done THEN
c.FixModelCursorPos;
c.Update^
END
END
END WheelMove;
PROCEDURE (c: ListBox) MouseDown (x, y: INTEGER; buttons: SET);
BEGIN
IF (c.lst.ctl # NIL) & (c.view # NIL) THEN
IF ~c.disabled THEN
IF c.NeedPopup() THEN
c.ShowPopup
ELSE
c.lst.MouseDown(x, y, buttons);
c.FixModelCursorPos;
c.Update^
END
END
END
END MouseDown;
PROCEDURE (c: ListBox) KeyDown (ch: CHAR; modifiers: SET);
BEGIN
IF (c.lst.ctl # NIL) & (c.view # NIL) THEN
IF (ch = PR) & c.NeedPopup() THEN
c.ShowPopup
ELSE
c.lst.KeyDown(ch, modifiers);
c.FixModelCursorPos;
c.Update^
END
END
END KeyDown;
PROCEDURE (c: ListBox) DblClickOk (x, y: INTEGER): BOOLEAN;
VAR w, h: INTEGER; res: BOOLEAN;
BEGIN
res := TRUE;
c.view.context.GetSize(w, h);
IF (c.lst.hsb # NIL) & (y > h - c.lst.hsb.Width()) THEN
res := FALSE
END;
IF (c.lst.vsb # NIL) & (x > w - c.lst.vsb.Width()) THEN
res := FALSE
END;
RETURN res
END DblClickOk;
PROCEDURE (c: ListBox) UpdateList;
BEGIN
IF c.view # NIL THEN
c.UpdateLCtl;
c.Update^
END
END UpdateList;
PROCEDURE (c: ListBox) Update;
VAR
cidx: INTEGER;
BEGIN
IF c.view # NIL THEN
IF c.lst.ctl = NIL THEN
c.UpdateLCtl
ELSE
c.Get(c, cidx);
cidx := MAX(0, MIN(cidx, c.lst.GetLength() - 1));
IF cidx # c.lst.pos THEN
c.lst.pos := cidx;
c.fixCursor := TRUE
END
END;
c.Update^
END
END Update;
(** **************** ComboBox **************** **)
PROCEDURE (c: ComboBox) UpdateEd, NEW;
VAR
s: Dialog.String;
BEGIN
c.ed.SetupCtl(c);
c.ed.changeCount := 0;
c.ed.maxLen := 255;
c.ed.SetupCtl(c);
c.Get(c, s);
IF c.ed.SetText(s) THEN INC(c.ed.changeCount) END
END UpdateEd;
PROCEDURE (c: ComboBox) UpdateLCtl, NEW;
BEGIN
c.lst.SetupCtl(c);
c.UpdateEd;
IF c.lst.UpdateFromCtl() THEN c.fixCursor := TRUE END
END UpdateLCtl;
(* with frame *)
PROCEDURE (c: ComboBox) GetEditorHeight (): INTEGER, NEW;
VAR
w, h, asc, dsc, sw: INTEGER;
BEGIN
c.font.GetBounds(asc, dsc, sw);
sw := asc + dsc + 6 * c.dot;
IF (c.view # NIL) & (c.view.context # NIL) THEN
c.view.context.GetSize(w, h);
sw := MIN(sw, h)
END;
RETURN sw
END GetEditorHeight;
(* k8: if the control is big enough, show popup under the edit line *)
(* k8: this returns 0, or the popup size *)
PROCEDURE (c: ComboBox) GetVisPopupHeight (): INTEGER, NEW;
VAR
w, h: INTEGER;
asc, dsc, sw: INTEGER;
res: INTEGER;
BEGIN
res := 0;
c.view.context.GetSize(w, h);
IF w > 12 * c.dot THEN
res := h - c.GetEditorHeight();
c.font.GetBounds(asc, dsc, sw);
IF res < asc + dsc + 6 * c.dot THEN res := 0 END
END;
RETURN res
END GetVisPopupHeight;
PROCEDURE (c: ComboBox) SetFromList, NEW;
VAR
s: Dialog.String;
ns: EditorCommonText;
BEGIN
IF (c.view # NIL) & (c.lst.ctl # NIL) & (c.lst.GetLength() # 0) THEN
c.Get(c, s);
ns := c.lst.items[c.lst.pos].text;
IF s$ # ns$ THEN
c.Set(c, ns^);
c.view(Controls.Control).item.CallWith(Update, c.lst^) (* second argument doesn't matter here *)
END
END
END SetFromList;
PROCEDURE (c: ComboBox) SetFromEd, NEW;
VAR
s: Dialog.String;
ns: EditorCommonText;
BEGIN
IF (c.view # NIL) & (c.ed.ctl # NIL) & (c.lst.GetLength() # 0) THEN
c.Get(c, s);
ns := c.ed.text;
IF s$ # ns$ THEN
c.Set(c, ns^);
c.view(Controls.Control).item.CallWith(Update, c.lst^) (* second argument doesn't matter here *)
END
END
END SetFromEd;
PROCEDURE (c: ComboBox) SetupCtl, NEW;
VAR w, h, vh: INTEGER;
BEGIN
IF c.view # NIL THEN
vh := c.GetVisPopupHeight();
c.view.context.GetSize(w, h);
IF vh = 0 THEN
c.ed.Setup(c, 3 * c.dot, c.dot, w - 5 * c.dot - c.GetEditorHeight(), c.GetEditorHeight() - 3 * c.dot)
ELSE
c.ed.Setup(c, 3 * c.dot, c.dot, w - 5 * c.dot, c.GetEditorHeight() - 3 * c.dot)
END;
c.ed.outMargin.SetUni(1);
IF vh > 0 THEN
c.lst.Setup(c, 2 * c.dot, c.GetEditorHeight() + 3 * c.dot, w - 4 * c.dot, vh - 4 * c.dot);
c.lst.outMargin.SetUni(0)
ELSE
c.lst.Setup(c, 0, 0, 0, 0);
c.lst.outMargin.SetUni(0)
END
ELSE
c.ed.Setup(c, 0, 0, 0, 0)
END
END SetupCtl;
PROCEDURE (c: ComboBox) GetCursor (x, y: INTEGER; modifiers: SET; VAR cursor: INTEGER);
BEGIN
IF (x >= c.ed.x0) & (y >= c.ed.y0) & (x < c.ed.x0+c.ed.w) & (y < c.ed.y0+c.ed.h) THEN
cursor := Ports.textCursor
ELSE
cursor := Ports.arrowCursor
END
END GetCursor;
PROCEDURE (c: ComboBox) Restore (l_, t_, r_, b_: INTEGER);
VAR w, h, x, y: INTEGER;
BEGIN
IF c.view # NIL THEN
SetupDialogBackground(c);
IF c.ed.ctl = NIL THEN c.UpdateLCtl END;
c.SetupCtl;
c.view.context.GetSize(w, h);
(* draw editor *)
c.ed.Restore;
h := c.GetEditorHeight();
IF ~c.lst.IsValid() THEN
(* draw arrow *)
c.DrawRect(w - h, 0, w, h, Ports.fill, skin.backScrollbar);
IF h > 3 * Ports.point THEN
y := h DIV 2 - 3 * Ports.point;
ELSE
y := h DIV 2
END;
x := w - h DIV 2 - 3 * Ports.point; (* minus one more because of borders *)
DrawArrowDown(c, x, y)
END;
IF c.readOnly THEN
c.DrawRect(0, 0, w, h, c.dot, skin.frameReadOnly)
ELSE
IF c.mark THEN
c.DrawRect(0, 0, w, h, c.dot * 2, skin.frameFocus)
ELSE
c.DrawRect(0, 0, w, h, c.dot, skin.frame)
END
END;
(* draw list *)
IF c.lst.IsValid() THEN
IF c.fixCursor THEN c.fixCursor := FALSE; c.lst.MakeCursorVisibleCentered END;
c.lst.Restore;
h := c.GetEditorHeight() + c.GetVisPopupHeight();
IF c.readOnly THEN
c.DrawRect(0, c.GetEditorHeight(), w, h, c.dot, skin.frameReadOnly)
ELSE
IF c.mark THEN
c.DrawRect(0, c.GetEditorHeight(), w, h, c.dot * 2, skin.frameFocus)
ELSE
c.DrawRect(0, c.GetEditorHeight(), w, h, c.dot, skin.frame)
END
END;
END
END
END Restore;
PROCEDURE (c: ComboBox) PopupClosed (popup: ANYPTR);
BEGIN
c.closedTime := Services.Ticks();
c.popupOverlay := NIL;
c.SetFromList;
c.Update
END PopupClosed;
PROCEDURE (c: ComboBox) ShowPopup, NEW;
BEGIN
IF (c.ed.ctl # NIL) & ~c.readOnly & ~c.disabled & (c.rider # NIL) & ~c.lst.IsValid() THEN
IF (c.popupOverlay = NIL) & (Services.Ticks() - c.closedTime > 100) THEN
c.popupOverlay := c.lst.ShowPopup(c.GetEditorHeight() - c.dot)
END
END
END ShowPopup;
PROCEDURE (c: ComboBox) GoOneUpDown (dir: INTEGER), NEW;
VAR
len, idx, old: INTEGER;
BEGIN
IF c.ed.ctl # NIL THEN
len := c.lst.GetLength();
IF len > 0 THEN
idx := GetCursorIndex(c);
IF idx < 0 THEN idx := c.lst.pos END;
old := idx;
IF dir > 0 THEN INC(idx) ELSE DEC(idx) END;
idx := MAX(0, MIN(idx, len - 1));
IF old # idx THEN
c.lst.pos := idx;
c.SetFromList;
c.Update^
END
END
END
END GoOneUpDown;
PROCEDURE (c: ComboBox) WheelMove (x, y, op, nofLines: INTEGER; VAR done: BOOLEAN);
BEGIN
(*k8:TODO: `incPage` and `decPage`*)
IF (c.ed.ctl # NIL) & ~c.readOnly & ~c.disabled & (c.rider # NIL) THEN
IF (op = Controllers.incLine) OR (op = Controllers.decLine) THEN
done := TRUE; (* eat it! *)
IF c.lst.IsValid() & (y > c.GetEditorHeight()) THEN
c.lst.WheelMove(x, y, op, nofLines, done);
c.Update^
ELSE
IF op = Controllers.decLine THEN nofLines := -nofLines END;
c.GoOneUpDown(nofLines)
END
END
END
END WheelMove;
PROCEDURE (c: ComboBox) MouseDown (x, y: INTEGER; buttons: SET);
VAR
w, h: INTEGER;
BEGIN
IF (c.ed.ctl # NIL) & ~c.readOnly & ~c.disabled & (c.rider # NIL) THEN
IF c.lst.IsValid() & (y > c.GetEditorHeight()) THEN
c.lst.MouseDown(x, y, buttons);
c.SetFromList;
c.Update^
ELSE
c.view.context.GetSize(w, h);
IF x >= w - 3 * c.dot - 10 * c.dot THEN
c.ShowPopup
ELSE
c.ed.MouseDown(x, y, buttons);
c.Update^
END
END
END
END MouseDown;
PROCEDURE (c: ComboBox) Edit (op: INTEGER; VAR v: Views.View; VAR w, h: INTEGER;
VAR singleton, clipboard: BOOLEAN);
BEGIN
IF c.ed.ctl # NIL THEN
IF ~c.disabled & ~c.readOnly THEN
c.ed.changeCount := 0;
c.ed.Edit(op, v, clipboard);
IF c.ed.changeCount # 0 THEN c.SetFromEd END;
c.Update^
END
END
END Edit;
PROCEDURE (c: ComboBox) KeyDown (ch: CHAR; modifiers: SET);
BEGIN
ASSERT(~c.disabled, 100);
IF c.ed.ctl # NIL THEN
CASE ch OF
| AU: c.GoOneUpDown(-1)
| AD: c.GoOneUpDown(1)
| PR: (* ctrl+page down *)
c.ShowPopup
ELSE
c.ed.changeCount := 0;
c.ed.KeyDown(ch, modifiers);
IF c.ed.changeCount # 0 THEN c.SetFromEd END;
c.ed.RetainCaret;
c.Update^
END
END
END KeyDown;
PROCEDURE (c: ComboBox) Close;
BEGIN
IF c.popupOverlay # NIL THEN c.popupOverlay.ClosePopup; c.popupOverlay := NIL END
END Close;
PROCEDURE (c: ComboBox) Select (from, to: INTEGER);
BEGIN
IF c.ed.ctl # NIL THEN
c.ed.Select(from, to);
c.Update^
END
END Select;
PROCEDURE (c: ComboBox) GetSelection (OUT from, to: INTEGER);
BEGIN
IF c.ed.ctl # NIL THEN c.ed.GetSelection(from, to)
ELSE from := 0; to := MAX(INTEGER)
END
END GetSelection;
PROCEDURE (c: ComboBox) Idle;
BEGIN
c.ed.BlinkCaret
END Idle;
PROCEDURE (c: ComboBox) Length (): INTEGER;
BEGIN
RETURN c.ed.textLen
END Length;
PROCEDURE (c: ComboBox) Mark (on_, focus_: BOOLEAN);
BEGIN
c.Update^
END Mark;
PROCEDURE (c: ComboBox) DblClickOk (x, y: INTEGER): BOOLEAN;
BEGIN
RETURN TRUE
END DblClickOk;
PROCEDURE (c: ComboBox) UpdateList;
BEGIN
IF c.view # NIL THEN
c.UpdateLCtl;
c.Update^
END
END UpdateList;
PROCEDURE (c: ComboBox) Update;
VAR
cidx: INTEGER;
BEGIN
IF c.view # NIL THEN
IF c.ed.ctl = NIL THEN
c.UpdateLCtl
ELSE
c.UpdateEd;
c.ed.RetainCaret;
cidx := GetCursorIndex(c);
cidx := MAX(0, MIN(cidx, c.lst.GetLength() - 1));
IF cidx # c.lst.pos THEN
c.lst.pos := cidx;
c.fixCursor := TRUE
END
END;
c.Update^
END
END Update;
(** **************** SelectionBox **************** **)
PROCEDURE (c: SelectionBox) UpdateLCtl, NEW;
BEGIN
c.lst.SetupCtl(c);
IF c.lst.UpdateFromCtl() THEN c.fixCursor := TRUE END
END UpdateLCtl;
PROCEDURE (c: SelectionBox) Restore (l_, t_, r_, b_: INTEGER);
VAR
w, h: INTEGER;
BEGIN
IF c.view # NIL THEN
SetupDialogBackground(c);
IF c.lst.ctl = NIL THEN c.UpdateLCtl END;
c.view.context.GetSize(w, h);
c.lst.Setup(c, c.dot, c.dot, w - 2 * c.dot, h - 2 * c.dot);
c.lst.outMargin.SetUni(0);
IF c.fixCursor THEN c.fixCursor := FALSE; c.lst.MakeCursorVisibleCentered END;
c.lst.Restore;
IF c.readOnly THEN
c.DrawRect(0, 0, w, h, c.dot, skin.frameReadOnly)
ELSE
IF c.mark THEN
c.DrawRect(0, 0, w, h, c.dot * 2, skin.frameFocus)
ELSE
c.DrawRect(0, 0, w, h, c.dot, skin.frame)
END
END
END
END Restore;
PROCEDURE (c: SelectionBox) Mark (on_, focus_: BOOLEAN);
BEGIN
c.Update^
END Mark;
PROCEDURE (c: SelectionBox) WheelMove (x, y, op, nofLines: INTEGER; VAR done: BOOLEAN);
BEGIN
IF c.lst.ctl # NIL THEN
c.lst.WheelMove(x, y, op, nofLines, done);
IF done THEN c.Update^ END
END
END WheelMove;
PROCEDURE (c: SelectionBox) MouseDown (x, y: INTEGER; buttons: SET);
BEGIN
IF c.lst.ctl # NIL THEN
IF ~c.disabled THEN
c.lst.MouseDown(x, y, buttons);
c.Update^
END
END
END MouseDown;
PROCEDURE (c: SelectionBox) KeyDown (ch: CHAR; modifiers: SET);
BEGIN
IF c.lst.ctl # NIL THEN
c.lst.KeyDown(ch, modifiers);
c.Update^
END
END KeyDown;
PROCEDURE (c: SelectionBox) DblClickOk (x, y: INTEGER): BOOLEAN;
BEGIN
RETURN TRUE
END DblClickOk;
PROCEDURE (c: SelectionBox) GetSelection (OUT from, to: INTEGER);
BEGIN
from := 0; to := MAX(INTEGER)
END GetSelection;
PROCEDURE (c: SelectionBox) Select (from, to: INTEGER);
BEGIN
END Select;
PROCEDURE (c: SelectionBox) UpdateList;
BEGIN
IF c.view # NIL THEN
c.UpdateLCtl;
c.Update^
END
END UpdateList;
PROCEDURE (c: SelectionBox) Update;
BEGIN
IF c.view # NIL THEN
c.UpdateLCtl;
c.Update^
END
END Update;
(** **************** UpDownField **************** **)
PROCEDURE (c: UpDownField) UpdateEd, NEW;
VAR
val: INTEGER;
s: Dialog.String;
BEGIN
c.Get(c, val); (* differs from field, that here is integer *)
IF c.ed.ctl = NIL THEN c.lastval := val + 1 END;
c.ed.SetupCtl(c);
c.ed.changeCount := 0;
c.ed.maxLen := 255;
IF val # c.lastval THEN
c.lastval := val;
Strings.IntToString(val, s);
IF c.ed.SetText(s) THEN INC(c.ed.changeCount) END
END
END UpdateEd;
PROCEDURE (c: UpDownField) SetFromEd (): BOOLEAN, NEW;
VAR
val, res: INTEGER;
modified: BOOLEAN;
BEGIN
modified := FALSE;
IF c.ed.ctl # NIL THEN
IF c.view # NIL THEN
Strings.StringToInt(c.ed.text^, val, res);
IF (res = 0) & (val # c.lastval) THEN
c.lastval := val;
c.Set(c, val);
modified := TRUE
END
END
END;
RETURN modified
END SetFromEd;
PROCEDURE (c: UpDownField) HasArrows (): BOOLEAN, NEW;
VAR
w, h: INTEGER;
res: BOOLEAN;
BEGIN
IF c.view # NIL THEN
c.view.context.GetSize(w, h);
res := w > 12 * Ports.point
ELSE res := FALSE
END;
RETURN res
END HasArrows;
PROCEDURE (c: UpDownField) Restore (l_, t_, r_, b_: INTEGER);
VAR
w, h: INTEGER;
hasArrows: BOOLEAN;
clip: ClipRect;
x0, y0, ah: INTEGER;
BEGIN
SetupDialogBackground(c);
IF c.ed.ctl = NIL THEN c.UpdateEd END;
c.view.context.GetSize(w, h);
hasArrows := c.HasArrows();
IF hasArrows THEN
c.ed.Setup(c, 3 * c.dot, c.dot, w - 5 * c.dot - 10 * Ports.point, h - 2 * c.dot)
ELSE
c.ed.Setup(c, 3*c.dot, c.dot, w - 5 * c.dot, h - 2 * c.dot)
END;
c.ed.outMargin.SetUni(1);
c.ed.maxLen := 255;
c.ed.Restore;
(* arrows *)
IF hasArrows THEN
x0 := w - 9 * Ports.point;
ah := h DIV 2;
IF ah >= 8 * Ports.point THEN
y0 := ah - 7 * Ports.point;
DrawArrowUp(c, x0, y0);
y0 := ah + Ports.point;
DrawArrowDown(c, x0, y0)
END
END;
IF c.readOnly THEN
c.DrawRect(0, 0, w, h, c.dot, skin.frameReadOnly)
ELSE
IF c.mark THEN
c.DrawRect(0, 0, w, h, c.dot * 2, skin.frameFocus)
ELSE
c.DrawRect(0, 0, w, h, c.dot, skin.frame)
END
END
END Restore;
PROCEDURE (c: UpDownField) GetCursor (x, y: INTEGER; modifiers: SET; VAR cursor: INTEGER);
BEGIN
IF (x >= c.ed.x0) & (y >= c.ed.y0) & (x < c.ed.x0 + c.ed.w) & (y < c.ed.y0 + c.ed.h) THEN
cursor := Ports.textCursor
ELSE
cursor := Ports.arrowCursor
END
END GetCursor;
PROCEDURE (c: UpDownField) IncDec (inc: BOOLEAN), NEW;
VAR
val: INTEGER;
BEGIN
val := c.lastval;
IF inc THEN
IF val < c.max THEN
IF LONG(c.max) - val <= c.inc THEN val := c.max ELSE INC(val, c.inc) END
END
ELSE
IF val > c.min THEN
IF LONG(val) - c.min <= c.inc THEN val := c.min ELSE DEC(val, c.inc) END
END
END;
IF val # c.lastval THEN
c.Set(c, val);
c.UpdateEd;
c.Update^
END
END IncDec;
PROCEDURE (c: UpDownField) WheelMove (x, y, op, nofLines: INTEGER; VAR done: BOOLEAN);
VAR
w, h: INTEGER;
BEGIN
IF c.view # NIL THEN
c.view.context.GetSize(w, h);
IF (x >= 0) & (y >= 0) & (x < w) & (y < h) THEN
done := TRUE;
c.IncDec(op = Controllers.decLine)
END
END
END WheelMove;
PROCEDURE (c: UpDownField) MouseDown (x, y: INTEGER; buttons: SET);
VAR
w, h: INTEGER;
BEGIN
IF c.ed.ctl # NIL THEN
IF ~c.disabled & ~c.readOnly & (c.rider # NIL) THEN
c.view.context.GetSize(w, h);
IF c.HasArrows() & (x > w - 3 * c.dot - 11 * c.dot) THEN
c.IncDec(y < h DIV 2)
ELSE
c.ed.changeCount := 0;
c.ed.MouseDown(x, y, buttons);
IF c.ed.changeCount # 0 THEN
IF c.SetFromEd() THEN END
END;
c.Update^
END
END
END
END MouseDown;
PROCEDURE (c: UpDownField) KeyDown (ch: CHAR; modifiers: SET);
VAR int, res: INTEGER;
BEGIN
IF c.ed.ctl # NIL THEN
c.ed.changeCount := 0;
CASE ch OF
| AU:
Strings.StringToInt(c.ed.text, int, res);
Strings.IntToString(int+1, c.ed.text);
c.ed.textLen := LEN(c.ed.text$);
c.ed.pos := c.ed.textLen;
INC(c.ed.changeCount)
| AD:
Strings.StringToInt(c.ed.text, int, res);
Strings.IntToString(int-1, c.ed.text);
c.ed.textLen := LEN(c.ed.text$);
c.ed.pos := c.ed.textLen;
INC(c.ed.changeCount)
ELSE
IF (ch > 20X) THEN
IF ((ch >= '0') & (ch <= '9')) OR (ch = '-') OR (ch = '+') OR (ch = 'E') OR (ch = '.') THEN
c.ed.KeyDown(ch, modifiers)
END
ELSIF (ch = AL) OR (ch = AR) OR (ch = BACKSPACE) OR (ch = DELETE) OR (ch = CHR(64977)) OR (ch = 019X) OR (ch = CHR(64978)) THEN
c.ed.KeyDown(ch, modifiers)
END
END;
IF c.ed.changeCount # 0 THEN
IF c.SetFromEd() THEN END
END;
c.ed.RetainCaret;
c.Update^
END
END KeyDown;
PROCEDURE (c: UpDownField) Edit (op: INTEGER; VAR v: Views.View; VAR w, h: INTEGER;
VAR singleton, clipboard: BOOLEAN);
BEGIN
IF c.ed.ctl # NIL THEN
IF ~c.disabled & ~c.readOnly THEN
c.ed.changeCount := 0;
c.ed.Edit(op, v, clipboard);
IF c.ed.changeCount # 0 THEN
IF c.SetFromEd() THEN END
END;
c.Update^
END
END
END Edit;
PROCEDURE (c: UpDownField) Select (from, to: INTEGER);
BEGIN
IF c.ed.ctl # NIL THEN
c.ed.Select(from, to);
c.Update^
END
END Select;
PROCEDURE (c: UpDownField) GetSelection (OUT from, to: INTEGER);
BEGIN
IF c.ed.ctl # NIL THEN c.ed.GetSelection(from, to)
ELSE from := 0; to := MAX(INTEGER)
END
END GetSelection;
PROCEDURE (c: UpDownField) Idle;
BEGIN
c.ed.BlinkCaret
END Idle;
PROCEDURE (c: UpDownField) Mark (on_, focus_: BOOLEAN);
BEGIN
c.Update^
END Mark;
PROCEDURE (c: UpDownField) DblClickOk (x, y: INTEGER): BOOLEAN;
BEGIN
RETURN FALSE
END DblClickOk;
PROCEDURE (c: UpDownField) Update;
BEGIN
IF c.view # NIL THEN
c.UpdateEd;
IF c.ed.changeCount # 0 THEN
c.ed.RetainCaret
END;
c.Update^
END
END Update;
(** **************** ColorField **************** **)
PROCEDURE (c: ColorField) Restore (l, t, r, b: INTEGER);
VAR w, h, col: INTEGER;
BEGIN
c.view.context.GetSize(w, h);
IF c.readOnly OR c.disabled THEN
c.DrawRect(0, 0, w, h, Ports.fill, skin.backDisabled)
ELSE
IF c.front THEN col := skin.backHover
ELSE col := skin.back
END;
c.Get(c, col);
c.DrawRect(0, 0, w, h, Ports.fill, col);
IF c.front & (w > 8 * c.dot) & (h > 8 * c.dot) THEN
c.MarkRect(4 * c.dot, 4 * c.dot, w - 4 * c.dot, h - 4 * c.dot, 0, Ports.invert, Ports.show)
END
END;
IF c.readOnly THEN
c.DrawRect(0, 0, w, h, c.dot, skin.frameReadOnly)
ELSE
IF c.mark THEN
c.DrawRect(0, 0, w, h, c.dot * 2, skin.frameFocus)
ELSE
c.DrawRect(0, 0, w, h, c.dot, skin.frame)
END
END
END Restore;
PROCEDURE (c: ColorField) MouseDown (x, y: INTEGER; buttons: SET);
VAR
set: BOOLEAN;
col: INTEGER;
BEGIN
c.Get(c, col);
Dialog.GetColor(col, col, set);
IF set THEN
c.Set(c, col);
c.Update^
END
END MouseDown;
PROCEDURE (c: ColorField) Mark (on, focus_: BOOLEAN);
BEGIN
c.Update^
END Mark;
PROCEDURE (c: ColorField) DblClickOk (x, y: INTEGER): BOOLEAN;
BEGIN
RETURN FALSE
END DblClickOk;
PROCEDURE (c: ColorField) Update;
BEGIN
c.Update^
END Update;
(** **************** VScrollBar **************** **)
PROCEDURE (sb: VScrollBar) Init;
BEGIN
END Init;
(* draw it; called from `Restore()`; `dim` is main dimension size in pixels *)
PROCEDURE (sb: VScrollBar) Draw (c: Views.Frame; x, y, length: INTEGER; pressed: BOOLEAN);
VAR w, h, kpos, ksize, mbo, m: INTEGER; color: Ports.Color;
BEGIN
sb.length := length;
IF sb.CanFit() THEN
mbo := sb.Width();
w := sb.Width();
h := length;
c.DrawRect(x, y, x + w, y + h, Ports.fill, skin.backScrollbarButtons);
c.DrawRect(x, y + mbo, x + w, y + h - mbo, Ports.fill, skin.backScrollbar);
DrawArrowUp(c(StdCFrames.Frame), x + (w - 6 * Ports.point) DIV 2, y + 3 * Ports.point);
IF pressed THEN
color := skin.knobScrollbarPressed
ELSE
color := skin.knobScrollbar
END;
kpos := sb.CalcKnobPos(sb.pos) + mbo;
ksize := sb.CalcKnobSize();
m := skin.scrollbarKnobMargin * c.dot;
c.DrawRect(x+m, y+kpos+m, x+w-m, y+kpos+ksize-m, Ports.fill, color);
DrawArrowDown(c(StdCFrames.Frame), x + (w - 6 * Ports.point) DIV 2, y + h - 9 * Ports.point)
END
END Draw;
(* return TRUE if the caller need to track the mouse and call `MouseTrack()` *)
PROCEDURE (sb: VScrollBar) SBMouseDown (x, y: INTEGER): BOOLEAN;
VAR mbs, kpos, mbo, ksize, dsz: INTEGER; res: BOOLEAN;
BEGIN
res := FALSE;
mbs := sb.length - sb.Width() * 2;
IF mbs > 0 THEN
mbo := sb.Width();
kpos := sb.CalcKnobPos(sb.pos) + mbo;
ksize := sb.CalcKnobSize();
IF y < mbo THEN
(* top arrow *)
DEC(sb.pos, sb.arrowStep);
sb.pos := MAX(sb.min, MIN(sb.max, sb.pos))
ELSIF (y >= mbo) & (y < kpos) THEN
(* before the knob *)
sb.pos := MAX(sb.min, MIN(sb.max, sb.pos - sb.pageSize))
ELSIF (y >= kpos) & (y < kpos + ksize) THEN
(* on the knob *)
sb.trackStartY := y - mbo;
sb.trackOfsY := y - kpos;
sb.trackSavedPos := sb.pos;
res := TRUE
ELSIF (y >= kpos + ksize) & (y < mbo + mbs) THEN
(* after the knob *)
sb.pos := MAX(sb.min, MIN(sb.max, sb.pos + sb.pageSize))
ELSE
(* bottom arrow *)
INC(sb.pos, sb.arrowStep);
sb.pos := MAX(sb.min, MIN(sb.max, sb.pos))
END
END;
RETURN res
END SBMouseDown;
PROCEDURE (sb: VScrollBar) SBMouseTrack (x, y: INTEGER);
CONST area = 40 * Ports.point;
VAR length, res, ksz: INTEGER;
BEGIN
IF (x < -area) OR (y < -area) OR (x > sb.Width() + area) OR (y > sb.length + area) THEN
sb.pos := sb.trackSavedPos;
sb.trackStartY := MIN(INTEGER)
ELSE
length := sb.length - sb.Width() * 2;
DEC(y, sb.Width());
IF (y < 0) OR (sb.min >= sb.max) THEN
res := sb.min
ELSIF y = sb.trackStartY THEN
res := sb.pos
ELSIF y >= length THEN
res := sb.max
ELSE
ksz := sb.CalcKnobSize();
IF ksz < length THEN
DEC(y, sb.trackOfsY);
DEC(length, ksz);
res := MIN(sb.max, SHORT(LONG(sb.GetTotalSize()) * LONG(y) DIV LONG(length)));
IF res < sb.min THEN res := sb.min END
END
END;
sb.pos := res
END
END SBMouseTrack;
(** **************** HScrollBar **************** **)
PROCEDURE (sb: HScrollBar) Init;
BEGIN
END Init;
(* draw it; called from `Restore()`; `dim` is main dimension size in pixels *)
PROCEDURE (sb: HScrollBar) Draw (c: Views.Frame; x, y, length: INTEGER; pressed: BOOLEAN);
VAR w, h, kpos, ksize, mbo, m: INTEGER; color: Ports.Color;
BEGIN
sb.length := length;
IF sb.CanFit() THEN
mbo := sb.Width();
h := sb.Width();
w := length;
c.DrawRect(x, y, x + w, y + h, Ports.fill, skin.backScrollbarButtons);
c.DrawRect(x + mbo, y, x + w - mbo, y + h, Ports.fill, skin.backScrollbar);
DrawArrowLeft(c(StdCFrames.Frame), x + 3 * Ports.point, y + (h - 6 * Ports.point) DIV 2);
IF pressed THEN color := skin.knobScrollbarPressed ELSE color := skin.knobScrollbar END;
kpos := sb.CalcKnobPos(sb.pos) + mbo;
ksize := sb.CalcKnobSize();
m := skin.scrollbarKnobMargin * c.dot;
c.DrawRect(x+kpos+m, y+m, x+kpos+ksize-m, y+h-m, Ports.fill, color);
DrawArrowRight(c(StdCFrames.Frame), x + w - 9 * Ports.point, y + (h - 6 * Ports.point) DIV 2)
END
END Draw;
(* return TRUE if the caller need to track the mouse and call `MouseTrack()` *)
PROCEDURE (sb: HScrollBar) SBMouseDown (x, y: INTEGER): BOOLEAN;
VAR
mbs, kpos, mbo, ksz, dsz: INTEGER;
res: BOOLEAN;
BEGIN
res := FALSE;
mbs := sb.length - sb.Width() * 2;
IF mbs > 0 THEN
mbo := sb.Width();
kpos := sb.CalcKnobPos(sb.pos) + mbo;
ksz := sb.CalcKnobSize();
IF x < mbo THEN
(* left arrow *)
DEC(sb.pos, sb.arrowStep);
sb.pos := MAX(sb.min, MIN(sb.max, sb.pos))
ELSIF (x >= mbo) & (x < kpos) THEN
(* before the knob *)
sb.pos := MAX(sb.min, MIN(sb.max, sb.pos - sb.pageSize))
ELSIF (x >= kpos) & (x < kpos + ksz) THEN
(* on the knob *)
sb.trackStartX := x - mbo;
sb.trackOfsX := x - kpos;
sb.trackSavedPos := sb.pos;
res := TRUE
ELSIF (x >= kpos + ksz) & (x < mbo + mbs) THEN
(* after the knob *)
sb.pos := MAX(sb.min, MIN(sb.max, sb.pos + sb.pageSize))
ELSE
(* right arrow *)
INC(sb.pos, sb.arrowStep);
sb.pos := MAX(sb.min, MIN(sb.max, sb.pos))
END
END;
RETURN res
END SBMouseDown;
PROCEDURE (sb: HScrollBar) SBMouseTrack (x, y: INTEGER);
CONST area = 40 * Ports.point;
VAR dim, res, ksz: INTEGER;
BEGIN
IF (x < -area) OR (y < -area) OR (x > sb.length + area) OR (y > sb.Width() + area) THEN
sb.pos := sb.trackSavedPos;
sb.trackStartX := MIN(INTEGER)
ELSE
dim := sb.length - sb.Width() * 2;
DEC(x, sb.Width());
IF (x < 0) OR (sb.min >= sb.max) THEN
res := sb.min
ELSIF x = sb.trackStartX THEN
res := sb.pos
ELSIF x >= dim THEN
res := sb.max
ELSE
ksz := sb.CalcKnobSize();
IF ksz < dim THEN
DEC(x, sb.trackOfsX);
DEC(dim, ksz);
res := MIN(sb.max, SHORT(LONG(sb.GetTotalSize()) * LONG(x) DIV LONG(dim)));
IF res < sb.min THEN res := sb.min END;
END
END;
sb.pos := res
END
END SBMouseTrack;
(** **************** ScrollBar **************** **)
PROCEDURE (c: ScrollBar) Restore (l_, t_, r_, b_: INTEGER);
VAR w, h, size, sect, pos: INTEGER; vsb: VScrollBar; hsb: HScrollBar;
BEGIN
c.view.context.GetSize(w, h);
c.Get(c, size, sect, pos);
(*
size = size of embedded (wrapped) view
sect = size of section, which we see in aperture
pos = position of aperture
*)
IF h > w THEN
(* vertical *)
IF c.vsb = NIL THEN
NEW(vsb);
vsb.Init;
c.vsb := vsb
ELSE
vsb := c.vsb
END;
vsb.min := 0;
vsb.max := size - sect;
vsb.contentSize := size;
vsb.pos := pos;
vsb.pageSize := sect;
vsb.arrowStep := 5 * Ports.mm;
vsb.Draw(c, 0, w - vsb.Width(), h, c.vsbPressed)
ELSIF h < w THEN
(* horisontal *)
IF c.hsb = NIL THEN
NEW(hsb);
hsb.Init;
c.hsb := hsb
ELSE
hsb := c.hsb
END;
hsb.min := 0;
hsb.max := size - sect;
hsb.contentSize := size;
hsb.pos := pos;
hsb.pageSize := sect;
hsb.arrowStep := 5 * Ports.mm;
hsb.Draw(c, h - hsb.Width(), 0, w, c.hsbPressed)
END
END Restore;
PROCEDURE (c: ScrollBar) MouseDown (x, y: INTEGER; buttons: SET);
VAR w, h, size, sect, pos, riderSize: INTEGER; (* doc: Views.View; *)
mx, my: INTEGER; isDown: BOOLEAN; modifiers: SET;
mbs, kpos, mbo, ksize, dsz, catchPos: INTEGER; res: BOOLEAN;
vsb: VScrollBar; hsb: HScrollBar;
BEGIN
ASSERT(~c.disabled, 100);
(*
doc := Views.UltimateRootOf(c).view;
WITH doc: Documents.Document DO
Documents.RemoveOverlay(doc);
ELSE END;
*)
IF c.rider # NIL THEN
c.view.context.GetSize(w, h);
IF (h > w) & (c.vsb # NIL) THEN
(* vertical *)
vsb := c.vsb;
mbs := vsb.length - vsb.Width() * 2;
mbo := vsb.Width();
vsb.length := h;
c.Get(c, size, sect, vsb.pos);
kpos := vsb.CalcKnobPos(vsb.pos) + mbo;
ksize := vsb.CalcKnobSize();
IF y < mbo THEN
(* top arrow *)
DEC(vsb.pos, vsb.arrowStep);
vsb.pos := MAX(vsb.min, MIN(vsb.max, vsb.pos));
c.Set(c, vsb.pos); c.Update
ELSIF (y >= mbo) & (y < kpos) THEN
(* before the knob *)
vsb.pos := MAX(vsb.min, MIN(vsb.max, vsb.pos - vsb.pageSize));
c.Set(c, vsb.pos); c.Update
ELSIF (y >= kpos) & (y < kpos + ksize) THEN
(* on the knob *)
catchPos := y - kpos;
c.vsbPressed := TRUE;
REPEAT
c.Input(mx, my, modifiers, isDown);
c.Get(c, size, sect, pos);
c.Set(c, SHORT(ENTIER(size * ((my - mbo - catchPos) / (h - mbo * 2)))));
c.Update
UNTIL ~isDown OR (c.rider = NIL);
c.vsbPressed := FALSE;
c.Update
ELSIF (y >= kpos + ksize) & (y < mbo + mbs) THEN
(* after the knob *)
vsb.pos := MAX(vsb.min, MIN(vsb.max, vsb.pos + vsb.pageSize));
c.Set(c, vsb.pos); c.Update
ELSE
(* bottom arrow *)
INC(vsb.pos, vsb.arrowStep);
vsb.pos := MAX(vsb.min, MIN(vsb.max, vsb.pos));
c.Set(c, vsb.pos); c.Update
END
ELSIF (h < w) & (c.hsb # NIL) THEN
(* horizontal *)
hsb := c.hsb;
mbs := hsb.length - hsb.Width() * 2;
mbo := hsb.Width();
hsb.length := w;
c.Get(c, size, sect, hsb.pos);
kpos := hsb.CalcKnobPos(hsb.pos) + mbo;
ksize := hsb.CalcKnobSize();
IF x < mbo THEN
(* top arrow *)
DEC(hsb.pos, hsb.arrowStep);
hsb.pos := MAX(hsb.min, MIN(hsb.max, hsb.pos));
c.Set(c, hsb.pos); c.Update
ELSIF (x >= mbo) & (x < kpos) THEN
(* before the knob *)
hsb.pos := MAX(hsb.min, MIN(hsb.max, hsb.pos - hsb.pageSize));
c.Set(c, hsb.pos); c.Update
ELSIF (x >= kpos) & (x < kpos + ksize) THEN
(* on the knob *)
catchPos := x - kpos;
c.hsbPressed := TRUE;
REPEAT
c.Input(mx, my, modifiers, isDown);
c.Get(c, size, sect, pos);
c.Set(c, SHORT(ENTIER(size * ((mx - mbo - catchPos) / (w - mbo * 2)))));
c.Update
UNTIL ~isDown OR (c.rider = NIL);
c.hsbPressed := FALSE;
c.Update;
ELSIF (x >= kpos + ksize) & (x < mbo + mbs) THEN
(* after the knob *)
hsb.pos := MAX(hsb.min, MIN(hsb.max, hsb.pos + hsb.pageSize));
c.Set(c, hsb.pos); c.Update
ELSE
(* bottom arrow *)
INC(hsb.pos, hsb.arrowStep);
hsb.pos := MAX(hsb.min, MIN(hsb.max, hsb.pos));
c.Set(c, hsb.pos); c.Update
END
END
END
END MouseDown;
PROCEDURE (c: ScrollBar) DblClickOk (x, y: INTEGER): BOOLEAN;
BEGIN
RETURN FALSE
END DblClickOk;
PROCEDURE (c: ScrollBar) Update;
BEGIN
c.Update^
END Update;
(** **************** DateField **************** **)
PROCEDURE (c: DateField) GetDatePart (VAR date: Dates.Date; part: INTEGER; OUT val, min, max: INTEGER), NEW;
(* GetDatePart picks the day, month or year part out of a given date and asigns it to the out
parameter val, together with the min and max possible values for this part
*)
BEGIN
IF part = -1 THEN part := 3 END;
IF part = c.yearPart THEN val := date.year; min := 1; max := 9999
ELSIF part = c.monthPart THEN val := date.month; min := 1; max := 12
ELSE
val := date.day; min := 1;
IF date.month = 0 THEN
max := 31
ELSIF date.month = 2 THEN
(* leap year check *)
IF (date.year MOD 4 = 0) & ((date.year < 1583) OR (date.year MOD 100 # 0) OR (date.year MOD 400 = 0))
THEN
max := 29
ELSE max := 28
END
ELSIF date.month IN {1, 3, 5, 7, 8, 10, 12} THEN max := 31
ELSE max := 30
END
END
END GetDatePart;
PROCEDURE (c: DateField) SetDatePart (VAR date: Dates.Date; part: INTEGER; val: INTEGER), NEW;
(* SetDatePart sets the day, month or year part in a given date to the value specivied
by the parameter val.
If the month is set, the day is adjusted to the possible range of days in this month.
If the day is set, then the month may be changed in order to obtain a valid date
*)
VAR
v, min, max: INTEGER;
BEGIN
IF part = -1 THEN part := 3 END;
IF part = c.yearPart THEN date.year := val
ELSIF part = c.monthPart THEN date.month := val
ELSE date.day := val
END;
c.GetDatePart(date, c.dayPart, v, min, max);
IF (part = c.monthPart) THEN (* adjust day if month value is set and day > max *)
IF v > max THEN date.day := max END
ELSIF part = c.yearPart THEN (* adjust month is day value is set and day > max *)
IF v > max THEN INC(date.month) END
END
END SetDatePart;
PROCEDURE (c: DateField) DateToString (VAR date: Dates.Date; VAR str: ARRAY OF CHAR), NEW;
VAR
val, min, max, p, i: INTEGER;
BEGIN
p := 1; i := 0;
WHILE p <= 3 DO
IF p > 1 THEN str[i] := c.dateSep; INC(i) END;
c.GetDatePart(date, p, val, min, max);
IF max = 9999 THEN
str[i] := CHR(val DIV 1000 MOD 10 + ORD("0")); INC(i);
str[i] := CHR(val DIV 100 MOD 10 + ORD("0")); INC(i)
END;
str[i] := CHR(val DIV 10 MOD 10 + ORD("0")); INC(i);
str[i] := CHR(val MOD 10 + ORD("0")); INC(i);
INC(p)
END;
str[i] := 0X
END DateToString;
PROCEDURE (c: DateField) Select, NEW;
VAR
sel, f, t: INTEGER;
BEGIN
IF c.ed.ctl # NIL THEN
c.GetSel(c, sel);
CASE sel OF
| 1: f := 0; t := c.del1
| 2: f := c.del1 + 1; t := c.del2
ELSE f := c.del2 + 1; t := c.del2 + 5
END;
c.ed.Select(f, t)
END
END Select;
PROCEDURE (c: DateField) UpdateEd, NEW;
VAR
ps: EditorCommonText;
date: Dates.Date;
s: ARRAY 20 OF CHAR;
BEGIN
c.ed.SetupCtl(c);
c.ed.changeCount := 0;
c.ed.maxLen := 10; c.ed.password := FALSE;
c.ed.left := TRUE; c.ed.right := FALSE;
IF c.undef THEN
s := ""
ELSE
c.Get(c, date);
c.DateToString(date, s)
END;
IF c.ed.SetText(s) THEN INC(c.ed.changeCount) END;
c.Select
END UpdateEd;
PROCEDURE (c: DateField) Restore (l_, t_, r_, b_: INTEGER);
VAR
w, h: INTEGER;
BEGIN
SetupDialogBackground(c);
IF c.ed.ctl = NIL THEN c.UpdateEd END;
c.view.context.GetSize(w, h);
c.ed.Setup(c, c.dot, c.dot, w - 2 * c.dot, h - 2 * c.dot);
c.ed.outMargin.SetUni(1);
c.ed.Restore;
IF c.readOnly THEN
c.DrawRect(0, 0, w, h, c.dot, skin.frameReadOnly)
ELSE
IF c.mark THEN
c.DrawRect(0, 0, w, h, c.dot * 2, skin.frameFocus)
ELSE
c.DrawRect(0, 0, w, h, c.dot, skin.frame)
END
END
END Restore;
PROCEDURE (c: DateField) Edit (op: INTEGER; VAR v: Views.View; VAR w, h: INTEGER;
VAR singleton, clipboard: BOOLEAN);
BEGIN
IF c.ed.ctl # NIL THEN
IF clipboard & (op = Controllers.copy) THEN
c.ed.changeCount := 0;
(* copy the whole string *)
c.ed.Select(0, 1024);
c.ed.Edit(op, v, clipboard);
c.Select
END
END
END Edit;
PROCEDURE (c: DateField) WheelMove (x, y, op, nofLines: INTEGER; VAR done: BOOLEAN);
VAR
mods: SET; isDown: BOOLEAN;
BEGIN
IF c.ed.ctl # NIL THEN
done := TRUE; (* eat it! *)
(* hack! *)
c.Input(x, y, mods, isDown);
IF mods * {Controllers.pick, Controllers.extend} # {} THEN INCL(mods, Controllers.modify) END;
IF op IN {Controllers.incLine, Controllers.incPage} THEN c.KeyDown(AD, mods)
ELSE c.KeyDown(AU, mods)
END
END
END WheelMove;
PROCEDURE (c: DateField) MouseDown (x, y: INTEGER; buttons: SET);
VAR
p, cp: INTEGER;
BEGIN
IF c.ed.ctl # NIL THEN
c.ed.changeCount := 0;
c.ed.MouseDown(x, y, buttons);
(* fix selection *)
IF c.ed.from < c.ed.to THEN p := c.ed.from ELSE p := c.ed.pos END;
IF p <= c.del1 THEN p := 1
ELSIF p <= c.del2 THEN p := 2
ELSE p := 3
END;
c.SetSel(c, p);
c.Select;
c.Update^
END
END MouseDown;
PROCEDURE (c: DateField) KeyDown (ch: CHAR; modifiers: SET);
VAR
sel, s, val, v, min, max, dd: INTEGER;
date: Dates.Date;
setNow: BOOLEAN;
BEGIN
IF c.ed.ctl # NIL THEN
setNow := FALSE;
c.ed.changeCount := 0;
c.GetSel(c, sel); s := sel;
IF s < 1 THEN s := 3 END;
c.Get(c, date);
c.GetDatePart(date, s, val, min, max); v := val;
CASE ch OF
| TAB, AR, ':', '/', ' ': s := s MOD 3 + 1
| LTAB, AL: IF s = 0 THEN s := 1 END; s := (s - 2) MOD 3 + 1
| PL, DL: s := 1
| PR, DR: s := 3
| DELETE, BACKSPACE: v := min
| AU:
IF Controllers.modify IN modifiers THEN dd := 10 ELSE dd := 1 END;
v := (v - min - dd) MOD (max - min + 1) + min
| AD:
IF Controllers.modify IN modifiers THEN dd := 10 ELSE dd := 1 END;
v := (v - min + dd) MOD (max - min + 1) + min
ELSE
(*
IF (ch >= "0") & (ch <= "9") THEN
v := v * 10 MOD 100 + ORD(ch) - ORD("0");
IF v > max THEN v := v MOD 10 ELSIF v < min THEN v := min END
ELSIF (ch = 'n') OR (ch = 'N') THEN
setNow := TRUE
END
*)
setNow := (ch = 'n') OR (ch = 'N');
END;
IF setNow THEN
IF ~c.disabled & ~c.readOnly THEN
Dates.GetDate(date); c.Set(c, date); c.Update
END
ELSIF v # val THEN
IF ~c.disabled & ~c.readOnly THEN
c.GetDatePart(date, s, val, min, max);
IF (min <= v) & (v <= max) THEN
c.SetDatePart(date, s, v); c.Set(c, date); c.Update
END
END
ELSIF s # sel THEN
c.SetSel(c, s); c.Select
END;
c.ed.RetainCaret;
c.Update^
END
END KeyDown;
PROCEDURE (c: DateField) Mark (on_, focus_: BOOLEAN);
BEGIN
c.Update^
END Mark;
PROCEDURE (c: DateField) DblClickOk (x, y: INTEGER): BOOLEAN;
BEGIN
RETURN TRUE
END DblClickOk;
(* called when the text is updated by the external actor *)
PROCEDURE (c: DateField) Update;
BEGIN
c.UpdateEd;
IF c.ed.changeCount # 0 THEN
c.ed.RetainCaret;
c.Update^
END
END Update;
(** **************** TimeField **************** **)
PROCEDURE GetTimePart (VAR time: Dates.Time; part: INTEGER; VAR val, min, max: INTEGER);
BEGIN
IF part = -1 THEN part := 3 END;
IF part = 4 THEN val := time.hour DIV 12; min := 0; max := 1
ELSIF part = 3 THEN val := time.second; min := 0; max := 59
ELSIF part = 2 THEN val := time.minute; min := 0; max := 59
ELSE val := time.hour; min := 0; max := 23
END
END GetTimePart;
PROCEDURE SetTimePart (VAR time: Dates.Time; part: INTEGER; val: INTEGER);
BEGIN
IF part = -1 THEN part := 3 END;
IF part = 4 THEN time.hour := val * 12 + time.hour MOD 12
ELSIF part = 3 THEN time.second := val
ELSIF part = 2 THEN time.minute := val
ELSE time.hour := val
END
END SetTimePart;
PROCEDURE TimeToString (VAR time: Dates.Time; VAR str: ARRAY OF CHAR);
CONST
timeSep = ':';
VAR
val, min, max, i, j, k: INTEGER;
BEGIN
GetTimePart(time, 1, val, min, max);
str[0] := CHR(val DIV 10 + ORD("0"));
str[1] := CHR(val MOD 10 + ORD("0"));
str[2] := timeSep;
GetTimePart(time, 2, val, min, max);
str[3] := CHR(val DIV 10 + ORD("0"));
str[4] := CHR(val MOD 10 + ORD("0"));
str[5] := timeSep;
GetTimePart(time, 3, val, min, max);
str[6] := CHR(val DIV 10 + ORD("0"));
str[7] := CHR(val MOD 10 + ORD("0"));
str[8] := 0X
END TimeToString;
PROCEDURE (c: TimeField) Select, NEW;
VAR
sel: INTEGER;
BEGIN
IF c.ed.ctl # NIL THEN
c.GetSel(c, sel);
IF sel = -1 THEN sel := 3 END;
c.ed.Select(3 * sel - 3, 3 * sel - 1)
END
END Select;
PROCEDURE (c: TimeField) UpdateEd, NEW;
VAR
ps: EditorCommonText;
time: Dates.Time;
s: ARRAY 20 OF CHAR;
BEGIN
c.ed.SetupCtl(c);
c.ed.changeCount := 0;
c.ed.maxLen := 10; c.ed.password := FALSE;
c.ed.left := TRUE; c.ed.right := FALSE;
IF c.undef THEN
s := ""
ELSE
c.Get(c, time);
TimeToString(time, s)
END;
IF c.ed.SetText(s) THEN INC(c.ed.changeCount) END;
c.Select
END UpdateEd;
PROCEDURE (c: TimeField) Restore (l_, t_, r_, b_: INTEGER);
VAR
w, h: INTEGER;
BEGIN
SetupDialogBackground(c);
IF c.ed.ctl = NIL THEN c.UpdateEd END;
c.view.context.GetSize(w, h);
c.ed.Setup(c, c.dot, c.dot, w - 2 * c.dot, h - 2 * c.dot);
c.ed.outMargin.SetUni(1);
c.ed.Restore;
IF c.readOnly THEN
c.DrawRect(0, 0, w, h, c.dot, skin.frameReadOnly)
ELSE
IF c.mark THEN
c.DrawRect(0, 0, w, h, c.dot * 2, skin.frameFocus)
ELSE
c.DrawRect(0, 0, w, h, c.dot, skin.frame)
END
END
END Restore;
PROCEDURE (c: TimeField) Edit (op: INTEGER; VAR v: Views.View; VAR w, h: INTEGER;
VAR singleton, clipboard: BOOLEAN);
BEGIN
IF c.ed.ctl # NIL THEN
IF clipboard & (op = Controllers.copy) THEN
c.ed.changeCount := 0;
(* copy the whole string *)
c.ed.Select(0, 1024);
c.ed.Edit(op, v, clipboard);
c.Select
END
END
END Edit;
PROCEDURE (c: TimeField) WheelMove (x, y, op, nofLines: INTEGER; VAR done: BOOLEAN);
VAR
mods: SET; isDown: BOOLEAN;
BEGIN
IF c.ed.ctl # NIL THEN
done := TRUE; (* eat it! *)
(* hack! *)
c.Input(x, y, mods, isDown);
IF mods * {Controllers.pick, Controllers.extend} # {} THEN INCL(mods, Controllers.modify) END;
IF op IN {Controllers.incLine, Controllers.incPage} THEN c.KeyDown(AD, mods)
ELSE c.KeyDown(AU, mods)
END
END
END WheelMove;
PROCEDURE (c: TimeField) MouseDown (x, y: INTEGER; buttons: SET);
VAR
p, cp: INTEGER;
BEGIN
IF c.ed.ctl # NIL THEN
c.ed.changeCount := 0;
c.ed.MouseDown(x, y, buttons);
(* fix selection *)
IF c.ed.from < c.ed.to THEN p := c.ed.from ELSE p := c.ed.pos END;
p := MAX(0, p) DIV 3 + 1;
IF p <= 3 THEN
c.SetSel(c, p);
c.Select
END;
c.Update^
END
END MouseDown;
PROCEDURE (c: TimeField) KeyDown (ch: CHAR; modifiers: SET);
VAR
sel, s, val, v, min, max, dd: INTEGER;
time: Dates.Time;
setNow: BOOLEAN;
BEGIN
IF c.ed.ctl # NIL THEN
setNow := FALSE;
c.ed.changeCount := 0;
c.GetSel(c, sel); s := sel;
IF s = -1 THEN s := 3 END;
c.Get(c, time);
GetTimePart(time, s, val, min, max); v := val;
CASE ch OF
| TAB, AR, ':', '/', ' ': s := s MOD 3 + 1;
| LTAB, AL: DEC(s); IF s <= 0 THEN s := 3 END
| PL, DL: s := 1
| PR, DR: s := 3
| DELETE, BACKSPACE: v := min
| AU:
IF Controllers.modify IN modifiers THEN dd := 10 ELSE dd := 1 END;
v := (v - min - dd) MOD (max - min + 1) + min
| AD:
IF Controllers.modify IN modifiers THEN dd := 10 ELSE dd := 1 END;
v := (v - min + dd) MOD (max - min + 1) + min
ELSE
(*
IF (ch >= "0") & (ch <= "9") THEN
v := v * 10 MOD 100 + ORD(ch) - ORD("0");
IF v > max THEN v := v MOD 10 ELSIF v < min THEN v := min END
ELSIF (ch = 'n') OR (ch = 'N') THEN
setNow := TRUE
END
*)
setNow := (ch = 'n') OR (ch = 'N')
END;
IF setNow THEN
IF ~c.disabled & ~c.readOnly THEN
Dates.GetTime(time); c.Set(c, time); c.Update
END
ELSIF v # val THEN
IF ~c.disabled & ~c.readOnly THEN
SetTimePart(time, s, v); c.Set(c, time); c.Update
END
ELSIF s # sel THEN
c.SetSel(c, s); c.Select
END;
c.ed.RetainCaret;
c.Update^
END
END KeyDown;
PROCEDURE (c: TimeField) Mark (on_, focus_: BOOLEAN);
BEGIN
c.Update^
END Mark;
PROCEDURE (c: TimeField) DblClickOk (x, y: INTEGER): BOOLEAN;
BEGIN
RETURN TRUE
END DblClickOk;
(* called when the text is updated by the external actor *)
PROCEDURE (c: TimeField) Update;
BEGIN
c.UpdateEd;
IF c.ed.changeCount # 0 THEN
c.ed.RetainCaret;
c.Update^
END
END Update;
(* TreeFrame *)
PROCEDURE (f: TreeFrame) DblClickOk (x, y: INTEGER): BOOLEAN;
BEGIN
RETURN TRUE
END DblClickOk;
PROCEDURE (c: TreeFrame) TreeTrackVSBMouse (), NEW;
VAR
x, y, ox, oy, opos: INTEGER; isDown: BOOLEAN; modifiers: SET;
BEGIN
IF c.rider # NIL THEN
c.vsbPressed := TRUE;
UpdateRoot(c);
c.ForceUpdate;
opos := c.vsb.pos;
ox := MIN(INTEGER); oy := MIN(INTEGER);
REPEAT
c.Input(x, y, modifiers, isDown);
x := x - c.vsb.x0;
y := y - c.vsb.y0;
IF ox = MIN(INTEGER) THEN ox := x END;
IF oy = MIN(INTEGER) THEN oy := y END;
IF (ox # x) OR (oy # y) THEN
ox := x; oy := y;
c.vsb.SBMouseTrack(x, y);
IF opos # c.vsb.pos THEN
opos := c.vsb.pos;
c.yoffs := opos;
c.ForceUpdate
END
END
UNTIL ~isDown;
c.vsbPressed := FALSE;
c.ForceUpdate
END
END TreeTrackVSBMouse;
PROCEDURE (c: TreeFrame) TreeTrackHSBMouse (), NEW;
VAR x, y, ox, oy, opos: INTEGER; isDown: BOOLEAN; modifiers: SET;
BEGIN
IF c.rider # NIL THEN
c.hsbPressed := TRUE;
UpdateRoot(c);
c.ForceUpdate;
opos := c.hsb.pos;
ox := MIN(INTEGER); oy := MIN(INTEGER);
REPEAT
c.Input(x, y, modifiers, isDown);
x := x - c.hsb.x0;
y := y - c.hsb.y0;
IF ox = MIN(INTEGER) THEN ox := x END;
IF oy = MIN(INTEGER) THEN oy := y END;
IF (ox # x) OR (oy # y) THEN
ox := x; oy := y;
c.hsb.SBMouseTrack(x, y);
IF opos # c.hsb.pos THEN
opos := c.hsb.pos;
c.xoffs := opos;
c.ForceUpdate
END
END
UNTIL ~isDown;
c.hsbPressed := FALSE;
c.ForceUpdate
END
END TreeTrackHSBMouse;
PROCEDURE (f: TreeFrame) CheckYPos (h: INTEGER), NEW;
VAR treeHeight: INTEGER;
BEGIN
IF f.yoffs < 0 THEN
f.yoffs := 0
ELSE
treeHeight := (f.lines + 1) * f.lineHeight;
IF treeHeight < h THEN
f.yoffs := 0
ELSE
IF f.yoffs > (treeHeight - h) THEN
f.yoffs := (treeHeight - h)
END
END
END;
END CheckYPos;
PROCEDURE (f: TreeFrame) MouseDown (x, y: INTEGER; buttons: SET);
VAR w, h, id: INTEGER;
BEGIN
IF f.view = NIL THEN RETURN END;
f.view.context.GetSize(w, h);
IF (f.vsb # NIL) & (f.vsb.length > 0) & (w - x < f.vsb.Width()) THEN
IF f.vsb.SBMouseDown(x - f.vsb.x0, y - f.vsb.y0) THEN
f.TreeTrackVSBMouse
ELSE
f.yoffs := f.vsb.pos (* the caller will repaint us *)
END
ELSIF (f.hsb # NIL) & (f.hsb.length > 0) & (h - y < f.hsb.Width()) THEN
IF f.hsb.SBMouseDown(x - f.hsb.x0, y - f.hsb.y0) THEN
f.TreeTrackHSBMouse
ELSE
f.xoffs := f.hsb.pos (* the caller will repaint us *)
END
ELSIF ~ f.readOnly & (f.lines > 0) THEN
id := (y + f.yoffs - f.lineHeight DIV 3) DIV f.lineHeight;
id := MAX(0, MIN(id, f.lines - 1) );
IF f.nodesCache # NIL THEN
IF x > f.nodesCache[id].p THEN
f.Select(f, f.nodesCache[id].n);
IF (Controllers.doubleClick IN buttons) THEN
IF f.nodesCache[id].n.IsExpanded() THEN
f.SetExpansion(f, f.nodesCache[id].n, FALSE)
ELSE
f.SetExpansion(f, f.nodesCache[id].n, TRUE)
END;
END;
ELSE
IF f.nodesCache[id].n.IsExpanded() THEN
f.SetExpansion(f, f.nodesCache[id].n, FALSE)
ELSE
f.SetExpansion(f, f.nodesCache[id].n, TRUE)
END;
END;
f.CheckYPos(h);
f.Update
END
END
END MouseDown;
PROCEDURE (f: TreeFrame) WheelMove (x, y, op, nofLines: INTEGER; VAR done: BOOLEAN);
VAR asc, dsc, sw, w, h: INTEGER;
BEGIN
f.view.context.GetSize(w, h);
done := TRUE;
IF op = Controllers.decLine THEN nofLines := -nofLines END;
f.font.GetBounds(asc, dsc, sw);
INC(f.yoffs, (asc + dsc) * nofLines);
f.CheckYPos(h);
f.Update
END WheelMove;
PROCEDURE (f: TreeFrame) Restore (l, t, r, b: INTEGER);
VAR sel: Dialog.TreeNode; bkcol, w, h, int: INTEGER;
str: Dialog.String; asc, dsc, sw, x, y, i: INTEGER;
vsb: VScrollBar; vsbSize: INTEGER; hsb: HScrollBar; hsbSize: INTEGER;
portState: BOOLEAN; selPath: ARRAY 16 OF Dialog.TreeNode;
PROCEDURE AddNodeToCache (node: Dialog.TreeNode; pos, i: INTEGER);
VAR nc: POINTER TO ARRAY OF NodeItem;
BEGIN
IF f.nodesCache = NIL THEN
IF i < 128 THEN
NEW(f.nodesCache, 128)
ELSE
NEW(f.nodesCache, i * 2)
END
ELSE
IF i >= LEN(f.nodesCache) THEN
NEW(nc, LEN(f.nodesCache)*2);
FOR i := 0 TO LEN(f.nodesCache) - 1 DO
nc[i] := f.nodesCache[i]
END;
f.nodesCache := nc
END
END;
f.nodesCache[i].n := node;
f.nodesCache[i].p := pos;
END AddNodeToCache;
PROCEDURE InSelPath (node: Dialog.TreeNode): BOOLEAN;
VAR i: INTEGER; res: BOOLEAN;
BEGIN
i := 0; res := FALSE;
WHILE ~ res & (selPath[i] # NIL) DO
IF selPath[i] = node THEN res := TRUE END;
INC(i)
END;
RETURN res
END InSelPath;
PROCEDURE DrawTriangle(f: Views.Frame; x, y: INTEGER; open: BOOLEAN);
VAR path: ARRAY 3 OF Ports.Point; point, point2, point3, point4: INTEGER;
BEGIN
point := Ports.point;
point2 := 2 * Ports.point - (2 * Ports.point) MOD f.unit;
point3 := 3 * Ports.point - (3 * Ports.point) MOD f.unit;
point4 := 4 * Ports.point - (4 * Ports.point) MOD f.unit;
IF open THEN
path[0].x := x - point2;
path[0].y := y + point;
path[1].x := x + point3;
path[1].y := y + point;
path[2].x := x + point3;
path[2].y := y - point4;
f.DrawPath(path, 3, Ports.fill, Ports.black, Ports.closedPoly)
ELSE
path[0].x := x;
path[0].y := y - point3;
path[1].x := x;
path[1].y := y + point3;
path[2].x := x + point3;
path[2].y := y;
f.DrawPath(path, 3, f.dot, Ports.grey50, Ports.closedPoly)
END
END DrawTriangle;
PROCEDURE DrawLeaves (node: Dialog.TreeNode; lev: INTEGER);
VAR n, nextNode: Dialog.TreeNode;
xShift, w, prevLineSameLevel: INTEGER;
exp: BOOLEAN;
BEGIN
n := f.Child(f, node);
IF f.haslines & (node # NIL) THEN
nextNode := f.Next(f, n);
IF (nextNode # NIL) & nextNode.IsFolder() THEN
sw := 3 * Ports.point
ELSE
sw := 0
END;
(* first vertical line *)
(*
f.MarkRect(
f.leftMargin + lev * Ports.point,
f.lineHeight * f.lines + f.strHeight DIV 4 - f.yoffs,
f.leftMargin + lev * Ports.point + f.dot,
f.lineHeight * (f.lines+1) - f.strHeight DIV 4 - f.yoffs - sw, f.dot,
Ports.dim50, Ports.show)
*)
f.DrawLine(
f.leftMargin + lev * Ports.point,
f.lineHeight * f.lines + f.strHeight DIV 4 - f.yoffs,
f.leftMargin + lev * Ports.point,
f.lineHeight * (f.lines+1) - f.strHeight DIV 4 - f.yoffs - sw,
f.dot, Ports.grey25)
END;
WHILE n # NIL DO
n.GetName(str);
nextNode := f.Next(f, n);
INC(f.lines);
IF f.haslines THEN
xShift := 5 * Ports.point;
prevLineSameLevel := f.lines;
ELSE
xShift := 0
END;
x := f.leftMargin + xShift + (lev + 5) * Ports.point;
y := f.lineHeight * f.lines - f.yoffs;
AddNodeToCache(n, x, f.lines-1);
w := f.font.StringWidth(str);
IF w > f.maxWidth THEN f.maxWidth := w END;
IF n = sel THEN
f.DrawRect(
x + 11 * Ports.point,
y - f.strHeight + 1 * Ports.point,
x + w + 3 * Ports.point + 13 * Ports.point,
y + 4 * Ports.point,
Ports.fill, Ports.grey12 (* skin.backHover *) )
END;
IF f.haslines THEN
IF n.IsFolder() THEN
sw := 4 * Ports.point
ELSE
sw := 0
END;
(* horizontal *)
(*
f.MarkRect(
f.leftMargin + lev * Ports.point + sw,
f.lineHeight * f.lines - f.strHeight DIV 4 - f.yoffs,
f.leftMargin + (lev + 9) * Ports.point,
f.lineHeight * f.lines - f.strHeight DIV 4 - f.yoffs + f.dot, f.dot,
Ports.dim50, Ports.show);
*)
f.DrawLine(
f.leftMargin + lev * Ports.point + sw,
f.lineHeight * f.lines - f.strHeight DIV 4 - f.yoffs,
f.leftMargin + (lev + 8) * Ports.point,
f.lineHeight * f.lines - f.strHeight DIV 4 - f.yoffs,
f.dot, Ports.grey25)
END;
exp := InSelPath(n) OR n.IsExpanded();
sw := f.strHeight - 3 * Ports.point;
asc := - 2 * Ports.point;
IF n.IsFolder() THEN
IF exp THEN
f.DrawRaster(folderopen.raster, x + asc, y - sw)
ELSE
f.DrawRaster(folder.raster, x + asc, y - sw)
END
ELSE
(*
IF n.leafType = Dialog.leaf_notOk THEN
f.DrawRaster(leafNotOk.raster, x + asc, y - sw)
ELSIF n.leafType = Dialog.leaf_ok THEN
f.DrawRaster(leafOk.raster, x + asc, y - sw)
ELSE
*)
f.DrawRaster(leaf.raster, x + asc, y - sw)
(*
END
*)
END;
IF n.IsFolder() THEN
DrawTriangle(f,
f.leftMargin + (lev - 1) * Ports.point,
f.lineHeight * f.lines - f.strHeight DIV 4 - f.yoffs,
exp)
END;
f.DrawString(x + 13 * Ports.point, y, skin.textList, str, f.font);
IF exp & (n.NofChildren() > 0) THEN
DrawLeaves(n, lev + 10)
END;
IF f.haslines & (nextNode # NIL) THEN
IF n.IsFolder() THEN
sw := 4 * Ports.point
ELSE
sw := 0
END;
IF (nextNode # NIL) & nextNode.IsFolder() THEN
asc := 3 * Ports.point
ELSE
asc := 0
END;
(*
f.MarkRect(
f.leftMargin + lev * Ports.point,
f.lineHeight * prevLineSameLevel - f.strHeight DIV 4 - f.yoffs + sw,
f.leftMargin + lev * Ports.point + f.dot,
f.lineHeight * (f.lines+1) - f.strHeight DIV 4 - f.yoffs - asc, f.dot,
Ports.dim50, Ports.show);
*)
f.DrawLine(
f.leftMargin + lev * Ports.point,
f.lineHeight * prevLineSameLevel - f.strHeight DIV 4 - f.yoffs + sw,
f.leftMargin + lev * Ports.point,
f.lineHeight * (f.lines+1) - f.strHeight DIV 4 - f.yoffs - asc,
f.dot, Ports.grey25);
END;
n := nextNode
END
END DrawLeaves;
BEGIN
f.view.context.GetSize(w, h);
f.font.GetBounds(asc, dsc, sw);
f.strHeight := asc + dsc;
f.lineHeight := (f.strHeight DIV 3) * 4;
IF f.disabled OR f.readOnly THEN
bkcol := skin.backListDisabled
ELSIF f.mark THEN
bkcol := skin.backList
ELSE
bkcol := skin.backListBlured
END;
f.DrawRect(0, 0, w, h, Ports.fill, bkcol);
sel := f.Selected(f);
i := 0;
WHILE sel # NIL DO
sel := f.Parent(f, sel);
selPath[i] := sel;
INC(i)
END;
sel := f.Selected(f);
f.lines := 0;
f.maxWidth := 0;
DrawLeaves(NIL, 0);
f.totalHeight := f.lineHeight * (f.lines + 1);
(* tree scroll bars *)
IF f.totalHeight > h THEN
IF f.vsb = NIL THEN
NEW(vsb);
vsb.Init;
f.vsb := vsb
ELSE
vsb := f.vsb
END;
vsb.min := 0;
vsb.max := f.totalHeight - h;
vsb.contentSize := f.totalHeight;
vsb.pos := f.yoffs;
vsb.pageSize := h;
vsb.arrowStep := f.lineHeight;
vsb.length := h;
IF ~vsb.CanFit() THEN
vsb := NIL
ELSE
vsbSize := MAX(0, vsb.Width());
vsb.length := h - vsb.Width();
IF (vsbSize = 0) OR ((vsbSize + 4 * Ports.point) >= w) THEN
vsb := NIL
END
END
ELSE
vsb := NIL
END;
IF vsb = NIL THEN vsbSize := 0; f.vsb := NIL END;
IF (f.maxWidth > (w - vsbSize)) & (h > f.lineHeight * 2) THEN
IF f.hsb = NIL THEN
NEW(hsb);
hsb.Init;
f.hsb := hsb
ELSE
hsb := f.hsb
END;
hsb.min := 0;
hsb.max := (f.maxWidth - w + vsbSize + Ports.mm);
hsb.contentSize := f.maxWidth;
hsb.pos := f.xoffs;
hsb.pageSize := w;
hsb.arrowStep := Ports.mm;
hsb.length := w;
IF ~hsb.CanFit() THEN
hsb := NIL
ELSE
hsbSize := MAX(0, hsb.Width());
hsb.length := w;
IF vsb # NIL THEN
DEC(hsb.length, vsbSize);
DEC(vsb.length, hsbSize)
END;
IF (hsbSize = 0) OR ((hsbSize + 4 * Ports.point) >= h) THEN
hsbSize := 0; hsb := NIL
END
END;
IF vsb # NIL THEN
INC(vsb.max, hsbSize);
INC(hsb.max, vsbSize);
END;
ELSE
f.hsb := NIL; hsbSize := 0; hsb := NIL;
END;
IF vsb # NIL THEN
vsb.x0 := w - vsbSize - Ports.point;
vsb.y0 := 0;
vsb.Draw(f, vsb.x0, vsb.y0, h - hsbSize, f.vsbPressed);
END;
IF hsb # NIL THEN
hsb.x0 := 0;
hsb.y0 := h - hsbSize;
hsb.Draw(f, hsb.x0, hsb.y0, w - vsbSize, f.hsbPressed);
END;
IF (hsbSize > 0) & (vsbSize > 0) THEN
f.DrawRect(w - vsbSize, h - hsbSize, w + 2 * f.dot, h + 2 * f.dot, Ports.fill, skin.backScrollbar)
END;
(* outer frame *)
IF f.readOnly THEN
f.DrawRect(0, 0, w, h, f.dot, skin.frameReadOnly)
ELSE
IF f.mark THEN
f.DrawRect(0, 0, w, h, f.dot * 2, skin.frameFocus)
ELSE
f.DrawRect(0, 0, w, h, f.dot, skin.frame)
END
END
END Restore;
PROCEDURE (f: TreeFrame) KeyDown (ch: CHAR; modifiers: SET);
VAR sel, parent, child, next, prev: Dialog.TreeNode;
BEGIN
CASE ch OF
| AL: (* arrow left *)
sel := f.Selected(f);
IF sel # NIL THEN
IF sel.IsExpanded() THEN
f.SetExpansion(f, sel, FALSE);
f.Update
END
END
| AR: (* arrow right *)
sel := f.Selected(f);
IF sel # NIL THEN
IF ~sel.IsExpanded() THEN
f.SetExpansion(f, sel, TRUE);
f.Update
END
END
| AU: (* arrow up *)
sel := f.Selected(f);
IF sel # NIL THEN
parent := f.Parent(f, sel);
prev := NIL;
next := f.Child(f, parent);
WHILE (next # NIL) & (sel # next) DO
prev := next;
next := f.Next(f, next)
END;
IF prev = NIL THEN
IF parent # NIL THEN
f.Select(f, parent);
f.Update
END
ELSE
IF sel = next THEN
f.Select(f, prev);
f.Update
END
END
END
| AD: (* arrow down *)
sel := f.Selected(f);
IF sel # NIL THEN
IF sel.IsExpanded() THEN
child := f.Child(f, sel);
IF child # NIL THEN
f.Select(f, child);
f.Update
ELSE
sel := f.Next(f, sel);
IF sel # NIL THEN
f.Select(f, sel);
f.Update
END
END
ELSE
next := f.Next(f, sel);
IF next # NIL THEN
f.Select(f, next);
f.Update
ELSE
parent := f.Parent(f, sel);
IF parent # NIL THEN
next := f.Next(f, parent);
IF next # NIL THEN
f.Select(f, next);
f.Update
END
END;
END
END
END
ELSE
END
END KeyDown;
PROCEDURE (f: TreeFrame) GetSize (OUT w, h: INTEGER);
BEGIN
f.view.context.GetSize(w, h)
END GetSize;
(* Directory *)
PROCEDURE (d: Directory) GetPushButtonSize (VAR w, h: INTEGER);
BEGIN
IF w = Views.undefined THEN w := 56 * Ports.point END;
IF h = Views.undefined THEN h := 28 * Ports.point END (* 18 on Windows *)
END GetPushButtonSize;
PROCEDURE (d: Directory) GetCheckBoxSize (VAR w, h: INTEGER);
BEGIN
IF w = Views.undefined THEN w := 60 * Ports.point END;
IF h = Views.undefined THEN h := 12 * Ports.point END
END GetCheckBoxSize;
PROCEDURE (d: Directory) GetRadioButtonSize (VAR w, h: INTEGER);
BEGIN
IF w = Views.undefined THEN w := 60 * Ports.point END;
IF h = Views.undefined THEN h := 12 * Ports.point END
END GetRadioButtonSize;
PROCEDURE (d: Directory) GetScrollBarSize (VAR w, h: INTEGER);
BEGIN
IF w = Views.undefined THEN w := 120 * Ports.point END;
IF h = Views.undefined THEN h := 12 * Ports.point END
END GetScrollBarSize;
PROCEDURE (d: Directory) GetFieldSize (max: INTEGER; VAR w, h: INTEGER);
BEGIN
IF w = Views.undefined THEN
IF max = 0 THEN w := 80 * Ports.point
ELSIF max < 10 THEN w := 32 * Ports.point
ELSIF max < 15 THEN w := 56 * Ports.point
ELSIF max < 30 THEN w := 80 * Ports.point
ELSIF max < 100 THEN w := 120 * Ports.point
ELSE w := 150 * Ports.point
END
END;
IF h = Views.undefined THEN h := 17 * Ports.point END
END GetFieldSize;
PROCEDURE (d: Directory) GetUpDownFieldSize (max: INTEGER; VAR w, h: INTEGER);
BEGIN
IF w = Views.undefined THEN w := 56 * Ports.point END;
IF h = Views.undefined THEN h := 17 * Ports.point END
END GetUpDownFieldSize;
PROCEDURE (d: Directory) GetDateFieldSize (VAR w, h: INTEGER);
BEGIN
IF w = Views.undefined THEN w := 72 * Ports.point END;
IF h = Views.undefined THEN h := 17 * Ports.point END
END GetDateFieldSize;
PROCEDURE (d: Directory) GetTimeFieldSize (VAR w, h: INTEGER);
BEGIN
IF w = Views.undefined THEN w := 72 * Ports.point END;
IF h = Views.undefined THEN h := 17 * Ports.point END
END GetTimeFieldSize;
PROCEDURE (d: Directory) GetColorFieldSize (VAR w, h: INTEGER);
BEGIN
IF w = Views.undefined THEN w := 36 * Ports.point END;
IF h = Views.undefined THEN h := 18 * Ports.point END
END GetColorFieldSize;
PROCEDURE (d: Directory) GetListBoxSize (VAR w, h: INTEGER);
BEGIN
IF w = Views.undefined THEN w := 100 * Ports.point END;
IF h = Views.undefined THEN h := 18 * Ports.point END
END GetListBoxSize;
PROCEDURE (d: Directory) GetSelectionBoxSize (VAR w, h: INTEGER);
BEGIN
IF w = Views.undefined THEN w := 100 * Ports.point END;
IF h = Views.undefined THEN h := 54 * Ports.point END
END GetSelectionBoxSize;
PROCEDURE (d: Directory) GetComboBoxSize (VAR w, h: INTEGER);
BEGIN
IF w = Views.undefined THEN w := 100 * Ports.point END;
IF h = Views.undefined THEN h := 18 * Ports.point END
END GetComboBoxSize;
PROCEDURE (d: Directory) GetCaptionSize (VAR w, h: INTEGER);
BEGIN
IF w = Views.undefined THEN w := 50 * Ports.point END;
IF h = Views.undefined THEN h := 12 * Ports.point END
END GetCaptionSize;
PROCEDURE (d: Directory) GetGroupSize (VAR w, h: INTEGER);
BEGIN
IF w = Views.undefined THEN w := 100 * Ports.point END;
IF h = Views.undefined THEN h := 100 * Ports.point END
END GetGroupSize;
PROCEDURE (d: Directory) GetTreeFrameSize (VAR w, h: INTEGER);
BEGIN
IF w = Views.undefined THEN w := 100 * Ports.point END;
IF h = Views.undefined THEN h := 100 * Ports.point END
END GetTreeFrameSize;
PROCEDURE (d: Directory) NewPushButton* (): StdCFrames.PushButton;
VAR
f: PushButton;
BEGIN
NEW(f);
f.noRedraw := TRUE;
RETURN f
END NewPushButton;
PROCEDURE (d: Directory) NewCheckBox* (): StdCFrames.CheckBox;
VAR
f: CheckBox;
BEGIN
NEW(f);
f.noRedraw := TRUE;
RETURN f
END NewCheckBox;
PROCEDURE (d: Directory) NewRadioButton* (): StdCFrames.RadioButton;
VAR
f: RadioButton;
BEGIN
NEW(f);
f.noRedraw := TRUE;
RETURN f
END NewRadioButton;
PROCEDURE (d: Directory) NewScrollBar* (): StdCFrames.ScrollBar;
VAR
f: ScrollBar;
BEGIN
NEW(f);
f.noRedraw := TRUE;
RETURN f
END NewScrollBar;
PROCEDURE (d: Directory) NewField* (): StdCFrames.Field;
VAR
f: Field;
BEGIN
NEW(f);
f.noRedraw := FALSE;
NEW(f.ed);
f.ed.Init;
RETURN f
END NewField;
PROCEDURE (d: Directory) NewUpDownField* (): StdCFrames.UpDownField;
VAR
f: UpDownField;
BEGIN
NEW(f);
f.noRedraw := FALSE;
NEW(f.ed);
f.ed.Init;
f.lastval := 0; (* doesn't matter *)
RETURN f
END NewUpDownField;
PROCEDURE (d: Directory) NewDateField* (): StdCFrames.DateField;
VAR
f: DateField;
BEGIN
NEW(f);
f.noRedraw := FALSE;
f.dateSep := '/';
f.yearPart := 1; f.monthPart := 2; f.dayPart := 3; f.del1 := 4; f.del2 := 7;
NEW(f.ed);
f.ed.Init; f.ed.noMouseSelect := TRUE;
RETURN f
END NewDateField;
PROCEDURE (d: Directory) NewTimeField* (): StdCFrames.TimeField;
VAR
f: TimeField;
BEGIN
NEW(f);
f.noRedraw := FALSE;
NEW(f.ed);
f.ed.Init; f.ed.noMouseSelect := TRUE;
RETURN f
END NewTimeField;
PROCEDURE (d: Directory) NewColorField* (): StdCFrames.ColorField;
VAR
f: ColorField;
BEGIN
NEW(f);
f.noRedraw := TRUE;
RETURN f
END NewColorField;
PROCEDURE (d: Directory) NewListBox* (): StdCFrames.ListBox;
VAR
f: ListBox;
BEGIN
NEW(f);
f.noRedraw := FALSE;
NEW(f.lst);
f.lst.Init;
f.fixCursor := TRUE;
f.closedTime := 0;
f.popupOverlay := NIL;
RETURN f
END NewListBox;
PROCEDURE (d: Directory) NewSelectionBox* (): StdCFrames.SelectionBox;
VAR
f: SelectionBox;
BEGIN
NEW(f);
f.noRedraw := FALSE;
NEW(f.lst);
f.lst.Init;
f.fixCursor := TRUE;
RETURN f
END NewSelectionBox;
PROCEDURE (d: Directory) NewComboBox* (): StdCFrames.ComboBox;
VAR
f: ComboBox;
BEGIN
NEW(f);
f.noRedraw := FALSE;
NEW(f.ed);
f.ed.Init;
NEW(f.lst);
f.lst.Init;
f.fixCursor := TRUE;
f.closedTime := 0;
f.popupOverlay := NIL;
RETURN f
END NewComboBox;
PROCEDURE (d: Directory) NewCaption* (): StdCFrames.Caption;
VAR
f: Caption;
BEGIN
NEW(f);
f.noRedraw := TRUE;
f.changeCount := 0;
RETURN f
END NewCaption;
PROCEDURE (d: Directory) NewGroup* (): StdCFrames.Group;
VAR
f: Group;
BEGIN
NEW(f);
f.noRedraw := TRUE;
RETURN f
END NewGroup;
PROCEDURE (d: Directory) NewTreeFrame* (): StdCFrames.TreeFrame;
VAR
f: TreeFrame;
BEGIN
NEW(f);
f.noRedraw := TRUE;
f.yoffs := 0;
f.leftMargin := 6 * Ports.point;
IF folder = NIL THEN
folder := StdRasters.NewModelFromSpec(Files.dir.This("Std/Rsrc"),
"tree_folder.png", FALSE);
folderopen := StdRasters.NewModelFromSpec(Files.dir.This("Std/Rsrc"),
"tree_folderopen.png", FALSE);
leaf := StdRasters.NewModelFromSpec(Files.dir.This("Std/Rsrc"),
"tree_leaf.png", FALSE);
END;
RETURN f
END NewTreeFrame;
PROCEDURE ParamDefaults (skin: ANYPTR);
VAR
selectColor: INTEGER;
BEGIN
selectColor := Ports.RGBColor(51, 153, 255);
WITH skin: ParamSkin DO
skin.backPopup := Ports.RGBColor(0AAH, 0AAH, 0AAH);
skin.textPopup := Ports.RGBColor(0, 0, 0);
skin.back := Ports.RGBColor(0E5H, 0E5H, 0E5H);
skin.text := Ports.black;
skin.backHover := Ports.RGBColor(0CCH, 0CCH, 0CCH);
skin.textHover := Ports.RGBColor(000H, 000H, 000H);
skin.backDisabled := Ports.grey25;
skin.textDisabled := Ports.grey50;
skin.backReadOnly := Ports.grey25;
skin.textReadOnly := Ports.RGBColor(055H, 055H, 055H);
skin.backPressed := Ports.RGBColor(37, 78, 118);
skin.textPressed := Ports.RGBColor(0FFH, 0FFH, 0FFH);
(* Editor *)
skin.backEditor := Ports.white;
skin.textEditor := Ports.black;
skin.backEditorSelection := selectColor;
skin.textEditorSelection := Ports.white;
skin.backEditorDisabled := Ports.grey25;
skin.textEditorDisabled := Ports.grey50;
skin.backEditorDisabledSelection := Ports.RGBColor(090H, 090H, 090H);
skin.textEditorDisabledSelection := Ports.RGBColor(066H, 066H, 066H);
skin.backEditorReadOnly := Ports.grey12;
skin.textEditorReadOnly := Ports.grey75;
skin.backEditorReadOnlySelection := Ports.grey50;
skin.textEditorReadOnlySelection := Ports.grey12;
skin.backEditorBlured := Ports.white;
skin.textEditorBlured := Ports.black;
skin.backEditorBluredSelection := Ports.RGBColor(074H, 074H, 073H);
skin.textEditorBluredSelection := Ports.RGBColor(000H, 000H, 000H);
(* List *)
skin.backList := Ports.white;
skin.textList := Ports.black;
skin.backSelList := selectColor;
skin.textSelList := Ports.white;
skin.backListCursor := selectColor;
skin.textListCursor := Ports.white;
skin.backSelListCursor := selectColor;
skin.textSelListCursor := Ports.white;
skin.backListDisabled := Ports.RGBColor(0E5H, 0E5H, 0E5H);
skin.textListDisabled := Ports.RGBColor(044H, 044H, 044H);
skin.backSelListDisabled := Ports.RGBColor(0AAH, 0AAH, 0AAH);
skin.textSelListDisabled := Ports.RGBColor(022H, 022H, 022H);
skin.backListCursorDisabled := Ports.RGBColor(0AAH, 0AAH, 0AAH);
skin.textListCursorDisabled := Ports.RGBColor(022H, 022H, 022H);
skin.backSelListCursorDisabled := Ports.RGBColor(0AAH, 0AAH, 0AAH);
skin.textSelListCursorDisabled := Ports.RGBColor(066H, 066H, 066H);
skin.backListBlured := Ports.RGBColor(0FAH, 0FAH, 0FAH);
skin.textListBlured := Ports.black;
skin.backSelListBlured := Ports.RGBColor(0AAH, 0AAH, 0FFH);
skin.textSelListBlured := Ports.black;
skin.backListCursorBlured := Ports.RGBColor(0DCH, 0DCH, 0DCH);
skin.textListCursorBlured := Ports.black;
skin.backSelListCursorBlured := Ports.RGBColor(0D0H, 0DDH, 0D0H);
skin.textSelListCursorBlured := Ports.RGBColor(000H, 000H, 0FFH);
(* scrollbar *)
skin.backSlider := Ports.RGBColor(077H, 077H, 077H);
skin.backPressedSlider := Ports.RGBColor(055H, 055H, 055H);
skin.trackSlider := Ports.RGBColor(055H, 055H, 055H);
skin.backScrollbar := Ports.RGBColor(0DDH, 0DDH, 0DDH);
skin.backScrollbarButtons := Ports.RGBColor(0CCH, 0CCH, 0CCH);
skin.knobScrollbar := Ports.RGBColor(0BBH, 0BBH, 0BBH);
skin.knobScrollbarPressed := Ports.RGBColor(090H, 090H, 090H);
skin.scrollbarKnobMargin := 2;
(* selecting controls *)
skin.frame := Ports.RGBColor(0AAH, 0AAH, 0AAH);
skin.frameFocus := Ports.RGBColor(099H, 099H, 099H);
skin.frameReadOnly := Ports.RGBColor(0AAH, 0AAH, 0AAH);
skin.frameDisabled := Ports.RGBColor(0AAH, 0AAH, 0AAH);
skin.frameFace := Ports.RGBColor(0AAH, 0AAH, 0AAH);
skin.frameLight := Ports.RGBColor(0FFH, 0FFH, 0FFH);
skin.frameSemi := Ports.RGBColor(0BBH, 0BBH, 0BBH);
skin.frameDark := Ports.RGBColor(000H, 000H, 000H);
skin.frameShadow := Ports.RGBColor(055H, 055H, 055H);
skin.arrowDisabled := Ports.RGBColor(090H, 090H, 090H);
skin.arrowReadOnly := Ports.RGBColor(090H, 090H, 090H);
skin.arrow := Ports.RGBColor(022H, 022H, 022H);
skin.checkBoxFont := Fonts.dir.This("Verdana", 12 * Fonts.point, {}, Fonts.normal);
END
END ParamDefaults;
PROCEDURE RevealPasswords*;
BEGIN
revealPasswords := TRUE
END RevealPasswords;
PROCEDURE HidePasswords*;
BEGIN
revealPasswords := FALSE
END HidePasswords;
PROCEDURE Init;
VAR dir: Directory;
BEGIN
StdCFrames.setFocus := TRUE;
inHandleMouse := FALSE;
revealPasswords := FALSE;
NEW(dir); StdCFrames.SetDir(dir);
NEW(skin); ParamDefaults(skin);
END Init;
BEGIN
Init
END StdStdCFrames. | Std/Mod/StdCFrames.odc |
MODULE StdTabFrames;
(**
project = "ypk Host"
subproject = "Control Frames"
organization = "https://bitbucket.org/oberoncore/ypk/src/default/Mod/HostTabFrames.odc"
contributors = "Peter Kushnir"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
purpose = ""
changes = ""
issues = ""
**)
IMPORT Controllers, TV := StdTabViews, Dialog, Fonts, Kernel, Models, Ports, Services, Stores, Views;
CONST
pixel = SHORT(ENTIER((3 / 4)*Ports.point)); (* Традиционный пиксел *)
scrollStep = 40*pixel;
none = -1;
TYPE
IteratorItem = POINTER TO ABSTRACT RECORD
root: Iterator;
prev, next: IteratorItem
END;
Iterator = POINTER TO LIMITED RECORD(IteratorItem)
first, last, this: IteratorItem;
length: INTEGER
END;
IntMap = POINTER TO LIMITED RECORD
list: Iterator
END;
IntItem = POINTER TO RECORD(IteratorItem)
id: INTEGER;
data: ANYPTR
END;
UpdateAction = POINTER TO RECORD(Services.Action)
v: Views.View;
l, t, r, b: INTEGER
END;
Directory = POINTER TO RECORD (TV.FrameDirectory)
list: IntMap
END;
Scroll = POINTER TO RECORD (Views.View) END;
ScrollContext = POINTER TO RECORD (Models.Context)
base: Views.View;
v: Scroll;
l, t, r, b: INTEGER
END;
Tab = POINTER TO RECORD (Views.View)
i: INTEGER;
title: ARRAY 256 OF CHAR;
END;
TabContext = POINTER TO RECORD (Models.Context)
base: Views.View;
v: Tab;
l, t, r, b: INTEGER
END;
Bar = POINTER TO RECORD (Views.View) END;
BarContext = POINTER TO RECORD (Models.Context)
base: Views.View;
v: Bar;
l, t, r, b, dx: INTEGER
END;
Frame = POINTER TO RECORD (TV.Frame)
tabs: RECORD
h: INTEGER;
c: BarContext;
s: ScrollContext
END
END;
Prop = POINTER TO RECORD
dx, bw, w, hl: INTEGER;
upd: INTEGER
END;
VAR
dir: Directory;
PROCEDURE NewIterator (): Iterator;
VAR it: Iterator;
BEGIN
NEW(it); it.length := 0;
RETURN(it)
END NewIterator;
PROCEDURE (i: Iterator) First (), NEW;
BEGIN
i.this := i.first
END First;
PROCEDURE (i: Iterator) Next (), NEW;
BEGIN
ASSERT(i.this # NIL, 20);
i.this := i.this.next
END Next;
PROCEDURE (i: Iterator) Add (item: IteratorItem), NEW;
BEGIN
ASSERT(item # NIL, 20);
item.root := i;
IF (i.last # NIL) & (i.first # NIL) THEN
i.last.next := item;
item.prev := i.last;
item.next := NIL;
i.last := item
ELSE
i.first := item;
i.last := item;
item.next := NIL;
item.prev := NIL
END;
INC(i.length)
END Add;
PROCEDURE (m: IntMap) Item2 (id: INTEGER): IntItem, NEW;
VAR x: IntItem;
BEGIN
x := NIL;
m.list.First;
WHILE (m.list.this # NIL) & (m.list.this IS IntItem) & (x = NIL) DO
IF m.list.this(IntItem).id = id THEN x := m.list.this(IntItem) END;
m.list.Next
END;
RETURN x
END Item2;
PROCEDURE (m: IntMap) Item (id: INTEGER): ANYPTR, NEW;
VAR x: IntItem;
BEGIN
x := m.Item2(id);
IF x # NIL THEN RETURN x.data ELSE RETURN NIL END
END Item;
PROCEDURE (m: IntMap) Add (id: INTEGER; item: ANYPTR), NEW;
VAR i: IntItem;
BEGIN
ASSERT(item # NIL, 20);
i := m.Item2(id);
IF i # NIL THEN i.data := item ELSE NEW(i); i.id := id; i.data := item; m.list.Add(i) END
END Add;
PROCEDURE NewIntMap (): IntMap;
VAR i: IntMap;
BEGIN
NEW(i);
i.list := NewIterator();
RETURN i
END NewIntMap;
PROCEDURE (a: UpdateAction) Do;
BEGIN
Views.UpdateIn(a.v, a.l, a.t, a.r, a.b, TRUE)
END Do;
PROCEDURE (d: Directory) This (v: Views.View): Prop, NEW;
VAR x: ANYPTR; p: Prop;
BEGIN
(* Kernel.Collect; *)
x := d.list.Item(Services.AdrOf(v));
IF x # NIL THEN p := x(Prop) END;
RETURN p
END This;
PROCEDURE (d: Directory) Add (v: Views.View; p: Prop), NEW;
BEGIN
d.list.Add(Services.AdrOf(v), p)
END Add;
PROCEDURE (d: Directory) NewFrame (v: Views.View), NEW;
VAR p: Prop;
BEGIN
p := dir.This(v);
IF p # NIL THEN
p.upd := 0
END
END NewFrame;
PROCEDURE (d: Directory) UpdateView (v: Views.View), NEW;
VAR p: Prop;
BEGIN
p := d.This(v);
IF (p # NIL) & (p.upd = 0) THEN
(* Kernel.Collect; *)
Views.Update(v, TRUE);
p.upd := 1
ELSE Views.Update(v, TRUE) END
END UpdateView;
PROCEDURE (d: Directory) UpdateFrame (f: Frame), NEW;
VAR p: Prop; a: UpdateAction;
BEGIN
p := d.This(f.view);
IF (p # NIL) THEN
(* Kernel.Collect; *)
NEW(a);
a.v := f.view; a.l := f.tabs.c.l; a.t := f.tabs.c.t; a.r := f.tabs.c.r; a.b := f.tabs.c.b;
Services.DoLater(a, Services.immediately);
p.upd := 1
END
END UpdateFrame;
PROCEDURE (d: Directory) Close (f: Frame), NEW;
VAR p: Prop;
BEGIN
p := d.This(f.view);
IF (p # NIL) THEN
(* Kernel.Collect; *)
p.upd := 0
END
END Close;
PROCEDURE NewTabContext (v, base: Views.View): TabContext;
VAR c: TabContext;
BEGIN
NEW(c);
c.v := v(Tab); c.base := base;
v.InitContext(c); Stores.Join(v, base);
RETURN c
END NewTabContext;
PROCEDURE (c: TabContext) ThisModel (): Models.Model;
BEGIN
RETURN NIL (* don't give the embedded views information about the dummy twin model *)
END ThisModel;
PROCEDURE (c: TabContext) GetSize (OUT w, h: INTEGER);
BEGIN
w := c.r - c.l;
h := c.b - c.t
END GetSize;
PROCEDURE (c: TabContext) MakeVisible (l, t, r, b: INTEGER);
VAR w, h, sep: INTEGER;
BEGIN
c.base.context.MakeVisible(l, t, r, b)
END MakeVisible;
PROCEDURE (c: TabContext) Consider (VAR p: Models.Proposal);
BEGIN
c.base.context.Consider(p)
END Consider;
PROCEDURE (c: TabContext) Normalize (): BOOLEAN;
BEGIN
RETURN c.base.context.Normalize()
END Normalize;
PROCEDURE NewBarContext (v, base: Views.View): BarContext;
VAR c: BarContext; p: Prop;
BEGIN
NEW(c);
c.v := v(Bar); c.base := base;
v.InitContext(c); Stores.Join(v, base);
p := dir.This(base);
IF p = NIL THEN
NEW(p); p.dx := 0; p.hl := none; p.upd := 0;
dir.Add(c.base, p)
END;
p.bw := 0; p.w := 0;
RETURN c
END NewBarContext;
PROCEDURE (c: BarContext) ThisModel (): Models.Model;
BEGIN
RETURN NIL (* don't give the embedded views information about the dummy twin model *)
END ThisModel;
PROCEDURE (c: BarContext) GetSize (OUT w, h: INTEGER);
BEGIN
w := c.r - c.l;
h := c.b - c.t
END GetSize;
PROCEDURE (c: BarContext) MakeVisible (l, t, r, b: INTEGER);
VAR w, h, sep: INTEGER;
BEGIN
c.base.context.MakeVisible(l, t, r, b)
END MakeVisible;
PROCEDURE (c: BarContext) Consider (VAR p: Models.Proposal);
BEGIN
c.base.context.Consider(p)
END Consider;
PROCEDURE (c: BarContext) Normalize (): BOOLEAN;
BEGIN
RETURN c.base.context.Normalize()
END Normalize;
PROCEDURE (c: BarContext) SetWidth (bw: INTEGER), NEW;
VAR p: Prop;
BEGIN
p := dir.This(c.base);
IF p # NIL THEN p.bw := bw; p.w := c.r - c.l END
END SetWidth;
PROCEDURE (c: BarContext) SetHover (idx: INTEGER), NEW;
VAR p: Prop;
BEGIN
p := dir.This(c.base);
IF (p # NIL) & (p.hl # idx) THEN
(* p.hl := idx не нужен *)
END
END SetHover;
PROCEDURE (c: BarContext) GetHover (): INTEGER, NEW;
VAR p: Prop; res: INTEGER;
BEGIN
res := none;
p := dir.This(c.base);
IF p # NIL THEN res := p.hl END;
RETURN res
END GetHover;
PROCEDURE NewScrollContext (v, base: Views.View): ScrollContext;
VAR c: ScrollContext;
BEGIN
NEW(c);
c.v := v(Scroll); c.base := base;
v.InitContext(c); Stores.Join(v, base);
RETURN c
END NewScrollContext;
PROCEDURE (c: ScrollContext) ThisModel (): Models.Model;
BEGIN
RETURN NIL (* don't give the embedded views information about the dummy twin model *)
END ThisModel;
PROCEDURE (c: ScrollContext) GetSize (OUT w, h: INTEGER);
BEGIN
w := c.r - c.l;
h := c.b - c.t
END GetSize;
PROCEDURE (c: ScrollContext) MakeVisible (l, t, r, b: INTEGER);
VAR w, h, sep: INTEGER;
BEGIN
c.base.context.MakeVisible(l, t, r, b)
END MakeVisible;
PROCEDURE (c: ScrollContext) Consider (VAR p: Models.Proposal);
BEGIN
c.base.context.Consider(p)
END Consider;
PROCEDURE (c: ScrollContext) Normalize (): BOOLEAN;
BEGIN
RETURN c.base.context.Normalize()
END Normalize;
PROCEDURE (c: ScrollContext) SetPos (x: INTEGER), NEW;
VAR p: Prop; n: INTEGER;
BEGIN
p := dir.This(c.base);
n := p.bw DIV scrollStep;
p.dx := MAX(0, MIN(p.dx + x, n - 2))
END SetPos;
PROCEDURE (c: ScrollContext) GetPos (OUT x: INTEGER), NEW;
VAR p: Prop;
BEGIN
p := dir.This(c.base);
x := p.dx
END GetPos;
PROCEDURE DrawRect3d (f: Views.Frame; l, t, r, b: INTEGER; dir: BYTE);
VAR x1, y1, h: INTEGER;
BEGIN
h := 7 * f.dot;
x1 := (r - l) DIV 2; y1 := ((b - t) DIV 2) - (h DIV 2);
CASE dir OF
| 2: (* влево *)
f.DrawRect(l + 5 * f.dot, t + 7 * f.dot + y1, l + 6 * f.dot, t + 8 * f.dot + y1, Ports.fill, Ports.black); (* лев - 1 *)
f.DrawRect(l + 6 * f.dot, t + 6 * f.dot + y1, l + 7 * f.dot, t + 9 * f.dot + y1, Ports.fill, Ports.black); (* 2 *)
f.DrawRect(l + 7 * f.dot, t + 5 * f.dot + y1, l + 8 * f.dot, t + 10 * f.dot + y1, Ports.fill, Ports.black); (* 3 *)
f.DrawRect(l + 8 * f.dot, t + 4 * f.dot + y1, l + 9 * f.dot, t + 11 * f.dot + y1, Ports.fill, Ports.black); (* 4 *)
| 3: (* вправо *)
f.DrawRect(r - 7 * f.dot, t + 7 * f.dot + y1, r - 6 * f.dot, t + 8 * f.dot + y1, Ports.fill, Ports.black); (* прав - 1 *)
f.DrawRect(r - 8 * f.dot, t + 6 * f.dot + y1, r - 7 * f.dot, t + 9 * f.dot + y1, Ports.fill, Ports.black); (* прав - 1 *)
f.DrawRect(r - 9 * f.dot, t + 5 * f.dot + y1, r - 8 * f.dot, t + 10 * f.dot + y1, Ports.fill, Ports.black); (* прав - 1 *)
f.DrawRect(r - 10 * f.dot, t + 4 * f.dot + y1, r - 9 * f.dot, t + 11 * f.dot + y1, Ports.fill, Ports.black); (* прав - 1 *)
ELSE END
END DrawRect3d;
PROCEDURE (v: Scroll) Restore (f: Views.Frame; l, t, r, b: INTEGER);
VAR w, h: INTEGER; p: Prop;
BEGIN
v.context.GetSize(w, h);
p := dir.This(v.context(ScrollContext).base);
IF (p # NIL) & (p.w < p.bw) THEN
f.DrawRect(0, 3 * pixel, (w - pixel) DIV 2, h, Ports.fill, Ports.grey12);
f.DrawRect((w - pixel) DIV 2, 3 * pixel, w - pixel, h, Ports.fill, Ports.grey12);
f.DrawRect(0, 3 * pixel, w - pixel, h, pixel, Ports.black);
f.DrawLine((w DIV 2) - pixel, 3 * pixel, (w DIV 2) - pixel, h - 2 * pixel, 2 * pixel, Ports.black);
DrawRect3d(f, 0, 0, (w DIV 2) - 2 * pixel, h - 2 * pixel, 2);
DrawRect3d(f, (w DIV 2) + 2 * pixel, 0, w - pixel, h - 2 * pixel, 3)
ELSE
f.DrawLine(0, h - pixel, w - pixel, h - pixel, pixel, Ports.black);
p.dx:=0;
END
END Restore;
PROCEDURE (v: Scroll) HandleCtrlMsg (f: Views.Frame; VAR msg: Views.CtrlMessage; VAR focus: Views.View);
VAR w, h, x, y, res: INTEGER; mods: SET; isDown: BOOLEAN; p: Prop;
BEGIN
v.context.GetSize(w, h);
WITH
|msg: Controllers.TrackMsg DO
f.Input(x, y, mods, isDown);
IF isDown THEN
p := dir.This(v.context(ScrollContext).base);
IF (p # NIL) & (p.w < p.bw) THEN
IF ((w DIV 2) >= x) THEN res := - 1 ELSE res := 1 END;
v.context(ScrollContext).SetPos(res);
dir.UpdateView(v.context(ScrollContext).base)
END
END
ELSE END;
focus := v
END HandleCtrlMsg;
PROCEDURE NewScroll (): Scroll;
VAR s: Scroll;
BEGIN
NEW(s);
RETURN s
END NewScroll;
(* processing '&' and "&&"; return amp position and width *)
PROCEDURE CleanAmp (VAR s: ARRAY OF CHAR; font: Fonts.Font; OUT awdt: INTEGER): INTEGER;
VAR
tmp: ARRAY 2 OF CHAR;
i, j: INTEGER;
apos: INTEGER;
BEGIN
apos := -1; awdt := -1; i := 0; j := 0;
WHILE s[i] # 0X DO
IF (s[i] = '&') & (s[i + 1] # 0X) THEN
INC(i);
IF (apos < 0) & (s[i] # '&') THEN apos := j END
END;
s[j] := s[i]; INC(i); INC(j)
END;
s[j] := 0X;
IF apos >= 0 THEN
ASSERT(apos < LEN(s$));
i := apos;
tmp[0] := s[i]; tmp[1] := 0X;
s[apos] := 0X; apos := font.StringWidth(s); s[i] := tmp[0];
awdt := font.StringWidth(tmp)
END;
awdt := MAX(0, awdt);
RETURN apos
END CleanAmp;
PROCEDURE (v: Tab) Restore (f: Views.Frame; l, t, r, b: INTEGER);
VAR w, h, dh: INTEGER; v0: Views.View; tv: TV.View; len, i: INTEGER; font: Fonts.Font; sw, tt, tl, tr, tb, col, mcol: INTEGER; asc, desc, weight, apos, awdt, x, y: INTEGER; hov, this: BOOLEAN;
s: ARRAY 256 OF CHAR;
BEGIN
v.context.GetSize(w, h);
font := Fonts.dir.Default();
font.GetBounds(asc, desc, weight);
tv := v.context(TabContext).base(Bar).context(BarContext).base(TV.View);
hov := (v.i = v.context(TabContext).base.context(BarContext).GetHover()); this := (v.i = tv.Index());
IF hov & this THEN
col := Ports.grey6
ELSIF hov OR this THEN
col := Ports.white; mcol:=Ports.black;
ELSE col := Ports.grey12; mcol:=Ports.grey50 END;
sw := font.StringWidth(v.title$);
tl := v.context(TabContext).l; tr := v.context(TabContext).r; tt := v.context(TabContext).t; tb := v.context(TabContext).b;
f.DrawRect(0, 0, w, h, pixel, mcol);
f.DrawRect(pixel, pixel, w - pixel, h, Ports.fill, col);
IF this THEN dh:=3*pixel ELSE dh:=1*pixel END;
s := v.title$;
apos := CleanAmp(s, font, awdt);
x := (w DIV 2) - (sw DIV 2);
y := (h DIV 2) + (asc DIV 2) - dh;
f.DrawString(x, y, Ports.black, s, font);
IF awdt > f.dot THEN
INC(y, 1 * f.dot);
f.DrawRect(x + apos, y, x + apos + awdt, y + f.dot, Ports.fill, Ports.black)
END
END Restore;
PROCEDURE (v: Tab) HandleCtrlMsg (f: Views.Frame; VAR msg: Views.CtrlMessage; VAR focus: Views.View);
VAR w, h, x, y: INTEGER; mods: SET; isDown: BOOLEAN; tv: TV.View; g: Views.Frame; dw: INTEGER;
BEGIN
v.context.GetSize(w, h);
WITH
|msg: Controllers.TrackMsg DO
f.Input(x, y, mods, isDown);
IF isDown THEN
g:=f;
REPEAT g:=Views.HostOf(g) UNTIL (g=NIL) OR (g IS Frame);
v.context(TabContext).base.context(BarContext).SetHover(v.i);
IF g#NIL THEN
dw:=v.context(TabContext).base.context(BarContext).r - v.context(TabContext).r;
IF dw<10*pixel THEN
g(Frame).tabs.s.SetPos(MAX(2, w DIV scrollStep));
ELSE
dw:=v.context(TabContext).l - v.context(TabContext).base.context(BarContext).l;
IF dw<10*pixel THEN
g(Frame).tabs.s.SetPos(- MAX(2,w DIV scrollStep));
END;
END;
END;
g(Frame).SetIndex(v.i); (* вытащил из ветки охраны *)
END
|msg: Controllers.PollCursorMsg DO
IF (msg.x > v.context(TabContext).l) & (msg.y > v.context(TabContext).t) & (msg.x < v.context(TabContext).r) & (msg.y < v.context(TabContext).b) THEN
(* v.context(TabContext).base.context(BarContext).SetHover(v.i) *)
ELSE END
ELSE END;
focus := NIL
END HandleCtrlMsg;
PROCEDURE NewTab (idx: INTEGER; title: ARRAY OF CHAR): Tab;
VAR t0: Tab;
BEGIN
NEW(t0);
t0.i := idx;
t0.title:=title$;
RETURN t0
END NewTab;
PROCEDURE (v: Bar) Restore (f: Views.Frame; l, t, r, b: INTEGER);
VAR dw, w, h: INTEGER; s: Dialog.String; v0: Views.View; tv: TV.View; len, i: INTEGER; font: Fonts.Font; sw, tt, tl, tr, tb, il, ir, col: INTEGER; asc, desc, weight: INTEGER; tab: Tab; tc: TabContext; bw, tw, th: INTEGER;
BEGIN
v.context.GetSize(w, h);
font := Fonts.dir.Default(); font.GetBounds(asc, desc, weight);
tv := v.context(BarContext).base(TV.View); i := 0; len := tv.NofTabs();
dw := - (scrollStep * v.context(BarContext).dx);
tl := dw + 5 * pixel; tb := h - pixel; tr := dw; tt := 0; il := 0; ir := 0; bw := 0;
WHILE i < len DO
tv.GetItem(i, s, v0); Dialog.MapString(s$, s);
(* s := v.vitle$; *)
sw := font.StringWidth(s$);
(* sw := MAX(sw + MAX(5*pixel, sw DIV 5), 20 * pixel); *)
sw:=sw+4*Ports.mm; tr := tr + sw;
tab := NewTab(i, s$);
tc := NewTabContext(tab, v);
IF i = tv.Index() THEN tt := 2 * pixel; il := tl; ir := tr ELSE tt := 4 * pixel END;
tc.l := tl - pixel; tc.r := tr; tc.t := tt; tc.b := tb;
IF i = tv.Index() THEN
Views.InstallFrame(f, tab, tl - pixel, tt, 1, TRUE);
ELSE
Views.InstallFrame(f, tab, tl - pixel, tt, 0, TRUE);
END;
tc.GetSize(tw, th); INC(bw, tw);
tl := tr;
INC(i)
END;
v.context(BarContext).SetWidth(bw);
f.DrawLine(0, h - pixel, il, h - pixel, pixel, Ports.black);
f.DrawLine(ir, h - pixel, w, h - pixel, pixel, Ports.black)
END Restore;
PROCEDURE (v: Bar) HandleCtrlMsg (f: Views.Frame; VAR msg: Views.CtrlMessage; VAR focus: Views.View);
VAR g: Views.Frame; hl: INTEGER;
BEGIN
WITH
|msg: Controllers.TrackMsg DO
g := Views.FrameAt(f, msg.x, msg.y);
IF g # NIL THEN
Views.ForwardCtrlMsg(g, msg);
END
|msg: Controllers.PollCursorMsg DO
g := Views.FrameAt(f, msg.x, msg.y);
(* hl := v.context(BarContext).GetHover();
IF g # NIL THEN
Views.ForwardCtrlMsg(g, msg)
ELSE v.context(BarContext).SetHover(none) END;
IF (hl # v.context(BarContext).GetHover()) THEN
dir.UpdateFrame(Views.HostOf(f)(Frame))
END *)
|msg: Controllers.PollOpsMsg DO
ELSE END;
focus := NIL
END HandleCtrlMsg;
PROCEDURE (f: Frame) GetDispSize (OUT x, y, w, h: INTEGER);
BEGIN
f.view.context.GetSize(w, h);
x := 2 * pixel; y := f.tabs.h + 2 * pixel;
w := w - 4 * pixel;
h := h - y - 2 * pixel
END GetDispSize;
PROCEDURE (f: Frame) InDispArea (x, y: INTEGER): BOOLEAN;
VAR ok: BOOLEAN; w, h: INTEGER;
PROCEDURE ResetHover;
VAR p: Prop;
BEGIN
p := dir.This(f.view);
IF p # NIL THEN
IF p.hl >= 0 THEN
p.hl := none;
dir.UpdateFrame(f)
END
END
END ResetHover;
BEGIN
f.view.context.GetSize(w, h);
ok := (ABS(w - x) > 2 * pixel) & (y > (f.tabs.h + 2 * pixel)) & (y < h);
IF ok THEN
(* ResetHover *)
END;
RETURN ok
END InDispArea;
PROCEDURE (f: Frame) DrawTabs, NEW;
VAR w, h, col: INTEGER;
BEGIN
f.view.context.GetSize(w, h);
f.tabs.c.l := 0; f.tabs.c.t := 0; f.tabs.c.r := w - f.tabs.h; f.tabs.c.b := f.tabs.h + pixel;
f.tabs.s.GetPos(f.tabs.c.dx);
Views.InstallFrame(f, f.tabs.c.v, 0, 0, 0, TRUE);
f.tabs.s.l := f.tabs.c.r; f.tabs.s.t := 0; f.tabs.s.r := w; f.tabs.s.b := f.tabs.h + pixel;
Views.InstallFrame(f, f.tabs.s.v, f.tabs.c.r, 0, 0, TRUE);
END DrawTabs;
PROCEDURE (f: Frame) UpdateList;
VAR v: Bar; s: Scroll; res: INTEGER;
BEGIN
IF f.tabs.c = NIL THEN
dir.NewFrame(f.view);
NEW(v); f.tabs.c := NewBarContext(v, f.view);
NEW(s); f.tabs.s := NewScrollContext(s, f.view);
Dialog.Call('Kernel.FastCollect', '', res);
END
END UpdateList;
PROCEDURE (f: Frame) Restore (l, t, r, b: INTEGER);
VAR w, h: INTEGER;
BEGIN
f.view.context.GetSize(w, h);
f.DrawTabs;
f.DrawLine(0, f.tabs.h, 0, h - pixel, pixel, Ports.black);
f.DrawLine(w - pixel, f.tabs.h, w - pixel, h - pixel, pixel, Ports.black);
f.DrawLine(0, h - pixel, w - pixel, h - pixel, pixel, Ports.black)
END Restore;
PROCEDURE (f: Frame) MouseDown (x, y: INTEGER; buttons: SET);
VAR g: Views.Frame; tm: Controllers.TrackMsg;
BEGIN
ASSERT(~f.disabled, 100);
IF f.rider # NIL THEN
g := Views.FrameAt(f, x, y);
IF g # NIL THEN
tm.x := x; tm.y := y; tm.modifiers := {};
Views.ForwardCtrlMsg(g, tm);
END
END;
END MouseDown;
PROCEDURE (f: Frame) GetCursor (x, y: INTEGER; mods: SET; VAR c: INTEGER);
VAR g: Views.Frame; cm: Controllers.PollCursorMsg;
BEGIN
ASSERT(~f.disabled, 100);
IF f.rider # NIL THEN
IF mods = {} THEN
g := Views.FrameAt(f, x, y);
IF g # NIL THEN
cm.x := x; cm.y := y; cm.modifiers := {};
Views.ForwardCtrlMsg(g, cm)
END
END
END
END GetCursor;
PROCEDURE (f: Frame) Close;
BEGIN
dir.Close(f);
END Close;
PROCEDURE (d: Directory) GetTabSize (VAR w, h: INTEGER);
BEGIN
IF w = Views.undefined THEN w := 150 * pixel END;
IF h = Views.undefined THEN h := 100 * pixel END
END GetTabSize;
PROCEDURE (d: Directory) New (): Frame;
VAR f: Frame;
BEGIN
NEW(f);
f.tabs.h := 25 * pixel;
RETURN f
END New;
PROCEDURE Init*;
BEGIN
NEW(dir); dir.list := NewIntMap();
TV.SetFrameDir(dir)
END Init;
END StdTabFrames.
| Std/Mod/TabFrames.odc |
MODULE StdTables;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20160321, center #110, use mapped strings for labels in all forms
"
issues = "
- ...
"
**)
IMPORT
Services, Fonts, Ports, Dialog, Meta, Stores, Models, Views, Controllers, Containers, Properties, Controls,
TextModels, TextViews (* , HostPorts *);
CONST
minVersion = 0;
tabVersion = 2;
maxCol = 256;
defColW = 30 * Ports.mm;
left = -1; right = -2; center = -3; (* adjustment modes *)
move = 1; adjust = 2; field = 3; (* cursor modes *)
tab = 09X; ltab = 0AX; lineChar = 0DX; esc = 1BX;
line* = 0DX; (* line feed characher for labels *)
deselect* = -1; select* = -2; changed* = -3; (* notifier op-values *)
layoutEditable* = 0; dataEditable* = 1; selectionStyle* = 2; (* values for property validity in Prop *)
noSelect* = 0; cellSelect* = 1; rowSelect* = 2; colSelect* = 3; crossSelect* = 4; (* selection style values *)
TYPE
Table* = RECORD
rows-, cols-: INTEGER;
selection: Selection;
labels: POINTER TO ARRAY OF Dialog.String;
data: POINTER TO ARRAY OF ARRAY OF Dialog.String;
weights: POINTER TO ARRAY OF ARRAY OF INTEGER;
styles: POINTER TO ARRAY OF ARRAY OF SET;
colors: POINTER TO ARRAY OF ARRAY OF Ports.Color
END;
Selection = POINTER TO RECORD
on: BOOLEAN;
row, col: INTEGER (** only valid if on = TRUE **)
END;
Prop* = POINTER TO RECORD (Properties.Property)
layoutEditable*, dataEditable*: BOOLEAN;
selectionStyle*: INTEGER
END;
Control = POINTER TO RECORD (Controls.Control)
(* persistent *)
sprop: Properties.StdProp; (* font attributes *)
tprop: Prop; (* table attributes *)
columns: INTEGER; (* width[0..columns-1] and mode[0..columns-1] are defined *)
width: ARRAY maxCol OF INTEGER;
mode: ARRAY maxCol OF INTEGER;
(* not persistent *)
fldFont, titFont: Fonts.Font; (* cell fonts *)
rowHeight, labelHeight, baseOff: INTEGER; (* height of rows, height of the label row and offset for font *)
orgRow, orgX: INTEGER; (* scroll state, orgX in coordinates, orgRow in rows *)
selRow, selCol: INTEGER; (* selected field *)
showSelection: BOOLEAN;
hasSelection: BOOLEAN; (* control has a selected field *)
x, y, w, h: INTEGER;
field: Views.View (* textfield used to enter cell content *)
END;
Directory* = POINTER TO ABSTRACT RECORD END;
StdDirectory = POINTER TO RECORD (Directory) END;
PropOp = POINTER TO RECORD (Stores.Operation) (* typeface, style and size *)
tab: Control;
sprop: Properties.StdProp;
tprop: Prop
END;
FormatOp = POINTER TO RECORD (Stores.Operation) (* cell format *)
tab: Control;
col, width, mode: INTEGER
END;
TableValue = RECORD (Meta.Value)
t: Table
END;
Context = POINTER TO RECORD (Models.Context)
w, h: INTEGER;
base: Views.View
END;
Action = POINTER TO RECORD (Services.Action) END;
VAR
dir-, stdDir-: Directory;
text*: Dialog.String; (* used to edit cell. Only one cell can be active at once *)
dlg*: RECORD
layoutEditable*, dataEditable*: BOOLEAN;
selectionStyle*: Dialog.List;
fingerprint: INTEGER;
known, valid: SET
END;
action: Action;
PROCEDURE CountLines (IN s: Dialog.String): INTEGER;
VAR i, r, l: INTEGER;
BEGIN
r := 1; l := LEN(s$);
FOR i := 0 TO l - 1 DO IF s[i] = line THEN INC(r) END END;
RETURN r
END CountLines;
(* Prop *)
PROCEDURE (p: Prop) IntersectWith* (q: Properties.Property; OUT equal: BOOLEAN);
VAR valid: SET; p0: Prop;
BEGIN
p0 := q(Prop);
valid := p.valid * p0.valid; equal := TRUE;
IF p.layoutEditable # p0.layoutEditable THEN EXCL(valid, layoutEditable) END;
IF p.dataEditable # p0.dataEditable THEN EXCL(valid, dataEditable) END;
IF p.selectionStyle # p0.selectionStyle THEN EXCL(valid, selectionStyle) END;
IF valid # p.valid THEN p.valid := valid; equal := FALSE END
END IntersectWith;
(* Table *)
PROCEDURE (VAR tab: Table) SetSize* (rows, cols: INTEGER), NEW;
VAR i, j, fr, fc: INTEGER;
labels: POINTER TO ARRAY OF Dialog.String;
data: POINTER TO ARRAY OF ARRAY OF Dialog.String;
weights: POINTER TO ARRAY OF ARRAY OF INTEGER;
styles: POINTER TO ARRAY OF ARRAY OF SET;
colors: POINTER TO ARRAY OF ARRAY OF Ports.Color;
BEGIN
ASSERT((rows >= 0) & (cols >= 0), 20);
ASSERT((cols > 0) OR ((cols = 0) & (rows = 0)), 21);
tab.rows := rows; tab.cols := cols;
IF rows > 0 THEN
data := tab.data; NEW(tab.data, rows, cols); weights := tab.weights; NEW(tab.weights, rows, cols);
styles := tab.styles; NEW(tab.styles, rows, cols); colors := tab.colors; NEW(tab.colors, rows, cols);
IF data # NIL THEN
FOR i := 0 TO MIN(rows, LEN(data, 0)) - 1 DO
FOR j := 0 TO MIN(cols, LEN(data, 1)) - 1 DO
tab.data[i, j] := data[i, j]; tab.weights[i, j] := weights[i, j]; tab.styles[i, j] := styles[i, j];
tab.colors[i, j] := colors[i, j]
END
END
END;
(* set defaults *)
IF data = NIL THEN fr := 0; fc := 0 ELSE fr := LEN(data, 0); fc := LEN(data, 1) END;
FOR i := fr TO LEN(tab.data, 0) - 1 DO
FOR j := fc TO LEN(tab.data, 1) - 1 DO
tab.weights[i, j] := Fonts.normal; tab.styles[i, j] := {}; tab.colors[i, j] := Ports.black
END
END
ELSE
tab.data := NIL
END;
IF cols > 0 THEN
labels := tab.labels; NEW(tab.labels, cols);
IF labels # NIL THEN
FOR i := 0 TO MIN(cols, LEN(labels)) - 1 DO
tab.labels[i] := labels[i]
END
END
ELSE
tab.labels := NIL
END;
IF tab.selection = NIL THEN
NEW(tab.selection)
ELSE
tab.selection.on := FALSE
END
END SetSize;
PROCEDURE (VAR tab: Table) SetItem* (row, col: INTEGER; (*IN*) item: Dialog.String), NEW;
BEGIN
ASSERT(tab.data # NIL, 20);
tab.data[row, col] := item
END SetItem;
PROCEDURE (VAR tab: Table) GetItem* (row, col: INTEGER; OUT item: Dialog.String), NEW;
BEGIN
ASSERT(tab.data # NIL, 20);
item := tab.data[row, col]
END GetItem;
PROCEDURE (VAR tab: Table) SetLabel* (col: INTEGER; (*IN*)label: Dialog.String), NEW;
BEGIN
ASSERT(tab.labels # NIL, 20);
tab.labels[col] := label
END SetLabel;
PROCEDURE (VAR tab: Table) GetLabel* (col: INTEGER; OUT label: Dialog.String), NEW;
BEGIN
ASSERT(tab.labels # NIL, 20);
label := tab.labels[col]
END GetLabel;
PROCEDURE (VAR tab: Table) HasSelection* (): BOOLEAN, NEW;
BEGIN
RETURN (tab.selection # NIL) & (tab.selection.on)
END HasSelection;
PROCEDURE (VAR tab: Table) GetSelection* (OUT row, col: INTEGER), NEW;
BEGIN
ASSERT(tab.selection # NIL, 20);
ASSERT(tab.selection.on, 21);
row := tab.selection.row; col := tab.selection.col
END GetSelection;
PROCEDURE (VAR tab: Table) Select* (row, col: INTEGER), NEW;
BEGIN
ASSERT(tab.selection # NIL, 20);
tab.selection.on := TRUE; tab.selection.row := row; tab.selection.col := col
END Select;
PROCEDURE (VAR tab: Table) Deselect*, NEW;
BEGIN
ASSERT(tab.selection # NIL, 20);
tab.selection.on := FALSE
END Deselect;
PROCEDURE (VAR tab: Table) SetAttr* (l, t, r, b: INTEGER; style: SET; weight: INTEGER; color: Ports.Color), NEW;
VAR i, j: INTEGER;
BEGIN
ASSERT(tab.data # NIL, 20);
FOR i := t TO b DO
FOR j := l TO r DO
tab.weights[i, j] := weight; tab.styles[i, j] := style; tab.colors[i, j] := color
END
END
END SetAttr;
PROCEDURE (VAR tab: Table) GetAttr* (row, col: INTEGER; OUT style: SET; OUT weight: INTEGER;
OUT color: Ports.Color), NEW;
BEGIN
ASSERT(tab.data # NIL, 20);
weight := tab.weights[row, col]; style := tab.styles[row, col]; color := tab.colors[row, col]
END GetAttr;
(* Context *)
PROCEDURE (c: Context) GetSize (OUT w, h: INTEGER);
BEGIN
w := c.w; h := c.h
END GetSize;
PROCEDURE (c: Context) Normalize (): BOOLEAN;
BEGIN
RETURN c.base.context.Normalize()
END Normalize;
PROCEDURE (c: Context) Consider (VAR p: Models.Proposal);
BEGIN
c.base.context.Consider(p)
END Consider;
PROCEDURE (c: Context) ThisModel (): Models.Model;
BEGIN
RETURN NIL
END ThisModel;
PROCEDURE NewField(t: Control; col, w, h: INTEGER): Views.View;
VAR c: Context; p: Controls.Prop; v: Views.View; prop: Properties.StdProp; setMsg: Properties.SetMsg;
BEGIN
NEW(p); p.link := "StdTables.text";
IF t.mode[col] = left THEN p.opt[Controls.left] := TRUE
ELSIF t.mode[col] = right THEN p.opt[Controls.right] := TRUE
END;
(* bug in controls, thus adjusting has to be set to left mode *)
p.opt[Controls.left] := TRUE;
p.opt[Controls.right] := FALSE;
v := Controls.dir.NewField(p);
NEW(c); c.w := w; c.h := h; c.base := t;
v.InitContext(c);
NEW(prop);
prop.typeface := t.fldFont.typeface;
prop.size := t.fldFont.size - Fonts.point;
prop.style.val := t.fldFont.style;
prop.style.mask := t.fldFont.style;
prop.weight := t.fldFont.weight;
prop.valid := {Properties.typeface..Properties.weight};
prop.known := prop.valid;
setMsg.prop := prop;
Views.HandlePropMsg(v, setMsg);
RETURN v
END NewField;
PROCEDURE SendNotifyMsg (c: Control);
VAR msg: Views.NotifyMsg;
BEGIN
msg.id0 := c.item.adr; msg.id1 := msg.id0 + c.item.Size();
msg.opts := {2, 4}; (* update, guardcheck *)
Views.Omnicast(msg)
END SendNotifyMsg;
PROCEDURE GetSize(c: Control; OUT rows, cols: INTEGER);
VAR item: Meta.Item;
BEGIN
IF c.item.Valid() THEN
item := c.item;
c.item.Lookup("rows", item); rows := item.IntVal();
c.item.Lookup("cols", item); cols := item.IntVal()
ELSE
rows := 0; cols := 0
END
END GetSize;
PROCEDURE GetLabel(c: Control; col: INTEGER; OUT val: Dialog.String; OUT ok: BOOLEAN);
VAR t: TableValue;
BEGIN
ASSERT(c.item.Valid(), 20);
c.item.GetVal(t, ok); t.t.GetLabel(col, val)
END GetLabel;
PROCEDURE GetAttr(c: Control; row, col: INTEGER;
OUT style: SET; OUT weight: INTEGER; OUT color: Ports.Color; OUT ok: BOOLEAN);
VAR t: TableValue;
BEGIN
ASSERT(c.item.Valid(), 20);
c.item.GetVal(t, ok); t.t.GetAttr(row, col, style, weight, color)
END GetAttr;
PROCEDURE GetText(c: Control; row, col: INTEGER; OUT val: Dialog.String; OUT ok: BOOLEAN);
VAR t: TableValue;
BEGIN
ASSERT(c.item.Valid(), 20);
c.item.GetVal(t, ok); t.t.GetItem(row, col, val)
END GetText;
PROCEDURE SetText(c: Control; f: Views.Frame; row, col: INTEGER; IN val: Dialog.String; OUT ok: BOOLEAN);
VAR t: TableValue;
BEGIN
ASSERT(c.item.Valid(), 20);
c.item.GetVal(t, ok);
IF ok THEN
t.t.SetItem(row, col, val);
(* Notify(c, row, col, {}, changed); *)
SendNotifyMsg(c);
Controls.Notify(c, f, changed, row, col)
END
END SetText;
PROCEDURE GetSelection(c: Control; OUT on: BOOLEAN; OUT row, col: INTEGER; OUT ok: BOOLEAN);
VAR t: TableValue;
BEGIN
ASSERT(c.item.Valid(), 20);
c.item.GetVal(t, ok);
IF ok THEN
on := t.t.HasSelection();
IF on THEN t.t.GetSelection(row, col) ELSE row := -1; col := -1 END
END
END GetSelection;
PROCEDURE SetSelection(c: Control; f: Views.Frame; on: BOOLEAN; row, col: INTEGER; OUT ok: BOOLEAN);
VAR t: TableValue;
BEGIN
ASSERT(c.item.Valid(), 20);
c.item.GetVal(t, ok);
IF ok THEN
IF on THEN t.t.Select(row, col); Controls.Notify(c, f, select, row, col)
ELSE t.t.Deselect; Controls.Notify(c, f, deselect, row, col)
END;
SendNotifyMsg(c)
END
END SetSelection;
PROCEDURE SetupControl (t: Control);
VAR i, asc, dsc, w: INTEGER;
BEGIN
t.fldFont := Fonts.dir.This(t.sprop.typeface, t.sprop.size, t.sprop.style.val, Fonts.normal);
t.titFont := Fonts.dir.This(t.sprop.typeface, t.sprop.size, t.sprop.style.val, Fonts.bold);
t.rowHeight := 3 * t.sprop.size DIV 2;
t.fldFont.GetBounds(asc, dsc, w);
t.rowHeight := asc + dsc + 4 * Ports.point;
t.baseOff := (t.rowHeight - asc - dsc) DIV 2 + asc;
i := t.columns;
WHILE i < maxCol DO t.width[i] := defColW; t.mode[i] := center; INC(i) END;
IF t.field # NIL THEN
t.field.context(Context).h := t.rowHeight
END;
t.labelHeight := t.rowHeight
END SetupControl;
(** Directory **)
PROCEDURE (d: Directory) NewControl* (p: Controls.Prop): Views.View, NEW, ABSTRACT;
(* PropOp *)
PROCEDURE (op: PropOp) Do;
VAR c: Control; sprop: Properties.StdProp; tprop: Prop;
BEGIN
ASSERT((op.sprop # NIL) OR (op.tprop # NIL), 20);
c := op.tab;
IF op.sprop # NIL THEN
sprop := Properties.CopyOf(c.sprop)(Properties.StdProp);
sprop.valid := op.sprop.valid; (* fields to be restored *)
IF Properties.typeface IN sprop.valid THEN c.sprop.typeface := op.sprop.typeface END;
IF Properties.size IN sprop.valid THEN c.sprop.size := op.sprop.size END;
IF Properties.style IN sprop.valid THEN
c.sprop.style.mask := c.sprop.style.mask + op.sprop.style.mask;
c.sprop.style.val := c.sprop.style.val - op.sprop.style.mask + op.sprop.style.val
END;
IF sprop.valid # {} THEN SetupControl(c) END;
op.sprop := sprop
END;
IF op.tprop # NIL THEN
tprop := Properties.CopyOf(c.tprop)(Prop);
tprop.valid := op.tprop.valid; (* fields to be restored *)
IF layoutEditable IN tprop.valid THEN c.tprop.layoutEditable := op.tprop.layoutEditable END;
IF dataEditable IN tprop.valid THEN c.tprop.dataEditable := op.tprop.dataEditable END;
IF selectionStyle IN tprop.valid THEN c.tprop.selectionStyle := op.tprop.selectionStyle END;
op.tprop := tprop
END;
Views.Update(c, Views.rebuildFrames)
END Do;
(* FormatOp *)
PROCEDURE (op: FormatOp) Do;
VAR t: Control; c, w, m: INTEGER;
BEGIN
t := op.tab; c := op.col; w := op.width; m := op.mode;
op.width := t.width[c]; op.mode := t.mode[c];
t.width[c] := w; t.mode[c] := m;
IF c >= t.columns THEN t.columns := c + 1 END;
Views.Update(t, Views.keepFrames)
END Do;
(* properties *)
PROCEDURE PollProp (c: Control; VAR list: Properties.Property);
VAR p: Properties.Property;
BEGIN
p := Properties.CopyOf(c.sprop);
p.valid := {Properties.typeface, Properties.size, Properties.style, Properties.weight};
p.known := p.valid; p.readOnly := {Properties.weight};
Properties.Insert(list, p);
p := Properties.CopyOf(c.tprop);
p.valid := {layoutEditable, dataEditable, selectionStyle}; p.known := p.valid; p.readOnly := {};
Properties.Insert(list, p)
END PollProp;
PROCEDURE SetProp (c: Control; p: Properties.Property);
VAR op: PropOp; valid: SET;
BEGIN
op := NIL;
WHILE p # NIL DO
WITH p: Properties.StdProp DO
valid := p.valid * {Properties.typeface, Properties.size, Properties.style};
IF valid # {} THEN
IF op = NIL THEN NEW(op); op.tab := c END;
op.sprop := Properties.CopyOf(p)(Properties.StdProp);
op.sprop.valid := valid
END
| p: Prop DO
valid := p.valid * {layoutEditable, dataEditable, selectionStyle};
IF valid # {} THEN
IF op = NIL THEN NEW(op); op.tab := c END;
op.tprop := Properties.CopyOf(p)(Prop);
op.tprop.valid := valid
END
ELSE
END;
p := p.next
END;
IF op # NIL THEN Views.Do(c, "#System:SetProp", op) END
END SetProp;
(* Control *)
PROCEDURE DrawBorder (f: Views.Frame; x, y, w, h: INTEGER);
BEGIN
f.DrawRect(x, y, x+f.dot, y+h, Ports.fill, Ports.white);
f.DrawRect(x+f.dot, y+0, x+2 * f.dot, y+ h, Ports.fill, Ports.grey25);
f.DrawRect(x+0, y+0, x+w, y+f.dot, Ports.fill, Ports.white);
f.DrawRect(x+f.dot, y+f.dot, x+w, y+2 * f.dot, Ports.fill, Ports.grey25);
f.DrawRect(x+w - f.dot, y+0, x+w, y+h, Ports.fill, Ports.grey50);
f.DrawRect(x+w - 2 * f.dot, y+f.dot, x+w - f.dot, y+h - f.dot, Ports.fill, Ports.black);
f.DrawRect(x+0, y+h - f.dot, x+w, y+h, Ports.fill, Ports.grey50);
f.DrawRect(x+f.dot, y+h - 2 * f.dot, x+w - f.dot, y+h - f.dot, Ports.fill, Ports.black)
END DrawBorder;
PROCEDURE DrawLabel (f: Views.Frame; x, y, w, x0, y0, w0, h0, mode: INTEGER;
VAR is: ARRAY OF CHAR; font: Fonts.Font; rowHeight: INTEGER);
VAR dx, i, j, si, sw, rw: INTEGER; s: Dialog.String;
BEGIN
DEC(w, 4 * f.dot); INC(x, 2 * f.dot);
j := 0; y := y - rowHeight;
WHILE is[j] # 0X DO
si := 0;
WHILE (is[j] # 0X) & (is[j] # line) DO s[si] := is[j]; INC(si); INC(j) END;
IF is[j] = line THEN INC(j) END;
s[si] := 0X; y := y + rowHeight;
sw := font.StringWidth(s);
IF sw > w THEN
rw := w - font.StringWidth("...");
IF (rw >= 0) & (LEN(s) >= 4) THEN
i := f.CharIndex(0, rw, s, font);
IF i > 0 THEN DEC(i) END;
IF i > LEN(s) - 4 THEN i := LEN(s) - 4 END;
s[i] := "."; s[i+1] := "."; s[i+2] := "."; s[i+3] := 0X;
sw := font.StringWidth(s)
ELSE sw := 0
END
END;
IF sw > 0 THEN
dx := x;
IF mode = center THEN dx := x + (w - sw) DIV 2
ELSIF mode = right THEN dx := x + w - sw
END;
f.DrawString(dx, y, Ports.black, s, font)
END
END;
DrawBorder(f, x0, y0, w0, h0)
END DrawLabel;
PROCEDURE DrawField (f: Views.Frame; x, y, w, mode: INTEGER; VAR s: ARRAY OF CHAR; font: Fonts.Font;
color: Ports.Color);
VAR i, sw, rw: INTEGER;
BEGIN
DEC(w, 4 * f.dot); INC(x, 2 * f.dot);
sw := font.StringWidth(s);
IF sw > w THEN
rw := w - font.StringWidth("...");
IF (rw >= 0) & (LEN(s) >= 4) THEN
i := f.CharIndex(0, rw, s, font);
IF i > 0 THEN DEC(i) END;
IF i > LEN(s) - 4 THEN i := LEN(s) - 4 END;
s[i] := "."; s[i+1] := "."; s[i+2] := "."; s[i+3] := 0X;
sw := font.StringWidth(s)
ELSE sw := 0
END
END;
IF sw > 0 THEN
IF mode = center THEN INC(x, (w - sw) DIV 2)
ELSIF mode = right THEN INC(x, w - sw)
END;
f.DrawString(x, y, color, s, font)
END
END DrawField;
PROCEDURE GetRect(t: Control; f: Views.Frame; row, col: INTEGER; OUT x, y, w, h: INTEGER;
OUT visible: BOOLEAN);
VAR c: INTEGER;
BEGIN
c := 0; x := 2 * f.dot - t.orgX;
WHILE c < col DO INC(x, t.width[c]); INC(c) END;
IF row >= t.orgRow THEN
visible := TRUE;
IF row = -1 THEN
h := t.labelHeight
ELSE
h := t.rowHeight
END;
y := (row - t.orgRow) * t.rowHeight + t.labelHeight + 3 * f.dot;
w := t.width[col]
ELSE
visible := FALSE
END
END GetRect;
PROCEDURE DrawSelection (tab: Control; f: Views.Frame; selRow, selCol: INTEGER; show: BOOLEAN);
VAR c, l, t, r, b, cols, rows: INTEGER;
BEGIN
IF (selRow >= tab.orgRow) OR (tab.tprop.selectionStyle IN {colSelect, crossSelect}) THEN
GetSize(tab, rows, cols);
IF (0 <= selRow) & (selRow < rows) & (0 <= selCol) & (selCol < cols) THEN
IF tab.tprop.selectionStyle = cellSelect THEN (* mark selected cell *)
l := 2 * f.dot - tab.orgX; c := 0;
WHILE c < selCol DO INC(l, tab.width[c]); INC(c) END;
r := l + tab.width[selCol];
t := (selRow - tab.orgRow) * tab.rowHeight + tab.labelHeight + 3 * f.dot;
b := t + tab.rowHeight;
f.MarkRect(l + f.dot, t + f.dot, r - 2 * f.dot, b - 2 * f.dot, Ports.fill, Ports.hilite, show)
ELSIF tab.tprop.selectionStyle = rowSelect THEN (* mark selected row *)
l := 2 * f.dot - tab.orgX; r := l; c := 0;
WHILE c < cols DO INC(r, tab.width[c]); INC(c) END;
t := (selRow - tab.orgRow) * tab.rowHeight + tab.labelHeight + 3 * f.dot;
b := t + tab.rowHeight;
f.MarkRect(l + f.dot, t + f.dot, r - 2 * f.dot, b - 2 * f.dot, Ports.fill, Ports.hilite, show)
ELSIF tab.tprop.selectionStyle = colSelect THEN (* mark selected column *)
l := 2 * f.dot - tab.orgX; c := 0;
WHILE c < selCol DO INC(l, tab.width[c]); INC(c) END;
r := l + tab.width[selCol];
t := tab.labelHeight + 3 * f.dot;
b := t + tab.rowHeight * (rows - tab.orgRow);
f.MarkRect(l + f.dot, t + f.dot, r - 2 * f.dot, b - 2 * f.dot, Ports.fill, Ports.hilite, show)
ELSIF tab.tprop.selectionStyle = crossSelect THEN (* mark both the row and column *)
IF selRow >= tab.orgRow THEN
l := 2 * f.dot - tab.orgX; r := l; c := 0;
t := (selRow - tab.orgRow) * tab.rowHeight + tab.labelHeight + 3 * f.dot;
b := t + tab.rowHeight;
IF selCol > 0 THEN
WHILE c < selCol DO INC(r, tab.width[c]); INC(c) END;
f.MarkRect(l + f.dot, t + f.dot, r - 2 * f.dot, b - 2 * f.dot, Ports.fill, Ports.hilite, show)
END;
IF selCol + 1 < cols THEN
r := r + tab.width[selCol]; l := r; c := selCol + 1;
WHILE c < cols DO INC(r, tab.width[c]); INC(c) END;
f.MarkRect(l + f.dot, t + f.dot, r - 2 * f.dot, b - 2 * f.dot, Ports.fill, Ports.hilite, show)
END
END;
l := 2 * f.dot - tab.orgX; c := 0;
WHILE c < selCol DO INC(l, tab.width[c]); INC(c) END;
r := l + tab.width[selCol];
t := tab.labelHeight + 3 * f.dot;
b := t + tab.rowHeight * (rows - tab.orgRow);
f.MarkRect(l + f.dot, t + f.dot, r - 2 * f.dot, b - 2 * f.dot, Ports.fill, Ports.hilite, show)
END
END
END
END DrawSelection;
PROCEDURE Select (c: Control; f: Views.Frame; on: BOOLEAN);
VAR ok: BOOLEAN;
BEGIN
IF on # c.hasSelection THEN
c.hasSelection := on; c.showSelection := on;
SetSelection(c, f, on, c.selRow, c.selCol, ok)
END
END Select;
PROCEDURE ViewFromSelection (t: Control): Views.View;
VAR str: Dialog.String; ok: BOOLEAN;
BEGIN
IF t.hasSelection & t.showSelection THEN
GetText(t, t.selRow, t.selCol, str, ok);
IF ok THEN
RETURN TextViews.dir.New(TextModels.dir.NewFromString(str))
ELSE
RETURN NIL
END
ELSE RETURN NIL
END
END ViewFromSelection;
PROCEDURE GetControlSize (t: Control; dot: INTEGER; OUT w, h: LONGINT);
VAR r, c, i: INTEGER;
BEGIN
IF ~t.disabled & t.item.Valid() THEN
w := 0; h := 0;
GetSize(t, r, c);
i := 0;
WHILE (i < c) & (i < maxCol) DO INC(w, t.width[i]); INC(i) END;
INC(w, 3 * dot);
h := LONG(r - t.orgRow) * t.rowHeight + t.labelHeight
ELSE
w := Views.undefined; h := Views.undefined
END
END GetControlSize;
PROCEDURE CheckPos (t: Control; x, y, dot: INTEGER; VAR col, type, p: INTEGER);
VAR c, a: INTEGER; w, h: LONGINT;
BEGIN
GetControlSize(t, dot, w, h);
INC(x, t.orgX);
IF (x >= 0) & (x <= w) & (y >= 0) & (y <= h) THEN
c := 0; w := 0; type := 0; INC(x, dot);
WHILE (c < maxCol) & (x >= w + t.width[c]) DO INC(w, t.width[c]); INC(c) END;
IF (x <= w + 3 * dot) & (c > 0) THEN
col := c - 1; p := SHORT(w) + dot - t.orgX; type := move
ELSIF y - dot < t.labelHeight THEN
type := adjust;
col := c; a := t.width[c] DIV 3;
IF x < w + a THEN p := left
ELSIF x > w + a * 2 THEN p := right
ELSE p := center
END
ELSE
col := c; p := (y - t.labelHeight - dot) DIV t.rowHeight + t.orgRow - 1 + 1; type := field
END
ELSE type := 0
END
END CheckPos;
PROCEDURE MoveLine (t: Control; f: Views.Frame; col, x0: INTEGER);
VAR w, h, x, y, x1, limit: INTEGER; m: SET; isDown: BOOLEAN; op: FormatOp;
BEGIN
t.context.GetSize(w, h);
x := x0; limit := x0 - t.width[col] + 2 * f.dot;
REPEAT
f.Input(x1, y, m, isDown);
IF x1 < limit THEN x1 := limit END;
IF x1 # x THEN
f.MarkRect(x, 0, x + f.dot, h, Ports.fill, Ports.invert, FALSE);
x := x1;
f.MarkRect(x, 0, x + f.dot, h, Ports.fill, Ports.invert, TRUE)
END
UNTIL ~isDown;
NEW(op); op.tab := t; op.col := col;
op.width := t.width[col] + x - x0; op.mode := t.mode[col];
Views.Do(t, "#System:SetLayout", op)
END MoveLine;
PROCEDURE ChangeAdjust (t: Control; col, mode: INTEGER);
VAR op: FormatOp;
BEGIN
NEW(op); op.tab := t; op.col := col;
op.width := t.width[col]; op.mode := mode;
Views.Do(t, "#System:SetLayout", op)
END ChangeAdjust;
PROCEDURE ControlSections (t: Control; f: Views.Frame; vertical: BOOLEAN; OUT size, part, pos: INTEGER);
VAR r, c, w, max: INTEGER;
BEGIN
size := 0; part := 0; pos := 0; GetSize(t, r, c);
IF vertical THEN
size := r;
part := (f.b - (f.t + t.labelHeight + 3*f.dot)) DIV t.rowHeight;
pos := t.orgRow
ELSE
w := 0; max := MIN(c, maxCol);
c := 0;
WHILE (c < max) DO INC(w, t.width[c]); INC(c) END;
size := w + 3 * f.dot;
part := f.r - f.l;
pos := t.orgX
END
END ControlSections;
PROCEDURE ScrollControl (t: Control; f: Views.Frame; op, pos: INTEGER; vertical: BOOLEAN);
VAR size, part, p, delta, l, t0, r, b: INTEGER;
BEGIN
IF vertical THEN
ControlSections(t, f, TRUE, size, part, p);
delta := part - 1;
IF delta < 1 THEN delta := 1 END;
CASE op OF
| Controllers.decLine: DEC(p)
| Controllers.incLine: INC(p)
| Controllers.decPage: DEC(p, delta)
| Controllers.incPage: INC(p, delta)
| Controllers.gotoPos: p := pos
END;
IF p > size - part THEN p := size - part END;
IF p < 0 THEN p := 0 END;
delta := (f.gy + t.labelHeight + 3 * f.dot) DIV f.unit;
f.rider.GetRect(l, t0, r, b);
IF b > delta THEN
IF t0 < delta THEN f.rider.SetRect(l, delta, r, b) END;
Views.Scroll(t, 0, (t.orgRow - p) * t.rowHeight);
IF f.rider # NIL THEN
f.rider.SetRect(l, t0, r, b)
END
END;
t.orgRow := p
ELSE
ControlSections(t, f, FALSE, size, part, p);
delta := part - defColW;
IF delta < defColW THEN delta := defColW END;
CASE op OF
| Controllers.decLine: DEC(p, defColW)
| Controllers.incLine: INC(p, defColW)
| Controllers.decPage: DEC(p, delta)
| Controllers.incPage: INC(p, delta)
| Controllers.gotoPos: p := pos
END;
IF p >= size - part THEN p := size - part END;
IF p < 0 THEN p := 0 END;
Views.Scroll(t, t.orgX - p, 0);
t.orgX := p
END
END ScrollControl;
PROCEDURE HandleChar (t: Control; f: Views.Frame; ch: CHAR);
BEGIN
CASE ch OF
| 10X: ScrollControl(t, f, Controllers.decPage, 0, FALSE)
| 11X: ScrollControl(t, f, Controllers.incPage, 0, FALSE)
| 12X: ScrollControl(t, f, Controllers.decPage, 0, TRUE)
| 13X: ScrollControl(t, f, Controllers.incPage, 0, TRUE)
| 14X: ScrollControl(t, f, Controllers.gotoPos, 0, FALSE)
| 15X: ScrollControl(t, f, Controllers.gotoPos, MAX(INTEGER), FALSE)
| 16X: ScrollControl(t, f, Controllers.gotoPos, 0, TRUE)
| 17X: ScrollControl(t, f, Controllers.gotoPos, MAX(INTEGER), TRUE)
| 1CX: ScrollControl(t, f, Controllers.decLine, 0, FALSE)
| 1DX: ScrollControl(t, f, Controllers.incLine, 0, FALSE)
| 1EX: ScrollControl(t, f, Controllers.decLine, 0, TRUE)
| 1FX: ScrollControl(t, f, Controllers.incLine, 0, TRUE)
| 07X, 08X, 1BX: Select(t, f, FALSE) (* rdel, del, esc *)
ELSE
END
END HandleChar;
PROCEDURE (t: Control) Internalize2 (VAR rd: Stores.Reader);
VAR thisVersion, i: INTEGER; lockedLayout, lockedData, markRow, markCol: BOOLEAN;
BEGIN
rd.ReadVersion(minVersion, tabVersion, thisVersion);
IF ~rd.cancelled THEN
IF thisVersion = tabVersion THEN (* current table version *)
NEW(t.tprop);
rd.ReadBool(t.tprop.layoutEditable);
rd.ReadBool(t.tprop.dataEditable);
rd.ReadInt(t.tprop.selectionStyle)
ELSIF thisVersion = 1 THEN (* intermediate Table version (after 1.4 Beta, before 1.4 final) *)
rd.ReadBool(lockedLayout);
rd.ReadBool(lockedData);
rd.ReadBool(markRow);
rd.ReadBool(markCol);
NEW(t.tprop);
t.tprop.layoutEditable := ~lockedLayout; t.tprop.dataEditable := ~lockedData;
IF markRow THEN
IF markCol THEN t.tprop.selectionStyle := noSelect ELSE t.tprop.selectionStyle := rowSelect END
ELSE
IF markCol THEN t.tprop.selectionStyle := colSelect ELSE t.tprop.selectionStyle := cellSelect END
END
ELSE (* old version, 1.4 Beta *)
t.tprop.layoutEditable := TRUE; t.tprop.dataEditable := TRUE; t.tprop.selectionStyle := cellSelect
END;
NEW(t.sprop);
rd.ReadString(t.sprop.typeface);
rd.ReadInt(t.sprop.size);
rd.ReadSet(t.sprop.style.val);
t.sprop.style.mask := {Fonts.italic, Fonts.underline, Fonts.strikeout};
t.sprop.weight := Fonts.normal;
rd.ReadInt(t.columns); i := 0;
WHILE i < t.columns DO
rd.ReadInt(t.width[i]);
rd.ReadInt(t.mode[i]);
INC(i)
END;
SetupControl(t)
END
END Internalize2;
PROCEDURE (t: Control) Externalize2 (VAR wr: Stores.Writer);
VAR i: INTEGER;
BEGIN
wr.WriteVersion(tabVersion);
wr.WriteBool(t.tprop.layoutEditable);
wr.WriteBool(t.tprop.dataEditable);
wr.WriteInt(t.tprop.selectionStyle);
wr.WriteString(t.sprop.typeface);
wr.WriteInt(t.sprop.size);
wr.WriteSet(t.sprop.style.val);
wr.WriteInt(t.columns); i := 0;
WHILE i < t.columns DO
wr.WriteInt(t.width[i]);
wr.WriteInt(t.mode[i]);
INC(i)
END
END Externalize2;
PROCEDURE (t: Control) CopyFromSimpleView2 (source: Controls.Control);
BEGIN
WITH source: Control DO
t.sprop := Properties.CopyOf(source.sprop)(Properties.StdProp);
t.tprop := Properties.CopyOf(source.tprop)(Prop);
t.columns := source.columns;
t.width := source.width;
t.mode := source.mode;
SetupControl(t)
END
END CopyFromSimpleView2;
PROCEDURE (t: Control) GetBackground (VAR color: Ports.Color);
BEGIN
color := Ports.background
END GetBackground;
PROCEDURE Paint (c: Control; f: Views.Frame; l, t, r, b: INTEGER);
VAR width, w, h, rows, cols, row, col, x, y, rowHeight, dl, weight: INTEGER; font: Fonts.Font;
str: Dialog.String; ok: BOOLEAN;style: SET; color: Ports.Color;
BEGIN
c.context.GetSize(w, h);
IF ~c.disabled & c.item.Valid() THEN
GetSize(c, rows, cols);
DEC(c.rowHeight, c.rowHeight MOD f.unit);
row := -1; y := 2 * f.dot; font := c.titFont;
WHILE (row < rows) & (y < b) DO
IF row = - 1 THEN
rowHeight := 1;
FOR col := 0 TO cols - 1 DO
GetLabel(c, col, str, ok); dl := CountLines(str);
IF dl > rowHeight THEN rowHeight := dl END
END;
rowHeight := rowHeight * c.rowHeight;
c.labelHeight := rowHeight
ELSE
rowHeight := c.rowHeight
END;
IF ~Views.IsPrinterFrame(f) OR (y + rowHeight < b) THEN
col := 0; x := 2 * f.dot - c.orgX;
WHILE (col < cols) & (col < maxCol) & (x < r) DO
width := c.width[col];
IF x + width >= 0 THEN
f.DrawRect(x - f.dot, y, x, y + rowHeight, Ports.fill, Ports.black); (* left vertical separation line *)
IF ~Views.IsPrinterFrame(f) OR (x + width < r) THEN
IF row = -1 THEN
GetLabel(c, col, str, ok);
f.DrawRect(x, y, x + width - f.dot, y + rowHeight - f.dot, Ports.fill, Ports.grey25);
(* background *)
DrawLabel(f, x, y + c.baseOff, width - f.dot, x, y, width, rowHeight,
c.mode[col], str, font, c.rowHeight)
ELSE
GetText(c, row, col, str, ok); GetAttr(c, row, col, style, weight, color, ok);
f.DrawRect(x, y, x + width - f.dot, y + rowHeight - f.dot, Ports.fill, Ports.white);
(* background *)
DrawField(f, x, y + c.baseOff, width - f.dot, c.mode[col], str,
Fonts.dir.This(font.typeface, font.size, style, weight), color)
END
END
END;
INC(col); INC(x, width)
END;
f.DrawRect(x - f.dot, y, x, y + rowHeight, Ports.fill, Ports.black); (* right vertical separator line *)
IF Views.IsPrinterFrame(f) & (x >= r) THEN DEC(x, width) END;
IF row = -1 THEN row := c.orgRow; font := c.fldFont; INC(y, f.dot)
ELSE INC(row)
END
END;
INC(y, rowHeight);
f.DrawRect(f.dot - c.orgX, y - f.dot, x, y, Ports.fill, Ports.black) (* bottom line *)
END;
IF f.dot - c.orgX < x THEN
f.DrawRect(f.dot - c.orgX, f.dot, x, 2 * f.dot, Ports.fill, Ports.black);
f.DrawRect(f.dot - c.orgX, c.labelHeight + f.dot, x, c.labelHeight + 2 * f.dot, Ports.fill, Ports.black)
END
ELSE
f.DrawRect(f.dot, f.dot, w - f.dot, h - f.dot, Ports.fill, Ports.grey25);
f.DrawRect(0, 0, w, h, f.dot, Ports.black)
END
END Paint;
PROCEDURE (c: Control) Restore (f: Views.Frame; l, t, r, b: INTEGER);
VAR visible: BOOLEAN; g: Views.Frame;
BEGIN
Paint(c, f, l, t, r, b);
IF c.field # NIL THEN
GetRect(c, f, c.selRow, c.selCol, c.x, c.y, c.w, c.h, visible);
IF visible THEN Views.InstallFrame(f, c.field, c.x, c.y, 0, TRUE)
ELSE
g := Views.ThisFrame(f, c.field); IF g # NIL THEN Views.RemoveFrame(f, g) END
END
END
END Restore;
PROCEDURE (c: Control) Update (f: Views.Frame; op, from, to: INTEGER);
BEGIN
Views.Update(c, Views.keepFrames)
END Update;
PROCEDURE (c: Control) RestoreMarks (f: Views.Frame; l, t, r, b: INTEGER);
VAR row, col: INTEGER; ok, on: BOOLEAN;
BEGIN
IF c.item.Valid() THEN
GetSelection(c, on, row, col, ok);
IF ok THEN
c.hasSelection := on;
IF on THEN
c.selRow := row; c.selCol := col;
c.showSelection := c.field = NIL;
IF c.showSelection THEN DrawSelection(c, f, c.selRow, c.selCol, TRUE) END
END
END
END
END RestoreMarks;
PROCEDURE AddEditField (t: Control; f: Views.Frame; row, col: INTEGER);
VAR g: Views.Frame; mMsg: Controllers.MarkMsg; ok, visible: BOOLEAN;
BEGIN
GetRect(t, f, row, col, t.x, t.y, t.w, t.h, visible);
IF visible THEN
GetText(t, row, col, text, ok);
t.field := NewField(t, col, t.w, t.h); Stores.Join(t, t.field);
Views.InstallFrame(f, t.field, t.x, t.y, 0, TRUE);
mMsg.show := TRUE; mMsg.focus := TRUE;
g := Views.ThisFrame(f, t.field);
IF g # NIL THEN Views.ForwardCtrlMsg(g, mMsg) END
END
END AddEditField;
PROCEDURE DisableEditField (t: Control; f: Views.Frame; update: BOOLEAN);
VAR g: Views.Frame; mMsg: Controllers.MarkMsg; ok: BOOLEAN;
BEGIN
IF t.field # NIL THEN
mMsg.show := FALSE; mMsg.focus := FALSE;
g := Views.ThisFrame(f, t.field);
IF g # NIL THEN Views.ForwardCtrlMsg(g, mMsg); Views.RemoveFrame(f, g) END;
t.field := NIL;
IF update THEN SetText(t, f, t.selRow, t.selCol, text, ok) END;
t.showSelection := TRUE
END
END DisableEditField;
PROCEDURE MoveEditField (t: Control; f: Views.Frame; right: BOOLEAN);
VAR rows, cols: INTEGER; ok: BOOLEAN;
BEGIN
DisableEditField(t, f, TRUE);
GetSize(t, rows, cols);
Select(t, f, FALSE);
IF right THEN
t.selCol := (t.selCol + 1) MOD cols;
IF t.selCol = 0 THEN t.selRow := (t.selRow + 1) MOD rows END
ELSE
t.selCol := (t.selCol - 1) MOD cols;
IF t.selCol = cols - 1 THEN t.selRow := (t.selRow - 1) MOD rows END
END;
t.hasSelection := TRUE; t.showSelection := FALSE;
SetSelection(t, f, TRUE, t.selRow, t.selCol, ok);
AddEditField(t, f, t.selRow, t.selCol)
END MoveEditField;
PROCEDURE TrackMouse (t: Control; f: Views.Frame; VAR r, c, type: INTEGER);
VAR x, y, selr, selc: INTEGER; m: SET; isDown, sel: BOOLEAN;
BEGIN
selr := t.selRow; selc := t.selCol; sel := t.hasSelection;
REPEAT
f.Input(x, y, m, isDown);
CheckPos(t, x, y, f.dot, c, type, r);
IF sel & ((type # field) OR (selr # r) OR (selc # c)) THEN
DrawSelection(t, f, selr, selc, FALSE)
END;
IF (type = field) & (~sel OR (selr # r) OR (selc # c)) THEN
DrawSelection(t, f, r, c, TRUE)
END;
sel := type = field; selr := r; selc := c
UNTIL ~isDown;
IF ~sel & t.hasSelection THEN
DrawSelection(t, f, t.selRow, t.selCol, TRUE)
END
END TrackMouse;
PROCEDURE (t: Control) HandleCtrlMsg2 (f: Views.Frame; VAR msg: Controllers.Message;
VAR focus: Views.View);
VAR p, col, type: INTEGER; x, y: INTEGER; m: SET; isDown: BOOLEAN;
ok, rebuild: BOOLEAN; c, w, size, part, pos: INTEGER;
BEGIN
IF ~t.disabled & t.item.Valid() THEN
WITH msg: Controllers.PollOpsMsg DO
IF t.field # NIL THEN focus := t.field
ELSIF t.hasSelection THEN msg.valid := {Controllers.copy}
END
| msg: Controllers.PollCursorMsg DO
IF (t.field # NIL) & (msg.x >= t.x) & (msg.x <= t.x + t.w) & (msg.y >= t.y) & (msg.y <= t.y + t.h) THEN
focus := t.field
ELSE
CheckPos(t, msg.x, msg.y, f.dot, col, type, p);
IF (type = move) & t.tprop.layoutEditable THEN
msg.cursor := Ports.refCursor (* HostPorts.resizeHCursor TODO *)
ELSIF (type = adjust) & t.tprop.layoutEditable THEN msg.cursor := Ports.refCursor
ELSIF ~t.readOnly & (type = field) THEN msg.cursor := Ports.tableCursor
END
END
| msg: Controllers.MarkMsg DO
IF t.field # NIL THEN DisableEditField(t, f, TRUE); Views.Update(t, Views.rebuildFrames) END
| msg: Controllers.SelectMsg DO
IF t.field # NIL THEN focus := t.field
ELSIF ~msg.set THEN Select(t, f, FALSE)
END
| msg: Controllers.EditMsg DO
IF t.field # NIL THEN
IF msg.op = Controllers.pasteChar THEN
IF (msg.char = lineChar) OR (msg.char = esc) THEN
DisableEditField(t, f, msg.char # esc); Views.Update(t, Views.rebuildFrames)
ELSIF (msg.char = tab) OR (msg.char = ltab) THEN
MoveEditField(t, f, msg.char = tab); Views.Update(t, Views.rebuildFrames)
ELSE
focus := t.field
END
ELSE
focus := t.field
END
ELSE
IF (msg.op = Controllers.pasteChar) & (msg.char = lineChar) &
(t.tprop.selectionStyle = cellSelect) & t.hasSelection THEN
t.showSelection := FALSE;
SetSelection(t, f, TRUE, t.selRow, t.selCol, ok);
AddEditField(t, f, t.selRow, t.selCol); Views.Update(t, Views.keepFrames)
ELSIF msg.op = Controllers.pasteChar THEN
HandleChar(t, f, msg.char)
ELSIF msg.op = Controllers.copy THEN
msg.view := ViewFromSelection(t);
msg.w := 0; msg.h := 0; msg.isSingle := FALSE
END
END
| msg: Controllers.TrackMsg DO
IF (t.field # NIL) & (msg.x >= t.x) & (msg.x <= t.x + t.w) & (msg.y >= t.y) & (msg.y <= t.y + t.h) THEN
focus := t.field
ELSE
rebuild := t.field # NIL; DisableEditField(t, f, TRUE); (* update below after notifications *)
CheckPos(t, msg.x, msg.y, f.dot, col, type, p);
IF type = move THEN
IF t.tprop.layoutEditable THEN
MoveLine(t, f, col, p)
END
ELSIF type = adjust THEN
IF t.tprop.layoutEditable THEN
ChangeAdjust(t, col, p);
REPEAT f.Input(x, y, m, isDown) UNTIL ~isDown
END
ELSIF ~t.readOnly & (type = field) THEN
TrackMouse(t, f, p, col, type);
IF type = field THEN
IF ~t.readOnly & t.tprop.dataEditable
& ((Controllers.doubleClick IN msg.modifiers) OR (t.tprop.selectionStyle = noSelect))
THEN
Select(t, f, FALSE);
t.selRow := p; t.selCol := col; t.hasSelection := TRUE; t.showSelection := FALSE;
SetSelection(t, f, TRUE, t.selRow, t.selCol, ok);
AddEditField(t, f, p, col); Views.Update(t, Views.keepFrames)
ELSE
IF (t.selRow # p) OR (t.selCol # col) OR ~t.hasSelection THEN
Select(t, f, FALSE);
t.selRow := p; t.selCol := col;
Select(t, f, TRUE)
ELSIF t.tprop.selectionStyle = cellSelect THEN Select(t, f, FALSE)
END
END
END
END;
IF rebuild THEN Views.Update(t, Views.rebuildFrames) END
END
| msg: Controllers.PollSectionMsg DO
ControlSections(t, f, msg.vertical, msg.wholeSize, msg.partSize, msg.partPos);
IF (msg.partPos > 0) & (msg.partPos > msg.wholeSize - msg.partSize) THEN
ScrollControl(t, f, Controllers.gotoPos, msg.wholeSize - msg.partSize, msg.vertical);
ControlSections(t, f, msg.vertical, msg.wholeSize, msg.partSize, msg.partPos)
END;
msg.valid := msg.partSize < msg.wholeSize;
msg.done := TRUE
| msg: Controllers.ScrollMsg DO
ScrollControl(t, f, msg.op, msg.pos, msg.vertical);
msg.done := TRUE
| msg: Controllers.PageMsg DO
IF msg.op IN {Controllers.nextPageY, Controllers.gotoPageY} THEN (* vertical *)
ControlSections(t, f, TRUE, size, part, pos);
IF msg.op = Controllers.nextPageY THEN
t.orgRow := pos + part
ELSE
t.orgRow := msg.pageY * part
END;
msg.done := TRUE;
msg.eoy :=t.orgRow >= size
ELSE (* horizontal *)
ControlSections(t, f, FALSE, size, part, pos);
IF msg.op = Controllers.nextPageX THEN
t.orgX := pos + part
ELSE
t.orgX := msg.pageX * part
END;
IF (t.orgX > 0) & (t.orgX < size) THEN
c := 0; w := 0;
WHILE w < t.orgX DO INC(w, t.width[c]); INC(c) END;
t.orgX := w - t.width[c-1] + 1*f.dot
END;
msg.done := TRUE;
msg.eox :=t.orgX >= size
END
ELSE
END
END
END HandleCtrlMsg2;
PROCEDURE (t: Control) HandlePropMsg2 (VAR msg: Properties.Message);
VAR w, h: LONGINT;
BEGIN
WITH msg: Properties.FocusPref DO
IF ~t.disabled THEN msg.setFocus := TRUE END
| msg: Properties.SizePref DO
IF (msg.w = Views.undefined) & (msg.h = Views.undefined) THEN
GetControlSize(t, Ports.point, w, h);
msg.w := SHORT(MIN(w, MAX(INTEGER)));
msg.h := SHORT(MIN(h, MAX(INTEGER)))
END;
IF msg.w = Views.undefined THEN msg.w := 80 * Ports.mm END;
IF msg.h = Views.undefined THEN msg.h := 30 * Ports.mm END
| msg: Properties.ResizePref DO
msg.horFitToWin := TRUE;
msg.verFitToWin := TRUE
| msg: Controls.PropPref DO
msg.valid := {Controls.link, Controls.label, Controls.guard, Controls.notifier}
| msg: Properties.PollMsg DO
PollProp(t, msg.prop)
| msg: Properties.SetMsg DO
SetProp(t, msg.prop)
| msg: Properties.ControlPref DO
IF (t.field # NIL) & ((msg.char = lineChar) OR (msg.char = esc) OR (msg.char = tab) OR (msg.char = ltab))
OR (t.field = NIL) & (t.tprop.selectionStyle = cellSelect) & t.hasSelection & (msg.char = lineChar)
THEN
msg.accepts := TRUE
END
ELSE
IF t.field # NIL THEN Views.HandlePropMsg(t.field, msg) END
END
END HandlePropMsg2;
PROCEDURE (c: Control) CheckLink (VAR ok: BOOLEAN);
VAR item: Meta.Item; mod: Meta.Name; name: Meta.Name;
BEGIN
item := c.item;
IF (item.typ = Meta.recTyp) THEN
item.GetTypeName(mod, name);
IF (mod = "StdTables") & (name = "Table") THEN
ok := TRUE
ELSE
ok := FALSE
END
ELSE ok := FALSE
END
END CheckLink;
(* Property Dialog *)
PROCEDURE PollPropForDlg;
VAR q: Properties.Property; p: Prop;
BEGIN
dlg.layoutEditable := TRUE; dlg.dataEditable := TRUE; dlg.selectionStyle.index := cellSelect;
dlg.known := {}; dlg.valid := {};
Properties.CollectProp(q);
WHILE (q # NIL) & ~(q IS Prop) DO q := q.next END;
IF q # NIL THEN
p := q(Prop);
dlg.known := p.known; dlg.valid := p.valid;
IF layoutEditable IN p.valid THEN dlg.layoutEditable := p.layoutEditable END;
IF dataEditable IN p.valid THEN dlg.dataEditable := p.dataEditable END;
IF selectionStyle IN p.valid THEN dlg.selectionStyle.index := p.selectionStyle END
END;
Dialog.Update(dlg)
END PollPropForDlg;
PROCEDURE SetPropFromDlg;
VAR p: Prop;
BEGIN
NEW(p);
p.known := dlg.known;
p.valid := dlg.valid;
p.layoutEditable := dlg.layoutEditable;
p.dataEditable := dlg.dataEditable;
p.selectionStyle := dlg.selectionStyle.index;
Properties.EmitProp(NIL, p)
END SetPropFromDlg;
PROCEDURE (a: Action) Do;
VAR c: Containers.Controller; v: Views.View; fp: INTEGER;
BEGIN
Controllers.SetCurrentPath(Controllers.targetPath);
c := Containers.Focus(); fp := 0;
IF c # NIL THEN
c.GetFirstView(Containers.selection, v);
WHILE v # NIL DO fp := fp + Services.AdrOf(v); c.GetNextView(Containers.selection, v) END
END;
IF fp # dlg.fingerprint THEN PollPropForDlg; dlg.fingerprint := fp END;
Controllers.ResetCurrentPath();
Services.DoLater(a, Services.Ticks() + Services.resolution DIV 2)
END Do;
PROCEDURE InitDialog*;
BEGIN
IF action = NIL THEN NEW(action); Services.DoLater(action, Services.now) END;
Controllers.SetCurrentPath(Controllers.targetPath);
PollPropForDlg;
Controllers.ResetCurrentPath()
END InitDialog;
PROCEDURE Set*;
BEGIN
Controllers.SetCurrentPath(Controllers.targetPath);
SetPropFromDlg; PollPropForDlg;
Controllers.ResetCurrentPath()
END Set;
PROCEDURE Guard* (idx: INTEGER; VAR par: Dialog.Par);
BEGIN
IF ~(idx IN dlg.known) THEN par.disabled := TRUE
ELSIF ~(idx IN dlg.valid) THEN par.undef := TRUE
END
END Guard;
PROCEDURE Notifier* (idx, op, from, to: INTEGER);
BEGIN
IF op = Dialog.changed THEN INCL(dlg.valid, idx) END
END Notifier;
(* StdDirectory *)
PROCEDURE InitStdProp (OUT p: Properties.StdProp);
VAR f: Fonts.Font;
BEGIN
NEW(p);
f := Fonts.dir.Default();
p.typeface := f.typeface;
p.size := f.size;
p.style.val := f.style;
p.style.mask := {Fonts.italic, Fonts.underline, Fonts.strikeout};
p.weight := Fonts.normal
END InitStdProp;
PROCEDURE InitTableProp (OUT p: Prop);
BEGIN
NEW(p);
p.layoutEditable := TRUE; p.dataEditable := TRUE; p.selectionStyle := cellSelect
END InitTableProp;
PROCEDURE (d: StdDirectory) NewControl (p: Controls.Prop): Views.View;
VAR c: Control;
BEGIN
NEW(c); Controls.OpenLink(c, p); InitStdProp(c.sprop); InitTableProp(c.tprop); SetupControl(c); RETURN c
END NewControl;
PROCEDURE SetDir* (d: Directory);
BEGIN
ASSERT(d # NIL, 20); dir := d
END SetDir;
PROCEDURE DepositControl*;
VAR p: Controls.Prop;
BEGIN
NEW(p);
p.link := ""; p.label := ""; p.guard := ""; p.notifier := "";
p.level := 0; p.opt[Controls.sorted] := FALSE;
Views.Deposit(dir.NewControl(p))
END DepositControl;
PROCEDURE SetupSelectionStyleList (VAR l: Dialog.List);
BEGIN
l.SetLen(5);
l.SetItem(noSelect, "#Std:No Selection");
l.SetItem(cellSelect, "#Std:Select Cell");
l.SetItem(rowSelect, "#Std:Select Row");
l.SetItem(colSelect, "#Std:Select Column");
l.SetItem(crossSelect, "#Std:Select Row & Column")
END SetupSelectionStyleList;
PROCEDURE Init;
VAR d: StdDirectory;
BEGIN
NEW(d); stdDir := d; dir := d;
SetupSelectionStyleList(dlg.selectionStyle)
END Init;
BEGIN
Init
CLOSE
Services.RemoveAction(action)
END StdTables.
| Std/Mod/Tables.odc |
MODULE StdTabViews;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20150114, center #93, Opening a Form with a Tab View
- 20160118, center #79, bug fixes in StdTabViews
"
issues = "
- ...
"
**)
IMPORT
Kernel, Dialog, FormViews, StdCFrames, Stores, Views, Controllers, Ports,
Properties, Containers, Services, Models, Fonts, Meta, StdApi;
CONST
minVersion = 1; maxVersion = 1;
noTab* = -1;
TYPE
Directory* = POINTER TO ABSTRACT RECORD END;
StdDirectory = POINTER TO RECORD (Directory) END;
TabInfo = RECORD
label: Dialog.String;
view: Views.View
END;
Tabs = POINTER TO ARRAY OF TabInfo;
View* = POINTER TO LIMITED RECORD (Views.View)
dispX, dispY, dispW, dispH: INTEGER;
deposited: BOOLEAN;
tabs: Tabs;
font: Fonts.Font;
index, nofTabs, scriptLevel: INTEGER;
notifier: Dialog.String;
ba: BalanceAction; tc: TrapCleaner
END;
TabContext = POINTER TO RECORD (Models.Context)
w, h: INTEGER
END;
Frame* = POINTER TO ABSTRACT RECORD (StdCFrames.Frame) END;
FrameDirectory* = POINTER TO ABSTRACT RECORD END;
FocusMsg = RECORD (Controllers.Message) view: View END;
SetItemOp = POINTER TO RECORD (Stores.Operation)
tv: View;
label: Dialog.String;
v: Views.View;
i, oldLen: INTEGER;
set: BOOLEAN
END;
DeleteOp = POINTER TO RECORD (Stores.Operation)
tv: View;
label: Dialog.String;
v: Views.View;
i: INTEGER;
set: BOOLEAN
END;
FontOp = POINTER TO RECORD (Stores.Operation)
v: View;
font: Fonts.Font
END;
SetNotifierOp = POINTER TO RECORD (Stores.Operation)
notifier: Dialog.String;
v: View
END;
NotifyProc = RECORD (Meta.Value) p*: PROCEDURE (tv: View; from, to: INTEGER) END;
BalanceAction = POINTER TO RECORD (Services.Action) v: View END;
TrapCleaner = POINTER TO RECORD (Kernel.TrapCleaner) v: View END;
NotifierProc* = PROCEDURE (tv: View; from, to: INTEGER);
VAR
dir-, stdDir-: Directory;
d: StdDirectory;
setFocus*: BOOLEAN;
frameDir-, frameStdDir-: FrameDirectory;
dlg*: RECORD
name*, notifier*: Dialog.String;
opt*, index: INTEGER;
tab, ntab: View
END;
nv: View;
oldModeHook: PROCEDURE(c: Containers.Controller);
PROCEDURE^ (tv: View) SetIndex* (i : INTEGER), NEW;
(* Auxiliary procedures *)
PROCEDURE LayoutMode(view: Views.View);
VAR c: Containers.Controller;
BEGIN
WITH view: Containers.View DO
c := view.ThisController();
(* set view in layout mode *)
c.SetOpts(c.opts - {Containers.noSelection, Containers.noCaret} + {Containers.noFocus} )
ELSE
END
END LayoutMode;
PROCEDURE MaskMode(view: Views.View);
VAR c: Containers.Controller;
BEGIN
WITH view: Containers.View DO
c := view.ThisController();
(* set view in mask mode *)
c.SetOpts(c.opts - {Containers.noFocus} + {Containers.noSelection, Containers.noCaret})
ELSE
END
END MaskMode;
PROCEDURE ExecNotifier (from, to, nop: INTEGER);
VAR i: Meta.Item; p: NotifyProc; ok: BOOLEAN;
BEGIN
ASSERT(nv # NIL, 20);
Meta.LookupPath(nv.notifier, i);
IF i.obj # Meta.undef THEN
i.GetVal(p, ok);
IF ok THEN
p.p(nv, from, to)
ELSE
Dialog.ShowParamMsg("#System:HasWrongType", nv.notifier, "", "")
END
ELSE
Dialog.ShowMsg(nv.notifier + ' is not a valid notifier for StdTabViews.View')
END
END ExecNotifier;
PROCEDURE CallNotifier (tv: View; from, to: INTEGER);
BEGIN
IF tv.notifier # "" THEN
nv := tv; Kernel.Try(ExecNotifier, from, to, 0); nv := NIL
END
END CallNotifier;
(* Frame *)
PROCEDURE (f: Frame) InDispArea* (x, y: INTEGER): BOOLEAN, NEW, ABSTRACT;
PROCEDURE (f: Frame) GetDispSize* (OUT x, y, w, h: INTEGER), NEW, ABSTRACT;
PROCEDURE (f: Frame) SetIndex* (i: INTEGER), NEW;
VAR from: INTEGER; tv: View;
BEGIN
tv := f.view(View); from := tv.index;
tv.Neutralize; (* avoids blocking controls in nested forms, in particular list boxes *)
tv.SetIndex(i);
CallNotifier(tv, from, i)
END SetIndex;
(** FrameDirectory **)
PROCEDURE (d: FrameDirectory) GetTabSize* (VAR w, h: INTEGER), NEW, ABSTRACT;
PROCEDURE (d: FrameDirectory) New* (): Frame, NEW, ABSTRACT;
PROCEDURE SetFrameDir* (d: FrameDirectory);
BEGIN
ASSERT(d # NIL, 20); frameDir := d;
IF frameStdDir = NIL THEN frameStdDir := d END
END SetFrameDir;
(* View *)
PROCEDURE (tv: View) Update (), NEW;
BEGIN
IF tv.scriptLevel = 0 THEN Views.Update(tv, Views.rebuildFrames) END
END Update;
PROCEDURE (tv: View) Reset (), NEW;
BEGIN
tv.scriptLevel := 0;
IF tv.tc # NIL THEN Kernel.PopTrapCleaner(tv.tc); tv.tc := NIL END;
IF tv.ba # NIL THEN Services.RemoveAction(tv.ba); tv.ba := NIL END;
tv.Update
END Reset;
PROCEDURE (tv: View) SetNofTabs* (nofTabs: INTEGER), NEW;
VAR i: INTEGER; nt: Tabs;
BEGIN
ASSERT(nofTabs >= 0, 20);
IF nofTabs = 0 THEN
tv.nofTabs := 0; tv.tabs := NIL; tv.index := 0
ELSE
NEW(nt, nofTabs);
IF tv.tabs # NIL THEN
FOR i := 0 TO MIN(nofTabs, tv.nofTabs) - 1 DO
nt[i].label := tv.tabs[i].label; nt[i].view := tv.tabs[i].view
END
END;
tv.tabs := nt; tv.nofTabs := nofTabs; tv.index := MIN(tv.index, tv.nofTabs - 1)
END;
tv.Update
END SetNofTabs;
PROCEDURE (tv: View) NofTabs* (): INTEGER, NEW;
BEGIN
IF tv.tabs = NIL THEN RETURN 0 END;
RETURN MAX(0, tv.nofTabs)
END NofTabs;
PROCEDURE (tv: View) Index* (): INTEGER, NEW;
BEGIN
RETURN MAX(0, MIN(tv.index, tv.NofTabs() - 1))
END Index;
PROCEDURE (tv: View) SetItem* (i: INTEGER; IN label: Dialog.String; v: Views.View), NEW;
VAR sop: SetItemOp;
BEGIN
ASSERT(i >= 0, 20); ASSERT(label # "", 21); ASSERT(v # NIL, 22);
NEW(sop);
sop.tv := tv; sop.i := i; sop.v := v; sop.label := label; sop.set := TRUE;
Views.Do(tv, "#Std:TabSetItem", sop)
END SetItem;
PROCEDURE (tv: View) GetItem* (i: INTEGER; OUT label: Dialog.String; OUT v: Views.View), NEW;
BEGIN
ASSERT((i >= 0) & (i < tv.NofTabs()), 21);
label := tv.tabs[i].label;
v := tv.tabs[i].view
END GetItem;
PROCEDURE (tv: View) View (i: INTEGER): Views.View, NEW;
BEGIN
ASSERT((i >= 0) & (i < tv.NofTabs()), 20);
RETURN tv.tabs[i].view
END View;
PROCEDURE (tv: View) SetIndex* (i : INTEGER), NEW;
BEGIN
ASSERT((i >= 0) & (i < tv.NofTabs()), 20);
tv.index := i;
tv.Update
END SetIndex;
PROCEDURE (tv: View) SetNotifier* (IN notifier: ARRAY OF CHAR), NEW;
VAR o: SetNotifierOp;
BEGIN
NEW(o);
o.v := tv; o.notifier := notifier$;
Views.Do(tv, "Set Notifier", o)
END SetNotifier;
PROCEDURE (tv: View) GetNotifier* (OUT notifier: Dialog.String), NEW;
BEGIN
notifier := tv.notifier
END GetNotifier;
PROCEDURE (tv: View) Externalize- (VAR wr: Stores.Writer);
VAR l: Dialog.String; i: INTEGER; v: Views.View;
BEGIN
tv.Externalize^(wr);
wr.WriteVersion(maxVersion);
wr.WriteInt(tv.NofTabs());
wr.WriteInt(tv.Index());
wr.WriteString(tv.notifier);
FOR i := 0 TO tv.NofTabs() - 1 DO
tv.GetItem(i, l, v);
wr.WriteString(l); Views.WriteView(wr, v)
END;
wr.WriteString(tv.font.typeface$); wr.WriteInt(tv.font.size); wr.WriteSet(tv.font.style); wr.WriteInt(tv.font.weight)
END Externalize;
PROCEDURE (tv: View) Internalize- (VAR rd: Stores.Reader);
VAR thisVersion, i, size, weight: INTEGER; l: Dialog.String; v: Views.View; face: Fonts.Typeface; style: SET;
BEGIN
ASSERT(frameStdDir # NIL, 20);
tv.Internalize^(rd);
rd.ReadVersion(minVersion, maxVersion, thisVersion);
IF (thisVersion >= minVersion) & (thisVersion <= maxVersion) THEN
rd.ReadInt(i); tv.SetNofTabs(i);
rd.ReadInt(tv.index);
rd.ReadString(tv.notifier);
FOR i := 0 TO tv.NofTabs() -1 DO
rd.ReadString(l); Views.ReadView(rd, v);
tv.SetItem(i, l, v)
END;
rd.ReadString(face); rd.ReadInt(size); rd.ReadSet(style); rd.ReadInt(weight);
tv.font := Fonts.dir.This(face, size, style, weight);
CallNotifier(tv, noTab, tv.index)
END
END Internalize;
PROCEDURE (tv: View) CopyFromSimpleView- (source: Views.View);
VAR l: Dialog.String; v: Views.View; i: INTEGER;
BEGIN
WITH source: View DO
tv.notifier := source.notifier;
tv.SetNofTabs(source.NofTabs());
FOR i := 0 TO tv.NofTabs() - 1 DO
source.GetItem(i, l, v);
v := Views.CopyOf(v, Views.deep);
tv.SetItem(i, l, v)
END;
tv.font := Fonts.dir.This(source.font.typeface, source.font.size, source.font.style, source.font.weight);
tv.SetIndex(source.Index())
END
END CopyFromSimpleView;
PROCEDURE (tv: View) GetNewFrame* (VAR frame: Views.Frame);
VAR f: Frame;
BEGIN
f := frameDir.New();
f.font := tv.font;
frame := f
END GetNewFrame;
PROCEDURE (tv: View) Restore* (f: Views.Frame; l, t, r, b: INTEGER);
VAR v: Views.View; label: Dialog.String;
BEGIN
WITH f: Frame DO
IF (~f.InDispArea(l,t) OR ~f.InDispArea(r,b)) THEN
(* redraw is not completely within the display area so the control itself also needs to be restored *)
f.UpdateList(); f.Restore(l , t , r, b)
END;
f.GetDispSize(tv.dispX, tv.dispY, tv.dispW, tv.dispH);
IF tv.NofTabs() > 0 THEN
tv.GetItem(tv.Index(), label, v); Dialog.MapString(label, label);
IF (label # "") & (v # NIL) & (Views.ThisFrame(f, v) = NIL) THEN
v.context.SetSize(tv.dispW, tv.dispH);
Views.InstallFrame(f, v, tv.dispX, tv.dispY, 0, TRUE)
END
END
END
END Restore;
PROCEDURE (tv: View) HandleCtrlMsg* (f: Views.Frame; VAR msg: Controllers.Message;
VAR focus: Views.View);
VAR sp: Properties.SizeProp;
BEGIN
WITH f: Frame DO
WITH msg: Controllers.TrackMsg DO
IF (tv.NofTabs() > 0) & (f.InDispArea(msg.x, msg.y)) THEN
focus := tv.View(tv.Index())
ELSE
f.MouseDown(msg.x, msg.y, msg.modifiers)
END
| msg: FocusMsg DO
msg.view := tv
| msg: Properties.PollPickMsg DO
msg.dest := f;
IF (tv.NofTabs() > 0) & (f.InDispArea(msg.x, msg.y)) THEN
focus := tv.View(tv.Index())
END
| msg: Properties.PickMsg DO
NEW(sp); sp.known := {Properties.width, Properties.height}; sp.valid := sp.known;
tv.context.GetSize(sp.width, sp.height);
Properties.Insert(msg.prop, sp);
IF (tv.NofTabs() > 0) & (f.InDispArea(msg.x, msg.y)) THEN
focus := tv.View(tv.Index())
END
|msg: Controllers.PollCursorMsg DO
IF (tv.NofTabs() > 0) & (f.InDispArea(msg.x, msg.y)) THEN
focus := tv.View(tv.Index())
ELSE
f.GetCursor(msg.x, msg.y, msg.modifiers, msg.cursor)
END
ELSE
IF tv.NofTabs() > 0 THEN
focus := tv.View(tv.Index())
ELSE
WITH msg: Controllers.PollOpsMsg DO
msg.valid := {Controllers.pasteChar}
| msg: Controllers.MarkMsg DO
f.Mark(msg.show, msg.focus)
ELSE
END
END
END
END
END HandleCtrlMsg;
PROCEDURE BeginChanges* (tv: View);
BEGIN
ASSERT(tv.scriptLevel >= 0, 20);
IF tv.tc = NIL THEN NEW(tv.tc); tv.tc.v := tv; Kernel.PushTrapCleaner(tv.tc) END;
IF tv.ba = NIL THEN NEW(tv.ba); tv.ba.v := tv; Services.DoLater(tv.ba, Services.now) END;
INC(tv.scriptLevel)
END BeginChanges;
PROCEDURE EndChanges* (tv: View);
BEGIN
ASSERT(tv.scriptLevel > 0, 20);
DEC(tv.scriptLevel);
IF tv.scriptLevel = 0 THEN tv.Reset END
END EndChanges;
PROCEDURE ModeHook(c: Containers.Controller);
VAR v, w: Views.View; i: INTEGER; label: Dialog.String;
BEGIN
IF oldModeHook # NIL THEN oldModeHook(c) END;
c.GetFirstView(FALSE, v);
WHILE v # NIL DO
WITH v: View DO
FOR i := 0 TO v.NofTabs() - 1 DO
v.GetItem(i, label, w);
WITH w: Containers.View DO
w.ThisController().SetOpts(c.opts);
StdApi.modeHook(w.ThisController())
ELSE
END
END
ELSE
END;
c.GetNextView(FALSE, v)
END
END ModeHook;
(* TrapCleaner *)
PROCEDURE (t: TrapCleaner) Cleanup;
BEGIN
t.v.tc := NIL;
t.v.Reset
END Cleanup;
(* Actions and Operations *)
PROCEDURE (a: BalanceAction) Do-;
BEGIN
a.v.Reset();
HALT(100) (* Unbalanced call to BeginChanges/EndChanges *)
END Do;
PROCEDURE (o: SetNotifierOp) Do;
VAR old: Dialog.String;
BEGIN
old := o.v.notifier;
o.v.notifier := o.notifier;
o.notifier := old
END Do;
PROCEDURE (o: FontOp) Do;
VAR f: Fonts.Font;
BEGIN
f := o.v.font; o.v.font := o.font; o.font := f;
o.v.Update
END Do;
PROCEDURE (o: SetItemOp) Do;
VAR tc: TabContext; label: Dialog.String; view: Views.View;
BEGIN
IF o.set THEN
o.set := FALSE; o.oldLen := o.tv.NofTabs();
view := Views.CopyOf(o.v, Views.deep); Stores.Join(o.tv, view);
label := o.label;
IF o.i >= o.oldLen THEN
o.tv.SetNofTabs(o.i + 1)
ELSE
o.tv.GetItem(o.i, o.label, o.v)
END;
NEW(tc); view.InitContext(tc);
o.tv.tabs[o.i].label := label; o.tv.tabs[o.i].view := view
ELSE
o.set := TRUE;
IF o.i >= o.oldLen THEN
o.tv.SetNofTabs(o.oldLen)
ELSE
view := o.v; label := o.label;
o.tv.GetItem(o.i, o.label, o.v);
o.tv.tabs[o.i].label := label; o.tv.tabs[o.i].view := view
END
END;
o.tv.Update
END Do;
PROCEDURE (o: DeleteOp) Do;
VAR j: INTEGER;
BEGIN
IF o.set THEN
ASSERT(o.i < o.tv.NofTabs(), 20);
o.set := FALSE;
o.tv.GetItem(o.i, o.label, o.v);
FOR j := o.i TO o.tv.NofTabs() - 2 DO
o.tv.tabs[j].label := o.tv.tabs[j + 1].label;
o.tv.tabs[j].view := o.tv.tabs[j + 1].view
END;
o.tv.SetNofTabs(o.tv.NofTabs() - 1)
ELSE
ASSERT(o.i <= o.tv.NofTabs(), 21);
o.set := TRUE;
o.tv.SetNofTabs(o.tv.NofTabs() + 1);
FOR j := o.tv.NofTabs() - 1 TO o.i + 1 BY - 1 DO
o.tv.tabs[j].label := o.tv.tabs[j - 1].label;
o.tv.tabs[j].view := o.tv.tabs[j - 1].view
END;
o.tv.tabs[o.i].label := o.label;
o.tv.tabs[o.i].view := o.v
END;
o.tv.Update
END Do;
PROCEDURE (tv: View) HandlePropMsg- (VAR msg: Properties.Message);
VAR stp: Properties.StdProp; p: Properties.Property;
face: Fonts.Typeface; size, weight, i, w, h, asc, dsc: INTEGER; style: SET;
smsg: Properties.SizePref; fo: FontOp;
v: Views.View; label: Dialog.String;
BEGIN
WITH msg: Properties.ControlPref DO
IF tv.NofTabs() = 0 THEN
IF msg.getFocus THEN msg.getFocus := StdCFrames.setFocus END
ELSE
msg.focus := tv.View(tv.Index());
Views.HandlePropMsg(msg.focus, msg)
END
| msg: Properties.FocusPref DO
IF (tv.NofTabs() = 0) OR (msg.atLocation & (msg.y < tv.dispY)) THEN
msg.hotFocus := TRUE
ELSE
IF msg.atLocation THEN msg.x := msg.x - tv.dispX; msg.y := msg.y - tv.dispY END;
Views.HandlePropMsg(tv.View(tv.Index()), msg)
END
| msg: Properties.SizePref DO
IF (msg.w = Views.undefined) OR (msg.h = Views.undefined) THEN
IF tv.deposited OR (tv.NofTabs() = 0) THEN
frameDir.GetTabSize(msg.w, msg.h)
ELSE
w := 0; h:= 0;
FOR i := 0 TO tv.NofTabs() - 1 DO
tv.GetItem(i, label, v); Dialog.MapString(label, label);
IF (label # "") & (v # NIL) THEN
smsg.w := Views.undefined; smsg.h := Views.undefined;
Views.HandlePropMsg(v, smsg);
w := MAX(smsg.w, w); h := MAX(smsg.h, h)
END
END;
IF (w = 0) OR (h = 0) THEN
frameDir.GetTabSize(msg.w, msg.h)
ELSE
(* add some constants to compensate for the tab view itself. *)
msg.w := w + 2 * Ports.mm;
tv.font.GetBounds(asc, dsc, w); msg.h := h + asc + dsc + 4 * Ports.mm;
IF msg.h < 0 THEN msg.h := MAX(INTEGER) END
END
END
END
| msg: Properties.ResizePref DO
msg.horFitToWin := TRUE; msg.verFitToWin := TRUE
| msg: Properties.PollMsg DO
NEW(stp);
stp.valid := {Properties.typeface..Properties.weight};
stp.known := stp.valid;
stp.typeface := tv.font.typeface;
stp.size := tv.font.size; stp.style.val := tv.font.style;
stp.weight := tv.font.weight;
stp.style.mask := {Fonts.italic, Fonts.strikeout, Fonts.underline};
Properties.Insert(msg.prop, stp)
| msg: Properties.SetMsg DO
p := msg.prop;
WHILE (p # NIL) DO
WITH p: Properties.StdProp DO
IF (p.valid * {Properties.typeface..Properties.weight}) # {} THEN
face := tv.font.typeface$; size := tv.font.size;
style := tv.font.style; weight := tv.font.weight;
IF Properties.typeface IN p.valid THEN face := p.typeface$;
IF face = Fonts.default THEN face := StdCFrames.defaultFont.typeface END
END;
IF Properties.size IN p.valid THEN size := p.size END;
IF Properties.style IN p.valid THEN
style := (p.style.val * p.style.mask) + (style - p.style.mask)
END;
IF Properties.weight IN p.valid THEN weight := p.weight END;
NEW(fo); fo.v := tv; fo.font := Fonts.dir.This(face, size, style, weight);
Views.Do(tv, "#System:SetProp", fo)
END
ELSE
END;
p := p.next
END
| msg: Containers.DropPref DO
msg.okToDrop := TRUE
ELSE
IF tv.NofTabs() > 0 THEN
Views.HandlePropMsg(tv.View(tv.Index()), msg)
END
END
END HandlePropMsg;
PROCEDURE (tv: View) Neutralize*;
VAR v: Views.View;
BEGIN
IF (tv.scriptLevel = 0) & (tv.NofTabs() > 0) THEN
v := tv.View(tv.Index());
IF v # NIL THEN v.Neutralize END
END
END Neutralize;
(* Tab context *)
PROCEDURE (c: TabContext) ThisModel (): Models.Model;
BEGIN
RETURN NIL
END ThisModel;
PROCEDURE (c: TabContext) GetSize (OUT w, h: INTEGER);
BEGIN
w := c.w; h := c.h
END GetSize;
PROCEDURE (c: TabContext) SetSize (w, h: INTEGER);
BEGIN
c.w := w; c.h := h
END SetSize;
PROCEDURE (c: TabContext) Normalize (): BOOLEAN;
BEGIN
RETURN FALSE
END Normalize;
(* Directory *)
PROCEDURE (d: Directory) New* (): View, NEW, ABSTRACT;
PROCEDURE SetDir* (d: Directory);
BEGIN
ASSERT(d # NIL, 20); dir := d
END SetDir;
(* StdDirectory *)
PROCEDURE (d: StdDirectory) New (): View;
VAR tv: View;
BEGIN
ASSERT(frameStdDir # NIL, 20);
NEW(tv); tv.deposited := FALSE; tv.scriptLevel := 0; tv.nofTabs := 0; tv.index :=0; tv.notifier := "";
tv.ba := NIL; tv.tc := NIL;
tv.font := StdCFrames.defaultFont;
RETURN tv
END New;
PROCEDURE Deposit*;
VAR tv: View; fv: FormViews.View;
BEGIN
tv := dir.New(); tv.deposited := TRUE;
fv := FormViews.New(); LayoutMode(fv); tv.SetItem(0, "Tab1", fv);
fv := FormViews.New(); LayoutMode(fv); tv.SetItem(1, "Tab2", fv);
Views.Deposit(tv)
END Deposit;
(* Procedures to find tab views *)
PROCEDURE This* (v: Views.View): View;
VAR c: Containers.Controller; v0: Views.View; v1: View;
BEGIN
ASSERT (v # NIL, 20);
IF v IS View THEN RETURN v(View)
ELSIF v IS Containers.View THEN
c := v(Containers.View).ThisController();
ASSERT(c # NIL, 100);
c.GetFirstView(Containers.any, v0);
IF v0 # NIL THEN v1 := This(v0) END;
WHILE (v0 # NIL) & (v1 = NIL) DO
c.GetNextView(Containers.any, v0);
IF v0 # NIL THEN v1 := This(v0) END
END;
RETURN v1
ELSE RETURN NIL
END
END This;
PROCEDURE Focus* (): View;
VAR msg: FocusMsg;
BEGIN
msg.view := NIL;
Controllers.Forward(msg);
RETURN msg.view
END Focus;
(* The property editor *)
PROCEDURE SingleView() : View;
VAR v: Views.View;
BEGIN
v := Containers.FocusSingleton();
IF v = NIL THEN v := Focus() END;
IF (v # NIL) & (v IS View) THEN RETURN v(View) ELSE RETURN NIL END
END SingleView;
PROCEDURE Right*;
VAR label1, label2: Dialog.String; v1, v2: Views.View; iv: View; script: Stores.Operation;
BEGIN
iv := SingleView();
IF (iv # NIL) & (iv.Index() < (iv.NofTabs() - 1)) THEN
Views.BeginScript(iv, "Shift tab right", script);
iv.GetItem(iv.Index() , label1, v1);
iv.GetItem(iv.Index() + 1 , label2, v2);
iv.SetItem(iv.Index(), label2, v2);
iv.SetItem(iv.Index() + 1, label1, v1);
Views.EndScript(iv, script);
iv.SetIndex(iv.Index() + 1);
Dialog.Update(iv)
END
END Right;
PROCEDURE Left*;
VAR label1, label2: Dialog.String; v1, v2: Views.View; iv: View;
BEGIN
iv := SingleView();
IF (iv # NIL) & (iv.Index() > 0) THEN
iv.GetItem(iv.Index() , label1, v1);
iv.GetItem(iv.Index() - 1 , label2, v2);
iv.SetItem(iv.Index(), label2, v2);
iv.SetItem(iv.Index() - 1, label1, v1);
iv.SetIndex(iv.Index() - 1);
Dialog.Update(iv)
END
END Left;
PROCEDURE AddTab*;
VAR v: View; fv: FormViews.View;
BEGIN
ASSERT(dlg.name # "", 20);
v := SingleView();
IF v # NIL THEN
fv := FormViews.New(); LayoutMode(fv);
v.SetItem(v.NofTabs(), dlg.name, fv)
END
END AddTab;
PROCEDURE Rename*;
VAR v: View;
BEGIN
ASSERT(dlg.name # "", 20);
v := SingleView();
IF (v # NIL) & (v.NofTabs() > 0) THEN
v.SetItem(v.Index(), dlg.name, v.View(v.Index()))
END
END Rename;
PROCEDURE Delete*;
VAR v: View; dop: DeleteOp;
BEGIN
v := SingleView();
IF (v # NIL) & (v.NofTabs() > 0) THEN
NEW(dop); dop.tv := v; dop.i := v.Index(); dop.set := TRUE;
Views.Do(v, "#Std:TabDeleteItem", dop)
END
END Delete;
PROCEDURE ModeNotifier* (op, from, to: INTEGER);
VAR tv: View; i: INTEGER;
BEGIN
IF op IN {Dialog.changed} THEN
tv := SingleView();
IF (tv # NIL) & (tv.NofTabs() > 0) THEN
IF to = 0 THEN
FOR i := 0 TO tv.NofTabs() - 1 DO LayoutMode(tv.View(i)) END
ELSE
FOR i := 0 TO tv.NofTabs() - 1 DO MaskMode(tv.View(i)) END
END
END
END
END ModeNotifier;
PROCEDURE SetNotifier*;
VAR v: View; o: SetNotifierOp;
BEGIN
v := SingleView();
IF v # NIL THEN
NEW(o); o.v := v; o.notifier := dlg.notifier;
Views.Do(v, "Set Notifier", o)
END
END SetNotifier;
PROCEDURE NewGuard* (VAR par: Dialog.Par);
VAR v: View;
BEGIN
v := SingleView();
par.disabled := (v = NIL) OR (dlg.name = "")
END NewGuard;
PROCEDURE RenameGuard* (VAR par: Dialog.Par);
VAR v: View;
BEGIN
v := SingleView();
par.disabled := (v = NIL) OR (dlg.name = "")
END RenameGuard;
PROCEDURE DeleteGuard* (VAR par: Dialog.Par);
VAR v: View;
BEGIN
v := SingleView();
par.disabled := (v = NIL) OR (v.NofTabs() < 1)
END DeleteGuard;
PROCEDURE LabelGuard* (VAR par: Dialog.Par);
VAR v: View; vv: Views.View;
BEGIN
v := SingleView();
IF v # NIL THEN
IF (v # dlg.tab) OR (v.Index() # dlg.index) THEN
par.disabled := FALSE;
v.GetItem(v.Index(), dlg.name, vv);
dlg.tab := v; dlg.index := v.Index();
Dialog.Update(dlg)
END
ELSE
dlg.tab := NIL; dlg.index := -1;
par.label := ""; par.disabled := TRUE
END
END LabelGuard;
PROCEDURE NotifierGuard* (VAR par: Dialog.Par);
VAR v: View;
BEGIN
v := SingleView();
IF v # NIL THEN
IF v # dlg.ntab THEN
par.disabled := FALSE;
dlg.notifier := v.notifier;
dlg.ntab := v;
Dialog.Update(dlg)
END
ELSE
dlg.ntab := NIL;
par.label := ""; par.disabled := TRUE
END
END NotifierGuard;
PROCEDURE SetGuard* (VAR par: Dialog.Par);
VAR v: View;
BEGIN
v := SingleView();
par.disabled := v = NIL
END SetGuard;
PROCEDURE ModeGuard (VAR par: Dialog.Par; layout: BOOLEAN);
CONST mode = {Containers.noSelection, Containers.noFocus, Containers.noCaret};
VAR tv: View; i, l, m: INTEGER; c: Containers.Controller;
BEGIN
tv := SingleView();
IF (tv # NIL) & (tv.NofTabs() > 0) THEN
l := 0; m := 0;
FOR i := 0 TO tv.NofTabs() - 1 DO
IF tv.View(i) IS Containers.View THEN
c := tv.View(i)(Containers.View).ThisController();
IF c.opts * mode = {Containers.noFocus} THEN INC(l)
ELSIF c.opts * mode = {Containers.noSelection, Containers.noCaret} THEN INC(m)
END
END
END;
IF ((m # 0) & (l # 0)) OR ((m + l) < tv.NofTabs()) THEN
par.undef := TRUE;
dlg.opt := -1
ELSIF layout & (m = 0) THEN dlg.opt := 0
ELSIF ~layout & (l = 0) THEN dlg.opt := 1
END
ELSE
par.disabled := TRUE
END
END ModeGuard;
PROCEDURE LayoutModeGuard*(VAR par: Dialog.Par);
BEGIN
ModeGuard(par, TRUE)
END LayoutModeGuard;
PROCEDURE MaskModeGuard*(VAR par: Dialog.Par);
BEGIN
ModeGuard(par, FALSE)
END MaskModeGuard;
PROCEDURE InitDialog*;
BEGIN
dlg.tab := NIL; dlg.index := -1
END InitDialog;
PROCEDURE Init;
VAR res: INTEGER;
BEGIN
oldModeHook := StdApi.modeHook;
StdApi.modeHook := ModeHook;
setFocus := FALSE; dlg.tab := NIL; dlg.index := -1;
NEW(d); stdDir := d; dir := d;
IF Kernel.ThisLoadedMod('MdiInit') = NIL THEN
Dialog.Call('StdTabFrames.Init', 'Could not load StdTabFrames', res)
ELSE
Dialog.Call('WinTabFrames.Init', 'Could not load WinTabFrames', res)
END
END Init;
BEGIN
Init
CLOSE
StdApi.modeHook := oldModeHook
END StdTabViews.
| Std/Mod/TabViews.odc |
MODULE StdTextConv;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems, Alexander Iljin"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20060905, ai, fixed trap upon copying an empty text view to the clipboard
- 20070201, bh, Unicode support
- 20070213, bh, improved paragraph handling in ParseRichText
- 20151008, center #74, adding small and capital letter z with caron in ThisWndChar & WriteWndChar
- 20151008, center #86, improvements in RTF import
- 20170620, center #163, adding decimal tabs to TextRulers
- 20171122, center #182, fixing code page conversion in RTF import
- 20180314, center #184, HYPERLINK ignored in RTF import
- 20190815, center #201, Importer and Exporter for UTF-8 texts added
"
issues = "
- ...
"
**)
IMPORT
SYSTEM, Strings, Log,
Files, Fonts, Ports, Stores, Views, Properties,
StdLinks, TextModels,
TextRulers, TextViews, TextMappers;
CONST
CR = 0DX; LF = 0AX; FF = 0EX; TAB = 09X;
halfpoint = Ports.point DIV 2;
twips = Ports.point DIV 20;
linkcmd = "Dialog.OpenExternal";
TYPE
MemReader = POINTER TO RECORD (Files.Reader)
adr, pos: INTEGER
END;
VAR
debug*: BOOLEAN;
codePageName: ARRAY [untagged] 16 OF SHORTCHAR;
fromS*: ARRAY [untagged] 64 OF SHORTCHAR;
toW*: ARRAY [untagged] 64 OF CHAR;
(* MemReader *)
PROCEDURE (r: MemReader) Base (): Files.File;
BEGIN
RETURN NIL
END Base;
PROCEDURE (r: MemReader) Pos (): INTEGER;
BEGIN
RETURN r.pos
END Pos;
PROCEDURE (r: MemReader) SetPos (pos: INTEGER);
BEGIN
r.pos := pos
END SetPos;
PROCEDURE (r: MemReader) ReadByte (OUT x: BYTE);
BEGIN
SYSTEM.GET(r.adr + r.pos, x); INC(r.pos)
END ReadByte;
PROCEDURE (r: MemReader) ReadBytes (VAR x: ARRAY OF BYTE; beg, len: INTEGER);
BEGIN
HALT(126)
END ReadBytes;
(*
PROCEDURE GenGlobalMedium (hg: WinApi.HGLOBAL; unk: COM.IUnknown; VAR sm: WinOle.STGMEDIUM);
BEGIN
sm.tymed := WinOle.TYMED_HGLOBAL;
sm.u.hGlobal := hg;
sm.pUnkForRelease := unk
END GenGlobalMedium;
PROCEDURE MediumGlobal (VAR sm: WinOle.STGMEDIUM): WinApi.HGLOBAL;
BEGIN
ASSERT(sm.tymed = WinOle.TYMED_HGLOBAL, 20);
RETURN sm.u.hGlobal
END MediumGlobal;
*)
PROCEDURE WriteWndChar (wr: TextModels.Writer; ch: CHAR);
BEGIN
CASE ch OF
| CR, TAB, " "..7EX, 0A0X..0FFX: wr.WriteChar(ch)
| LF:
| 80X: wr.WriteChar(20ACX) (* euro *)
| 82X: wr.WriteChar(201AX)
| 83X: wr.WriteChar(0192X)
| 84X: wr.WriteChar(201EX)
| 85X: wr.WriteChar(2026X)
| 86X: wr.WriteChar(2020X)
| 87X: wr.WriteChar(2021X)
| 88X: wr.WriteChar(02C6X)
| 89X: wr.WriteChar(2030X)
| 8AX: wr.WriteChar(0160X)
| 8BX: wr.WriteChar(2039X)
| 8CX: wr.WriteChar(0152X)
| 8EX: wr.WriteChar(017DX)
| 91X: wr.WriteChar(2018X)
| 92X: wr.WriteChar(2019X)
| 93X: wr.WriteChar(201CX)
| 94X: wr.WriteChar(201DX)
| 95X: wr.WriteChar(2022X)
| 96X: wr.WriteChar(2013X)
| 97X: wr.WriteChar(2014X)
| 98X: wr.WriteChar(02DCX)
| 99X: wr.WriteChar(2122X)
| 9AX: wr.WriteChar(0161X)
| 9BX: wr.WriteChar(203AX)
| 9CX: wr.WriteChar(0153X)
| 9EX: wr.WriteChar(017EX)
| 9FX: wr.WriteChar(0178X)
| 0X..8X, 0BX, 0CX, 0EX..1FX, 7FX, 81X, 8DX, 8FX..90X, 9DX:
wr.WriteChar(CHR(0EF00H + ORD(ch)))
END
END WriteWndChar;
PROCEDURE ThisWndChar (ch: CHAR): CHAR;
BEGIN
IF ch >= 100X THEN
IF (ch >= 0EF00X) & (ch <= 0EFFFX) THEN ch := CHR(ORD(ch) - 0EF00H)
ELSIF ch = 20ACX THEN ch := 80X (* euro *)
ELSIF ch = 201AX THEN ch := 82X
ELSIF ch = 0192X THEN ch := 83X
ELSIF ch = 201EX THEN ch := 84X
ELSIF ch = 2026X THEN ch := 85X
ELSIF ch = 2020X THEN ch := 86X
ELSIF ch = 2021X THEN ch := 87X
ELSIF ch = 02C6X THEN ch := 88X
ELSIF ch = 2030X THEN ch := 89X
ELSIF ch = 0160X THEN ch := 8AX
ELSIF ch = 2039X THEN ch := 8BX
ELSIF ch = 0152X THEN ch := 8CX
ELSIF ch = 017DX THEN ch := 8EX
ELSIF ch = 2018X THEN ch := 91X
ELSIF ch = 2019X THEN ch := 92X
ELSIF ch = 201CX THEN ch := 93X
ELSIF ch = 201DX THEN ch := 94X
ELSIF ch = 2022X THEN ch := 95X
ELSIF ch = 2013X THEN ch := 96X
ELSIF ch = 2014X THEN ch := 97X
ELSIF ch = 02DCX THEN ch := 98X
ELSIF ch = 2122X THEN ch := 99X
ELSIF ch = 0161X THEN ch := 9AX
ELSIF ch = 203AX THEN ch := 9BX
ELSIF ch = 0153X THEN ch := 9CX
ELSIF ch = 017EX THEN ch := 9EX
ELSIF ch = 0178X THEN ch := 9FX
ELSE ch := "?"
END
ELSIF ch = 08FX THEN ch := " " (* digit space *)
END;
RETURN ch
END ThisWndChar;
PROCEDURE ImportText* (f: Files.File; OUT s: Stores.Store);
VAR r: Stores.Reader; t: TextModels.Model; wr: TextModels.Writer; ch, nch: SHORTCHAR;
BEGIN
ASSERT(f # NIL, 20);
r.ConnectTo(f); r.SetPos(0);
t := TextModels.dir.New(); wr := t.NewWriter(NIL);
r.ReadSChar(ch);
WHILE ~r.rider.eof DO
r.ReadSChar(nch);
IF (ch = CR) & (nch = LF) THEN r.ReadSChar(nch)
ELSIF ch = LF THEN ch := CR
END;
WriteWndChar(wr, ch); ch := nch
END;
s := TextViews.dir.New(t)
END ImportText;
PROCEDURE ImportTabText* (f: Files.File; OUT s: Stores.Store);
VAR r: Stores.Reader; t: TextModels.Model; wr: TextModels.Writer; ch, nch: SHORTCHAR;
BEGIN
ASSERT(f # NIL, 20);
r.ConnectTo(f); r.SetPos(0);
t := TextModels.dir.New(); wr := t.NewWriter(NIL);
r.ReadSChar(ch);
WHILE ~r.rider.eof DO
r.ReadSChar(nch);
IF (ch = CR) & (nch = LF) THEN r.ReadSChar(nch)
ELSIF ch = LF THEN ch := CR
ELSIF (ch = " ") & (nch = " ") THEN ch := TAB; r.ReadSChar(nch)
END;
WriteWndChar(wr, ch); ch := nch
END;
s := TextViews.dir.New(t)
END ImportTabText;
PROCEDURE ImportUnicode* (f: Files.File; OUT s: Stores.Store);
VAR r: Stores.Reader; t: TextModels.Model; v: TextViews.View; w: TextModels.Writer;
ch0, ch1: SHORTCHAR; len, res: INTEGER; uc: CHAR; rev: BOOLEAN;
BEGIN
ASSERT(f # NIL, 20);
r.ConnectTo(f); r.SetPos(0);
len := f.Length(); rev := FALSE;
t := TextModels.dir.New(); w := t.NewWriter(NIL); w.SetPos(0);
WHILE len > 0 DO
r.ReadSChar(ch0); r.ReadSChar(ch1);
IF rev THEN uc := CHR(ORD(ch1) + 256 * ORD(ch0))
ELSE uc := CHR(ORD(ch0) + 256 * ORD(ch1))
END;
DEC(len, 2);
IF uc = 0FFFEX THEN rev := ~rev
ELSIF uc < 100X THEN WriteWndChar(w, uc)
ELSIF uc # 0FEFFX THEN w.WriteChar(uc)
END
END;
v := TextViews.dir.New(t);
s := v
END ImportUnicode;
PROCEDURE ImportDosText* (f: Files.File; OUT s: Stores.Store);
VAR r: Stores.Reader; t: TextModels.Model; wr: TextModels.Writer; ch, nch: SHORTCHAR;
PROCEDURE ConvertChar (wr: TextModels.Writer; ch: CHAR);
(* PC Code Page Mappings M4 (Latin) to Unicode Encoding *)
(* Reference: The Unicode Standard, Version 1.0, Vol 1, Addison Wesley, p. 536 *)
BEGIN
CASE ch OF
| CR, TAB, " "..7EX: wr.WriteChar(ch)
| LF:
| 080X: wr.WriteChar(0C7X)
| 081X: wr.WriteChar(0FCX)
| 082X: wr.WriteChar(0E9X)
| 083X: wr.WriteChar(0E2X)
| 084X: wr.WriteChar(0E4X)
| 085X: wr.WriteChar(0E0X)
| 086X: wr.WriteChar(0E5X)
| 087X: wr.WriteChar(0E7X)
| 088X: wr.WriteChar(0EAX)
| 089X: wr.WriteChar(0EBX)
| 08AX: wr.WriteChar(0E8X)
| 08BX: wr.WriteChar(0EFX)
| 08CX: wr.WriteChar(0EEX)
| 08DX: wr.WriteChar(0ECX)
| 08EX: wr.WriteChar(0C4X)
| 08FX: wr.WriteChar(0C5X)
| 090X: wr.WriteChar(0C9X)
| 091X: wr.WriteChar(0E6X)
| 092X: wr.WriteChar(0C6X)
| 093X: wr.WriteChar(0F4X)
| 094X: wr.WriteChar(0F6X)
| 095X: wr.WriteChar(0F2X)
| 096X: wr.WriteChar(0FBX)
| 097X: wr.WriteChar(0F9X)
| 098X: wr.WriteChar(0FFX)
| 099X: wr.WriteChar(0D6X)
| 09AX: wr.WriteChar(0DCX)
| 09BX: wr.WriteChar(0F8X)
| 09CX: wr.WriteChar(0A3X)
| 09DX: wr.WriteChar(0D8X)
| 09EX: wr.WriteChar(0D7X)
| 09FX: wr.WriteChar(0192X)
| 0A0X: wr.WriteChar(0E1X)
| 0A1X: wr.WriteChar(0EDX)
| 0A2X: wr.WriteChar(0F3X)
| 0A3X: wr.WriteChar(0FAX)
| 0A4X: wr.WriteChar(0F1X)
| 0A5X: wr.WriteChar(0D1X)
| 0A6X: wr.WriteChar(0AAX)
| 0A7X: wr.WriteChar(0BAX)
| 0A8X: wr.WriteChar(0BFX)
| 0A9X: wr.WriteChar(0AEX)
| 0AAX: wr.WriteChar(0ACX)
| 0ABX: wr.WriteChar(0BDX)
| 0ACX: wr.WriteChar(0BCX)
| 0ADX: wr.WriteChar(0A1X)
| 0AEX: wr.WriteChar(0ABX)
| 0AFX: wr.WriteChar(0BBX)
| 0B5X: wr.WriteChar(0C1X)
| 0B6X: wr.WriteChar(0C2X)
| 0B7X: wr.WriteChar(0C0X)
| 0B8X: wr.WriteChar(0A9X)
| 0BDX: wr.WriteChar(0A2X)
| 0BEX: wr.WriteChar(0A5X)
| 0C6X: wr.WriteChar(0E3X)
| 0C7X: wr.WriteChar(0C3X)
| 0CFX: wr.WriteChar(0A4X)
| 0D0X: wr.WriteChar(0F0X)
| 0D1X: wr.WriteChar(0D0X)
| 0D2X: wr.WriteChar(0CAX)
| 0D3X: wr.WriteChar(0CBX)
| 0D4X: wr.WriteChar(0C8X)
| 0D5X: wr.WriteChar(0131X)
| 0D6X: wr.WriteChar(0CDX)
| 0D7X: wr.WriteChar(0CEX)
| 0D8X: wr.WriteChar(0CFX)
| 0DDX: wr.WriteChar(0A6X)
| 0DEX: wr.WriteChar(0CCX)
| 0E0X: wr.WriteChar(0D3X)
| 0E1X: wr.WriteChar(0DFX)
| 0E2X: wr.WriteChar(0D4X)
| 0E3X: wr.WriteChar(0D2X)
| 0E4X: wr.WriteChar(0F5X)
| 0E5X: wr.WriteChar(0D5X)
| 0E6X: wr.WriteChar(0B5X)
| 0E7X: wr.WriteChar(0FEX)
| 0E8X: wr.WriteChar(0DEX)
| 0E9X: wr.WriteChar(0DAX)
| 0EAX: wr.WriteChar(0DBX)
| 0EBX: wr.WriteChar(0D9X)
| 0ECX: wr.WriteChar(0FDX)
| 0EDX: wr.WriteChar(0DDX)
| 0EEX: wr.WriteChar(0AFX)
| 0EFX: wr.WriteChar(0B4X)
| 0F0X: wr.WriteChar(0ADX)
| 0F1X: wr.WriteChar(0B1X)
| 0F2X: wr.WriteChar(02017X)
| 0F3X: wr.WriteChar(0BEX)
| 0F4X: wr.WriteChar(0B6X)
| 0F5X: wr.WriteChar(0A7X)
| 0F6X: wr.WriteChar(0F7X)
| 0F7X: wr.WriteChar(0B8X)
| 0F8X: wr.WriteChar(0B0X)
| 0F9X: wr.WriteChar(0A8X)
| 0FAX: wr.WriteChar(0B7X)
| 0FBX: wr.WriteChar(0B9X)
| 0FCX: wr.WriteChar(0B3X)
| 0FDX: wr.WriteChar(0B2X)
| 0X..8X, 0BX, 0CX, 0EX..1FX, 7FX,
0B0X..0B4X, 0B9X..0BCX, 0BFX..0C5X, 0C8X..0CEX, 0D9X..0DCX, 0DFX, 0FEX, 0FFX:
wr.WriteChar(CHR(0EF00H + ORD(ch)))
END
END ConvertChar;
BEGIN
ASSERT(f # NIL, 20);
r.ConnectTo(f); r.SetPos(0);
t := TextModels.dir.New(); wr := t.NewWriter(NIL);
r.ReadSChar(ch);
WHILE ~r.rider.eof DO
r.ReadSChar(nch);
IF (ch = CR) & (nch = LF) THEN r.ReadSChar(nch)
ELSIF ch = LF THEN ch := CR
END;
ConvertChar(wr, ch); ch := nch
END;
s := TextViews.dir.New(t)
END ImportDosText;
PROCEDURE TextView(s: Stores.Store): Stores.Store;
BEGIN
IF s IS Views.View THEN RETURN Properties.ThisType(s(Views.View), "TextViews.View")
ELSE RETURN NIL
END
END TextView;
PROCEDURE ExportText* (s: Stores.Store; f: Files.File);
VAR w: Stores.Writer; t: TextModels.Model; r: TextModels.Reader; ch: CHAR;
BEGIN
ASSERT(s # NIL, 20); ASSERT(f # NIL, 21);
s := TextView(s);
IF s # NIL THEN
w.ConnectTo(f); w.SetPos(0);
t := s(TextViews.View).ThisModel();
IF t # NIL THEN
r := t.NewReader(NIL);
r.ReadChar(ch);
WHILE ~r.eot DO
IF (ch # TextModels.viewcode) & (ch # TextModels.para) THEN
ch := ThisWndChar(ch);
w.WriteSChar(SHORT(ch));
IF ch = CR THEN w.WriteSChar(LF) END
END;
r.ReadChar(ch)
END
END
END
END ExportText;
PROCEDURE ExportTabText* (s: Stores.Store; f: Files.File);
VAR w: Stores.Writer; t: TextModels.Model; r: TextModels.Reader; ch: CHAR;
BEGIN
ASSERT(s # NIL, 20); ASSERT(f # NIL, 21);
s := TextView(s);
IF s # NIL THEN
w.ConnectTo(f); w.SetPos(0);
t := s(TextViews.View).ThisModel();
IF t # NIL THEN
r := t.NewReader(NIL);
r.ReadChar(ch);
WHILE ~r.eot DO
IF (ch # TextModels.viewcode) & (ch # TextModels.para) THEN
ch := ThisWndChar(ch);
IF ch = CR THEN w.WriteSChar(CR); w.WriteSChar(LF)
ELSIF ch = TAB THEN w.WriteSChar(" "); w.WriteSChar(" ")
ELSE w.WriteSChar(SHORT(ch))
END
END;
r.ReadChar(ch)
END
END
END
END ExportTabText;
PROCEDURE ExportUnicode* (s: Stores.Store; f: Files.File);
VAR w: Stores.Writer; t: TextModels.Model; r: TextModels.Reader; ch: CHAR;
BEGIN
ASSERT(s # NIL, 20); ASSERT(f # NIL, 21);
s := TextView(s);
IF s # NIL THEN
w.ConnectTo(f); w.SetPos(0);
w.WriteChar(0FEFFX); (* little endian *)
t := s(TextViews.View).ThisModel();
IF t # NIL THEN
r := t.NewReader(NIL);
r.ReadChar(ch);
WHILE ~r.eot DO
IF ch = CR THEN
w.WriteChar(CR); w.WriteChar(LF)
ELSIF (ch >= " ") OR (ch = TAB) THEN
IF (ch >= 0EF00X) & (ch <= 0EFFFX) THEN ch := CHR(ORD(ch) - 0EF00H) END;
w.WriteChar(ch)
END;
r.ReadChar(ch)
END
END
END
END ExportUnicode;
PROCEDURE ImportHex* (f: Files.File; OUT s: Stores.Store);
VAR r: Stores.Reader; t: TextModels.Model; w: TextMappers.Formatter; ch: SHORTCHAR; a: INTEGER;
i: INTEGER; str: ARRAY 17 OF CHAR;
BEGIN
ASSERT(f # NIL, 20);
r.ConnectTo(f); r.SetPos(0);
t := TextModels.dir.New();
w.ConnectTo(t); w.SetPos(0);
r.ReadSChar(ch); a := 0;
WHILE ~r.rider.eof DO
IF a MOD 16 = 0 THEN
w.WriteChar("[");
w.WriteIntForm(a, TextMappers.hexadecimal, 8, "0", FALSE);
w.WriteSString("]")
END;
w.WriteIntForm(ORD(ch), TextMappers.hexadecimal, 2, "0", FALSE);
IF ch > 20X THEN str[a MOD 16] := ch ELSE str[a MOD 16] := "" END;
INC(a);
IF a MOD 16 = 0 THEN
str[16] := 0X; w.WriteString(""); w.WriteString(str);
w.WriteLn
ELSIF a MOD 4 = 0 THEN
w.WriteString("")
ELSE
w.WriteChar("")
END;
r.ReadSChar(ch)
END;
IF a MOD 16 # 0 THEN
str[a MOD 16] := 0X;
i := (16 - a MOD 16) * 3 + (3 - a MOD 16 DIV 4) + 3;
WHILE i # 0 DO w.WriteChar(""); DEC(i) END;
w.WriteString(str)
END;
s := TextViews.dir.New(t)
END ImportHex;
(*
imports a UTF-8 encoded file:
1. if the optional byte order mark (BOM) is found at the beginning of the file, it is skipped
2. three forms of line separators are supported: CR, LF, and CR LF
3. characters larger than 16 bit are reported as '?'
4. in case of finding an illegal encoding it falls back to importing a windows text
*)
PROCEDURE ImportUtf8* (f: Files.File; OUT s: Stores.Store);
VAR r: Files.Reader; t: TextModels.Model; wr: TextModels.Writer; ch, nch: CHAR; formatError: BOOLEAN;
PROCEDURE ReadUtf8Char (VAR rd: Files.Reader; VAR ch: CHAR);
VAR c1, c2, c3: BYTE;
PROCEDURE FormatError;
BEGIN rd.SetPos(rd.Base().Length()); rd.eof := TRUE; ch := 0X; formatError := TRUE
END FormatError;
BEGIN
rd.ReadByte(c1);
IF c1 >= 0 THEN (* 0xxx xxxx *)
ch := CHR(c1)
ELSIF BITS(c1) * {7, 6, 5} = {7, 6} THEN (* 110x xxxx, 10xx xxxx *)
rd.ReadByte(c2);
IF BITS(c2) * {7, 6} = {7} THEN
ch := CHR(64 * (c1 MOD 32) + (c2 MOD 64))
ELSE FormatError
END
ELSIF BITS(c1) * {7, 6, 5, 4} = {7, 6, 5} THEN (* 1110 xxxx, 10xx xxxx, 10xx xxxx *)
rd.ReadByte(c2); rd.ReadByte(c3);
IF (BITS(c2) * {7, 6} = {7}) & (BITS(c3) * {7, 6} = {7}) THEN
ch := CHR(4096 * (c1 MOD 16) + 64 * (c2 MOD 64) + (c3 MOD 64))
ELSE FormatError
END
ELSIF BITS(c1) * {7, 6, 5, 4, 3} = {7, 6, 5, 4} THEN (* 1111 0xxx, 10xx xxxx, 10xx xxxx, 10xx xxxx *)
rd.ReadByte(c2); rd.ReadByte(c3); rd.ReadByte(c3); ch := '?'
ELSE FormatError
END
END ReadUtf8Char;
BEGIN
ASSERT(f # NIL, 20);
r := f.NewReader(NIL);
t := TextModels.dir.New(); wr := t.NewWriter(NIL); formatError := FALSE;
ReadUtf8Char(r, ch);
IF ch = 0FEFFX THEN ReadUtf8Char(r, ch) END; (* skip BOM *)
WHILE ~r.eof DO
ReadUtf8Char(r, nch);
IF (ch = CR) & (nch = LF) THEN ReadUtf8Char(r, nch)
ELSIF ch = LF THEN ch := CR
END;
wr.WriteChar(ch);
ch := nch
END;
IF ~formatError THEN s := TextViews.dir.New(t)
ELSE ImportText(f, s) (* fallback to Windows text importer *)
END
END ImportUtf8;
(* exports a UTF-8 encoded file without inserting a byte order mark (BOM) and with LF as line separator *)
PROCEDURE ExportUtf8* (s: Stores.Store; f: Files.File);
VAR w: Stores.Writer; t: TextModels.Model; r: TextModels.Reader; ch: CHAR;
PROCEDURE WriteUtf8Char (VAR wr: Stores.Writer; ch: CHAR);
BEGIN
IF ch <= 7FX THEN
wr.WriteByte(SHORT(SHORT(ORD(ch))))
ELSIF ch <= 7FFX THEN
wr.WriteByte(SHORT(SHORT( -64 + ORD(ch) DIV 64)));
wr.WriteByte(SHORT(SHORT( -128 + ORD(ch) MOD 64)))
ELSE
wr.WriteByte(SHORT(SHORT( -32 + ORD(ch) DIV 4096)));
wr.WriteByte(SHORT(SHORT( -128 + ORD(ch) DIV 64 MOD 64)));
wr.WriteByte(SHORT(SHORT( -128 + ORD(ch) MOD 64)))
END
END WriteUtf8Char;
BEGIN
ASSERT(s # NIL, 20); ASSERT(f # NIL, 21);
s := TextView(s);
IF s # NIL THEN
w.ConnectTo(f); w.SetPos(0);
t := s(TextViews.View).ThisModel();
IF t # NIL THEN
r := t.NewReader(NIL);
r.ReadChar(ch);
WHILE ~r.eot DO
IF (ch # TextModels.viewcode) & (ch # TextModels.para) THEN
IF ch = CR THEN WriteUtf8Char(w, LF) ELSE WriteUtf8Char(w, ch) END
END;
r.ReadChar(ch)
END
END
END
END ExportUtf8;
END StdTextConv.
| Std/Mod/TextConv.odc |
MODULE StdTiles;
(**
project = "BlackBox 2.0"
organizations = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Contributors, Anton Dmitriev, Ivan Denisov"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- YYYYMMDD, nn, ...
"
issues = "
-
"
**)
IMPORT Kernel, Meta, Models,
Controllers, Properties, Ports, Stores, Dialog, Views, Containers,
Documents, Files, Converters, Fonts, Log, Sequencers, Windows,
StdCmds, StdWindows, StdGrids, StdDocuments, StdLog, StdDialog, StdMenus,
TextViews, Strings, TextControllers;
CONST
version = 1;
badKind = 1;
(* externalized proxy content kinds *)
external = 1; log = 2; internal = 3; empty = 4;
stopCursor = 22; (* keep in sync with HostPorts.stopCursor *)
dark* = 0; light* = 1;
TYPE
Param* = POINTER TO RECORD
closeDialogLocation*,
closeDialogDocument*: Files.Name;
Init-, InitDefaults-: PROCEDURE (a: ANYPTR)
END;
Pixels = INTEGER; (* for values in pixel coordinates *)
UCs = INTEGER; (* used for values in universal coordinates *)
Backend = POINTER TO RECORD (StdWindows.WindowBackend)
proxy: Proxy
END;
BackendDirectory = POINTER TO RECORD (StdWindows.BackendDirectory)
nextProxy: Proxy
END;
Proxy = POINTER TO RECORD (Views.View)
wb: Backend; (* wb = NIL => window was closed; Proxy's host may not have removed Proxy *)
base: Windows.Window; (* the non-Tiler window in which .wb is opened *)
filler: StdGrids.View; (* param for Backend.Open *)
delayed: RECORD (* data for delayed opening of a window with .view *)
is: BOOLEAN; (* flags that proxy is delayed; for one of two reasons: after Internalize (=>.delayed.view # NIL) or after CopyFromSimpleView *)
view: Views.View;
title: Views.Title;
flags: SET;
loc: Files.Locator;
fname: Files.Name;
conv: Converters.Converter;
END
END;
SeqNotifier = POINTER TO RECORD (Sequencers.Notifier)
loc: Files.Locator;
fname: Files.Name;
view: Views.View;
win: Windows.Window;
END;
BeforeCloseMsg = RECORD (Sequencers.Message) END;
FindFrameMsg = RECORD (Views.Message)
frame: Views.Frame
END;
ViewHook = POINTER TO RECORD (StdDialog.ViewHook)
tiled: BOOLEAN; (* whether tiling is on or off *)
END;
AttachedCheckHook = POINTER TO RECORD (StdWindows.AttachedCheckHook) END;
VAR
bckndDir-: BackendDirectory;
param*: Param;
lastWorkspaceName: Files.Name; lastWorkspaceLoc: Files.Locator;
viewHook: ViewHook;
attCheckHook: AttachedCheckHook;
windowsRouter, backUp: PROCEDURE (IN title: ARRAY OF CHAR);
targetTrack-: Views.Title;
PROCEDURE SetWindowsRouter* (r: PROCEDURE (IN title: ARRAY OF CHAR));
BEGIN
windowsRouter := r
END SetWindowsRouter;
PROCEDURE SetTarget* (IN target: ARRAY OF CHAR);
BEGIN
targetTrack := target$
END SetTarget;
PROCEDURE GetInnermostFiller (VAR f: Views.Frame; OUT filler: StdGrids.View);
VAR msg: StdGrids.TrackPropMsg; v: Views.View;
BEGIN
REPEAT
f := Views.HostOf(f);
IF f # NIL THEN
msg.done := FALSE; msg.poll := TRUE;
Views.HandlePropMsg(f.view, msg)
END
UNTIL (f = NIL) OR msg.done;
IF msg.done THEN
v := f.view;
WITH v: StdGrids.View DO filler := v ELSE HALT(126) END
END
END GetInnermostFiller;
PROCEDURE GetBase (f: Views.Frame; OUT base: Windows.Window);
(* since Proxy.base is not eliminatable at this point, is GetBase eliminatable? *)
(** Get outermost window base that f is installed under *)
BEGIN
IF f # NIL THEN f := Views.UltimateRootOf(f);
base := Windows.dir.First();
WHILE (base # NIL) & (base.frame # f) DO base := Windows.dir.Next(base) END
END
END GetBase;
PROCEDURE GetThisFiller (IN name: Views.Title; OUT filler: StdGrids.View; OUT frame: Views.Frame);
VAR msg: StdGrids.TrackMsg;
BEGIN
msg.name := name$; msg.cnt := 0; Views.Omnicast(msg);
IF msg.cnt = 1 THEN filler := msg.track; frame := msg.frame
END
END GetThisFiller;
PROCEDURE DoOpen (v: Views.View; IN title: Views.Title; loc: Files.Locator;
IN fname: Files.Name; conv: Converters.Converter; flags: SET; proxy: Proxy;
forceMain: BOOLEAN; OUT win: StdWindows.Window);
VAR
opts, pvopts: SET;
d: Documents.Document;
c: Containers.Controller;
s: ANYPTR;
seq: Sequencers.Sequencer;
bd: StdWindows.BackendDirectory;
view: Views.View;
ctx: Models.Context;
gooddoc: BOOLEAN;
BEGIN
ASSERT(v # NIL, 20);
win := NIL;
IF conv = NIL THEN conv := Converters.list END; (* use document converter *)
(* IF proxy # NIL THEN EXCL(flags, Views.modal) END; *)
WITH v: Documents.Document DO
d := v; view := v.ThisView()
ELSE
view := v;
ctx := v.context;
IF ctx # NIL THEN WITH ctx: Documents.Context DO d := ctx.ThisDoc() END END
END;
IF (d # NIL) & (d.context # NIL) THEN
d := Documents.DuplicateAs(d, StdDocuments.dir);
view := d.ThisView()
END;
IF d = NIL THEN d := Documents.dir.New(view, Views.undefined, Views.undefined) END;
ASSERT(d.Domain() = view.Domain(), 100); ASSERT(d.Domain() # NIL, 101);
ASSERT(d.context = NIL, 102);
s := d.Domain().GetSequencer();
IF s # NIL THEN WITH s: Sequencers.Sequencer DO seq := s END END;
c := d.ThisController();
gooddoc := (c # NIL) & (c IS TextControllers.Controller);
opts := c.opts;
IF { Windows.isTool, Windows.isAux } * flags # {} THEN
INCL(opts, Containers.noSelection)
END;
(* k8: in primary windows too *)
pvopts := opts;
IF (Windows.neverDirty IN flags)
OR ((proxy # NIL) & ~(Windows.noResize IN flags)) THEN
(* change "fit to page" to "fit to window" in secondary windows *)
IF Documents.pageWidth IN opts THEN
opts := opts - {Documents.pageWidth} + {Documents.winWidth};
END;
IF Documents.pageHeight IN opts THEN
opts := opts - {Documents.pageHeight} + {Documents.winHeight};
END;
(* k8: fixed size windows should be changed too *)
IF gooddoc & ~(Containers.noSelection IN opts) THEN
IF opts * {Documents.pageWidth, Documents.winWidth} = {} THEN
INCL(opts, Documents.winWidth);
END;
IF opts * {Documents.pageHeight, Documents.winHeight} = {} THEN
INCL(opts, Documents.winHeight);
END
END
END;
IF opts # c.opts THEN
c.SetOpts(opts);
IF (opts # pvopts) & (seq # NIL) THEN seq.SetDirty(FALSE) END
END;
IF (Windows.neverDirty IN flags) & (seq # NIL) THEN seq.SetDirty(FALSE) END;
bd := StdWindows.backendDir;
IF proxy = NIL THEN
StdWindows.SetBackendDir(StdWindows.stdBackendDir)
ELSE
StdWindows.SetBackendDir(bckndDir);
bckndDir.nextProxy := proxy
END;
win := StdWindows.dir.New()(StdWindows.Window);
StdWindows.SetBackendDir(bd);
IF ~forceMain & (seq # NIL) THEN
Windows.dir.OpenSubWindow(win, d, flags, title)
ELSE
Windows.dir.Open(win, d, flags, title, loc, fname, conv)
END
END DoOpen;
PROCEDURE ProxyFor (IN title: Views.Title): Proxy;
VAR filler: StdGrids.View; f: Views.Frame; proxy: Proxy;
BEGIN
proxy := NIL;
WITH StdWindows.backendDir: BackendDirectory DO
IF windowsRouter # NIL THEN
windowsRouter(title)
END;
GetThisFiller(targetTrack, filler, f);
IF (filler # NIL) & (f # NIL) THEN
NEW(proxy);
GetBase(f, proxy.base);
proxy.filler := filler
END
ELSE
END;
RETURN proxy
END ProxyFor;
(* ViewHook *)
PROCEDURE (h: ViewHook) Open (v: Views.View; title: ARRAY OF CHAR;
loc: Files.Locator; name: Files.Name; conv: Converters.Converter;
asTool, asAux, noResize, allowDuplicates, neverDirty: BOOLEAN);
VAR t: Views.Title; flags: SET; proxy: Proxy; done: BOOLEAN; len: INTEGER;
w_: StdWindows.Window; (* changes from StdDialog.Open marked by blue *)
BEGIN
IF conv = NIL THEN conv := Converters.list END; (* use document converter *)
ASSERT(v # NIL, 20);
flags := {}; done := FALSE;
IF noResize THEN
flags := flags + {Windows.noResize, Windows.noHScroll, Windows.noVScroll}
END;
IF asTool THEN INCL(flags, Windows.isTool) END;
IF asAux THEN INCL(flags, Windows.isAux) END;
IF neverDirty THEN INCL(flags, Windows.neverDirty) END;
len := MIN(LEN(title$), LEN(Views.Title) - 1);
Strings.Extract(title, 0, len, t);
IF len = LEN(Views.Title) - 1 THEN
t[len - 1] := "."; t[len - 2] := "."; t[len - 3] := "."
END;
IF ~allowDuplicates THEN
Windows.SelectBySpec(loc, name, conv, flags, done);
IF ~done & (title # "") & (loc = NIL) & (name = "") THEN
Windows.SelectByTitle(v, flags, t, done)
END
ELSE
INCL(flags, Windows.allowDuplicates)
END;
IF ~done THEN
IF asTool OR ~h.tiled THEN
(* nothing *)
ELSE
proxy := ProxyFor(t)
END;
DoOpen(v, t, loc, name, conv, flags, proxy, FALSE, w_)
END
END Open;
PROCEDURE DelayedOpen (p: Proxy; f: Views.Frame);
VAR w_: StdWindows.Window; ffm: FindFrameMsg; v: Views.View;
BEGIN
ASSERT(p.delayed.is, 22); p.delayed.is := FALSE;
IF f # NIL THEN ASSERT(f.view = p, 21)
ELSE Views.Broadcast(p, ffm); f := ffm.frame
END;
v := p.delayed.view;
IF v # NIL THEN p.delayed.view := NIL; (* delayed after Internalize *)
IF f # NIL THEN
GetInnermostFiller(f, p.filler); ASSERT(p.filler # NIL, 126);
GetBase(f, p.base);
DoOpen(v, p.delayed.title, p.delayed.loc, p.delayed.fname, p.delayed.conv, p.delayed.flags, p, FALSE, w_);
p.delayed.loc := NIL; p.delayed.conv := NIL
IF v.context # NIL THEN
ASSERT(v.context IS Documents.Context, 24);
doc := v.context(Documents.Context).ThisDoc();
IF doc.context # NIL THEN
Con.String("DelayedOpen: opts: "); Con.Set(doc.ThisController().opts); Con.Ln;
doc := Documents.dir.New(Views.CopyOf(v, Views.shallow), Views.undefined, Views.undefined)
ELSE ;Con.String("DelayedOpen: doc.context = NIL, opts: "); Con.Set(doc.ThisController().opts); Con.Ln;
END
ELSE doc := Documents.dir.New(v, Views.undefined, Views.undefined)
END;
bd := StdWindows.backendDir; StdWindows.SetBackendDir(bckndDir);
bckndDir.nextProxy := p;
win := StdWindows.dir.New()(StdWindows.Window);
IF bd # NIL THEN StdWindows.SetBackendDir(bd) END;
StdWindows.Open(win, doc, p.delayed.flags, p.delayed.title);
StdWindows.SetSpec(win, p.delayed.loc, p.delayed.fname, p.delayed.conv);
END
ELSE GetBase(f, p.base) (* delayed after Proxy.CopyFromSimpleView *)
END
END DelayedOpen;
PROCEDURE (p: Proxy) HandleViewMsg (f: Views.Frame; VAR msg: Views.Message);
BEGIN
IF p.delayed.is THEN DelayedOpen(p, f) END;
WITH msg: FindFrameMsg DO msg.frame := f ELSE END
END HandleViewMsg;
PROCEDURE DirtyHook* (w: Windows.Window; OUT action: INTEGER);
VAR loc: Files.Locator; dlg: Views.View; doc: Documents.Document; c: Containers.Controller;
wid, hei: INTEGER; name: Files.Name;
BEGIN ASSERT(w # NIL, 20); ASSERT(w.doc # NIL, 21);
action := StdCmds.default; doc := w.doc;
WITH doc: StdDocuments.Document DO
loc := Files.dir.This(param.closeDialogLocation);
IF loc # NIL THEN
name := param.closeDialogDocument;
dlg := Views.OldView(loc, name);
IF dlg # NIL THEN action := StdCmds.defer;
WITH dlg: Containers.View DO
c := dlg.ThisController(); IF c # NIL THEN c.SetOpts(c.opts + Containers.mask) END
ELSE
END;
dlg.context.GetSize(wid, hei);
TylerLayouts.InsertBar(w.doc(TylerDocuments.Document), TylerLayouts.top,
Views.CopyOf(v, Views.deep), NIL, FALSE, w)StdDocuments.InsertOverlaid(StdDocuments.AddBackground(Views.CopyOf(dlg, Views.deep)), NIL, doc, StdDocuments.center, StdDocuments.center, wid, hei, w)
END
END
ELSE
END
END DirtyHook;
PROCEDURE CloseNestedWindows (w: Windows.Window; OUT cancelled, deferred: BOOLEAN);
CONST maxDeff = 50;
VAR
wnd, next: Windows.Window; wb: StdWindows.WindowBackend; defThis: BOOLEAN;
deff, copy: POINTER TO ARRAY OF StdWindows.Window; i, nDef, len, j: INTEGER;
BEGIN
cancelled := FALSE; deferred := FALSE; wnd := Windows.dir.First(); nDef := 0;
WHILE (wnd # NIL) & ~cancelled DO
WITH wnd: StdWindows.Window DO
wb := wnd.backend;
IF wnd # w THEN
WITH wb: Backend DO
IF wb.proxy.base = w THEN
i := 0; WHILE (i < nDef) & (deff[i] # wnd) DO INC(i) END;
IF i = nDef THEN
StdCmds.GuardedClose(wnd, cancelled, defThis);
deferred := deferred OR defThis;
IF defThis THEN
IF deff = NIL THEN
NEW(deff, maxDeff)
ELSIF nDef = LEN(deff) THEN
len := LEN(deff); NEW(copy, len + maxDeff);
j := 0; WHILE j < len DO copy[j] := deff[j]; INC(j) END; deff := copy
END;
deff[nDef] := wnd; INC(nDef)
END;
IF ~cancelled & ~defThis THEN next := Windows.dir.First()
ELSIF ~cancelled & defThis THEN next := Windows.dir.Next(wnd)
ELSE next := NIL
END
END
END
ELSE
END
END;
ELSE
END;
IF next # NIL THEN
wnd := next
ELSIF ~cancelled THEN
wnd := Windows.dir.Next(wnd)
END;
next := NIL
END
END CloseNestedWindows;
PROCEDURE CloseNow*;
(** Command for use in a File close dialog. Causes immediate closing of the document losing all modifications. Only works when TilerWindows.par is initialized appropriately - that is, this is actually a private procedure. *)
BEGIN
IF StdDocuments.par # NIL THEN
WITH StdDocuments.par: StdWindows.Window DO
Windows.dir.Close(StdDocuments.par); Kernel.Cleanup
ELSE
Log.String(
"TW.CloseNow: ~(TilerWindows.par IS StdWindows.Window); cannot Close")
END
END
END CloseNow;
PROCEDURE SaveNClose*;
(** Command for use in a File close dialog. Causes the document to be saved and then closed. Only works when TilerWindows.par is initialized appropriately - that is, this is actually a private procedure. *)
BEGIN
IF StdDocuments.par # NIL THEN
WITH StdDocuments.par: StdWindows.Window DO
StdCmds.SaveDialog;
Windows.dir.Close(StdDocuments.par);
Kernel.Cleanup
ELSE
Log.String("StdTiles.SaveNClose: ~(StdDocuments.par IS StdWindows.Window); cannot SaveNClose")
END
END
END SaveNClose;
PROCEDURE ThisFiller* (w: StdWindows.Window): StdGrids.View;
(** Returns the filler in which w is opened. *)
VAR res: StdGrids.View;
BEGIN ASSERT(w # NIL, 20);
IF (w.backend # NIL) & (w.backend IS Backend) THEN
res := StdGrids.ThisFiller(w.backend(Backend).proxy)
END;
RETURN res
END ThisFiller;
PROCEDURE (wb: Backend) Close;
VAR prop: StdGrids.Proposal;
BEGIN
IF wb.proxy # NIL THEN
prop.op := StdGrids.remove;
wb.proxy.context.Consider(prop) (* this removes the proxy from the filler *)
END;
wb.proxy := NIL
END Close;
(* Proxy view *)
PROCEDURE (dst: Proxy) CopyFromSimpleView (src: Views.View);
(* Proxies are tricky: they display windows. But a window can only be displayed in one, well, window, one place. This is why, when a copy is made of a proxy, the original is stripped of it's window. I am not sure how well this will work with the rest of the framework, because the framework feels free to make copies of views for various reasons, even for the sake of externalizing a view. Like this: a copy of a view is made, this copy is exteralized, and then the copy is disposed, and what the user sees on the screen is actually the original. But, with a proxy, the original proxy would be stripped of it's window and would display nothing. So, I'm not sure how well this will work. At the time, this does not happen because when a filler is saved, it does not make a copy of it's content. The only time (now) that a copy of a proxy is made is explicitly when the proxy is dragged into another filler *)
BEGIN
WITH src: Proxy DO
dst.wb := src.wb; src.wb := NIL; dst.wb.proxy := dst;
dst.wb.proxy.base := NIL; dst.delayed.is := TRUE
END
END CopyFromSimpleView;
PROCEDURE Transfer* (w: StdWindows.Window; to: StdGrids.View);
(** Transfer tiled window w into another filler to. *)
VAR prop: StdGrids.Proposal;
BEGIN ASSERT(w # NIL, 20); ASSERT(to # NIL, 20);
IF (w.backend # NIL) & (w.backend IS Backend) THEN
StdGrids.Transfer(w.backend(Backend).proxy, to, StdGrids.append);
prop.op := StdGrids.activate; w.backend(Backend).proxy.context.Consider(prop);
END
END Transfer;
PROCEDURE TransferTo* (w: StdWindows.Window; IN track: Views.Title);
(** Transfer tiled window w into track track *)
VAR prop: StdGrids.Proposal; to: StdGrids.View; _: Views.Frame;
BEGIN ASSERT(w # NIL, 20);
IF (w.backend # NIL) & (w.backend IS Backend) THEN
GetThisFiller(track, to, _); ASSERT(to # NIL, 20);
StdGrids.Transfer(w.backend(Backend).proxy, to, StdGrids.append);
prop.op := StdGrids.activate; w.backend(Backend).proxy.context.Consider(prop);
END
END TransferTo;
PROCEDURE (proxy: Proxy) HandleCtrlMsg (f: Views.Frame; VAR msg: Views.CtrlMessage; VAR focus: Views.View );
VAR w: StdWindows.Window;
BEGIN
IF proxy.delayed.is THEN DelayedOpen(proxy, f) END;
WITH msg: Controllers.PollFocusMsg DO msg.focus := f
ELSE
IF proxy.wb # NIL THEN w := proxy.wb.win;
IF w # NIL THEN
WITH msg: Controllers.MarkMsg DO
IF msg.show & (w # StdWindows.front) THEN
Windows.dir.Select(w, Windows.lazy)
END
| msg: StdGrids.RemoveMsg DO
msg.processed := TRUE;
StdWindows.GuardedClose(w)
| msg: StdWindows.PrefocusMsg DO
msg.win := w
ELSE
StdWindows.ForwardCtrlMsg(w, msg)
END
END
ELSE WITH msg: Controllers.PollCursorMsg DO msg.cursor := stopCursor ELSE END
END
END
END HandleCtrlMsg;
PROCEDURE (p: Proxy) HandlePropMsg (VAR msg: Properties.Message);
BEGIN
IF p.delayed.is THEN DelayedOpen(p, NIL) END;
WITH msg: Properties.FocusPref DO msg.setFocus := p.wb # NIL
| msg: StdGrids.WindowPref DO
IF p.wb # NIL THEN msg.win := p.wb.win END
ELSE
END
END HandlePropMsg;
PROCEDURE (p: Proxy) GetBackground (VAR col: Ports.Color);
BEGIN
IF (p.wb # NIL) & (p.wb.win.doc # NIL) THEN p.wb.win.doc.GetBackground(col) END
END GetBackground;
PROCEDURE (proxy: Proxy) Restore (f: Views.Frame; l_, t_, r_, b_: UCs);
VAR wid, hei, asc, dsc, u, dummy: UCs; w: StdWindows.Window; title: Views.Title; fnt: Fonts.Font;
BEGIN
IF proxy.delayed.is THEN DelayedOpen(proxy, f) END;
proxy.context.GetSize(wid, hei);
IF proxy.wb # NIL THEN
w := proxy.wb.win;
IF (w # NIL) & (w.frame # NIL) & (w.backend IS Backend) THEN u := f.unit;
w.SetSize((f.gx + wid) DIV u - f.gx DIV u, (f.gy + hei) DIV u - f.gy DIV u);
StdWindows.InstallRoot(w, f, 0, 0, 0, StdWindows.front = w)
END
ELSE
(*
f.DrawRect(0, 0, wid, hei, Ports.fill, celadon);
*)
fnt := Fonts.dir.Default(); fnt := Fonts.dir.This(fnt.typeface, fnt.size, fnt.style, Fonts.bold);
fnt.GetBounds(asc, dsc, dummy);
IF w = NIL THEN title := "NIL" ELSE title := w.title END;
f.DrawString((wid - u) DIV 2, (hei - asc - dsc) DIV 2, Ports.red, title, fnt)
END
END Restore;
PROCEDURE Export (f: Files.File; v: Views.View; OUT ok: BOOLEAN);
VAR val: RECORD (Meta.Value) p: Converters.Exporter END; it: Meta.Item;
BEGIN
Meta.LookupPath(Converters.list.exp, it);
IF (it.obj = Meta.procObj) OR (it.obj = Meta.varObj) & (it.typ = Meta.procTyp) THEN
it.GetVal(val, ok)
ELSE ok := FALSE
END;
IF ok THEN val.p(v, f) END
END Export;
PROCEDURE Import (f: Files.File; OUT v: Views.View);
VAR val: RECORD (Meta.Value) p: Converters.Importer END; it: Meta.Item; ok: BOOLEAN;
s: Stores.Store;
BEGIN
Meta.LookupPath(Converters.list.imp, it);
IF (it.obj = Meta.procObj) OR (it.obj = Meta.varObj) & (it.typ = Meta.procTyp) THEN
it.GetVal(val, ok)
ELSE ok := FALSE
END;
IF ok THEN
val.p(f, s); IF s # NIL THEN WITH s: Views.View DO v := s ELSE END END
END
END Import;
PROCEDURE GetRelativeLocation (IN wrt: Files.Name; VAR loc: Files.Name);
(** wrt: /home/anto/bb; loc: /home/anto/bb/Box => Box*)
VAR j, i: INTEGER; a, b: CHAR;
BEGIN
i := -1; REPEAT INC(i); a := wrt[i]; b := loc[i] UNTIL (a = 0X) OR (b = 0X) OR (a # b);
IF (b = '/') OR (b = '\') THEN INC(i) END;
j := 0; IF j < i THEN REPEAT b := loc[i]; loc[j] := b; INC(i); INC(j) UNTIL b = 0X END
END GetRelativeLocation;
PROCEDURE (proxy: Proxy) Externalize (VAR wr: Stores.Writer);
VAR w: StdWindows.Window; root, location: Files.Name; kind: INTEGER; rd: Files.Reader; b: BYTE;
tmp: Files.File; ok: BOOLEAN;
BEGIN
wr.WriteVersion(version);
IF proxy.wb # NIL THEN w := proxy.wb.win END;
IF w # NIL THEN
IF (w.name # "") & (w.loc # NIL) THEN kind := external
ELSIF w.doc.ThisView().ThisModel() = StdLog.text THEN kind := log
ELSIF w.doc.ThisView() IS TextViews.View THEN kind := internal
ELSE kind := empty
END;
wr.WriteByte(SHORT(SHORT(kind)));
IF kind = external THEN
wr.WriteString(w.name);
Dialog.GetLocPath(w.loc, location); Dialog.GetLocPath(Files.dir.This(''), root);
GetRelativeLocation(root, location);
wr.WriteString(location);
wr.WriteString(w.conv.imp); wr.WriteString(w.title); wr.WriteSet(w.flags)
ELSIF kind = internal THEN
tmp := Files.dir.Temp(); Export(tmp, w.doc.ThisView(), ok);
IF ~ok THEN wr.WriteInt(0)
ELSE wr.WriteInt(tmp.Length()); rd := tmp.NewReader(NIL); rd.SetPos(0);
REPEAT rd.ReadByte(b); IF ~rd.eof THEN wr.WriteByte(b) END UNTIL rd.eof;
wr.WriteString(w.title); wr.WriteSet(w.flags)
END
END
ELSE
END
END Externalize;
PROCEDURE (p: Proxy) Internalize (VAR rd: Stores.Reader);
VAR location: Files.Name; len, ver: INTEGER; loc: Files.Locator; old: StdWindows.Window;
conv: Converters.Converter; imp: Dialog.String; s: Stores.Store; b, kind: BYTE;
tmp: Files.File; wr: Files.Writer; path: Files.Name;
BEGIN
rd.ReadVersion(version, version, ver);
IF ~rd.cancelled THEN
rd.ReadByte(kind);
CASE kind OF
| empty:
| external:
rd.ReadString(p.delayed.fname);
rd.ReadString(location); loc := Files.dir.This(location);
rd.ReadString(imp); rd.ReadString(p.delayed.title); rd.ReadSet(p.delayed.flags);
conv := Converters.list; WHILE (conv # NIL) & (conv.imp # imp) DO conv := conv.next END;
IF conv # NIL THEN
old := StdWindows.GetBySpec(loc, p.delayed.fname, conv, p.delayed.flags);
IF old # NIL THEN s := old.doc.ThisView()
ELSE Converters.Import(loc, p.delayed.fname, conv, s)
END;
IF s # NIL THEN
WITH s: Views.View DO
Dialog.GetLocPath(loc, path);
p.delayed.view := s; p.delayed.conv := conv; p.delayed.loc := loc;
ELSE
END
END
END
| internal:
rd.ReadInt(len);
IF len > 0 THEN tmp := Files.dir.Temp(); wr := tmp.NewWriter(NIL); wr.SetPos(0);
REPEAT rd.ReadByte(b); wr.WriteByte(b); DEC(len) UNTIL len = 0;
Import(tmp, p.delayed.view);
rd.ReadString(p.delayed.title); rd.ReadSet(p.delayed.flags); p.delayed.fname := ''
END
| log:
p.delayed.view := TextViews.dir.New(StdLog.text); p.delayed.fname := '';
Dialog.MapString("#Dev:Log", p.delayed.title);
p.delayed.flags := { Windows.neverDirty, Windows.isAux, Documents.winWidth }
ELSE rd.TurnIntoAlien(badKind)
END;
p.delayed.is := p.delayed.view # NIL;
END
END Internalize;
(* Backend *)
PROCEDURE (wb: Backend) SetSize (w, h: Pixels), EMPTY;
PROCEDURE (wb: Backend) SetTitle (IN title: Views.Title);
VAR prop: StdGrids.Proposal;
BEGIN
IF (wb.proxy # NIL) & (wb.proxy.context # NIL) THEN
prop.title := title$; prop.op := StdGrids.setTitle;
wb.proxy.context.Consider(prop)
END
END SetTitle;
PROCEDURE (wb: Backend) Select;
VAR prop: StdGrids.Proposal;
BEGIN
IF (wb.proxy # NIL) & (wb.proxy.context # NIL) THEN
prop.op := StdGrids.activate; wb.proxy.context.Consider(prop);
IF wb.proxy.base IS StdWindows.Window THEN
wb.proxy.base(StdWindows.Window).backend.Select;
END;
(* This is the only place where proxy.base is needed. If proxy were guaranteed to have a frame, then this frame could be obtained thru FindFrameMessage, then UltimateRootOf this frame would be the base window's root frame. But the proxy is NOT guaranteed to have a frame at this point: the context may not have granted the activation request, for example; or if it did, the update may have been requested but not validated, so the proxy may not have a frame at this point. *)
(* this ↓ is done in StdWindows.Open, actually
StdWindows.Validate(wb.base)
(* during window initialization (StdWindows.Open), this forces Restore'ation and building of the frame tree -- ensures that proxy gets a frame and wb.win.rootFrame gets properly positioned thru Proxy.Restore->StdWindows.InstallRoot. This way, the same command that opens a window can also operate on it's content (frame tree). *)
*)
(* k8: we need proper frame structure to make things like TextCmds.FindFirst work. so let's built it!
note that only newly created windows has no root host. *)
IF (wb.win # NIL) & (wb.win.frame # NIL) & (Views.HostOfRoot(wb.win.frame) = NIL) THEN
Views.BuildFrameTree(wb.win.frame, TRUE)
END
END
END Select;
PROCEDURE (wb: Backend) Open (isDialog: BOOLEAN);
(* VAR w: StdWindows.Window; loc: Files.Locator; fname: Files.Name;
conv: Converters.Converter; flags: SET; title: Views.Title;
doc: Documents.Document; dirty: BOOLEAN; proxy: Proxy;
wasSub: BOOLEAN; *)
VAR f: StdGrids.View;
BEGIN
(* w := wb.win;
IF isDialog & w.sub THEN
IF w # NIL THEN
doc := w.doc; title := w.title; loc := w.loc; fname := w.name$;
conv := w.conv; flags := w.flags;
dirty := w.seq.Dirty();
proxy := NIL;
(*
IF ~(w.backend IS Backend) THEN proxy := ProxyFor(title) END;
*)
(* Windows.dir.Close(w); *)
DoOpen(doc, title, loc, fname, conv, flags, proxy, TRUE, w);
IF ~dirty THEN w.seq.SetDirty(FALSE) END
END
ELSE
*)
(* at this point, wb.win.port # NIL, but wb.proxy may have no frame *)
ASSERT(wb.proxy # NIL, 20); ASSERT(wb.win # NIL, 21); ASSERT(wb.proxy.wb = wb, 22);
ASSERT(wb.win.doc # NIL, 23); ASSERT(wb.win.doc.context # NIL, 24);
IF wb.proxy.context = NIL THEN
f := wb.proxy.filler; wb.proxy.filler := NIL;
IF f.kind = StdGrids.divider THEN
StdGrids.AppendDivTile(f, wb.proxy, 0, 0)
ELSIF f.kind = StdGrids.stack THEN
StdGrids.AppendStackTab(f, wb.proxy, wb.win.title)
ELSE HALT(27)
END
END;
Views.Obscure(wb.win.frame);
(* obscure the root frame until it has a position. It will be unobscured with InstallRoot from Proxy.Restore when wb.proxy is grated a frame (which implies a position for the root frame) *)
(* END *)
END Open;
PROCEDURE (d: BackendDirectory) NewBackend (): StdWindows.WindowBackend;
VAR wb: Backend; res: StdWindows.WindowBackend; p: Proxy;
BEGIN
p := d.nextProxy;
IF (p = NIL) & (targetTrack # "") THEN
p := ProxyFor(targetTrack)
END;
IF p # NIL THEN
d.nextProxy := NIL; ASSERT(p.base # NIL, 25); ASSERT(p.filler # NIL, 26);
NEW(wb); res := wb; wb.proxy := p; p.wb := wb
ELSE
res := StdWindows.stdBackendDir.NewBackend()
END;
RETURN res
END NewBackend;
PROCEDURE (wb: BackendDirectory) GetBounds (OUT w, h: Pixels);
BEGIN
StdWindows.stdBackendDir.GetBounds(w, h)
END GetBounds;
PROCEDURE (wb: Backend) Port (): Ports.Port;
BEGIN RETURN wb(Backend).proxy.base.port
END Port;
(* Commands *)
PROCEDURE InstallViewHook*;
BEGIN
StdDialog.SetViewHook(viewHook);
END InstallViewHook;
PROCEDURE UninstallViewHook*;
BEGIN
StdDialog.SetViewHook(NIL);
END UninstallViewHook;
PROCEDURE BindCloseNotifier* (w: Windows.Window);
VAR notifier: SeqNotifier;
BEGIN
NEW(notifier);
notifier.win := w; w.seq.InstallNotifier(notifier);
END BindCloseNotifier;
PROCEDURE On*;
BEGIN
StdWindows.SetBackendDir(bckndDir); viewHook.tiled := TRUE;
InstallViewHook
END On;
PROCEDURE Off*;
BEGIN
StdWindows.SetBackendDir(StdWindows.stdBackendDir); viewHook.tiled := FALSE;
UninstallViewHook
END Off;
PROCEDURE OnOff*;
(** Toggle Tiler on and off; for use in menus *)
BEGIN
IF StdWindows.backendDir = bckndDir THEN Off ELSE On END
END OnOff;
PROCEDURE OnOffGuard* (VAR par: Dialog.Par);
BEGIN
par.checked := StdWindows.backendDir # bckndDir
END OnOffGuard;
PROCEDURE GetThisTrack* (w: StdWindows.Window; OUT track: Views.Title);
VAR msg: StdGrids.TrackPropMsg; f: Views.Frame;
BEGIN
f := Views.HostOfRoot(w.frame); msg.done := FALSE;
WHILE (f # NIL) & ~msg.done DO
msg.poll := TRUE; Views.HandlePropMsg(f.view, msg);
f := Views.HostOf(f)
END;
IF msg.done THEN track := msg.name ELSE track := "" END
END GetThisTrack;
PROCEDURE (hook: AttachedCheckHook) IsAttached- (w: StdWindows.Window): BOOLEAN;
BEGIN RETURN (w # NIL) & (w.backend IS Backend)
END IsAttached;
(* menu commands *)
PROCEDURE ToggleAttached*;
(** Attach (tile)/Detach (untile) target window *)
VAR w: StdWindows.Window; loc: Files.Locator; fname: Files.Name;
conv: Converters.Converter; flags: SET; title: Views.Title;
doc: Documents.Document; dirty: BOOLEAN; proxy: Proxy;
wasSub: BOOLEAN;
BEGIN
w := StdWindows.target;
IF w # NIL THEN
doc := w.doc; title := w.title; loc := w.loc; fname := w.name$;
conv := w.conv; flags := w.flags;
dirty := w.seq.Dirty();
wasSub := w.sub;
IF ~(w.backend IS Backend) THEN proxy := ProxyFor(title) END;
Windows.dir.Close(w);
DoOpen(doc, title, loc, fname, conv, flags, proxy, ~wasSub, w);
IF ~dirty THEN w.seq.SetDirty(FALSE) END
END
END ToggleAttached;
PROCEDURE AttachedGuard* (VAR par: Dialog.Par);
BEGIN
par.disabled := StdWindows.target = NIL;
par.checked := ~par.disabled & (StdWindows.target.backend IS Backend)
END AttachedGuard;
PROCEDURE ToggleSub*;
VAR w: StdWindows.Window;
BEGIN
w := StdWindows.dir.Focus(Controllers.frontPath);
IF w.link = w THEN
GetThisTrack(w, targetTrack);
(* ask router where to shift duplication window *)
windowsRouter(">>>");
(* halt windows router during new window open *)
backUp := windowsRouter;
windowsRouter := NIL;
StdCmds.NewWindow;
windowsRouter := backUp;
ELSE
Windows.dir.Select(w.link, Windows.eager)
END
END ToggleSub;
(* experimental workspace section *)
PROCEDURE SaveAs* (loc: Files.Locator; name: ARRAY OF CHAR);
VAR f: Views.Frame; w: Windows.Window; file: Files.File; _res: INTEGER;
BEGIN
IF StdWindows.target # NIL THEN
f := Views.UltimateRootOf(StdWindows.target.frame)
END;
IF f # NIL THEN
IF f = StdWindows.target.frame THEN
ELSE
w := Windows.dir.First();
WHILE w.frame # f DO w := Windows.dir.Next(w) END
END;
file := Files.dir.New(loc, Files.dontAsk);
Documents.ExportDocument(w.doc.OriginalView(), file);
file.Register(name$, 'odc', ~Files.ask, _res);
END
END SaveAs;
PROCEDURE SaveWorkspace*;
BEGIN
SaveAs(lastWorkspaceLoc, lastWorkspaceName);
END SaveWorkspace;
PROCEDURE OpenAs* (loc: Files.Locator; name: ARRAY OF CHAR);
VAR v: Views.View; w: Windows.Window; quit: BOOLEAN;
BEGIN
lastWorkspaceLoc := loc;
lastWorkspaceName := name$;
v := Views.OldView(lastWorkspaceLoc, lastWorkspaceName);
IF v # NIL THEN
quit := TRUE;
w := Windows.dir.First();
WHILE (w # NIL) & quit DO
StdWindows.GuardedClose(w);
w := Windows.dir.First();
END;
IF quit THEN
Off;
StdWindows.border := 0;
Views.OpenAux(v, Dialog.appName$);
BindCloseNotifier(Windows.dir.First());
On;
END;
END
END OpenAs;
PROCEDURE OpenWorkspace*;
BEGIN
OpenAs(lastWorkspaceLoc, lastWorkspaceName);
END OpenWorkspace;
PROCEDURE SaveGuard* (VAR par: Dialog.Par);
BEGIN
par.disabled := lastWorkspaceLoc = NIL
END SaveGuard;
PROCEDURE (n: SeqNotifier) Notify (VAR msg: Sequencers.Message);
VAR file: Files.File; _: INTEGER; cancelled, deferred: BOOLEAN;
BEGIN
WITH msg: Sequencers.CloseMsg DO
IF n.loc # NIL THEN
file := Files.dir.New(n.loc, Files.dontAsk);
Documents.ExportDocument(n.view, file);
file.Register(n.fname, 'odc', ~Files.ask, _)
END;
CloseNestedWindows(n.win, cancelled, deferred);
msg.sticky := cancelled OR deferred
ELSE
END
END Notify;
(*
PROCEDURE Autosave* (v: Views.View; IN location, fname: Files.Name);
VAR s: ANYPTR; n: SeqNotifier;
BEGIN
s := v.Domain().GetSequencer();
WITH s: Sequencers.Sequencer DO
NEW(n); n.loc := Files.dir.This(location); n.fname := fname$; n.view := v;
s.InstallNotifier(n)
ELSE HALT(20)
END
END Autosave;
example:
StdCmds.OpenDoc('Workspace.odc');
w := StdWindows.GetBySpec(Files.dir.This(''), 'Workspace.odc', Converters.list, {});
IF w # NIL THEN StdTiles.Autosave(w.doc.ThisView(), '', 'Workspace') END;
StdTiles.On;
*)
(* color themes *)
PROCEDURE UpdateUIColors*;
BEGIN
IF Dialog.colorTheme = dark THEN
IF StdMenus.param.InitDefaults # NIL THEN
StdMenus.param.InitDefaults(StdMenus.param)
END;
IF StdGrids.param.InitDefaults # NIL THEN
StdGrids.param.InitDefaults(StdGrids.param)
END;
ELSIF Dialog.colorTheme = light THEN
StdMenus.param.bgColorLine := Ports.RGBColor(212, 208, 200);
StdMenus.param.statusBg := Ports.RGBColor(212, 208, 200);
StdMenus.param.bgColor := Ports.RGBColor(212, 208, 200);
StdMenus.param.color := Ports.black;
StdMenus.param.colorLine := Ports.black;
StdMenus.param.focusBg := Ports.RGBColor(10, 36, 106);
StdMenus.param.focusColor := Ports.white;
StdMenus.param.focusColorLine := Ports.black;
StdMenus.param.focusBgLine := Ports.RGBColor(180, 180, 180);
StdMenus.param.statusColor := Ports.black;
IF StdMenus.param.Init # NIL THEN
StdMenus.param.Init(StdMenus.param)
END;
StdGrids.param.bgColor := Ports.RGBColor(128, 128, 128);
StdGrids.param.gutterColor := Ports.RGBColor(140, 140, 140);
IF StdGrids.param.Init # NIL THEN
StdGrids.param.Init(StdGrids.param)
END;
END;
IF (StdDocuments.param # NIL) & (StdDocuments.param.Init # NIL) THEN
StdDocuments.param.Init(StdDocuments.param)
END;
END UpdateUIColors;
PROCEDURE InitDefaults (p: ANYPTR);
BEGIN
WITH p: Param DO
p.closeDialogLocation := "Std/Rsrc";
p.closeDialogDocument := "ConfirmCloseOverlaid.odc";
p.InitDefaults := InitDefaults;
END
END InitDefaults;
PROCEDURE Init;
BEGIN
NEW(attCheckHook);
StdWindows.SetAttachedCheckHook(attCheckHook);
targetTrack := "";
NEW(viewHook); viewHook.tiled := TRUE;
NEW(bckndDir);
NEW(param);
InitDefaults(param);
lastWorkspaceLoc := Files.dir.This("");
lastWorkspaceName := "workspace.odc";
UpdateUIColors;
END Init;
BEGIN
Init
CLOSE
UninstallViewHook
END StdTiles. | Std/Mod/Tiles.odc |
MODULE StdViewSizer;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20160321, center #110, use mapped strings for labels in all forms
"
issues = "
- ...
"
**)
IMPORT Services, Ports, Dialog, Views, Containers, Properties;
CONST width = 1; height = 2;
VAR
size*: RECORD
typeName-: Dialog.String;
w*, h*: REAL;
proportional*, fixedW, fixedH: BOOLEAN;
unit, scaleW, scaleH, lastChanged: INTEGER;
unitText: ARRAY 12 OF CHAR;
view: Views.View;
container: Containers.Controller
END;
PROCEDURE ConnectDialog (v: Views.View; c: Containers.Controller);
VAR pref: Properties.ResizePref;
BEGIN
IF (v # NIL) & (v.context # NIL) THEN
IF Dialog.metricSystem THEN size.unit := Ports.mm * 10; size.unitText := "#Std:cm"
ELSE size.unit := Ports.inch; size.unitText := "#Std:inch"
END;
size.view := v; size.container := c;
Services.GetTypeName(v, size.typeName);
v.context.GetSize(size.scaleW, size.scaleH);
size.w := size.scaleW / size.unit; size.h := size.scaleH / size.unit;
pref.fixed := FALSE;
pref.horFitToPage := FALSE; pref.verFitToPage := FALSE;
pref.horFitToWin := FALSE; pref.verFitToWin := FALSE;
Views.HandlePropMsg(v, pref);
size.fixedW := pref.fixed;
size.fixedH := pref.fixed;
size.proportional := FALSE
ELSE
size.view := NIL; size.container := c; size.typeName := ""
END;
Dialog.Update(size)
END ConnectDialog;
PROCEDURE SetViewSize*;
BEGIN
IF size.view # NIL THEN
size.view.context.SetSize(SHORT(ENTIER(size.w * size.unit + 0.5)),
SHORT(ENTIER(size.h * size.unit + 0.5)));
IF size.container # NIL THEN size.container.SetSingleton(size.view) END;
ConnectDialog(size.view, size.container)
ELSE Dialog.Beep
END
END SetViewSize;
PROCEDURE InitDialog*;
VAR v: Views.View; c: Containers.Controller;
BEGIN
c := Containers.Focus();
IF c # NIL THEN v := c.Singleton() ELSE v := NIL END;
IF (v # size.view) OR (c # size.container) THEN ConnectDialog(v, c) END
END InitDialog;
PROCEDURE ResetDialog*;
VAR proportional: BOOLEAN; v: Views.View;
BEGIN
proportional := size.proportional; v := size.view;
size.view := NIL; InitDialog;
IF proportional & (v = size.view) THEN size.proportional := TRUE; Dialog.Update(size) END
END ResetDialog;
PROCEDURE WidthGuard* (VAR par: Dialog.Par);
BEGIN
InitDialog;
par.disabled := size.view = NIL;
par.readOnly := size.fixedW
END WidthGuard;
PROCEDURE HeightGuard* (VAR par: Dialog.Par);
BEGIN
InitDialog;
par.disabled := size.view = NIL;
par.readOnly := size.fixedH
END HeightGuard;
PROCEDURE ProportionGuard* (VAR par: Dialog.Par);
BEGIN
par.disabled := (size.view = NIL) OR size.fixedW OR size.fixedH OR (size.scaleW = 0) OR (size.scaleH = 0)
END ProportionGuard;
PROCEDURE UnitGuard* (VAR par: Dialog.Par);
BEGIN
IF size.view # NIL THEN par.label := size.unitText$ ELSE par.label := "" END
END UnitGuard;
PROCEDURE AdjustDialogToPref (fixedW, fixedH: BOOLEAN);
VAR w, h: INTEGER; w0, h0: REAL; pref: Properties.SizePref;
BEGIN
w := SHORT(ENTIER(size.w * size.unit + 0.5)); h := SHORT(ENTIER(size.h * size.unit + 0.5));
IF size.proportional & (w > 0) & (h > 0) & (size.scaleW > 0) & (size.scaleH > 0) THEN
Properties.ProportionalConstraint(size.scaleW, size.scaleH, fixedW, fixedH, w, h)
END;
pref.w := w; pref.h := h; pref.fixedW := fixedW; pref.fixedH := fixedH;
Views.HandlePropMsg(size.view, pref);
IF ~fixedW THEN w0 := pref.w / size.unit ELSE w0 := size.w END;
IF ~fixedH THEN h0 := pref.h / size.unit ELSE h0 := size.h END;
IF (w0 # size.w) OR (h0 # size.h) THEN size.w := w0; size.h := h0; Dialog.Update(size) END
END AdjustDialogToPref;
PROCEDURE WNotifier* (op, from, to: INTEGER);
BEGIN
IF size.w > 0 THEN AdjustDialogToPref(TRUE, FALSE); size.lastChanged := width
ELSIF size.w # 0 THEN Dialog.Beep
END
END WNotifier;
PROCEDURE HNotifier* (op, from, to: INTEGER);
BEGIN
IF size.h > 0 THEN AdjustDialogToPref(FALSE, TRUE); size.lastChanged := height
ELSIF size.h # 0 THEN Dialog.Beep
END
END HNotifier;
PROCEDURE ProportionNotifier* (op, from, to: INTEGER);
BEGIN
IF (op = Dialog.changed) & size.proportional THEN
IF size.lastChanged = width THEN AdjustDialogToPref(TRUE, FALSE)
ELSIF size.lastChanged = height THEN AdjustDialogToPref(FALSE, TRUE)
END
END
END ProportionNotifier;
END StdViewSizer.
| Std/Mod/ViewSizer.odc |
MODULE StdWindows;
(** project = "BlackBox 2.0"
organization = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Contributors, Anton Dmitriev"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 20150329, center #34, fixing the reuse of open documents
- 20150703, center #65, notRecorded-operation overwrites Redo-tail in StdSequencer
- 20150703, Anton Dmitriev, ...
"
issues = "
- AD: "technical debt" issues (specific to a particular source code part) are marked with color 0BC2AF4H
- In Browser mode, Home End buttons don't work as expected
- AD: A whitepaper on my proposed amendments is missing and needs to be produced!
"
**)
IMPORT
Kernel, Strings, Ports, Files, Services, Stores, Sequencers, Models, Views,
Controllers, Properties, Dialog, Converters, Containers, Documents, Windows,
StdDocuments;
CONST
notRecorded = 3;
untitledKey = "#System:untitled";
none* = -1; (* value for global variable L, indicates LTRB is not set *)
borderW = 5 * Ports.point;
scrollLock* = 8; (* modifier value for ScrollLock *)
defW = 640; defH = 480; (* default screen size *)
useSeparators = TRUE; noSeparators = FALSE; (* parameters to be used with AppendInt *)
(* these constants need to be in sync with Backends; actually, they are defined in Containers docu *)
(* ENTER = 0DX; ESC = 1BX;
TAB = 09X; LTAB = 0AX; RDEL = 07X; LDEL = 08X;
PL = 10X; PR = 11X; *) PU = 12X; PD = 13X;
DL = 14X; DR = 15X; (* DU = 16X; DD = 17X; *)
AL = 1CX; AR = 1DX; AU = 1EX; AD = 1FX;
WL = 5; WR = 6; (* wheel left/right; picks up numbering after Controllers.gotoPos *)
(**)
TYPE
Pixels = INTEGER; (* make declarations more self-documenting *)
UCs = INTEGER;
Ident = Kernel.Name;
Window* = POINTER TO EXTENSIBLE RECORD (Windows.Window)
next: Window;
hook*: Hook; (** window activity notification *)
backend-: WindowBackend;
title-, initialTitle: Views.Title;
path: Files.Name;
width, height: Pixels; (* window size *)
END;
(** A window is the cornerstone abstraction in the windowing system. It's main responsibility is to bring together the many abstractions that provide different aspects of the windowing system:
* the Document - as the standard container for an arbitrary view, responsible for storing, paging, printing;
* the Port - the bitmap canvas on which the content of the window is restored
* the Layout - the view responsible for window layout, see below
* two scrollbars
* the sequencer - non-visible abstraction responsible for message delivery and model undo/redo operations
* the backend - abstraction responsible for translating BB windows to underlying host mechanisms
* the rootFrame and docFrame - connection points between the views framework and windowing system
* the Locator, filename and Converter, connecting the window's root view to the permanent store (typically the filesystem)
Another vital responsibility is connecting windows that present the same root view - duplicate windows; this is a distinguishing feature of the BlackBox windowing system.
And don't forget the window title!
In this version, Window is marked as EXTENSIBLE; however, the experiment in Tyler project showed that it may not be necessary to extend Window to implement new functionality; in Tyler, addition of features was achieved thru extending WindowBackend and Layout. *)
(** Directory is responsible for creating and initializing new windows. *)
StdDirectory = POINTER TO RECORD (Windows.Directory) END;
WindowBackend* = POINTER TO ABSTRACT RECORD
win-: Window; (** the window that this backend is connected to; may be NIL *)
END;
(** This type is responsible for translating a window in "host" terms; typically, the host is the underlying host system and it's windowing facilities. However, in Tyler project - the tiling widow manager - a "host" can be another window that serves as the container for "tiled" windows. This type is extended and impelemnted in HostWindows. *)
BackendDirectory* = POINTER TO ABSTRACT RECORD END;
(** BackendDirectory is responsible for creating and initializing new backends. *)
Hook* = POINTER TO ABSTRACT RECORD END; (** window state notification hook *)
AttachedCheckHook* = POINTER TO ABSTRACT RECORD END;
OpElem = POINTER TO RECORD
next: OpElem;
st: Stores.Store;
op: Stores.Operation;
name: Stores.OpName;
invisible, transparent: BOOLEAN
END;
Script = POINTER TO RECORD (Stores.Operation)
up: Script;
list: OpElem;
level: INTEGER; (* nestLevel at creation time *)
name: Stores.OpName
END;
StdSequencer = POINTER TO RECORD (Sequencers.Sequencer)
home: Window;
trapEra: INTEGER; (* last observed TrapCount value *)
modLevel: INTEGER; (* dirty if modLevel > 0 *)
entryLevel: INTEGER; (* active = (entryLevel > 0) *)
nestLevel: INTEGER; (* nesting level of BeginScript/Modification *)
modStack: ARRAY 64 OF RECORD store: Stores.Store; type: INTEGER END;
lastSt: Stores.Store;
lastOp: Stores.Operation;
script: Script;
undo, redo: OpElem; (* undo/redo stacks *)
noUndo: BOOLEAN; (* script # NIL and BeginModification called *)
invisibleLevel, transparentLevel, notRecordedLevel: INTEGER;
END;
SequencerDirectory = POINTER TO RECORD (Sequencers.Directory) END;
Forwarder = POINTER TO RECORD (Controllers.Forwarder) END;
(* Provided by Windows => not needed here any more *)
Context = POINTER TO ABSTRACT RECORD (Models.Context)
win: Window;
END;
DocContext = POINTER TO RECORD (Context) END;
Reducer = POINTER TO RECORD (Kernel.Reducer) END;
MsgHook = POINTER TO RECORD (Views.MsgHook) END;
PrefocusMsg* = RECORD (Controllers.CursorMessage)
win*: Window
END;
(** Forwarded before a TrackMsg when a click occurs in an unfocussed window. Normally in such case the window is focussed (selected) first, and then the TrackMsg is forwarded. Receiver may set .hotFocus to indicate that it doesn't require containing window to be focussed before tracking the mouse. For use by views that would change focus to another window as a result of TrackMsg - otherwise, there'd be a cascade of unwanted window selections *)
UpdateMsg* = RECORD (Controllers.Message) END;
(** Forwarded to windows' root views before validation to let them update their state. Used for scrollbars *)
CheckAction = POINTER TO RECORD (Services.Action)
wait: WaitAction
END;
WaitAction = POINTER TO RECORD (Services.Action)
check: CheckAction
END;
LangNotifier = POINTER TO RECORD (Dialog.LangNotifier) END;
SafeOpen = RECORD (Services.SafeAction)
w: Window; doc: Documents.Document; flags: SET; title: Views.Title
END;
Param* = POINTER TO RECORD
bgColor*: Ports.Color;
wheelScrollByPage*: BOOLEAN;
debug*: BOOLEAN;
markTitles*: BOOLEAN;
frontStr*, targetStr*, frontTargetStr*, markStr*: ARRAY 8 OF CHAR;
InitDefaults-, Init-: PROCEDURE (par: ANYPTR)
END;
Ext* = POINTER TO ABSTRACT RECORD END;
(** A hook that provides services that are standard (because they are in this module), but may or may not be present in a particular situation. Right now, this is the support for multihead settings: Windows (and it's clients) have an interface to this feature, but the feature may or may not be provided. *)
StdExt = POINTER TO RECORD (Ext) END;
VAR
dir-, (*Windows.Directory;*)
stdDir-: StdDirectory;
backendDir-, stdBackendDir-: BackendDirectory;
backoff* : RECORD (** after an interaction with a menu, focus should be returned to backoff revisit *)
front*, target-: Window
END;
front-: Window; (** Front window: the one receiving keyboard input *)
target-: Window; (** Target window: the one that tool dialogs (may) operate on, if they so choose *)
mark-: Window; (** Marked window: clients may provide commands operating on the marked wnd *)
zList: Window; (* Z-ordered list of open windows, linked by .next, zList being topmost window *)
border*: UCs; (** The document border for the next window to be opened; a request *)
newNumber: INTEGER; (* number for next untitled document *) (* AD: from HostWindows *)
dump-, stdDump-: PROCEDURE (p: ANYPTR);
(** called to dump window or frame when ^Sh+LMB/MMB is clicked, see StdTrack *)
guardedCloseHook*: PROCEDURE (w: Windows.Window);
PortOrigin(*Hook*)*: PROCEDURE (p: Ports.Port; OUT xRoot, yRoot: Pixels): BOOLEAN;
(** HostWindows should provide this procedure. Returns global screen coordinates of a Port's origin: translates Port's (0,0) to global screen coords. *)
param*: Param;
ext*: Ext; (** holder of extended Windows services that may not be provided by the host implementation *)
attachedCheckHook-: AttachedCheckHook;
(* Backend Directory *)
PROCEDURE (bd: BackendDirectory) NewBackend* (): WindowBackend, NEW, ABSTRACT;
(** Produce a new backend. *)
PROCEDURE (bd: BackendDirectory) GetBounds* (OUT w, h: INTEGER), NEW, ABSTRACT;
(** a procedure returning screen dimensions; to be proivided by HostWindows *)
(** Returns the number of heads (monitors) currently connected to the system.
ATTN: it's a VAR par, extensions have no obligation to actually fill it!
In case no Ext is provided, ext may leave count unchanged *)
PROCEDURE (e: Ext) GetNumHeads* (VAR count: INTEGER), NEW, ABSTRACT;
(** Request to send wb.win to head. May be ignored *)
PROCEDURE (e: Ext) ToHead* (wb: WindowBackend; head: INTEGER), NEW, ABSTRACT;
(** Request to maximize wb.win. May be ignored *)
PROCEDURE (e: Ext) Maximize* (wb: WindowBackend), NEW, ABSTRACT;
PROCEDURE (e: StdExt) GetNumHeads (VAR count: INTEGER), EMPTY;
PROCEDURE (e: StdExt) ToHead (wb: WindowBackend; head: INTEGER), EMPTY;
PROCEDURE (e: StdExt) Maximize (wb: WindowBackend), EMPTY;
(* can be called with w = NIL! *)
PROCEDURE (hook: AttachedCheckHook) IsAttached- (w: Window): BOOLEAN, NEW, ABSTRACT;
(** Window **)
PROCEDURE First (): Window;
(** Returns the first (top) window in Z-order. NIL if no window is open *)
BEGIN RETURN zList
END First;
PROCEDURE Next (w: Window): Window;
(** Returns the window following w in Z-order. NIL if w is the last (bottom) window *)
BEGIN IF w # NIL THEN w := w.next END; RETURN w
END Next;
PROCEDURE IsAttached* (w: Window): BOOLEAN;
BEGIN
RETURN (w # NIL) & (attachedCheckHook # NIL) & attachedCheckHook.IsAttached(w)
END IsAttached;
PROCEDURE IsDetached* (w: Window): BOOLEAN;
BEGIN RETURN ~IsAttached(w)
END IsDetached;
(* Scrolling procedures *)
PROCEDURE ^ (w: Window) ForwardCtrlMsg* (VAR msg: Controllers.Message), EXTENSIBLE;
(* auxiliary portable prcedures (scrolling) *)
PROCEDURE GetSection (w: Window; focus, vertical: BOOLEAN;
VAR size, sect, pos: INTEGER; VAR valid: BOOLEAN);
VAR msg: Controllers.PollSectionMsg;
BEGIN (* portable *)
msg.focus := focus; msg.vertical := vertical;
msg.wholeSize := 1; msg.partSize := 0; msg.partPos := 0;
msg.valid := FALSE; msg.done := FALSE;
(*w.trapped := TRUE; *)w.ForwardCtrlMsg(msg); (*w.trapped := FALSE;*)
IF msg.done THEN
size := msg.wholeSize; sect := msg.partSize; pos := msg.partPos;
IF size < 0 THEN size := 0 END;
IF sect < 0 THEN sect := 0 ELSIF sect > size THEN sect := size END;
IF pos > size - sect THEN pos := size - sect END;
IF pos < 0 THEN pos := 0 END
ELSE size := 1; sect := 0; pos := 0
END;
valid := msg.valid
END GetSection;
PROCEDURE Scroll (w: Window; focus, vertical: BOOLEAN; op, pos: INTEGER);
(* scroll w by sending a Controllers.ScrollMsg. pos is ignored if op # Controllers.gotoPos. AD: based on Scroll and SetOrigin *)
VAR msg: Controllers.ScrollMsg; c: Containers.Controller; v: Views.View;
BEGIN (* portable *)
IF op # Controllers.gotoPos THEN (* AD: not sure why marks aren't faded for op = gotoPos *)
c := w.doc.ThisController(); v := c.ThisFocus();
IF (v # NIL) & (v IS Containers.View) THEN
Containers.FadeMarks(v(Containers.View).ThisController(), FALSE)
END
ELSE msg.pos := pos
END;
msg.focus := focus; msg.vertical := vertical; msg.op := op; msg.done := FALSE;
w.ForwardCtrlMsg(msg)
END Scroll;
(* Window *)
PROCEDURE (w: Window) GetSize* (OUT width, height: Pixels), (*NEW, *)EXTENSIBLE;
BEGIN
IF w.port = NIL THEN width := 0; height := 0 (* closed window *)
ELSE width := w.width; height := w.height
END
END GetSize;
PROCEDURE InstallRoot* (w: Window; f: Views.Frame; x, y, level: INTEGER; focus: BOOLEAN);
(** Installs a root frame for window w into frame f at position x,y and z-order level, marking it as focus frame if focus = TRUE. *)
BEGIN ASSERT(w # NIL, 20); ASSERT(w.frame # NIL, 21);
Views.InstallRoot(f, w.frame, x, y, level, focus);
w.port := w.rootFrame.rider.Base(); IF w.port = NIL THEN w.Init(w.frame.rider.Base())
ELSE ASSERT(w.port = w.frame.rider.Base(), 90)
END
END InstallRoot;
PROCEDURE UpdateIn* (win: Window; l, t, r, b: Pixels; rebuild: BOOLEAN);
(** Request delayed update of box l,t,r,b in win with frame rebuild flag rebuild. *)
VAR f: Views.Frame; w, h, u: UCs;
BEGIN ASSERT(win # NIL, 20); f := win.frame;
IF f # NIL THEN win.GetSize(w, h); u := f.unit;
l := l * u; t := t * u; r := r * u; b := b * u;
r := MIN(r, w * u); b := MIN(b, h * u);
Views.UpdateRoot(win.frame, l, t, r, b, rebuild); (* this does not respect frame scrolling *)
END
END UpdateIn;
PROCEDURE Update* (win: Window; rebuild: BOOLEAN);
(** Request delayed update of win with frame rebuild flag rebuild *)
VAR f: Views.RootFrame; w, h: UCs;
BEGIN
IF win # NIL THEN f := win.frame;
IF f # NIL THEN Views.AdaptRoot(f);
win.GetSize(w, h);
Views.UpdateRoot(f, 0, 0, w * f.unit, h * f.unit, rebuild) (* this doesn't respect frame scrolling *)
END
ELSE win := First(); WHILE win # NIL DO Update(win, rebuild); win := Next(win) END
END
END Update;
PROCEDURE (w: Window) RRestore* (l, t, r, b: INTEGER), NEW;
(** deprecated, use Windows.UpdateIn or Windows.Update with rebuild = Views.KeepFrames *)
BEGIN
UpdateIn(w, l, t, r, b, Views.keepFrames)
END RRestore;
PROCEDURE ^ ValidateRing* (w: Window);
PROCEDURE ScrollDir (w: Window; op, value: INTEGER; focus, vertical: BOOLEAN);
VAR size, sect, pos: INTEGER; valid: BOOLEAN;
BEGIN
GetSection(w, focus, vertical, size, sect, pos, valid);
IF valid THEN Scroll(w, focus, vertical, op, value);
ValidateRing(w);
(* why does it have to update all sequencer's windows? replace w/Validate? *)
END
END ScrollDir;
(** Force the restoration of w's update region. Use with care! Validation of a window's (as well as root frame's) update region may result in closing any or all subframes; thus, if Validate is called from a handler that was handed a frame f, after the call f may be closed and no operations on it permitted. A proper use case for Validate is forced restoration during mouse tracking. *)
PROCEDURE Validate* (w: Window);
VAR d: Documents.Document;
BEGIN
IF w # NIL THEN
IF ~Views.IsObscured(w.frame) THEN
d := w.doc;
WITH d: StdDocuments.Document DO
StdDocuments.UpdateScrollbars(w.frame)
ELSE
END;
Views.ValidateRoot(w.frame)
END
ELSE
w := First();
WHILE w # NIL DO
Validate(w);
w := Next(w)
END
END;
END Validate;
PROCEDURE (w: Window) UUpdate*, NEW;
BEGIN Validate(w)
END UUpdate;
PROCEDURE (w: Window) Init* (port: Ports.Port)(*, NEW*);
(** Initialize w with port. Pre: w.port = NIL 20, port # NIL 21 *)
BEGIN
w.Init^(port); w.title := ""; w.initialTitle := ""
END Init;
PROCEDURE (w: Window) InitBackend* (wb: WindowBackend), NEW, EXTENSIBLE;
(** Initialize w with backend wb (connect w and wb). EXTENSIBLE so that extensions could be notified of receiving a backend - just in case. Extensions have to call the base procedure in order for wb and w to be connected *)
BEGIN ASSERT(wb # NIL, 20); ASSERT((w.backend = NIL) OR (w.backend = wb), 21);
ASSERT(wb.win = NIL, 22);
w.backend := wb; wb.win := w
END InitBackend;
PROCEDURE IsDialog (flags: SET; doc: Documents.Document): BOOLEAN;
VAR isDialog: BOOLEAN; c: Containers.Controller; v: Views.View;
BEGIN
isDialog := Windows.isTool IN flags;
IF ~isDialog THEN
v := doc.ThisView();
WITH v: Containers.View DO c := v.ThisController();
isDialog := (c # NIL) & ({Containers.noCaret, Containers.noSelection} - c.opts = {})
ELSE
END
END;
RETURN isDialog
END IsDialog;
PROCEDURE (wb: WindowBackend) SetSize- (width, height: Pixels), NEW, ABSTRACT;
PROCEDURE (w: Window) SetSize* (width, height: Pixels);
(** Set the size of w to width, height in pixels. *)
VAR w0, h0: Pixels;
BEGIN
IF w.port # NIL THEN w.GetSize(w0, h0);
IF (width # w0) OR (height # h0) THEN
w.width := width; w.height := height;
IF w.backend # NIL THEN w.backend.SetSize(width, height) END;
IF w.frame # NIL THEN Views.AdaptRoot(w.frame) END;
Views.Update(w.doc, Views.keepFrames)
END
END
END SetSize;
PROCEDURE GetInitSize (w: Window; doc: Documents.Document; OUT wid, hei: Pixels; flags: SET);
VAR isDialog: BOOLEAN; u, dl, dt, dr, db, dw, dh, bw: UCs; W, H: Pixels;
BEGIN
ASSERT(doc.context = NIL, 20); (* to obtain a doc's desired size, it has to not be embedded *)
isDialog := IsDialog(flags, doc);
u := w.port.unit;
IF isDialog THEN
bw := 0;
ELSE
IF border < 0 THEN
bw := borderW
ELSE
bw := border
END;
END;
border := -1;
IF (dir.l # none) & (dir.r > dir.l) & (dir.b > dir.t) THEN
wid := dir.r - dir.l; hei := dir.b - dir.t;
dr := wid* u - bw; db := hei * u - bw
ELSE
doc.PollRect(dl, dt, dr, db);
dw := dr - dl; dh := db - dt;
IF backendDir # NIL THEN
backendDir.GetBounds(W, H)
ELSE
W := defW; H := defH
END;
IF ~(Windows.noHScroll IN w.flags) & ((dw DIV u) > (W - 40)) THEN
dw := (W - 80) * u
END;
IF ~(Windows.noVScroll IN w.flags) & ((dh DIV u) > (H - 40)) THEN
dh := (H - 160) * u
END;
dr := bw + dw; db := bw + dh;
wid := (dr + bw) DIV u;
hei := (db + bw) DIV u;
END;
dl := bw; dt := bw;
IF ~ (Windows.isTool IN flags) THEN
IF ~(Windows.noHScroll IN flags) THEN
INC(wid, StdDocuments.param.sbThickness)
END;
IF ~(Windows.noVScroll IN flags) THEN
INC(hei, StdDocuments.param.sbThickness)
END;
END;
IF isDialog THEN
dir.l := (W - wid) DIV 2;
dir.t := (H - hei) DIV 2;
END;
doc.SetRect(dl, dt, dr, db);
IF wid < 0 THEN wid := 0 END;
IF hei < 0 THEN hei := 0 END;
END GetInitSize;
PROCEDURE (w: Window) BroadcastModelMsg2* (VAR msg: Models.Message), NEW, EMPTY;
(** This should be implemented by a Window extender in case it wants to add to the standard broadcasting behavior - for example, if it adds it's own (root) frames where model messages have to be broadcast. *)
PROCEDURE (w: Window) BroadcastModelMsg* (VAR msg: Models.Message);
(** Broadcast msg into w. A Window extender's w.BroadcastModelMsg2 is called, too, to give it a chance to broadcast msg message into it's (possible) structures. *)
BEGIN
Views.BroadcastModelMsg(w.frame, msg);
w.BroadcastModelMsg2(msg);
END BroadcastModelMsg;
PROCEDURE (w: Window) BroadcastViewMsg2* (VAR msg: Views.Message), NEW, EMPTY;
(** This should be implemented by a Window extender in case it wants to add to the standard broadcasting behavior - for example, if it adds it's own (root) frames where view messages have to be broadcast. *)
PROCEDURE (w: Window) BroadcastViewMsg* (VAR msg: Views.Message);
(** Broadcast msg into w. A Window extender's w.BroadcastViewMsg2 is called, too, to give it a chance to broadcast msg message into it's (possible) structures *)
VAR name: ARRAY 256 OF CHAR;
BEGIN
Services.GetTypeName(msg, name);
Views.BroadcastViewMsg(w.frame, msg);
w.BroadcastViewMsg2(msg);
END BroadcastViewMsg;
PROCEDURE (w: Window) ForwardCtrlMsg* (VAR msg: Controllers.Message), EXTENSIBLE;
(** Forward msg into w. An extension may add to this or override *)
(* based on Windows.Window.ForwardCtrlMsg & HostWindows.Window.ForwardCtrlMsg *)
VAR flags: SET;
BEGIN
IF (w.frame # NIL) & ~Views.IsObscured(w.frame) THEN
flags := {};
IF w = front THEN INCL(flags, StdDocuments.front) END;
IF w = target THEN INCL(flags, StdDocuments.target) END;
Views.SetRoot(w.frame, w.frame.view, w = front, w.flags + flags);
Views.ForwardCtrlMsg(w.frame, msg);
END
END ForwardCtrlMsg;
PROCEDURE ^ Select (w: Window; lazy: BOOLEAN);
PROCEDURE StdTrack (w: Window; VAR track: Controllers.TrackMsg);
CONST
showWindow = {Controllers.extend, Controllers.modify, Controllers.pick};
showFrame = {Controllers.extend, Controllers.modify, Controllers.popup};
VAR x, y: UCs; f, g: Views.Frame; mod: SET; pan: StdDocuments.PanWindowPref;
prefocus: PrefocusMsg;
BEGIN mod := track.modifiers; x := track.x; y := track.y;
IF dump # NIL THEN
(* This was commented out in (Lin)HostWindows.HandleMouse;
AD: brought it back in and adapted *)
IF showWindow - mod = {} THEN
dump(w)
ELSIF showFrame - mod = {} THEN
f := w.frame;
REPEAT g := f; f := Views.FrameAt(g, x - g.gx, y - g.gy) UNTIL f = NIL;
dump(g)
END
END;
pan.atLocation := TRUE; pan.x := x; pan.y := y; pan.panWindow := FALSE;
Views.HandlePropMsg(w.doc, pan);
IF ~pan.panWindow THEN
prefocus.x := x; prefocus.y := y; prefocus.win := w;
w.ForwardCtrlMsg(prefocus);
IF prefocus.win # NIL THEN
Select(prefocus.win, Windows.lazy)
END;
backoff.front := NIL
ELSIF pan.panWindow & (w # front) & (backoff.front = NIL) THEN
backoff.front := front
END;
w.ForwardCtrlMsg(track)
END StdTrack;
PROCEDURE StdWheel (w: Window; VAR msg: Controllers.WheelMsg);
VAR scroll: Controllers.ScrollMsg; mod: SET; op: INTEGER;
BEGIN
mod := msg.modifiers; op := msg.op;
IF ~(Controllers.modify IN mod) THEN w.ForwardCtrlMsg(msg) END;
IF ~msg.done THEN
scroll.vertical := ~(Controllers.extend IN mod) OR (op = WL) OR (op = WR);
scroll.focus := Controllers.modify IN mod;
IF ~param.wheelScrollByPage & (Controllers.pick IN mod)
OR param.wheelScrollByPage & ~(Controllers.pick IN mod) THEN
CASE op OF Controllers.decLine, WL: scroll.op := Controllers.decPage
| Controllers.incLine, WR: scroll.op := Controllers.incPage
ELSE scroll.op := op
END
ELSE
IF op = WL THEN scroll.op := Controllers.decLine
ELSIF op = WR THEN scroll.op := Controllers.incLine
ELSE scroll.op := op
END
END;
scroll.done := FALSE;
w.ForwardCtrlMsg(scroll);
IF scroll.done THEN msg.done := TRUE
ELSE scroll.focus := ~scroll.focus; w.ForwardCtrlMsg(scroll);
msg.done := scroll.done
END
END
END StdWheel;
PROCEDURE StdPasteChar (w: Window; msg: Controllers.EditMsg);
VAR scroll, scrolled, horizontal: BOOLEAN; ch: CHAR; mod: SET;
c: Containers.Controller; pmsg: Controllers.PollFocusMsg;
BEGIN ASSERT(w # NIL, 20); ASSERT(msg.op = Controllers.pasteChar, 21);
ch := msg.char; mod := msg.modifiers;
scroll := FALSE;
pmsg.focus := NIL; w.ForwardCtrlMsg(pmsg);
IF (pmsg.focus # NIL) & (pmsg.focus.view IS Containers.View) THEN
c := pmsg.focus.view(Containers.View).ThisController();
IF (c # NIL) & (Containers.noCaret IN c.opts) THEN scroll := TRUE END
END;
IF (scrollLock IN mod) OR scroll THEN scrolled := TRUE; horizontal := Controllers.modify IN mod;
CASE ch OF
| PU: ScrollDir(w, Controllers.decPage, 0, TRUE, ~horizontal)
| PD: ScrollDir(w, Controllers.incPage, 0, TRUE, ~horizontal)
| DR: ScrollDir(w, Controllers.gotoPos, MAX(INTEGER), TRUE, horizontal)
| DL: ScrollDir(w, Controllers.gotoPos, 0, TRUE, horizontal)
| AL: ScrollDir(w, Controllers.decLine, 0, TRUE, FALSE)
| AU: ScrollDir(w, Controllers.decLine, 0, TRUE, TRUE)
| AR: ScrollDir(w, Controllers.incLine, 0, TRUE, FALSE)
| AD: ScrollDir(w, Controllers.incLine, 0, TRUE, TRUE)
ELSE scrolled := FALSE
END;
IF scrolled THEN ch := 0X END
END;
IF ch = 0X THEN Dialog.Beep ELSE w.ForwardCtrlMsg(msg) END
END StdPasteChar;
PROCEDURE ForwardCtrlMsg* (w: Window; VAR msg: Controllers.Message);
(** Forward a controller message into the window, providing standard behaviour: wheel scrolling, frame and window dumping, and scroll position respect. If these standard behaviours are to be avoided, call Windows.Window.ForwardCtrlMsg instead *)
BEGIN
Controllers.SetCurrentPath(Controllers.targetPath); (* AD: copypasted from HostWindows; not sure what it's for *)
WITH
| msg: Controllers.WheelMsg DO StdWheel(w, msg)
| msg: Controllers.TrackMsg DO StdTrack(w, msg)
| msg: Controllers.EditMsg DO
IF msg.op = Controllers.pasteChar THEN StdPasteChar(w, msg) ELSE w.ForwardCtrlMsg(msg)
END
ELSE w.ForwardCtrlMsg(msg)
END;
Controllers.ResetCurrentPath();
Properties.IncEra
END ForwardCtrlMsg;
PROCEDURE Wheel* (w: Window; op, x, y: Pixels; mod: SET);
(** Handle a mouse wheel event in the window.
Intended for use from platform modules by WindowBackend extensions *)
VAR msg: Controllers.WheelMsg; u: UCs;
BEGIN
u := w.port.unit; msg.modifiers := mod;
msg.x := x * u; msg.y := y * u; msg.done := FALSE; msg.op := op; msg.nofLines := 1;
ForwardCtrlMsg(w, msg)
END Wheel;
PROCEDURE UpdateCursor* (w: Window; x, y: Pixels; modifiers: SET);
VAR pw, ph: INTEGER; msg: Controllers.PollCursorMsg; cur: INTEGER;
BEGIN
w.GetSize(pw, ph);
IF (x >= 0) & (x < pw) & (y >= 0) & (y < ph) THEN
msg.x := x * w.frame.unit - w.frame.gx;
msg.y := y * w.frame.unit - w.frame.gy;
msg.cursor := Ports.arrowCursor;
msg.modifiers := modifiers;
(* does this ↓ need to be bracketed by Controllers.SetCurrentPath/ResetCurrentPath? *)
w.ForwardCtrlMsg(msg); cur := msg.cursor
ELSE cur := Ports.arrowCursor
END;
IF cur >= 0 THEN w.frame.SetCursor(cur) END
END UpdateCursor;
PROCEDURE Track* (w: Window; x, y: Pixels; modifiers: SET);
(** Handle a mouse down event in window. Intended for use in HostWidows by WindowBackend extensions *)
VAR u: UCs; track: Controllers.TrackMsg;
BEGIN
u := w.port.unit; track.modifiers := modifiers; track.x := x * u; track.y := y * u;
ForwardCtrlMsg(w, track)
END Track;
PROCEDURE (w: Window) KeyDown* (ch: CHAR; modifiers: SET);
VAR msg: Controllers.EditMsg;
BEGIN ASSERT(w # NIL, 20);
msg.op := Controllers.pasteChar; msg.char := ch; msg.modifiers:= modifiers;
ForwardCtrlMsg(w, msg)
END KeyDown;
PROCEDURE (w: Window) MouseDown* (x, y, time: INTEGER; modifiers: SET), EMPTY;
PROCEDURE (wb: WindowBackend) GetOrigin* (OUT xRoot, yRoot: Pixels
): BOOLEAN, NEW, EXTENSIBLE;
(** Translate wb's (0,0) into global screen coordinates, if possible. Result is TRUE if translation was possible/successful, FALSE otherwise. Post: res = FALSE => xRoot, yRoot undefined *)
BEGIN RETURN FALSE
END GetOrigin;
PROCEDURE (w: Window) IsTool* (): BOOLEAN, NEW, EXTENSIBLE;
(** Returns TRUE if w was opened as a Tool dialog, FALSE otherwise. *)
BEGIN RETURN Windows.isTool IN w.flags
END IsTool;
PROCEDURE Reset (s: StdSequencer);
BEGIN
s.trapEra := Kernel.trapCount;
IF (s.entryLevel # 0) OR (s.nestLevel # 0) THEN
s.modLevel := 0;
s.entryLevel := 0;
s.nestLevel := 0;
s.lastSt := NIL;
s.lastOp := NIL;
s.script := NIL;
s.noUndo := FALSE;
s.undo := NIL; s.redo := NIL;
s.invisibleLevel := 0;
s.transparentLevel := 0;
s.notRecordedLevel := 0
END
END Reset;
PROCEDURE NewSequencer*(): Sequencers.Sequencer;
(** Creates and returns a new sequencer. *)
VAR s: StdSequencer;
BEGIN
NEW(s); Reset(s); RETURN s
END NewSequencer;
PROCEDURE AppendInt (VAR s: ARRAY OF CHAR; n: INTEGER; useSeparators: BOOLEAN);
VAR len: INTEGER; i, j: INTEGER; d: ARRAY 32 OF CHAR;
BEGIN
ASSERT(n >= 0, 20);
i := 0; REPEAT
d[i] := CHR(30H + n MOD 10); INC(i); n := n DIV 10;
IF useSeparators & (i MOD 4 = 3) & (n # 0) THEN d[i] := "'"; INC(i) END
UNTIL n = 0;
len := LEN(s) - 1;
j := 0; WHILE s[j] # 0X DO INC(j) END;
IF j + i < len THEN
REPEAT DEC(i); s[j] := d[i]; INC(j) UNTIL i = 0;
s[j] := 0X
END
END AppendInt;
PROCEDURE Append (VAR s: ARRAY OF CHAR; t: ARRAY OF CHAR);
VAR len: INTEGER; i, j: INTEGER; ch: CHAR;
BEGIN
len := LEN(s);
i := 0; WHILE s[i] # 0X DO INC(i) END;
j := 0; REPEAT ch := t[j]; s[i] := ch; INC(j); INC(i) UNTIL (ch = 0X) OR (i = len);
s[len - 1] := 0X
END Append;
PROCEDURE StripTitle (VAR s: Views.Title);
VAR i: INTEGER;
BEGIN
IF s[0] = "<" THEN
i := 1; WHILE (s[i] # ">") & (s[i] # 0X) DO s[i - 1] := s[i]; INC(i) END;
DEC(i); s[i] := 0X
END
END StripTitle;
PROCEDURE GenTitle (w: Window; name: ARRAY OF CHAR; VAR title: ARRAY OF CHAR);
(* generate window title for a document *)
VAR newName: ARRAY 64 OF CHAR; i: INTEGER;
BEGIN
IF w.sub THEN title[0] := "<"; title[1] := 0X ELSE title[0] := 0X END;
IF name # "" THEN
i := 0;
WHILE name[i] # 0X DO INC(i) END;
IF (i > 4) & (name[i-4] = ".") & (CAP(name[i-3]) = "O") & (CAP(name[i-2]) = "D") & (CAP(name[i-1]) = "C")
THEN
name[i-4] := 0X
END;
Append(title, name)
ELSE
Dialog.MapString(untitledKey, newName);
Append(title, newName); AppendInt(title, newNumber, noSeparators);
INC(newNumber)
END;
IF w.sub THEN Append(title, ">") END
END GenTitle;
PROCEDURE GenPathTitle (w: Window; OUT title: ARRAY OF CHAR);
CONST mlen = LEN(Views.Title) - 1;
VAR loc: Files.Locator; path: Files.Name;
ch: CHAR; s1, s2: Views.Title; i, j: INTEGER;
BEGIN
loc := w.loc;
title := "";
Dialog.GetLocPath(loc, path);
w.path := path$;
i := 0; ch := path[0]; j := 0; s2 := "";
WHILE (ch # 0X) & (j < mlen) DO
IF (ch = "/") OR (ch = "\") THEN s1[j] := 0X; s2 := s1$; j := 0
ELSE s1[j] := ch; INC(j)
END;
INC(i); ch := path[i]
END;
s1[j] := 0X;
i := 0;
WHILE (i < 4) & (i < j) DO s1[i] := CAP(s1[i]); INC(i) END;
s1[i] := 0X;
IF s1 = "MOD" THEN
IF LEN(title) <= LEN(s2$) + 2 THEN s2[LEN(title) - 3] := 0X END;
title := "(" + s2$ + ")"
ELSIF s1 = "DOCU" THEN
IF LEN(title) <= LEN(s2$) + 2 THEN s2[LEN(title) - 3] := 0X END;
title := "{" + s2$ + "}"
ELSIF s1 = "RSRC" THEN
IF LEN(title) <= LEN(s2$) + 2 THEN s2[LEN(title) - 3] := 0X END;
title := "[" + s2$ + "]"
END;
Append(title, w.name)
END GenPathTitle;
PROCEDURE (wb: WindowBackend) SetTitle* (IN title: Views.Title), NEW, ABSTRACT;
PROCEDURE (w: Window) SetTitle* (title: Views.Title);
VAR t0: Views.Title; h: Window;
BEGIN
w.initialTitle := title$; Dialog.MapString(title, t0);
h := w;
REPEAT
GenTitle(w, t0, w.title);
w.backend.SetTitle(w.title);
w := w.link(Window)
UNTIL w = h
END SetTitle;
PROCEDURE (w: Window) RefreshTitle* (), EXTENSIBLE;
VAR title: Views.Title;
BEGIN
Dialog.MapString(w.initialTitle, title);
w.SetTitle(title)
END RefreshTitle;
PROCEDURE (w: Window) GetTitle* (OUT title: Views.Title);
BEGIN
title := w.initialTitle$;
IF title = "" THEN
title := w.title$;
StripTitle(title)
END
END GetTitle;
PROCEDURE (w: Window) SetSpec* (loc: Files.Locator; name: Files.Name; conv: Converters.Converter);
VAR title: Views.Title;
BEGIN
IF name # "" THEN
Files.dir.GetFileName(name, Files.docType, name)
END;
w.SetSpec^ (loc, name, conv);
IF (loc # NIL) THEN GenPathTitle(w, title); w.SetTitle(title) END
END SetSpec;
(* Procedures relating to selecting (activating) a window *)
PROCEDURE MarkTitle (w: Window);
VAR mark2, mark1: ARRAY 16 OF CHAR;
BEGIN ASSERT(w # NIL, 20);
IF w.backend # NIL THEN
IF (w = front) & (w = target) THEN
mark2 := param.frontTargetStr$
ELSIF w = front THEN
mark2 := param.frontStr$
ELSIF w = target THEN
mark2 := param.targetStr$
ELSE mark2 := ""
END;
IF w = mark THEN mark1 := param.markStr$ ELSE mark1 := "" END;
w.backend.SetTitle(mark1$ + w.title + mark2$)
END
END MarkTitle;
PROCEDURE SetFrontWindow (w: Window);
VAR u, v: Window;
BEGIN ASSERT(w # NIL, 20);
u := front; v := target;
IF w.IsTool() & (front # NIL) & ~front.IsTool() THEN target := front
ELSE target := w END;
front := w;
IF param.markTitles THEN
MarkTitle(front);
IF front # target THEN MarkTitle(target) END;
IF (u # NIL) & (u # front) & (u # target) THEN MarkTitle(u) END;
IF (v # NIL) & (v # front) & (v # target) THEN MarkTitle(v) END;
END;
IF (u # NIL) & (u # front) & (u # target) THEN
Views.SetRoot(u.frame, u.frame.view, FALSE, u.flags);
END;
IF (v # NIL) & (v # front) & (v # target) THEN
Views.SetRoot(v.frame, v.frame.view, FALSE, v.flags);
END;
IF front = target THEN
Views.SetRoot(front.frame, front.frame.view, TRUE,
front.flags + { StdDocuments.front, StdDocuments.target }
);
ELSE
Views.SetRoot(front.frame, front.frame.view, TRUE,
front.flags + { StdDocuments.front }
);
Views.SetRoot(target.frame, target.frame.view, TRUE,
target.flags + { StdDocuments.target }
);
END
END SetFrontWindow;
PROCEDURE Mark (w: Window; show, focus: BOOLEAN);
VAR mark: Controllers.MarkMsg;
BEGIN
mark.show := show; mark.focus := focus; w.ForwardCtrlMsg(mark); Properties.IncEra
END Mark;
PROCEDURE (h: Hook) NotifySelect*, NEW, EMPTY;
(** Called after the window that h is attached to has been selected (activated). *)
PROCEDURE (wb: WindowBackend) Select*, NEW, ABSTRACT;
(** Make wb.win activated (selected) host window (bring it up). If the host procedure(s) imply a callback, then such callback should not eventually call Windows.Select, otherwise unterminated recusion will take place *)
PROCEDURE Select (w: Window; lazy: BOOLEAN);
(** Select (activate, bring to front) w. *)
CONST guardCheck = 4; (* adapted from HostWindows.ChildActivateHandler *)
VAR u: Window;
BEGIN
ASSERT(w # NIL, 20);
ASSERT(zList # NIL, 21 (* w is selected => w is in zList => zList # NIL *));
(* This is where the select candidate (the alternative window) should be suggested - cf. the F9 problem *)
IF w # front THEN
refrontAction.win := w;
Services.DoLater(refrontAction, Services.immediately)
IF front # NIL THEN Mark(front, FALSE, TRUEFALSE) END;
SetFrontWindow(w);
IF zList # w THEN
u := zList; WHILE (u.next # NIL) & (u.next # w) DO u := u.next END;
ASSERT(u.next # NIL, 21 (* w is not in Z-list - it hasn't been Open()ed properly *));
u.next := u.next.next; w.next := zList; zList := w
END; ASSERT(zList = w, 60);
IF w.backend # NIL THEN w.backend.Select END;
(* k8: we need proper frame structure to make things like TextCmds.FindFirst work. so let's built it!
note that only newly created windows has no root host. *)
(* HACK: if this is first ever window, don't do it; otherwise main window flashes *)
IF (zList.next # NIL) & (zList.next # zList) THEN
IF (w.frame # NIL) & IsDetached(w) & (Views.HostOfRoot(w.frame) = NIL) & ~Views.HasAnyFrames(w.frame) THEN
Views.BuildFrameTree(w.frame, FALSE)
END
END;
Mark(w, TRUE, TRUEFALSE);
IF w = front THEN
IF w.hook # NIL THEN w.hook.NotifySelect() END;
Dialog.Notify(0, 0, {guardCheck}) (* adapted from HostWindows.ChildActivateHandler *)
END
ELSE IF w.backend # NIL THEN w.backend.Select END
END;
backoff.front := NIL;
IF lazy THEN
Views.Update(w.doc, Views.keepFrames)
ELSE (* experimental, need to be tested *)
Validate(w) (* this ensures w has actualized frame structure right after Select *)
END
END Select;
(* Procedures relating to closing a window *)
PROCEDURE (wb: WindowBackend) Close-, NEW, ABSTRACT;
(** Close/Remove host window.
Pre: .port # NIL, .link = .next = .rootFrame = .frame = .loc = .layout = .hook = NIL *)
PROCEDURE Close (w: Window);
(** Close window unconditionally and without dialogueing with the user *)
VAR t, u, v: Window; s: Sequencers.Sequencer;
BEGIN
ASSERT(w # NIL, 20);
u := zList; WHILE (u # NIL) & (u # w) DO u := u.next END;
IF u # NIL THEN
v := w;
IF w.sub THEN WHILE v.link # w DO v := v.link(Window) END END;
REPEAT
u := v.link(Window); (* u is to be removed; u # NIL 'cause .link is a ring, so v.link = v if 1 wnd in ring *)
IF front = u THEN front := NIL END;
IF target = u THEN target := NIL END; (* new values for front and target are not needed at this point: after a window is closed, the underlying host OS or library will activate another window, and that will cause a call to Select, which will assign new values for front and target *)
IF mark = u THEN mark := NIL END;
(* remove u from window list *)
IF u = zList THEN zList := zList.next
ELSE
t := zList; WHILE (t.next # NIL) & (t.next # u) DO t := t.next END;
ASSERT(t.next # NIL, 100 (* t is in window ring but not in window list *) );
t.next := t.next.next
END;
u.next := NIL;
s := u.seq; WITH s: StdSequencer DO IF s.home = u THEN s.home := NIL END ELSE END;
(* revisit when the duplicity Windows.StdSequencer <=> StdWindows.StdSequencer is resolved *)
u.backend.SetSize(0, 0); (* may or may not be necessary *)
u.Close;
u.hook := NIL;
u.backend.Close; u.next := NIL;
u.backend.win := NIL; u.backend := NIL
UNTIL w.sub OR (v.link = NIL)
END;
IF (front = NIL) & (zList # NIL) THEN Select(zList, Windows.lazy)
END
END Close;
PROCEDURE GuardedClose* (w: Windows.Window);
BEGIN
ASSERT(guardedCloseHook # NIL, 39);
guardedCloseHook(w)
END GuardedClose;
(* Procedures relating to opening a window *)
PROCEDURE (w: Window) NewContext* (): Models.Context, NEW, EXTENSIBLE;
(** Allows extenders to provide a custom context for the window's document. *)
VAR c: DocContext;
BEGIN NEW(c); c.win := w; RETURN c
END NewContext;
PROCEDURE (wb: WindowBackend) Open- (isDialog: BOOLEAN), NEW, EMPTY;
(** Called by Windows to have wb opened as a host window *)
PROCEDURE (VAR so: SafeOpen) Do;
VAR w: Window; doc: Documents.Document;
s: Sequencers.Sequencer; f: Views.Frame; any: ANYPTR; wid, hei: Pixels; dw, dh: UCs;
BEGIN
w := so.w;
doc := so.doc;
IF (doc IS Documents.Document) & ~ (doc IS StdDocuments.Document) THEN
doc := Documents.DuplicateAs(doc, StdDocuments.dir);
END;
GetInitSize(w, doc, wid, hei, so.flags);
IF w.seq = NIL THEN
any := doc.Domain().GetSequencer();
IF any # NIL THEN
ASSERT(any IS Sequencers.Sequencer, 26);
s := any(Sequencers.Sequencer)
ELSE
s := NewSequencer(); (* AD: in the future, I think Windows will have to ask Window for a new Sequencer - like it does ask .doc for a new frame *)
doc.Domain().SetSequencer(s)
END
END;
WITH s: StdSequencer DO
IF s.home = NIL THEN s.home := w END
ELSE
END;
doc.InitContext(w.NewContext());
doc.GetNewFrame(f);
WITH f: Views.RootFrame DO
f.ConnectTo(w.port);
Views.SetRoot(f, doc, FALSE, so.flags);
Windows.SetupWindow(w, f, doc, s, so.flags)
END;
w.SetSize(wid, hei); (* SetSize calls Views.AdaptRoot *)
(* check: *) doc.context.GetSize(dw, dh); ASSERT((dw # 0) & (dh # 0), 61);
w.backend.Open(IsDialog(so.flags, doc));
(* AD: copypasted this section from (Lin)HostWindows.Directory.Open; without this, some documents can't forward messages down to their view; I haven't figured out exact conditions. Also, it's unclear why this had to be done explicitly, and why it's not done somewhere in Documents. *)
w.SetTitle(so.title)
END Do;
PROCEDURE Open (w: Window; doc: Documents.Document; flags: SET; IN title: Views.Title);
(** Open doc in w with flags and title. *)
(* Protected: if any traps occur in extenders' procedures involved in opening a window, the module Windows and it's data structures remain intact. *)
VAR v: Views.View; so: SafeOpen;
BEGIN
ASSERT(w # NIL, 20); ASSERT(doc # NIL, 21); ASSERT(doc.context = NIL, 22);
v := doc.ThisView(); ASSERT(v # NIL, 23);
ASSERT(w.doc = NIL, 24); ASSERT(w.port # NIL, 25); ASSERT(doc.Domain() # NIL, 27);
ASSERT(v.context # NIL, 28);
so.w := w; so.doc := doc; so.flags := flags; so.title := title;
Services.Try(so);
dir.l := none;
IF ~so.trapped THEN
w.next := zList; zList := w; Select(w, Windows.lazy);
(* here w is "registered" and becomes known to the rest of module Windows. If a trap occurs before this point, the window is not registered, and a poorly initialized window does not cause further traps. *)
(* Validate(w) (* this makes sure w's frame tree is built *) *)
ELSE w.next := NIL; w.hook := NIL; w.backend := NIL
END
END Open;
PROCEDURE RestoreSequencer (seq: Sequencers.Sequencer);
VAR w: Window;
BEGIN
w := First();
WHILE w # NIL DO
ASSERT(w.frame # NIL, 100);
IF (seq = NIL) OR (w.seq = seq) THEN
Validate(w) (* causes redrawing of BlackBox region *)
END;
w := Next(w)
END
END RestoreSequencer;
PROCEDURE ValidateRing* (w: Window);
(** Validates all windows displaying w's domain, or all windows if w = NIL *)
BEGIN
IF w = NIL THEN RestoreSequencer(NIL)
ELSE ASSERT(w.seq # NIL, 21); RestoreSequencer(w.seq)
END
END ValidateRing;
PROCEDURE (wb: WindowBackend) IsInside* (xRoot, yRoot: Pixels; OUT inClient: BOOLEAN
): BOOLEAN, NEW, EXTENSIBLE;
(** Tells if screen pixel coordinates xRoot, yRoot are inside wb; tell if they are inside wb's client area (as opposed to window decorations and borders)*)
VAR x, y: Pixels;
BEGIN
IF wb.GetOrigin(x, y) THEN x := xRoot - x; y := yRoot - y;
inClient := (0 <= x) & (x <= wb.win.width) & (0 <= y) & (y <= wb.win.height)
ELSE inClient := FALSE
END;
RETURN inClient
END IsInside;
(* Directory *)
PROCEDURE (d: StdDirectory) First* (): Window;
BEGIN RETURN First() END First;
PROCEDURE (d: StdDirectory) Next* (w: Windows.Window): Window;
BEGIN RETURN Next(w(Window)) END Next;
PROCEDURE (wb: WindowBackend) Port* (): Ports.Port, NEW, ABSTRACT;
(** Returns the port that wb is displayed on. *)
PROCEDURE (d: StdDirectory) New* (): Window;
(** Produce a new window. Post: .backend # NIL, .port # NIL *)
VAR w: Window; wb: WindowBackend; p: Ports.Port;
BEGIN
ASSERT(backendDir # NIL, 20);
NEW(w); wb := backendDir.NewBackend();
ASSERT(wb # NIL, 60); w.InitBackend(wb);
p := wb.Port();
IF p = NIL THEN w := NIL ELSE w.Init(p) END;
ASSERT(w # NIL, 70);
RETURN w
END New;
PROCEDURE (d: StdDirectory) Open* (w: Windows.Window; doc: Documents.Document; flags: SET; name: Views.Title; loc: Files.Locator; fname: Files.Name; conv: Converters.Converter );
BEGIN
ASSERT(w # NIL, 20); ASSERT(doc # NIL, 21); ASSERT(doc.context = NIL, 22);
IF (d.l >= 0) & (d.t >= 0) & ~((d.l = 0) & (d.t = 0) & (d.r = 0) & (d.b = 0)) THEN
dir.l := d.l; dir.t := d.t; dir.r := d.r; dir.b := d.b
END;
Open(w(Window), doc, flags, name);
w(Window).SetSpec(loc, fname, conv);
d.l := none
END Open;
PROCEDURE (d: StdDirectory) OpenSubWindow* (w: Windows.Window; doc: Documents.Document; flags: SET; title: Views.Title );
(** Open w as a subwindow (a duplicate window) displaying doc with flags set to flgs and title set to title *)
VAR u: Window;
BEGIN
ASSERT(w # NIL, 20); ASSERT(doc # NIL, 21);
u := d.First();
WHILE (u # NIL) & (u.seq # doc.Domain().GetSequencer()) DO u := d.Next(u) END;
IF u # NIL THEN
WHILE u.sub DO u := u.link(Window) END;
u.GetTitle(title);
Open(w(Window), doc, flags, title);
IF w.doc # NIL THEN w.SetSpec(u.loc, u.name, u.conv) END
ELSE
Open(w(Window), doc, flags, title)
END
END OpenSubWindow;
PROCEDURE (d: StdDirectory) Focus* (targetPath: BOOLEAN): Window;
(** Returns the focus window on one of focus paths: Controllers.targetPath or Controllers.frontPath. Preserved for compatibility reasons, now is duplicated by global variables front and target. May be deprecated. *)
VAR res: Window;
BEGIN
IF targetPath = Controllers.targetPath THEN res := target ELSE res := front END;
RETURN res
END Focus;
PROCEDURE (d: StdDirectory) GetThisWindow* (p: Ports.Port; px, py: Pixels; OUT x, y: Pixels; OUT w: Windows.Window );
(** Get topmost w such that (px,py) on p fall inside w, and translate (px,py) to (x,y) in w's coordinates *)
VAR xRoot, yRoot: Pixels; found, dummy: BOOLEAN; ww: Window;
BEGIN
IF (PortOrigin # NIL) & PortOrigin(p, xRoot, yRoot) THEN INC(px, xRoot); INC(py, yRoot);
ww := First(); found := FALSE;
WHILE ~found & (ww # NIL) DO
found := ww.backend.GetOrigin(xRoot,yRoot) & ww.backend.IsInside(px,py,dummy);
IF ~found THEN ww := Next(ww) END
END;
IF found THEN x := px - xRoot; y := py - yRoot END
END;
w := ww
END GetThisWindow;
PROCEDURE (d: StdDirectory) Select* (w: Windows.Window; lazy: BOOLEAN);
BEGIN Select(w(Window), lazy)
END Select;
PROCEDURE (d: StdDirectory) Close* (w: Windows.Window);
BEGIN Close(w(Window));
END Close;
PROCEDURE (d: StdDirectory) UUpdate* (w: Window), NEW;
(** deprecated, use Windows.UpdateRing instead *)
BEGIN ValidateRing(w) END UUpdate;
PROCEDURE (d: StdDirectory) GetBounds* (OUT w, h: INTEGER);
BEGIN
backendDir.GetBounds(w, h)
END GetBounds;
(* Contexts *)
PROCEDURE (c: Context) Normalize (): BOOLEAN, EXTENSIBLE;
BEGIN RETURN TRUE
END Normalize;
PROCEDURE (c: Context) ThisModel (): Models.Model, EXTENSIBLE;
BEGIN RETURN NIL
END ThisModel;
PROCEDURE (c: DocContext) GetSize (OUT w, h: UCs);
VAR p: Ports.Port;
BEGIN
(* c.win.layout = NIL => c.win has been closed; w=h=0 signals to Views that doc's frame may be Closed as well *)
p := c.win.port;
IF p # NIL THEN
c.win.GetSize(w, h); w := w * p.unit; h := h * p.unit
ELSE
w := 0; h := 0
END
END GetSize;
(* sequencing utilities *)
PROCEDURE Prepend (s: Script; st: Stores.Store; IN name: Stores.OpName; op: Stores.Operation);
VAR e: OpElem;
BEGIN
ASSERT(op # NIL, 20);
NEW(e); e.st := st; e.op := op; e.name := name;
e.next := s.list; s.list := e
END Prepend;
PROCEDURE Push (VAR list, e: OpElem);
BEGIN
e.next := list; list := e
END Push;
PROCEDURE Pop (VAR list, e: OpElem);
BEGIN
e := list; list := list.next
END Pop;
PROCEDURE Reduce (VAR list: OpElem; max: INTEGER);
VAR e: OpElem;
BEGIN
e := list; WHILE (max > 1) & (e # NIL) DO DEC(max); e := e.next END;
IF e # NIL THEN e.next := NIL END
END Reduce;
PROCEDURE (r: Reducer) Reduce (full: BOOLEAN);
VAR e: OpElem; n: INTEGER; w: Window;
BEGIN
IF dir # NIL THEN
w := First();
WHILE w # NIL DO
IF w.seq IS StdSequencer THEN
IF full THEN
n := 1
ELSE
n := 0; e := w.seq(StdSequencer).undo;
WHILE e # NIL DO INC(n); e := e.next END;
IF n > 20 THEN n := n DIV 2 ELSE n := 10 END
END;
Reduce(w.seq(StdSequencer).undo, n)
END;
w := Next(w)
END
END;
Kernel.InstallReducer(r)
END Reduce;
PROCEDURE Neutralize (st: Stores.Store);
VAR neutralize: Models.NeutralizeMsg;
BEGIN
IF st # NIL THEN (* st = NIL for scripts *)
WITH st: Models.Model DO
Models.Broadcast(st, neutralize)
| st: Views.View DO
st.Neutralize
ELSE
END
END
END Neutralize;
PROCEDURE Do (s: StdSequencer; st: Stores.Store; op: Stores.Operation);
BEGIN
INC(s.entryLevel); s.lastSt := NIL; s.lastOp := NIL;
Neutralize(st); op.Do;
DEC(s.entryLevel)
END Do;
PROCEDURE AffectsDoc (s: StdSequencer; st: Stores.Store): BOOLEAN;
VAR v, w: Windows.Window;
BEGIN
w := s.home;
IF (w = NIL) OR (st = w.doc) OR (st = w.doc.ThisView()) THEN
RETURN TRUE
ELSE
v := w.link;
WHILE (v # w) & (st # v.doc) & (st # v.doc.ThisView()) DO v := v.link END;
RETURN v = w
END
END AffectsDoc;
(* Script *)
PROCEDURE (s: Script) Do;
VAR e, f, g: OpElem;
BEGIN
e := s.list; f := NIL;
REPEAT
Neutralize(e.st); e.op.Do;
g := e.next; e.next := f; f := e; e := g
UNTIL e = NIL;
s.list := f
END Do;
(* StdSequencer *)
PROCEDURE (s: StdSequencer) Handle (VAR msg: ANYREC);
(* send message to all windows attached to s *)
VAR w: Window;
BEGIN
IF s.trapEra # Kernel.trapCount THEN Reset(s) END;
WITH msg: Models.Message DO
IF msg IS Models.UpdateMsg THEN
Properties.IncEra;
IF s.entryLevel = 0 THEN
(* updates in dominated model bypassed the sequencer *)
Reset(s); (* panic reset: clear sequencer *)
INC(s.modLevel) (* but leave dirty *)
END
END;
w := First();
WHILE w # NIL DO
IF w.seq = s THEN w.BroadcastModelMsg(msg) END;
w := Next(w)
END
| msg: Views.Message DO
w := First();
WHILE w # NIL DO
IF w.seq = s THEN w.BroadcastViewMsg(msg) END;
w := Next(w)
END
ELSE
END
END Handle;
PROCEDURE (s: StdSequencer) Dirty (): BOOLEAN;
BEGIN
RETURN s.modLevel > 0
END Dirty;
PROCEDURE (s: StdSequencer) SetDirty (dirty: BOOLEAN);
BEGIN
IF dirty THEN INC(s.modLevel) ELSE s.modLevel := 0 END
END SetDirty;
PROCEDURE (s: StdSequencer) LastOp (st: Stores.Store): Stores.Operation;
BEGIN
ASSERT(st # NIL, 20);
IF s.lastSt = st THEN RETURN s.lastOp ELSE RETURN NIL END
END LastOp;
PROCEDURE (s: StdSequencer) BeginScript (IN name: Stores.OpName; VAR script: Stores.Operation);
VAR sop: Script;
BEGIN
IF s.trapEra # Kernel.trapCount THEN Reset(s) END;
INC(s.nestLevel);
IF (s.nestLevel = 1) & (s.invisibleLevel = 0)
& (s.transparentLevel = 0) & (s.notRecordedLevel = 0) THEN
INC(s.modLevel)
END;
s.lastSt := NIL; s.lastOp := NIL;
NEW(sop);
sop.up := s.script; sop.list := NIL; sop.level := s.nestLevel; sop.name := name;
s.script := sop;
script := sop
END BeginScript;
PROCEDURE (s: StdSequencer) Do (st: Stores.Store; IN name: Stores.OpName; op: Stores.Operation);
VAR e: OpElem;
BEGIN
ASSERT(st # NIL, 20); ASSERT(op # NIL, 21);
IF s.trapEra # Kernel.trapCount THEN Reset(s) END;
Do(s, st, op);
IF s.noUndo THEN (* cannot undo: unbalanced BeginModification pending *)
s.lastSt := NIL; s.lastOp := NIL
ELSIF (s.entryLevel = 0) (* don't record when called from within op.Do *)
& AffectsDoc(s, st) THEN (* don't record when Do affected child window only *)
s.lastSt := st; s.lastOp := op;
IF s.notRecordedLevel = 0 THEN
s.redo := NIL; (* clear redo stack *)
END;
IF s.script # NIL THEN
Prepend(s.script, st, name, op)
ELSE
IF (s.invisibleLevel = 0) & (s.transparentLevel = 0) & (s.notRecordedLevel = 0) THEN
INC(s.modLevel)
END;
IF s.notRecordedLevel = 0 THEN
NEW(e); e.st := st; e.op := op; e.name := name;
e.invisible := s.invisibleLevel > 0; e.transparent := s.transparentLevel > 0;
Push(s.undo, e)
END
END
END
END Do;
PROCEDURE (s: StdSequencer) Bunch (st: Stores.Store);
VAR lastOp: Stores.Operation;
BEGIN
IF s.trapEra # Kernel.trapCount THEN Reset(s) END;
ASSERT(st # NIL, 20); ASSERT(st = s.lastSt, 21);
lastOp := s.lastOp;
Do(s, st, lastOp);
IF s.noUndo THEN
s.lastSt := NIL; s.lastOp := NIL
ELSIF (s.entryLevel = 0) (* don't record when called from within op.Do *)
& AffectsDoc(s, st) THEN (* don't record when Do affected child window only *)
s.lastSt := st; s.lastOp := lastOp
END
END Bunch;
PROCEDURE (s: StdSequencer) EndScript (script: Stores.Operation);
VAR e: OpElem;
BEGIN
IF s.trapEra # Kernel.trapCount THEN Reset(s) END;
ASSERT(script # NIL, 20); ASSERT(s.script = script, 21);
WITH script: Script DO
ASSERT(s.nestLevel = script.level, 22);
s.script := script.up;
IF s.entryLevel = 0 THEN (* don't record when called from within op.Do *)
IF script.list # NIL THEN
IF s.script # NIL THEN
Prepend(s.script, NIL, script.name, script)
ELSE (* outermost scripting level *)
s.redo := NIL; (* clear redo stack *)
IF ~s.noUndo THEN
NEW(e); e.st := NIL; e.op := script; e.name := script.name;
e.invisible := s.invisibleLevel > 0; e.transparent := s.transparentLevel > 0;
IF s.notRecordedLevel=0 THEN Push(s.undo, e) END
END;
s.lastSt := NIL; s.lastOp := NIL
END
ELSE
IF (s.script = NIL) & (s.modLevel > 0)
& (s.invisibleLevel = 0) & (s.transparentLevel = 0) THEN
DEC(s.modLevel)
END
END
END
END;
DEC(s.nestLevel);
IF s.nestLevel = 0 THEN ASSERT(s.script = NIL, 22); s.noUndo := FALSE END
END EndScript;
PROCEDURE (s: StdSequencer) StopBunching;
BEGIN
s.lastSt := NIL; s.lastOp := NIL
END StopBunching;
PROCEDURE (s: StdSequencer) BeginModification (type: INTEGER; st: Stores.Store);
BEGIN
IF s.trapEra # Kernel.trapCount THEN Reset(s) END;
IF s.nestLevel < LEN(s.modStack) THEN
s.modStack[s.nestLevel].store := st; s.modStack[s.nestLevel].type := type
END;
INC(s.nestLevel);
IF type = Sequencers.notUndoable THEN
INC(s.modLevel); (* unbalanced! *)
s.noUndo := TRUE; s.undo := NIL; s.redo := NIL;
s.lastSt := NIL; s.lastOp := NIL;
INC(s.entryLevel) (* virtual entry of modification "operation" *)
ELSIF type = Sequencers.invisible THEN
INC(s.invisibleLevel)
ELSIF type = Sequencers.clean THEN
INC(s.transparentLevel)
ELSIF type = notRecorded THEN
INC(s.notRecordedLevel)
END
END BeginModification;
PROCEDURE (s: StdSequencer) EndModification (type: INTEGER; st: Stores.Store);
BEGIN
IF s.trapEra # Kernel.trapCount THEN Reset(s) END;
ASSERT(s.nestLevel > 0, 20);
IF s.nestLevel <= LEN(s.modStack) THEN
ASSERT((s.modStack[s.nestLevel - 1].store = st) & (s.modStack[s.nestLevel - 1].type = type), 21)
END;
DEC(s.nestLevel);
IF type = Sequencers.notUndoable THEN
DEC(s.entryLevel)
ELSIF type = Sequencers.invisible THEN
DEC(s.invisibleLevel)
ELSIF type = Sequencers.clean THEN
DEC(s.transparentLevel)
ELSIF type = notRecorded THEN
DEC(s.notRecordedLevel)
END;
IF s.nestLevel = 0 THEN ASSERT(s.script = NIL, 22); s.noUndo := FALSE END
END EndModification;
PROCEDURE (s: StdSequencer) CanUndo (): BOOLEAN;
VAR op: OpElem;
BEGIN
IF s.trapEra # Kernel.trapCount THEN Reset(s) END;
op := s.undo;
WHILE (op # NIL) & op.invisible DO op := op.next END;
RETURN op # NIL
END CanUndo;
PROCEDURE (s: StdSequencer) CanRedo (): BOOLEAN;
VAR op: OpElem;
BEGIN
IF s.trapEra # Kernel.trapCount THEN Reset(s) END;
op := s.redo;
WHILE (op # NIL) & op.invisible DO op := op.next END;
RETURN op # NIL
END CanRedo;
PROCEDURE (s: StdSequencer) GetUndoName (VAR name: Stores.OpName);
VAR op: OpElem;
BEGIN
IF s.trapEra # Kernel.trapCount THEN Reset(s) END;
op := s.undo;
WHILE (op # NIL) & op.invisible DO op := op.next END;
IF op # NIL THEN name := op.name$ ELSE name[0] := 0X END
END GetUndoName;
PROCEDURE (s: StdSequencer) GetRedoName (VAR name: Stores.OpName);
VAR op: OpElem;
BEGIN
IF s.trapEra # Kernel.trapCount THEN Reset(s) END;
op := s.redo;
WHILE (op # NIL) & op.invisible DO op := op.next END;
IF op # NIL THEN name := op.name$ ELSE name[0] := 0X END
END GetRedoName;
PROCEDURE (s: StdSequencer) Undo;
VAR e: OpElem;
BEGIN
IF s.trapEra # Kernel.trapCount THEN Reset(s) END;
IF s.undo # NIL THEN
REPEAT
Pop(s.undo, e); Do(s, e.st, e.op); Push(s.redo, e)
UNTIL ~e.invisible OR (s.undo = NIL);
IF ~e.transparent THEN
IF s.modLevel > 0 THEN DEC(s.modLevel) END
END
END
END Undo;
PROCEDURE (s: StdSequencer) Redo;
VAR e: OpElem;
BEGIN
IF s.trapEra # Kernel.trapCount THEN Reset(s) END;
IF s.redo # NIL THEN
Pop(s.redo, e); Do(s, e.st, e.op); Push(s.undo, e);
WHILE (s.redo # NIL) & s.redo.invisible DO
Pop(s.redo, e); Do(s, e.st, e.op); Push(s.undo, e)
END;
IF ~e.transparent THEN
INC(s.modLevel)
END
END
END Redo;
(* Forwarder *)
PROCEDURE (f: Forwarder) Forward (target: BOOLEAN; VAR msg: Controllers.Message);
VAR w: Window;
BEGIN
w := stdDir.Focus(target);
IF w # NIL THEN ForwardCtrlMsg(w, msg) END
END Forward;
PROCEDURE (f: Forwarder) Transfer (VAR msg: Controllers.TransferMessage);
VAR w: Windows.Window; h: Views.Frame; p: Ports.Port; sx, sy, tx, ty, pw, ph: INTEGER;
BEGIN
h := msg.source; p := h.rider.Base();
(* (msg.x, msg.y) is point in local coordinates of source frame *)
sx := (msg.x + h.gx) DIV h.unit;
sy := (msg.y + h.gy) DIV h.unit;
(* (sx, sy) is point in global coordinates of source port *)
stdDir.GetThisWindow(p, sx, sy, tx, ty, w);
IF w # NIL THEN
(* (tx, ty) is point in global coordinates of target port *)
w.port.GetSize(pw, ph); (* what's this for? *)
msg.x := tx * w.port.unit;
msg.y := ty * w.port.unit;
(* (msg.x, msg.y) is point in coordinates of target window *)
w.ForwardCtrlMsg(msg)
END
END Transfer;
PROCEDURE GetByTitle* (IN title: Views.Title): Window;
(** Get topmost window that has .title = title$ *)
VAR w: Window;
BEGIN
w := zList;
WHILE (w # NIL) & (w.title$ # title$) DO w := w.next END;
RETURN w
END GetByTitle;
PROCEDURE MarkWindow*;
(** Mark window at pointer: save it in mark. It can be used in subsequent commands. Post: IFF mouse pointer is over w: Window THEN mark = w ELSE mark = NIL. *)
VAR w, u: Window; dummy: SET; found, dummy2: BOOLEAN;
x, y, xRoot, yRoot: Pixels;
BEGIN
w := First();
WHILE (w # NIL) & ~w.backend.GetOrigin(xRoot, yRoot) DO w := Next(w) END;
IF w # NIL THEN w.port.NewRider().Input(x, y, dummy, dummy2);
INC(xRoot, x); INC(yRoot, y); found := FALSE;
WHILE ~found & (w # NIL) DO
found := w.backend.IsInside(xRoot, yRoot, dummy2);
IF ~found THEN w := Next(w) END
END;
u := mark; mark := w;
IF w # NIL THEN MarkTitle(w) END; IF u # NIL THEN MarkTitle(u) END
END
END MarkWindow;
PROCEDURE MarkGuard* (VAR par: Dialog.Par); (** Menu guard for MarkWindow *)
BEGIN
par.disabled := mark = NIL
END MarkGuard;
(** miscellaneous **)
PROCEDURE SetBackendDir* (d: BackendDirectory);
BEGIN
ASSERT(d # NIL, 20);
IF stdBackendDir = NIL THEN
stdBackendDir := d
END;
backendDir := d
END SetBackendDir;
PROCEDURE SetDumper* (d: PROCEDURE (p: ANYPTR));
(** Sets the dumper procedure, cf. ForwardCtrlMsg *)
BEGIN IF stdDump = NIL THEN stdDump := dump END; dump := d
END SetDumper;
PROCEDURE GetBySpec* (loc: Files.Locator; name: Files.Name;
conv: Converters.Converter; flags: SET): Window;
(** Reuse of open documents; IF ~(allowDuplicates IN flags), THEN returns the topmost window that displays the permanent store, if any, identified by loc, name, internalized with conv, and has (isAux IN .flags) = (isAux IN flags) and (isTool IN .flags) = (isTool IN flags) ELSE returns NIL. *)
VAR found, tool, aux: BOOLEAN; w: Window;
BEGIN
IF ~(Windows.allowDuplicates IN flags) & (loc # NIL) & (loc.res # 77) & (name # "") THEN
Files.dir.GetFileName(name, Files.docType, name); (* appends .odc if no extension *)
IF conv = NIL THEN conv := Converters.list END;
tool := Windows.isTool IN flags; aux := Windows.isAux IN flags;
w := First();
REPEAT
found := (w # NIL) &
~(Windows.allowDuplicates IN w.flags) & (w.loc # NIL) & (w.loc.res # 77) & (w.name # "")
& Files.dir.SameFile(loc, name, w.loc, w.name) & (w.conv = conv)
& (tool = (Windows.isTool IN w.flags)) & (aux = (Windows.isAux IN w.flags));
IF ~found THEN w := Next(w) END
UNTIL (w = NIL) OR found
END;
RETURN w
END GetBySpec;
PROCEDURE SelectBySpec* (loc: Files.Locator; name: Files.Name; conv: Converters.Converter; flags: SET; VAR done: BOOLEAN);
(** A convenience procedure, selects the window returned by GetBySpec, if any. Post: done = TRUE => window was found and selected; done = FALSE => window was not found *)
VAR w: Window;
BEGIN
w := GetBySpec(loc, name, conv, flags);
IF w # NIL THEN Select(w, Windows.lazy); done := TRUE ELSE done := FALSE END
END SelectBySpec;
PROCEDURE SelectByTitle* (v: Views.View; flags: SET; title: Views.Title; VAR done: BOOLEAN);
(** Select the window with title that displays a view of the same (dynamic) type as v (if specified) or v(Documents.Document).ThisView() and has (.flags / flags) * {isAux, isTool} = {} and ~(allowDuplicates in .flags).
Post:
done = TRUE => window was found;
done = FALSE window was not found. *)
VAR w: Window; n1, n2: ARRAY 64 OF CHAR;
BEGIN
done := FALSE;
IF v # NIL THEN
IF v IS Documents.Document THEN v := v(Documents.Document).ThisView() END;
Services.GetTypeName(v, n1)
ELSE n1 := ""
END;
w := First();
WHILE w # NIL DO
IF ((w.flags / flags) * {Windows.isAux, Windows.isTool} = {})
& ~(Windows.allowDuplicates IN w.flags) & (w.initialTitle$ = title$)
THEN
Services.GetTypeName(w.doc.ThisView(), n2);
IF (n1 = "") OR (n1 = n2) THEN Select(w, Windows.lazy); done := TRUE; RETURN END
END;
w := Next(w)
END
END SelectByTitle;
PROCEDURE (h: MsgHook) Omnicast (VAR msg: ANYREC);
VAR w: Window;
BEGIN
w := First();
WHILE w # NIL DO
IF ~w.sub THEN w.seq.Handle(msg) END;
w := Next(w)
END
END Omnicast;
PROCEDURE (h: MsgHook) RestoreDomain (d: Stores.Domain);
VAR seq: ANYPTR;
BEGIN
IF d = NIL THEN
RestoreSequencer(NIL)
ELSE
seq := d.GetSequencer();
IF seq # NIL THEN
RestoreSequencer(seq(Sequencers.Sequencer))
END
END
END RestoreDomain;
(* SequencerDirectory *)
PROCEDURE (d: SequencerDirectory) New (): Sequencers.Sequencer;
BEGIN
RETURN NewSequencer()
END New;
(** CheckAction **)
PROCEDURE (a: CheckAction) Do;
VAR w: Window; s: Sequencers.Sequencer;
BEGIN
Services.DoLater(a.wait, Services.resolution);
w := First();
WHILE w # NIL DO
s := w.seq(*(StdSequencer)*);
WITH s: StdSequencer DO
IF s.trapEra # Kernel.trapCount THEN Reset(s) END;
ASSERT(s.nestLevel = 0, 100);
(* unbalanced calls of Views.BeginModification/EndModification or Views.BeginScript/EndScript *)
ELSE
END;
w := Next(w)
END
END Do;
PROCEDURE (a: WaitAction) Do;
BEGIN
Services.DoLater(a.check, Services.immediately)
END Do;
PROCEDURE SetAttachedCheckHook* (hook: AttachedCheckHook);
BEGIN attachedCheckHook := hook
END SetAttachedCheckHook;
PROCEDURE (n: LangNotifier) Notify;
VAR w: Window;
BEGIN
w := First();
WHILE w # NIL DO
Update(w, Views.keepFrames);
w.SetTitle(w.initialTitle);
w := Next(w)
END
END Notify;
PROCEDURE InitDefaults (p: ANYPTR);
BEGIN
WITH p: Param DO
p.wheelScrollByPage := FALSE; (* monitored in StdWheel *)
p.markTitles := FALSE;
p.bgColor := Ports.white;
p.frontStr := " ⌨";
p.targetStr := " ⦿";
p.frontTargetStr := " ⌨ ⦿";
p.markStr := "⚹";
p.InitDefaults := InitDefaults;
END
END InitDefaults;
PROCEDURE Init*;
VAR f: Forwarder; r: Reducer; sdir: SequencerDirectory;
a: CheckAction; w: WaitAction; h: MsgHook; ln: LangNotifier; stdExt: StdExt;
BEGIN
NEW(sdir); Sequencers.SetDir(sdir);
NEW(h); Views.SetMsgHook(h);
NEW(f); Controllers.Register(f);
NEW(r); Kernel.InstallReducer(r);
NEW(a); NEW(w); a.wait := w; w.check := a; Services.DoLater(a, Services.immediately);
NEW(ln); Dialog.RegisterLangNotifier(ln);
NEW(stdDir); dir := stdDir; border := -1;
Windows.SetDir(stdDir);
dir.l := none;
NEW(param);
InitDefaults(param);
newNumber := 1;
NEW(stdExt); ext := stdExt;
END Init;
END StdWindows.
Closing windows
Windows.Close(w) - unconditional synchronous closing of w
Windows.DialogClose(w) - allows to dialog with user before closing of w; may end up in Windows.Close(w)
Menu
↳StdCmds.Close
↳Windows.DialogClose(Windows.First())
Windows.DialogClose(w)
IF closeHook # NIL THEN
↳Windows.closeHook.Close(w)
ELSE
↳Windows.Close
END
⮾ (close button in window title bar)
↳ GTK sends "delete-event" signal to Gtk2Gtk.GtkWindow
↳HostWindows.DeleteSignal
↳HostWindows.DeleteHandler.Execute
↳Windows.DialogClose(w)
HostCmds.CloseHook.Close(w) (* default impl *)
↳HostDialog.CloseDialog(res)
IF ... THEN
↳Windows.Close(w)
END
| Std/Mod/Windows.odc |
Std/Rsrc/Cmds.odc |
|
Std/Rsrc/Cmds1.odc |
|
Std/Rsrc/Coder.odc |
|
⮾ UNSAVED CHANGES
Save & Close Close! | Std/Rsrc/ConfirmCloseOverlaid.odc |
Std/Rsrc/Folds.odc |
|
Std/Rsrc/Headers.odc |
|
Std/Rsrc/Links.odc |
|
MENU "#System:&Window"
"#System:&Dup Window" "F2" "StdTiles.ToggleSub" "StdCmds.ModelViewGuard"
"#System:&New Window" "" "StdCmds.NewWindow" "StdCmds.ModelViewGuard"
"#System:&Separate new windows" "" "StdTiles.OnOff" "StdTiles.OnOffGuard"
"#System:Attached" "" "StdTiles.ToggleAttached" "StdTiles.AttachedGuard"
SEPARATOR
"#System:Save Workspace" "" "StdTiles.SaveWorkspace" ""
"#System:Open Workspace." "" "StdTiles.OpenWorkspace" ""
"Context menu" "*F10" "StdMenuTool.PopupMenu" "StdMenus.HidingGuard"
"Context menu" "Apps" "StdMenuTool.PopupMenu" "StdMenus.HidingGuard"
"Cut" "*Del" "StdCmds.Cut" "StdCmds.CutGuardHidden"
"Copy" "^Ins" "StdCmds.Copy" "StdCmds.CopyGuardHidden"
"Paste" "*Ins" "StdCmds.Paste" "StdCmds.PasteGuardHidden"
END
| Std/Rsrc/Menus.odc |
Std/Rsrc/PageSetup.odc |
|
Preferences of BlackBox Component Builder
Default font being used for texts:
Default font being used for controls:
Language:
Scale factor (50-200): %
When checked, beeps are generated in case of certain errors and warnings. Unchecking this option allows to operate BlackBox more silently, which may be required in a shared office or in a public space.
Use a thick caret for marking the text insertion point instead of the default caret.
Caret blink period (in milliseconds).
Format of the status bar at the bottom of the BlackBox application window:
no status bar at all
status messages for user
left part for status messages and
the right part shows the memory
consumption and actions in the queue
Color theme:
Document background:
Default color:
| Std/Rsrc/Preferences.odc |
Std/Rsrc/Scroller.odc |
|
Std/Rsrc/Stamps.odc |
|
STRINGS
Adapted Adapted
All tabs in Layout Mode All tabs in Layout Mode
All tabs in Mask Mode All tabs in Mask Mode
alternate alternate
Always Always
Apply Apply
&Apply &Apply
Automatic Automatic
Browse &Browse
Close &Close
Close: Close:
Collapse Collapse
Comment Comment
Create Collapsed Fold Create Collapsed Fold
Create Expanded Fold Create Expanded Fold
Data Editable Data Editable
Date Date
Decode &Decode
Decode All Decode &All
DecodeDialog Decode
Delete &Delete
Expand Expand
Find First Find First
Find Next Find Next
Fix: Fix:
Fixed Fixed
Font... &Font...
Foot gap Foot gap
Head gap Head gap
Height Height
Height: &Height:
Horizontal Scrollbar Horizontal Scrollbar
Keep proportions &Keep proportions
Label: Label:
Layout Editable Layout Editable
Left Foot Left Foot
Left Head Left Head
Link: Link:
Links & Targets Docu Links & Targets Docu
Move Move
Nested Nested
Never Never
New Tab &New Tab
No Selection No Selection
Notifier Notifier
Page Height Page Height
Page Width Page Width
Rename &Rename
Reset &Reset
Right Foot Right Foot
Right Head Right Head
Save position Save position
Select Cell Select Cell
Select Column Select Column
Selection Style: Selection Style:
Select Row Select Row
Select Row & Column Select Row & Column
Seq. Nr. Seq. Nr.
Set Set
Set Label Set Label
Show 3d border Show 3d border
Show Foot Show Foot
Size: &Size:
Start with new page number Start with new page number
Tabs Tabs
Target: Target:
Type: Type:
Use Filter: Use Filter:
Use Name: &Use Name:
Vertical Scrollbar Vertical Scrollbar
View Height View Height
View Width View Width
Width Width
Width: &Width:
Window Height Window Height
Window Width Window Width
cm cm
comment comment
date and time date and time
fingerprint fingerprint
inch inch
new new
seq nr. seq nr.
bad characters bad characters in code!
checksum error checksum error!
incompatible version Code has been created with an incompatible version of Coder!
filing error Could not store file!
directory ^0 not found Folder ^0 does not exist!
file ^0 not found File ^0 does not exist!
illegal path '^0' is not a legal path name!
no tag No Coder Tag found!
^0 characters coded Document coded into ^0 characters.
Install all? Install all the coded files? This operation might overwrite old versions!
Install individual? Install some of the coded files individually?
Info Info
Set Comment Set Comment
StdETHConv.ImportETHDoc ETH V4 Oberon
StdClocks.StdViewDesc StdClocks view
StdLogos.ViewDesc StdLogos view
StdStamps.StdViewDesc StdStamps view
HeaderChange Header Change
Link Link
Target Target
Create Link Create Link
Create Target Create Target
Reveal Link Command Reveal Link Command
Reveal Target Ident Reveal Target Ident
LinkChange Link Change
Link Call Failed Link Call Failed
Target Not Found target '^0' not found
links[0] always
links[1] if Shift-Key is pressed
links[2] never
Scrollers.Prop StdScrollers.InitDialog; StdCmds.OpenToolDialog('Std/Rsrc/Scroller', 'Scroller')
Headers.Prop StdHeaders.InitDialog; StdCmds.OpenToolDialog('Std/Rsrc/Headers', 'Headers')
Folds.Prop StdCmds.OpenToolDialog('Std/Rsrc/Folds','Zoom')
Links.Prop StdLinks.InitDialog; StdCmds.OpenToolDialog('Std/Rsrc/Links', 'Links & Targets')
TabViews.View StdTabViews.InitDialog; StdCmds.OpenToolDialog('Std/Rsrc/TabViews','Tab View Inspector')
TabSetItem Set Item
TabDeleteItem Delete Item
Tables.Prop StdTables.InitDialog; StdCmds.OpenToolDialog('Std/Rsrc/Tables', 'Tables')
Font Font
Typeface Typeface
Default font Default font
Dialog font Dialog font
SaveNClose Save && Close
CloseNow No
Shift Shift+
Ctrl Ctrl+
Space Space
Edit &Edit
Open &Open
MoveHere &Move Here
CopyHere &Copy Here
LinkHere &Link Here
Object &Object
MissingDirectory Missing Directory
CreateDir The directory ^0 will be created
FileError File Error
ReplaceWriteProtected ^0 could not be replaced^1because it is write protected
ReplaceInUse ^0 could not be replaced^1because it is in use
ReplaceAccessDenied ^0 could not be replaced^1because access is denied
PreferencesDocu Preferences Docu
AllocatedMemory Allocated Memory:
ActionsInTheQueue Actions in the queue:
Total Total:
Bytes Bytes
Print Print
OpenFile Open
ControlInspector Control Inspector
SaveChanges ^0 has changed.^1^2Do you want to save the changes?
Saving saving
Saved saved
Failed failed
Document Document
AllFiles All Files
NotUnderWindows3 Feature not available under Windows 3.11
Read File As: Read File As:
Use true type metric &Use true type metric
Visual scrolling &Visual scrolling
Beep &Beep
Server Mode Server &Mode
Caret Caret
Thick Caret &Thick Caret
Caret Period (in ms): &Caret Period (in ms):
Language: &Language:
Default font... D&efault font...
Dialog font... Di&alog font...
Status bar Status bar
No &No
Simple &Simple
Double &Double
Printing Page: Printing Page:
Printer... Printer...
Layout Layout
Standard Header Standard Header
Orientation Orientation
Portrait Portrait
Landscape Landscape
Margins Margins
Left: Left:
Right: Right:
Top: Top:
Bottom: Bottom:
StdDocuments.ImportDocument Document
StdTextConv.ImportUtf8 UTF-8 Text
StdTextConv.ImportText Text
StdTextConv.ImportTabText Text (space pairs as tabs)
WinTextConv.ImportRichText Rich Text
StdTextConv.ImportUnicode Unicode Text
StdTextConv.ImportHex Data File (hex)
StdTextConv.ImportDosText Text (Dos encoding)
WinBitmaps.ImportBitmap Bitmap
StdRasters.Import Import raster image
StdDocuments.ExportDocument Document
StdTextConv.ExportUtf8 UTF-8 Text
StdTextConv.ExportText Plain Text
StdTextConv.ExportTabText Plain Text (tabs as space pairs)
WinTextConv.ExportRichText Rich Text
StdTextConv.ExportUnicode Unicode Text
WinBitmaps.ExportBitmap Bitmap
WinTextConv.ImportDRichText Rich Text
WinTextConv.ImportDUnicode Unicode Text
WinTextConv.ImportDText Plain Text
WinTextConv.ImportDPict Picture (Metafile)
WinTextConv.ImportDBitmap Picture (Bitmap)
WinTextConv.ImportDPictAsBitmap Picture (Bitmap)
TextViews.StdView Text
WinPictures.StdView Metafile-Picture
WinBitmaps.StdView Bitmap-Picture
TextViews.View Text
WinPictures.View Metafile-Picture
WinBitmaps.View Bitmap-Picture
Properties.StdProp StdDialog.FontDialog
Bitmaps.Evaluate.101 Not enough memory to allocate bitmap
openExtErr Failed to open external document:
runExtErr Failed to run external command: | Std/Rsrc/Strings.odc |
Std/Rsrc/Tables.odc |
|
Std/Rsrc/TabViews.odc |
|
Std/Rsrc/ViewSizer.odc |
|
Console
DEFINITION Console;
PROCEDURE ReadLn (OUT text: ARRAY OF CHAR);
PROCEDURE SetConsole (c: Console);
PROCEDURE WriteChar (c: CHAR);
PROCEDURE WriteLn;
PROCEDURE WriteStr (IN text: ARRAY OF CHAR);
END Console.
PROCEDURE ReadLn (OUT text: ARRAY OF CHAR);
Wait for new line input.
PROCEDURE WriteChar (c: CHAR);
Write c to output.
PROCEDURE WriteLn;
Write new line to output.
PROCEDURE WriteStr (IN text: ARRAY OF CHAR);
Write text to output.
Example:
MODULE ObxConsole;
IMPORT Console;
PROCEDURE Init;
VAR name: ARRAY 256 OF CHAR;
BEGIN
Console.WriteStr("What is your name?");
Console.WriteLn;
Console.ReadLn(name);
Console.WriteStr("Hello, " + name);
END Init;
BEGIN
Init
END ObxConsole.
DevCompiler.Compile
For Windows
DevLinker.LinkExe dos demo.exe := Kernel+ Utf WinKernel Files WinEnv WinFiles Console WinConsole ObxConsole
For Linux:
DevLinker1.LinkElfExe Linux demo := Kernel+ Utf LinKernel Files LinEnv LinFiles Console LinConsole ObxConsole
| System/Docu/Console.odc |
Containers
DEFINITION Containers;
IMPORT Controllers, Stores, Views, Models, Properties;
CONST
noSelection = 0; noFocus = 1; noCaret = 2;
mask = {noSelection, noCaret}; layout = {noFocus};
deselect = FALSE; select = TRUE;
any = FALSE; selection = TRUE;
hide = FALSE; show = TRUE;
TYPE
Model = POINTER TO ABSTRACT RECORD (Models.Model)
(m: Model) GetEmbeddingLimits (OUT minW, maxW, minH, maxH: INTEGER), NEW, ABSTRACT;
(m: Model) ReplaceView (old, new: Views.View), NEW, ABSTRACT;
(m: Model) InitFrom- (source: Model), NEW, EMPTY
END;
View = POINTER TO ABSTRACT RECORD (Views.View)
(v: View) CopyFromModelView2- (source: Views.View; model: Models.Model), NEW, EMPTY;
(v: View) Externalize2- (VAR rd: Stores.Writer), NEW, EMPTY;
(v: View) HandleCtrlMsg2- (f: Views.Frame; VAR msg: Views.CtrlMessage;
VAR focus: Views.View), NEW, EMPTY;
(v: View) HandleModelMsg2- (VAR msg: Models.Message), NEW, EMPTY;
(v: View) HandlePropMsg2- (VAR p: Views.PropMessage), NEW, EMPTY;
(v: View) HandleViewMsg2- (f: Views.Frame; VAR msg: Views.Message), NEW, EMPTY;
(v: View) Internalize2- (VAR rd: Stores.Reader), NEW, EMPTY;
(v: View) InitModel (m: Model), NEW;
(v: View) InitModel2- (m: Model), NEW, EMPTY;
(v: View) AcceptableModel- (m: Model): BOOLEAN, NEW, ABSTRACT;
(v: View) ThisModel (): Model, EXTENSIBLE;
(v: View) SetController (c: Controller), NEW;
(v: View) ThisController (): Controller, NEW, EXTENSIBLE;
(v: View) GetRect (f: Views.Frame; view: Views.View; OUT l, t, r, b: INTEGER), NEW, ABSTRACT;
(v: View) CatchModelMsg (VAR msg: Models.Message), NEW, EMPTY;
(v: View) CatchViewMsg (f: Views.Frame; VAR msg: Views.Message), NEW, EMPTY;
(v: View) CatchCtrlMsg (f: Views.Frame; VAR msg: Views.CtrlMessage;
VAR focus: Views.View), NEW, EMPTY;
(v: View) CatchPropMsg (VAR msg: Views.PropMessage), NEW, EMPTY
END;
Controller = POINTER TO ABSTRACT RECORD (Controllers.Controller)
opts-: SET;
(c: Controller) ThisView (): View, EXTENSIBLE;
(c: Controller) SetOpts (opts: SET), NEW, EXTENSIBLE;
(c: Controller) GetContextType (OUT type: Stores.TypeName), NEW, ABSTRACT;
(c: Controller) GetValidOps (OUT valid: SET), NEW, ABSTRACT;
(c: Controller) NativeModel (m: Models.Model): BOOLEAN, NEW, ABSTRACT;
(c: Controller) NativeView (v: Views.View): BOOLEAN, NEW, ABSTRACT;
(c: Controller) NativeCursorAt (f: Views.Frame; x, y: INTEGER): INTEGER, NEW, ABSTRACT;
(c: Controller) PickNativeProp (f: Views.Frame; x, y: INTEGER;
VAR p: Properties.Property), NEW, EMPTY;
(c: Controller) PollNativeProp (selection: BOOLEAN; VAR p: Properties.Property;
VAR truncated: BOOLEAN), NEW, EMPTY;
(c: Controller) SetNativeProp (selection: BOOLEAN; old, p: Properties.Property), NEW, EMPTY;
(c: Controller) MakeViewVisible (v: Views.View), NEW, EMPTY;
(c: Controller) GetFirstView (selection: BOOLEAN; OUT v: Views.View), NEW, ABSTRACT;
(c: Controller) GetNextView (selection: BOOLEAN; VAR v: Views.View), NEW, ABSTRACT;
(c: Controller) GetPrevView (selection: BOOLEAN; VAR v: Views.View), NEW, EXTENSIBLE;
(c: Controller) CanDrop (f: Views.Frame; x, y: INTEGER): BOOLEAN, NEW, EXTENSIBLE;
(c: Controller) MarkDropTarget (src, dst: Views.Frame; sx, sy, dx, dy, w, h, rx, ry: INTEGER;
type: Stores.TypeName; isSingle, show: BOOLEAN), NEW, EMPTY;
(c: Controller) Drop (src, dst: Views.Frame; sx, sy, dx, dy, w, h, rx, ry: INTEGER;
view: Views.View; isSingle: BOOLEAN), NEW, ABSTRACT;
(c: Controller) MarkPickTarget (src, dst: Views.Frame;
sx, sy, dx, dy: INTEGER; show: BOOLEAN), NEW, EMPTY;
(c: Controller) TrackMarks (f: Views.Frame; x, y: INTEGER;
units, extend, add: BOOLEAN), NEW, ABSTRACT;
(c: Controller) Resize (view: Views.View; l, t, r, b: INTEGER), NEW, ABSTRACT;
(c: Controller) GetSelectionBounds (f: Views.Frame;
OUT x, y, w, h: INTEGER), NEW, EXTENSIBLE;
(c: Controller) DeleteSelection, NEW, ABSTRACT;
(c: Controller) MoveLocalSelection (src, dst: Views.Frame;
sx, sy, dx, dy: INTEGER), NEW, ABSTRACT;
(c: Controller) CopyLocalSelection (src, dst: Views.Frame;
sx, sy, dx, dy: INTEGER), NEW, ABSTRACT;
(c: Controller) SelectionCopy (): Model, NEW, ABSTRACT;
(c: Controller) NativePaste (m: Models.Model; f: Views.Frame), NEW, ABSTRACT;
(c: Controller) ArrowChar (f: Views.Frame; ch: CHAR; units, select: BOOLEAN), NEW, ABSTRACT;
(c: Controller) ControlChar (f: Views.Frame; ch: CHAR), NEW, ABSTRACT;
(c: Controller) PasteChar (ch: CHAR), NEW, ABSTRACT;
(c: Controller) PasteView (f: Views.Frame; v: Views.View; w, h: INTEGER), NEW, ABSTRACT;
(c: Controller) HasSelection (): BOOLEAN, NEW, EXTENSIBLE;
(c: Controller) Selectable (): BOOLEAN, NEW, ABSTRACT;
(c: Controller) Singleton (): Views.View, NEW;
(c: Controller) SetSingleton (s: Views.View), NEW, EXTENSIBLE;
(c: Controller) SelectAll (select: BOOLEAN), NEW, ABSTRACT;
(c: Controller) InSelection (f: Views.Frame; x, y: INTEGER): BOOLEAN, NEW, ABSTRACT;
(c: Controller) MarkSelection (f: Views.Frame; show: BOOLEAN), NEW, EXTENSIBLE;
(c: Controller) SetFocus (focus: Views.View), NEW;
(c: Controller) HasCaret (): BOOLEAN, NEW, ABSTRACT;
(c: Controller) MarkCaret (f: Views.Frame; show: BOOLEAN), NEW, ABSTRACT;
(c: Controller) Mark (f: Views.Frame; l, t, r, b: INTEGER; show: BOOLEAN), NEW, EXTENSIBLE
END;
Directory = POINTER TO ABSTRACT RECORD
(d: Directory) New (): Controller, NEW, EXTENSIBLE;
(d: Directory) NewController (opts: SET): Controller, NEW, ABSTRACT
END;
DropPref = RECORD (Properties.Preference)
mode-: SET;
okToDrop: BOOLEAN
END;
GetOpts = RECORD (Views.PropMessage)
valid, opts: SET
END;
SetOpts = RECORD (Views.PropMessage)
valid, opts: SET
END;
PROCEDURE Focus (): Controller;
PROCEDURE FocusSingleton (): Views.View;
PROCEDURE MarkSingleton (c: Controller; f: Views.Frame; show: BOOLEAN);
PROCEDURE FadeMarks (c: Controller; show: BOOLEAN);
END Containers.
Containers are views which may contain other (embedded) views. Typically, containers belong to one of two categories. The first category contains containers with a fixed structure and fixed types of the embedded views. For example, an e-mail container view may consist of exactly two views: a toolbar view at the top, and a text view below. The layout of these views typically cannot be edited. Such views are called static containers.
The second category of containers can embed arbitrary numbers of views, which can be of arbitrary types. Text views and form views are typical examples of such dynamic container views. Only this second category of container views, called dynamic containers, is supported by module Containers, and it is the topic of this text.
Dynamic containers consist of a variable number of embedded views, plus some intrinsic contents. Text views for example have text as their intrinsic contents, but also allow to let arbitrary views (i.e., non-intrinsic contents) flow along in the text. Form views are degenerated in the sense that they provide no intrinsic contents of their own.
Different compound document standards (OLE, OpenDoc) differ in the way they treat selections and the focus. The focus is the currently edited view, the view which receives keyboard events, the view which determines the currently available menus, the view which contains the currently relevant selection, caret, or other mark.
Containers provides the building blocks for container views, including special container models and container controllers. Other than most BlackBox modules, Containers exports several partially implemented types, rather than pure interface types. What is implemented is provided in a form suitable for the used platform, i.e. user interface differences are hidden by the implementation of Containers.
In particular, Containers fully implements singleton selections, i.e., selections which cover exactly one view and no intrinsic contents. Such selections are subject to special operations and require platform-dependent treatment. Also, Containers implements the focus concept: a single embedded view within a controller's model that is picked by the user as current focus.
Example: Formsubsystemmap
CONST noSelection, noFocus, noCaret
Possible elements of Controller.opt. noSelection denotes that selections should be switched off, noFocus denotes that no embedded view should be allowed to become focus, and noCaret denotes that the caret (insertion mark) and thus the possibility to type or paste should be switched off.
CONST mask, layout
Two particularly useful subsets of Controller.opt. A mask prevents editing of the container's intrinsic contents, but enables focusing and thereby editing of the contained objects; for example, this allows to use a form without changing the form itself. A layout does just the opposite: focusing and therefore editing of contained objects is inhibited, but the container's intrinsic contents may be freely edited; for example, this is useful when editing a form without wanting to actually activate, say, a button, while editing its position in the form.
CONST deselect, select
Possible values of the select parameter of Controller.SelectAll.
CONST any, selection
Possible values of the selection parameters of Controller.GetFirstView, Controller.GetNextView, Controller.GetPrevView, Controller.PollNativeProp, and Controller.SetNativeProp. Controls whether the range of the operation is the current selection or the whole container contents.
CONST hide, show
Possible values of the show parameter of FadeMarks, MarkSingleton, Controller.Mark, Controller.MarkCaret, Controller.MarkDropTarget, Controller.MarkPickTarget, and Controller.MarkSelections. Controls whether the respective mark is to be hidden or shown.
TYPE Model (Models.Model)
ABSTRACT
Models for containers.
PROCEDURE (m: Model) GetEmbeddingLimits (OUT minW, maxW, minH, maxH: INTEGER)
NEW, ABSTRACT
Return minimum (minW, minH) and maximum (maxW, maxH) bounds on view sizes to be embedded in model m. If it is tried to embed a view into m with width < minW, width >= maxW, height < minH, or height >= maxH, then m should (but is not absolutely required to) modify the size of the embedded view in order to make it fit.
Post
0 <= minW <= maxW
0 <= minH <= maxH
PROCEDURE (m: Model) ReplaceView (old, new: Views.View)
NEW, ABSTRACT
In-place substitution of view old which must be embedded in m by view new which must not yet be embedded anywhere. As a result, new gets embedded in m, but old retains its context which it then shares with new. Replacing a view inplace allows wrapping of views: A new view takes place of an existing one, adds some new properties, but still can hold a reference to the old view and delegate requests to the old view. Since the old view has maintained its context, it will continue to function as if it where directly embedded in m.
Pre
old # NIL
old.context.ThisModel() = m
EmbeddedIn(old, m)
new # NIL
new.context = NIL
Post
NotEmbedded(old)
new.context.ThisModel() = m
new.context = old.context
PROCEDURE (m: Model) InitFrom- (source: Model)
NEW, EMPTY
Initialize model m, which has been newly allocated as an object of the same type as source. In some (rare) cases, it may be useful to share some internal data structures between m and source.
Pre
source # NIL
Type(m) = Type(source)
TYPE View (Views.View)
ABSTRACT
Views for containers.
PROCEDURE (v: View) Internalize (VAR rd: Stores.Reader)
Clarification of inherited procedure
Fully implements internalization for views without intrinsic persistent state by handling internalization of the container view's model and controller. If the model internalization fails, the view is turned into an alien and internalization of v is cancelled; otherwise the model is attached to v. If the controller internalization fails, the controller is kept for later externalization to prevent loss of information, but is otherwise not connected to the view (v.ThisController() = NIL), and the view is internalized normally (i.e., not turned into an alien).
Super call at the beginning is mandatory
PROCEDURE (v: View) Externalize (VAR wr: Stores.Writer)
Clarification of inherited procedure
Fully implements externalization for views without intrinsic persistent state by handling externalization of the container view's model and controller. If v has been internalized before with an alien controller, and no other controller has been installed thereafter, then the alien controller will be externalized, although v.ThisController() = NIL.
Super call at the beginning is mandatory
Pre
v.ThisModel() # NIL 20
PROCEDURE (v: View) CopyFrom (source: Stores.Store)
Clarification of inherited procedure
Assuming that the model of v has already been established, copy the controller and possibly other view state from source. If source holds a hidden alien controller (cf. Internalize above), a reference to it is also copied.
Super call at the beginning is mandatory
Pre
v.ThisModel() # NIL 20
Post
source.ThisController() = NIL
v.ThisController() = NIL
source.ThisController() # NIL
v.ThisController() = source.ThisController().Clone().CopyFrom(source.ThisController())
PROCEDURE (v: View) ThisModel (): Model
EXTENSIBLE
Return the model of v.
Covariant narrowing of function result.
PROCEDURE (v: View) InitModel (m: Containers.Model)
NEW
Assign a model to this view.
Pre
(v.ThisModel() = NIL) OR (v.ThisModel() = m) 20
m # NIL 21
v.AcceptableModel(m) 22
PROCEDURE (v: View) InitModel2- (m: Containers.Model)
NEW, EMPTY
Extension hook called by InitModel.
PROCEDURE (v: View) SetController (c: Controller)
NEW, EXTENSIBLE, Operation
Set the controller of v. If v holds a hidden alien controller, it is removed.
Pre
v.ThisModel() # NIL 20
Post
v.ThisController() = c
PROCEDURE (v: View) ThisController (): Controller
NEW, EXTENSIBLE
Return the controller of v.
PROCEDURE (v: View) GetRect (f: Views.Frame; view: Views.View; OUT l, t, r, b: INTEGER)
NEW, ABSTRACT
For display in frame f, determine the bounding box of view which must be a view contained in v. Should the computation of the bounding box be too expensive, returning an approximation is acceptable.
Post
l <= r
t<= b
PROCEDURE (v: View) CatchModelMsg (VAR msg: Models.Message)
NEW, EMPTY
Extension hook for HandleModelMsg which has become final.
PROCEDURE (v: View) CatchViewMsg (f: Views.Frame; VAR msg: Views.Message)
NEW, EMPTY
Extension hook for HandleViewMsg which has become final.
PROCEDURE (v: View) CatchCtrlMsg
(f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View)
NEW, EMPTY
Extension hook for HandleCtrlMsg which has become final.
PROCEDURE (v: View) CatchPropMsg (VAR p: Properties.Message)
NEW, EMPTY
Extension hook for HandlePropMsg which has become final.
PROCEDURE (v: View) HandleCtrlMsg (f: Views.Frame;
VAR msg: Controllers.Message; VAR focus: Views.View)
Clarification of inherited procedure
If v has a controller installed, calls v.ThisController().HandleCtrlMsg(f, msg, focus), then calls v.CatchCtrlMsg(f, msg, focus). That is, the controller sees the controller message msg before the view does.
Additionally, a strict filter is applied to throw away unwanted messages: messages are only delegated to the controller or view if they fulfill one of the following three criteria:
First, the frame f is a target or front frame. Second, the message is derived from Controllers.PollOpsMsg, Controllers.PollCursorMsg, Controllers.TransferMessage, or Controllers.PageMsg. Third, the context of v is normalizing, i.e., v.context.Normalize() holds, and the message is derived from Controllers.PollSectionMsg or Controllers.ScrollMsg. This is a standard message filtering condition making components more robust against spurious message sends.
Finally, scrolling messages (derived from Controllers.PollSectionMsg or Controllers.ScrollMsg) may ask for shallow handling (~msg.focus), i.e., supression of forwarding to a possibly existing subfocus. This is generically handled by clearing focus on return in these cases.
Post
(msg IS Controllers.PollSectionMsg) OR (msg IS Controllers.ScrollMsg)
~msg.focus
focus = NIL
TYPE Controller (Controllers.Controller)
ABSTRACT
Controllers for containers.
opts-: SET
Option set of controller; used to restrict controller functionality to defined subsets.
PROCEDURE (c: Controller) ThisView (): View
EXTENSIBLE
Return type is narrowed.
PROCEDURE (c: Controller) SetOpts (opts: SET)
NEW, EXTENSIBLE, Operation
Set the options of c. This is only an operation after a view has been installed, i.e., c.ThisView() # NIL, otherwise it is a simple assignment of opts to c.opts. Options 0..7 are used or reserved by BlackBox, the rest may be used by extensions.
Post
c.opts = opts
PROCEDURE (c: Controller) GetContextType (OUT type: Stores.TypeName)
NEW, ABSTRACT
Called by c.HandleCtrlMsg to fill in Controllers.PollOpsMsg.type.
PROCEDURE (c: Controller) GetValidOps (OUT valid: SET)
NEW, ABSTRACT
Called by c.HandleCtrlMsg to fill in Controllers.PollOpsMsg.ops.
PROCEDURE (c: Controller) NativeModel (m: Models.Model): BOOLEAN
NEW, ABSTRACT
Check whether m is a native model of c, i.e., a model that could be attached to a view attachable to c.
PROCEDURE (c: Controller) NativeView (v: Views.View): BOOLEAN
NEW, ABSTRACT
Check whether v is a native view of c, i.e., a view that could be attached to c.
PROCEDURE (c: Controller) NativeCursorAt (f: Views.Frame; x, y: INTEGER): INTEGER
NEW, ABSTRACT
The cursor that c would display in f at point (x, y), irrespective of possible embedded views at that position.
PROCEDURE (c: Controller) PickNativeProp (f: Views.Frame; x, y: INTEGER;
VAR p: Properties.Property)
NEW, EMPTY
The properties of c's native contents in f at point (x, y), irrespective of possible embedded views at that position.
PROCEDURE (c: Controller) PollNativeProp (selection: BOOLEAN;
VAR p: Properties.Property; VAR truncated: BOOLEAN);
NEW, EMPTY
The properties of c's native selected or whole contents, irrespective of possible embedded views in that range.
PROCEDURE (c: Controller) SetNativeProp (selection: BOOLEAN; old, p: Properties.Property)
NEW, EMPTY
Set the properties of c's native selected or whole contents to p, irrespective of possible embedded views in that range. For properties also in old change only those property values of c that match the ones given in old. This allows for masked modification of properties. For example, in a colored model, all red objects could be changed to become green.
PROCEDURE (c: Controller) MakeViewVisible (v: Views.View)
NEW, EMPTY
Make the embedded view v visible in the controller's view.
Pre
v is embedded in c's view 20
PROCEDURE (c: Controller) GetFirstView (selection: BOOLEAN; OUT v: Views.View)
NEW, ABSTRACT
Get the first view embedded in c's model, relative to the model's start or that of a possible selection.
PROCEDURE (c: Controller) GetNextView (selection: BOOLEAN; VAR v: Views.View)
NEW, ABSTRACT
Get the next view in the specified range, which is either the selected or the whole contents of c's model. The next view of the last view in the range is NIL.
PROCEDURE (c: Controller) GetPrevView (selection: BOOLEAN; VAR v: Views.View)
NEW, EXTENSIBLE
Get the previous view in the specified range, which is either the selected or the whole contents of c's model. The default uses GetFirstView and GetNextView to seek the previous view of v. The previous view of the first view in the range is NIL.
Pre
v # NIL 20
EmbeddedIn(v, c.ThisModel()) 21
PROCEDURE (c: Controller) CanDrop (f: Views.Frame; x, y: INTEGER): BOOLEAN
NEW, EXTENSIBLE
Return whether the material being dragged could be dropped into frame f at its local coordinate (x, y). The default is to accept any drop request, i.e., to return TRUE.
PROCEDURE (c: Controller) MarkDropTarget (src, dst: Views.Frame;
sx, sy, dx, dy, w, h, rx, ry: INTEGER;
type: Stores.TypeName;
isSingle, show: BOOLEAN)
NEW, EMPTY
Mark the drop target in destination frame dst at point (dx, dy) for a potential dropping of material from source frame src, origin (sx, sy). show determines whether the mark should be drawn or removed. isSingle determines whether the selection to be dropped is a singleton. show indicates whether the mark should be shown or removed. (rx, ry) is the reference point inside the selection, where the drag & drop operation has started. See also Controllers.PollDropMsg.
PROCEDURE (c: Controller) Drop (src, dst: Views.Frame; sx, sy, dx, dy, w, h, rx, ry: INTEGER;
view: Views.View; isSingle: BOOLEAN)
NEW, ABSTRACT
Drop the material being dragged from source frame src, origin (sx, sy) and encapsulated in view under control of c in destination frame dst at point (dx, dy). The default is to ignore the drop. isSingle determines whether the selection to be dropped is a singleton. (rx, ry) is the reference point inside the selection, where the drag & drop operation has started. See also Controllers.DropMsg.
PROCEDURE (c: Controller) MarkPickTarget (src, dst: Views.Frame; sx, sy, dx, dy: INTEGER; show: BOOLEAN)
NEW, EMPTY
Mark the drop target in destination frame dst at point (dx, dy) for a potential dropping of material from source frame src, origin (sx, sy). show determines whether the mark should be drawn or removed. The default is not to mark at all.
PROCEDURE (c: Controller) TrackMarks (f: Views.Frame; x, y: INTEGER; units, extend, add: BOOLEAN)
NEW, ABSTRACT
Track marks in frame f starting at point (x, y) as specified by units, extend, and add. Marks are general selections and insertion points (carets). Tracking of larger logical units (e.g., words instead of characters) is requested by units. Continuous extension of an existing selection is requested by extend. Discontinuous addition to an existing selection is requested by add.
Some controllers may ignore one or the other request, e.g., may not distinguish units of varying granularity, may not support multiple selected objects, or may not support discontinuous selections.
PROCEDURE (c: Controller) Resize (view: Views.View; l, t, r, b: INTEGER)
NEW, ABSTRACT
Request to resize view, which must be embedded in c's model, to the size given by rectangle (l, t, r, b).
(Typically, a controller delegates this request to its model which implements the request by using Properties.PreferredSize to negotiate the new size with view.)
PROCEDURE (c: Controller) GetSelectionBounds (f: Views.Frame; OUT x, y, w, h: INTEGER)
NEW, ABSTRACT
Return the bounding box of the selection, by giving its top-left reference point and its width and height. The bounding box is used for giving drag & drop feedback.
PROCEDURE (c: Controller) DeleteSelection
NEW, ABSTRACT
Delete all objects in the current selection.
PROCEDURE (c: Controller) MoveLocalSelection (src, dst: Views.Frame; sx, sy, dx, dy: INTEGER)
NEW, ABSTRACT
Move selected objects within the model of c from the origin given by source frame src and point (sx, sy) to the target given by destination frame dst and point (dx, dy). Since this is a move of material within a single model, there is no need for conversions, and the most "natural" moving semantics can be provided.
PROCEDURE (c: Controller) CopyLocalSelection (src, dst: Views.Frame; sx, sy, dx, dy: INTEGER)
NEW, ABSTRACT
Copy selected objects within the model of c from the origin given by source frame src and point (sx, sy) to the target given by destination frame dst and point (dx, dy). Since this is a copy of material within a single model, there is no need for conversions, and the most "natural" copying semantics can be provided.
PROCEDURE (c: Controller) SelectionCopy (): Model
NEW, ABSTRACT
Return a copy of the selected objects, encapsulated in the returned model.
PROCEDURE (c: Controller) NativePaste (m: Models.Model; f: Views.Frame)
NEW, ABSTRACT
Paste a native model into the model of c as displayed in frame f. Since the model is native, it is to be merged into the model of c rather than wrapped into a view and embedded.
PROCEDURE (c: Controller) ArrowChar (f: Views.Frame; ch: CHAR; units, select: BOOLEAN)
NEW, ABSTRACT
Interpret the arrow character ch, i.e., one out of the following list. The interpretation is to be modified as requested by units and select. The standard interpretation of arrow characters is the modification of the current selection or the moving of the insertion point. Modifying or moving in larger units (e.g., words instead of characters) is requested by units. Establishment of a selection if requested by select.
Some controllers may ignore one or the other request, e.g., may not distinguish units of varying granularity or may not support selections.
Table of arrow characters:
name code meaning
aL 1CX arrow left
aR 1DX arrow right
aU 1EX arrow up
aD 1FX arrow down
pL 10X page left
pR 11X page right
pU 12X page up
pD 13X page down
dL 14X document left
dR 15X document right
dU 16X document up
dD 17X document down
The intention is a modification or move in the indicated direction on the smallest supported granularity ("arrow"), on the basis of "pages" as defined by the size of frame f, or on the basis of the whole "document", i.e., the far extremes of the model of c. The precise interpretation of the directions and units is left to the specific controller.
PROCEDURE (c: Controller) ControlChar (f: Views.Frame; ch: CHAR)
NEW, ABSTRACT
Handle entry of control character ch related to the model and view of c as displayed in frame f.
Table of control characters:
name code meaning
enter 3X enter
rdel 7X right delete
del 8X left delete
tab 09X tabulator
ltab 0AX reverse tabulator
line 0DX line
para 0EX paragraph
esc 1BX escape
PROCEDURE (c: Controller) PasteChar (ch: CHAR)
NEW, ABSTRACT
Paste character ch into the model of c.
PROCEDURE (c: Controller) PasteView (f: Views.Frame; v: Views.View; w, h: INTEGER)
NEW, ABSTRACT
Paste view v with desired size (w, h) into the model of c.
(Typically, a controller delegates this request to its model which implements the request by using Properties.PreferredSize to negotiate the new size with v.)
PROCEDURE (c: Controller) HasSelection (): BOOLEAN
NEW, EXTENSIBLE
Return whether the controller currently has a selection. By default, only singleton selections are supported. To be extended to include intrinsic selections.
Pre
c.ThisModel() # NIL 20
PROCEDURE (c: Controller) Selectable (): BOOLEAN
NEW, ABSTRACT
Return whether the controller could establish a nonempty selection. If something (or everything) is already selected, this is considered selectable.
PROCEDURE (c: Controller) Singleton (): Views.View
NEW
If the controller currently has a singleton selection, then the selected view is returned, else NIL.
PROCEDURE (c: Controller) SetSingleton (s: Views.View)
NEW, EXTENSIBLE
Set the controller's selection to a singleton selection covering view s. IF s = NIL, the current singleton selection is cleared. Needs to be extended to adjust intrinsic selection state accordingly.
Pre
c.ThisModel() # NIL 20
~(noSelection IN c.opts) 21
s # NIL
s.context # NIL 22
s.context.ThisModel() = c.ThisModel() 23
Post
c.Singleton() = s
PROCEDURE (c: Controller) SelectAll (select: BOOLEAN)
NEW, ABSTRACT
Set the selection to its maximum extent, i.e., select all intrinsic content of the controller's model plus all embedded views. For an empty model there is no visible result; for a model with only one embedded view and no intrinsic contents a singleton selection results.
PROCEDURE (c: Controller) InSelection (f: Views.Frame; x, y: INTEGER): BOOLEAN
NEW, ABSTRACT
Test whether in frame f the point (x, y) lies within the current selection.
PROCEDURE (c: Controller) MarkSelection (f: Views.Frame; show: BOOLEAN)
NEW, EXTENSIBLE
Depending on show, show or hide the selection's visual marking. The default handles singleton selections only. To be replaced to include intrinsic selections.
PROCEDURE (c: Controller) SetFocus (focus: Views.View)
NEW
Sets the current subfocus to focus; if focus = NIL, the current subfocus is removed.
Pre
c.ThisModel() # NIL 20
focus # NIL
focus.context # NIL 21
focus.context.ThisModel() = c.ThisModel() 22
Post
c.ThisFocus() = focus
PROCEDURE (c: Controller) HasCaret (): BOOLEAN
NEW, ABSTRACT
Return whether the controller has a valid caret (insertion point).
PROCEDURE (c: Controller) MarkCaret (f: Views.Frame; show: BOOLEAN)
NEW, ABSTRACT
Depending on show, show or hide the current caret's visual marking.
PROCEDURE (c: Controller) Mark (f: Views.Frame; l, t, r, b: INTEGER; show: BOOLEAN)
NEW, EXTENSIBLE
Except for performance, equivalent to:
MarkFocus(c, f, show); c.MarkSelection(f, show); c.MarkCaret(f, show)
To be extended to cover additional intrinsic marking.
PROCEDURE (c: Controller) RestoreMarks (f: Views.Frame; l, t, r, b: INTEGER)
Clarification of inherited procedure
Calls Mark to show all marks in (l, t, r, b), then, if no subfocus exists and c.opts indicates mask mode, tries to establish a subfocus: the first embedded view that wants to claim the focus (Properties.FocusPref.setFocus) gets it. If the new subfocus wants to start off with an initially selected contents (Properties.FocusPref.selectOnFocus), it is also fully selected.
PROCEDURE (c: Controller) Neutralize
Clarification of inherited procedure
Remove all modal marks, including focus, selection, and caret. The default handles focus and selection. To be extended to handle caret and possibly further marks.
Except for performance, the default is equivalent to:
c.SetFocus(NIL); c.SelectAll(deselect)
PROCEDURE (c: Controller) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message;
VAR focus: Views.View)
Clarification of inherited procedure
Handles Controllers.PollCursorMsg, Controllers.PollOpsMsg, Controllers.TrackMsg, Controllers.EditMsg, Controllers.TransferMessage, Controllers.SelectMsg, Controllers.MarkMsg, Controllers.ReplaceViewMsg, Properties.CollectMsg, and Properties.EmitMsg.
PROCEDURE (c: Controller) HandlePropMsg (VAR p: Properties.Message)
Clarification of inherited procedure
The default is to handle Properties.SetMsg and Properties.PollMsg by splitting the handling of native and embedded properties and set or return the combined property list. Also, unless noSelection, noFocus, and noCaret are set in c.opts, field Properties.FocusPref.setFocus is set.
Pre
c.ThisModel() # NIL 20
TYPE Directory
ABSTRACT
Directory for controllers.
PROCEDURE (d: Directory) New (): Controller
NEW, EXTENSIBLE
Except for performance, equivalent to:
RETURN d.NewController({})
PROCEDURE (d: Directory) NewController (opts: SET): Controller
NEW, ABSTRACT
Return new controller with options opts.
TYPE DropPref = RECORD (Properties.Preference)
This message is sent to a contained view in a container when the container needs to decide if something should be dropped into the view or into the container. This message can be intercepted to allow drag and drop also when the container itself normally would catch the drop messages, i.e. when the container is in layout mode.
mode-: SET
The current mode of the container.
okToDrop: BOOLEAN
Set to TRUE if the view should recieve drop messages also in the mode given by mode.
TYPE GetOpts = RECORD (Views.PropMessage)
This message is sent to a selected view to ask about the container mode of this view. If a view answers this message it should set valid to the options that apply to the view and opts to the current values of these options. Whenever GetOpts is answered the SetOpts-message must also be answered.
valid: SET
Should be set to the options that apply to the view.
opts: SET
Current values of the options pointed out in valid.
TYPE SetOpts = RECORD (Views.PropMessage)
Sent to a view to indicate that its options should be changed to the values indicated by valid and opts.
valid: SET
Mask to indicate which values should be set.
opts: SET
Values of the options indicated by valid.
PROCEDURE Focus (): Controller
Returns the current focus view's container controller, if possible.
PROCEDURE FocusSingleton (): Views.View
Returns the current focus view's singleton selection, if possible.
PROCEDURE MarkSingleton (c: Controller; f: Views.Frame; show: BOOLEAN)
Used internally.
PROCEDURE FadeMarks (c: Controller; show: BOOLEAN)
Used internally.
| System/Docu/Containers.odc |
Controllers
DEFINITION Controllers;
IMPORT Fonts, Ports, Stores, Views;
CONST
frontPath = FALSE; targetPath = TRUE;
decLine = 0; incLine = 1; decPage = 2; incPage = 3; gotoPos = 4;
nextPageX = 0; nextPageY = 0; gotoPageX = 2; gotoPageY = 3;
cut = 0; copy = 1; pasteChar = 2; paste = 4;
doubleClick = 0; extend = 1; modify = 2; popup = 3; pick = 4;
noMark = FALSE; mark = TRUE;
hide = FALSE; show = TRUE;
TYPE
Controller = POINTER TO ABSTRACT RECORD (Stores.Store) END;
Directory = POINTER TO ABSTRACT RECORD
(d: Directory) New (): Controller, NEW, ABSTRACT
END;
Forwarder = POINTER TO ABSTRACT RECORD
(n: Forwarder) Forward (target: BOOLEAN; VAR msg: Message), NEW, ABSTRACT;
(n: Forwarder) Transfer (VAR msg: TransferMessage), NEW, ABSTRACT
END;
Message = Views.CtrlMessage;
PollFocusMsg = EXTENSIBLE RECORD (Message)
focus: Views.Frame
END;
PollSectionMsg = RECORD (Message)
focus, vertical: BOOLEAN
wholeSize, partSize, partPos: LONGINT;
valid, done: BOOLEAN
END;
PollOpsMsg = RECORD (Message)
type: Stores.TypeName;
pasteType: Stores.TypeName;
singleton: Views.View;
selectable: BOOLEAN;
valid: SET
END;
ScrollMsg = RECORD (Message)
focus, vertical: BOOLEAN
op: INTEGER;
pos: LONGINT;
done: BOOLEAN
END;
PageMsg = RECORD (Message)
op: INTEGER;
pageX, pageY: INTEGER;
done, eox, eoy: BOOLEAN
END;
TickMsg = RECORD (Message)
tick: INTEGER
END;
MarkMsg = RECORD (Message)
show, focus: BOOLEAN
END;
SelectMsg = RECORD (Message)
set: BOOLEAN
END;
RequestMessage = ABSTRACT RECORD (Message)
requestFocus: BOOLEAN
END;
EditMsg = RECORD (RequestMessage)
op: INTEGER;
modifiers: SET;
char: CHAR;
view: Views.View;
w, h: INTEGER;
isSingle: BOOLEAN;
clipboard: BOOLEAN
END;
ReplaceViewMsg = RECORD (RequestMessage)
old, new: Views.View
END;
CursorMessage = ABSTRACT RECORD (RequestMessage)
x, y: INTEGER
END;
PollCursorMsg = RECORD (CursorMessage)
cursor: INTEGER;
modifiers: SET
END;
TrackMsg = RECORD (CursorMessage)
modifiers: SET
END;
WheelMsg = RECORD (CursorMessage)
done: BOOLEAN;
op, nofLines: INTEGER
END;
TransferMessage = ABSTRACT RECORD (CursorMessage)
source: Views.Frame;
sourceX, sourceY: INTEGER
END;
PollDropMsg = RECORD (TransferMessage)
mark: BOOLEAN;
show: BOOLEAN;
type: Stores.TypeName;
isSingle: BOOLEAN;
w, h: INTEGER;
rx, ry: INTEGER;
dest: Views.Frame
END;
DropMsg = RECORD (CursorMessage)
view: Views.View;
isSingle: BOOLEAN;
w, h: INTEGER;
rx, ry: INTEGER
END;
VAR path-: BOOLEAN;
PROCEDURE Forward (VAR msg: Message);
PROCEDURE FocusFrame (): Views.Frame;
PROCEDURE FocusView (): Views.View;
PROCEDURE FocusModel (): Models.Model;
PROCEDURE Register (f: Forwarder);
PROCEDURE Delete (f: Forwarder);
PROCEDURE ForwardVia (target: BOOLEAN; VAR msg: Message);
PROCEDURE SetCurrentPath (target: BOOLEAN);
PROCEDURE ResetCurrentPath;
PROCEDURE PollSection (VAR msg: PollSectionMsg);
PROCEDURE PollOps (VAR msg: PollOpsMsg);
PROCEDURE PollCursor (x, y: INTEGER; OUT cursor: INTEGER);
PROCEDURE Transfer (x, y: INTEGER; source: Views.Frame; sourceX, sourceY: INTEGER;
VAR msg: TransferMessage);
PROCEDURE PollDrop (x, y: INTEGER; source: Views.Frame; sourceX, sourceY: INTEGER;
mark, show: BOOLEAN; type: Stores.TypeName; isSingle: BOOLEAN;
w, h, rx, ry: INTEGER; OUT dest: Views.Frame; OUT destX, destY: INTEGER);
PROCEDURE Drop (x, y: INTEGER; source: Views.Frame; sourceX, sourceY: INTEGER;
view: Views.View; isSingle: BOOLEAN; w, h, rx, ry: INTEGER);
PROCEDURE PasteView (view: Views.View; w, h: INTEGER; clipboard: BOOLEAN);
END Controllers.
Figure 1. Model-View-Controller Separation
A controller implements the interactive behavior for a view class. It is an object which transforms controller messages into model or view transformations.
A controller message is a message which is sent along exactly one path in a view hierarchy, the focus path. Every view on such a path decides for itself whether it is the terminal of this path, i.e., whether it is the current focus, or whether the message should be forwarded to one of its embedded views. BlackBox supports two focus paths, namely a target and a front focus. Both paths may fall together into one. The target path defines which view is the target of commands in dialogs. The front path defines which view is being edited, via mouse, keyboard, or menus.
Figure 2. Simplified Example of Focus Hierarchy
It is important to note that all controller messages which are not relevant for a particular view type can simply be ignored.
CONST frontPath
This value may be passed as target parameter to several procedures of this module. It lets a focus message be sent along the front focus path.
CONST targetPath
This value may be passed as target parameter to several procedures of this module. It lets a controller message be sent along the target focus path.
CONST decLine, incLine, decPage, incPage
These values can be assigned to the ScrollMsg.op field. They will cause the receiver view to scroll by increments or decrements of one line or page. It is up to the receiver to define what constitutes a "line" in its model, except that it should be smaller than a page. A page should correspond to the width/height of the focus frame.
CONST gotoPos
This value can be assigned to the ScrollMsg.op field. It causes the receiver view to scroll to the position given by ScrollMsg.pos.
CONST nextPageX, nextPageY
This value can be assigned to the PageMsg.op field. It causes the receiver view to display the next page in x resp. in y direction.
CONST gotoPageX, gotoPageY
This value can be assigned to the PageMsg.op field. It causes the receiver view to display a given page in x resp. in y direction.
CONST cut, copy
These values can be assigned to the EditMsg.op field. They should be handled by the receiver view in the following way:
• cut delete selection, and assign a new view containing the deleted data or a copy thereof to EditMsg.view
• copy copy selection, and assign a new view containing the copied data to EditMsg.view
CONST pasteChar
This value can be assigned to the EditMsg.op field. It denotes the input of some (Unicode or Latin-1) character.
CONST paste
This value can be assigned to the EditMsg.op field. The receiver view should insert a copy of the data that EditMsg.view contains. If it cannot insert the data directly because it doesn't know its type, it should insert a copy of the whole EditMsg.view into its model if it has this capability, i.e., if it is a container.
CONST doubleClick, extend, modify, popup, pick
BlackBox abstracts from the details of the pointing device (usually a mouse) and keyboard layout by passing information about special kinds of mouse clicks and mouse/key combinations as platform independent modifiers. For the mapping of platform specific keys see platform specific modifiers. Modifier sets are used in Controllers.TrackMsg, Controllers.EditMsg, and Ports.Frame.Input.
doubleClick means that a mouse button has been pressed in a way which is interpreted by the underlying user interface as a "double click".
extend is used to extend or toggle selections (usually by pressing the Shift key).
modify is used to change the default behavior of a command, for example to change a drag-and-move into a drag-and-copy (usually by pressing the Ctrl key).
popup means that a mouse button has been pressed in a way which is intended for showing a popup menu (usually by pressing the right mouse button if a multi-button mouse is available).
pick means that a mouse button has been pressed in a way which is intended for drag-and-pick (usually by pressing the middle mouse button if a three-button mouse is available, or by pressing the Alt key).
CONST noMark, mark
Used internally.
CONST hide, show
These constants may be used for the PollDropMsg message and the PollDrop procedure. They determine whether target feedback during drag & drop should be drawn (show) or removed (hide).
TYPE Controller (Stores.Store)
ABSTRACT
A controller is the third component of the model-view-controller triple. Its main purpose is to translate controller messages into model or view transformations. Simple applications can implement the controller's functionality in the view itself, thus needing no separate controller object at all. Container views usually have a separate controller.
TYPE Directory
ABSTRACT
Usually there is a controller directory in the views module of a subsystem, since the view directory must be able to allocate an appropriate controller. Such a directory is installed by the corresponding controller module upon loading. To guarantee the loading of the corresponding controller module is loaded, the view module's body usually contains a statement of the form Dialog.Call("XYZControllers.Install, "", res).
PROCEDURE (d: Directory) New (): Controller
NEW, ABSTRACT
Returns a new controller.
Post
result # NIL
result.ThisView() = NIL
TYPE Forwarder
ABSTRACT
Used internally.
PROCEDURE (n: Forwarder) Forward (target: BOOLEAN; VAR msg: Message)
NEW, ABSTRACT
Used internally.
PROCEDURE (n: Forwarder) Transfer (VAR msg: TransferMsg)
NEW, ABSTRACT
Used internally
TYPE Message
ABSTRACT
Base type of all controller messages. In contrast to model and view messages, a controller message is never broadcast. Instead, it is passed along a focus path. The target and front focus paths are predefined.
TYPE PollFocusMsg (Message)
EXTENSIBLE
This message is sent to find out the leaf view of a focus path. The message is handled by the framework itself. If your view should not give away its identity when it is focus, set focus to NIL when receiving the message. Otherwise ignore the message.
focus: Views.Frame
After the message returns from the traversal of a focus path, it should contain the frame of the leaf view of this path.
TYPE PollSectionMsg (Message)
This message is sent to poll the focus view's current scroll state. BlackBox contains a generic scrolling mechanism which scrolls simply by changing the scrolled frame's origin. Explicit handling of scrolling is only necessary for views which can become extremely large, and whose efficient implementation crucially depends on keeping frames small.
focus: BOOLEAN
This flag tells whether a container should forward the message to its focus or not. Non-containers obviously cannot forward to a focus.
vertical: BOOLEAN
Tells whether the vertical or horizontal direction is polled.
wholeSize: INTEGER wholeSize >= 1
This value denotes the focus view's width or height, in coordinates which a view can freely choose, i.e., they need not necessarily be universal units.
partSize: INTEGER 0 <= partSize <= wholeSize
This value denotes the focus view frame's width or height, in the same coordinates as above. If partSize cannot be easily defined, it should be set to 0.
partPos: INTEGER 0 <= partPos <= wholeSize - partSize
This value denotes the focus view's origin, in the same coordinates as above.
valid: BOOLEAN
The receiving view should set this flag if it supports scrolling in the given direction. valid indicates that wholeSize, partSize, and partPos are valid indicators of the view's scroll position.
done: BOOLEAN
This flag should be set if the message has been interpreted, i.e., if the above output fields have been set. For some controllers this may depend on vertical, i.e., the controller only supports one scrolling direction.
TYPE PollOpsMsg (Message)
This message is sent to inquire which editing operations the focus view supports, depending on its current selection.
type: Stores.TypeName
This field denotes a context for the focus view. This context is used to determine which menus are relevant for the focus view. As a convention, a view assigns the type name of its abstract base pointer type to type, e.g., "TextViews.View". This convention guarantees globally unique context names, since module names are considered globally unique. If the view doesn't support any such context, ignore this field.
pasteType: Stores.TypeName valid iff type = paste
The type of the view of which a copy would be pasted, if a paste operation occurred.
singleton: Views.View
A container view which supports a selection should set this field to the selected view, if this view is the only contents currently selected.
selectable: BOOLEAN
This field should be set to TRUE if the focus view contains selectable elements, independent of whether they are currently selected or not.
valid: SET valid IN {cut, copy, paste}
This set denotes which edit operations are currently possible, out of the set {cut, copy, paste}. It is used by the framework to enable or disable the appropriate menu items. However, there is no guarantee that the framework will not send an edit message for cut/copy/paste even if the view returns an empty set in valid. Such a message can simply be ignored.
TYPE ScrollMsg (Message)
This message is sent in order to let the focus view scroll to another position. It is used only in conjunction with PollSectionMsg (cf. above).
focus: BOOLEAN
This flag tells whether a container should forward the message to its focus or not. Non-containers obviously cannot forward to a focus.
vertical: BOOLEAN
Denotes whether scrolling should occur in the vertical or in the horizontal direction.
op: INTEGER op IN {decLine..gotoPos}
Scroll operation to be performed.
pos: INTEGER valid iff op = gotoPos pos >= 0
This denotes the position to be scrolled to, in the same coordinates that the PollSectionMsg uses.
done: BOOLEAN
This flag should be set if the message has been interpreted; for some controllers, this may depend on op.
TYPE PageMsg (Message)
A page message is similar to a scroll message, but its measures are in pages. It can be interpreted if the view should behave differently depending whether it is being printed or not. This is done e.g. in TextViews to avoid the last line on a page to become clipped, which is acceptable on screen.
If this message is not interpreted for a view which cannot be printed on one page, a default printing strategy is used which decomposes the view into suitable pieces for printing.
op: INTEGER op IN {nextPageX, nextPageY, gotoPageX, gotoPageY}
Where to scroll to.
pageX, pageY: INTEGER
Current page in x and in y directions.
done: BOOLEAN
This flag should be set if the message has been interpreted; for some controllers, this may depend on op.
eox, eoy: BOOLEAN
These flags should be set when it is attempted to go beyond the last page in the x resp. in y direction.
TYPE TickMsg (Message)
This message is sent to the front focus view periodically. It can be used to realize effects like a blinking caret.
tick: INTEGER
Tick count. The difference between two ticks is given by the global variable resolution.
TYPE MarkMsg (Message)
This message is sent whenever the target or front focus paths change. Before the change, the message is sent along the focus path with show = FALSE, such that the focus view can switch off visible marks like the selection or the caret. After the change (e.g., another window coming to the top), a MarkMsg is sent along the focus path with show = TRUE, such that the focus view can switch on its marks again, if there are any.
Behavior can be different if the focus path changes due to window reordering or due to user interaction (a user clicking in some other embedded view).
In the former case, a focused view may still keep its focus state (selection, caret), even while it is temporarily in a non-focus window. When the window becomes focus again, the old focus view becomes focus again. In this case, it should show the same selection/caret state again.
In the latter case, a view that becomes newly focused may behave in a special way. In particular, a control may focus its contents (e.g., a text field may select the entire text string that it contains). To detect such a situation, a field focus is provided in the MarkMsg.
Wrapper views and special container views (i.e., containers not derived from the types in module Containers) have to forward the MarkMsg to their embedded views.
show: BOOLEAN
Tells whether the focus view's marks should be switched on or off.
focus: BOOLEAN
Tells whether the view is being focused or defocused.
A view may use this information e.g. to select itself upon becoming focus (this is done by text field controls). This is done in the following way:
IF msg.focus THEN
IF msg.show THEN (* set selection on focus *)
... select contents of view ...
ELSE (* remove selection on defocus *)
... remove selection ...
END
END
TYPE SelectMsg (Message)
This message is sent when the focus view should select all selectable items, or when it should deselect all selected items. Selection occurs e.g. when the Edit->Select All command is executed.
set: BOOLEAN
Determines whether everything should be selected (set = TRUE) or whether everything should be deselected (set = FALSE).
TYPE RequestMessage (Message)
ABSTRACT
A view (or its controller) receiving a request message can indicate, by setting requestFocus to TRUE, that it wants to become focus afterwards, if it isn't already.
requestFocus: BOOLEAN
Set this flag to TRUE if receiver should become/remain focus after the message has been handled.
TYPE EditMsg (RequestMessage)
This message is sent when a key was pressed, or when a cut/copy/paste operation was invoked. The following operations can be supported (for every supported operation except pasting of characters, the corresponding flag in PollOpsMsg.valid should be set when receiving a PollOpsMsg):
• cut
Create a clone of the focus view, with a copy of its selection as contents. Assign this clone to EditMsg.view and delete the focus' selection. There is one exception: if the selection consists of exactly one view (a singleton), this view's clone should be copied to EditMsg.view, not a clone of its container.
• copy
Create a clone of the focus view, with a copy of the focus' selection as contents. Assign this clone to EditMsg.view. If the selection consists of exactly one view (a singleton), this view's clone should be copied to EditMsg.view.
• pasteChar
Interpret EditMsg.char, e.g., insert it into a text model.
char may be a control character. For control characters, check field modifiers also.
• paste
Insert EditMsg.view view into the focus view's contents.
If the receiver is a container:
If EditMsg.isSingle:
It should insert the view as a complete view, independent of its type.
This means that merging of contents is not permitted, even if this were possible.
If ~EditMsg.isSingle:
If it knows the contents of EditMsg.view, it should insert it, otherwise the complete view.
If the receiver is not a container:
If it knows the contents of EditMsg.view, it should insert it, otherwise it should do nothing.
op: INTEGER op IN {cut .. paste}
Operation to be performed.
modifiers: SET valid iff op= pasteChar
Modifier keys. For the mapping of platform specific keys see platform specific modifiers.
char: CHAR valid iff op = pasteChar
Character to be pasted, or to be interpreted in the case of control characters.
view: Views.View valid iff op IN {paste, cut, copy} & view # NIL & view.context = NIL
If op = paste: (IN parameter)
View which should be pasted.
If op IN {cut, copy}: (OUT parameter)
View which should be assigned by the message handler.
w, h: INTEGER valid iff op IN {paste, cut, copy}
w >= Views.undefined & h >= Views.undefined [units]
If op = paste: (IN parameter)
The desired width and height of the pasted view. These values can be treated as hints. If they are not suitable, others can be used. The value Views.undefined should be handled also.
If op IN {cut, copy}: (OUT parameter)
Current width and height of the view.
isSingle: BOOLEAN valid iff op IN {paste, cut, copy}
If op = paste: (IN parameter)
Tells whether the pasted view should be inserted as singleton, i.e., not be merged even if this were possible.
If op IN {cut, copy}: (OUT parameter)
The message handler should set this flag if the cut/copied view is selected as a singleton.
clipboard: BOOLEAN valid iff op IN {cut, copy, paste}
This input parameter tells whether the cut/copied view will be transferred to the system clipboard, or whether the pasted view comes from the system clipboard.
TYPE ReplaceViewMsg (RequestMessage)
A container should check whether it contains old. If so, it should replace old by new, without modifying the view's context in any way.
old, new: Views.View old # NIL & new # NIL
old should be replaced by new.
TYPE CursorMessage (RequestMessage)
ABSTRACT
The base type of all messages which denote some interaction that depends on the current cursor position. The cursor position is always measured in units relative to the view's top-left corner.
x, y: INTEGER [units]
Current cursor position.
TYPE PollCursorMsg (CursorMessage)
This message is sent regularly to inquire which cursor the focus view currently desires.
cursor: INTEGER cursor IN {Ports.arrowCursor .. Ports.refCursor}
This field can be set to the cursor appropriate for the focus view.
modifiers: SET
This is an input field that gives the current modifer state of the mouse.
TYPE TrackMsg (CursorMessage)
Extension
This message is sent when the mouse button is pressed down.
modifiers: SET
Determines which modifier keys have been pressed together with the mouse button. For the mapping of platform specific keys see platform specific modifiers.
TYPE WheelMsg (CursorMessage)
Extension
This message is sent when the wheel on a wheel mouse is rolled.
done: BOOLEAN
If a view handles this message it must set the done flag to TRUE.
op: INTEGER
Indicates which kind of event the mouse wheel caused. The same constants as for scrolling are used, but only the following values are valid: incPage, decPage, incLine and decLine.
nofLines: INTEGER nofLines >= 1
If op is either incLine or decLine then nofLines indicates how many lines should be scrolled. For incPage and decPage this value is undefined.
TYPE TransferMessage (CursorMessage)
ABSTRACT
This is the base type of all messages which denote an interaction between several views, e.g., for drag and drop.
source: Views.Frame
The frame from which the interaction started, e.g., where the mouse button has been clicked for dragging.
sourceX, sourceY: INTEGER
The position in the source frame where the mouse button has been clicked, e.g., when starting to drag.
TYPE PollDropMsg (TransferMessage)
While an item is being dragged around, PollDropMsgs are sent to enable feedback about the drop target.
mark: BOOLEAN
A container which supports drop feedback should show (hide) its feedback mark when mark is set (cleared). You don't need to deal with the view's border mark (the rectangular outline of the view which is drawn while you are dragging over a view), this is handled completely by BlackBox itself.
show: BOOLEAN valid iff mark
Indicates whether the mark should be drawn or removed.
type: Stores.TypeName
The type of the view to be dropped. The same naming convention as for the PollOpsMsg is used. Based on type, the message handler can determine whether the view to be dropped can be accepted. Note that if drag & drop happens completely within BlackBox, the inherited message field source may also be used for this test. However, source may be NIL if OLE drag & drop occurs.
isSingle: BOOLEAN
Tells whether the view to be dropped is a singleton selection.
w, h: INTEGER
Size of the view to be dropped. May be equal to Views.undefined.
rx, ry: INTEGER rx >= 0 & ry >= 0
The reference point inside the selection where drag & drop started.
dest: Views.Frame (OUT parameter)
The receiver should set dest to its own frame, if it would accept a drop.
TYPE DropMsg (CursorMessage)
This message is used if a view should be dragged and dropped to the cursor location.
view: Views.View view # NIL
The view which is dropped. It is a copy of the original, and ready to be inserted at the drop destination.
isSingle: BOOLEAN
Tells whether the view to be dropped is a singleton selection.
w, h: INTEGER [units]
The size of the dropped view. One or both sizes may have the value Views.undefined.
rx, ry: INTEGER
The reference point inside the selection where drag & drop started.
VAR path-: BOOLEAN
The currently set path, either frontPath or targetPath. The path is set and reset by SetCurrentPath and ResetCurrentPath.
PROCEDURE Forward (VAR msg: Message)
Send msg to to current focus.
PROCEDURE FocusFrame (): Views.Frame
Returns the current focus frame, if there is any.
PROCEDURE FocusView (): Views.View
Returns the current focus view, if there is any.
PROCEDURE FocusModel (): Models.Model
Returns the current focus view's model, if there is any.
The following procedures are used internally:
PROCEDURE Register (f: Forwarder)
Add forwarder f to the list of forwarders. If f is already registered, Register(f) does nothing.
Pre
f # NIL 20
PROCEDURE Delete (f: Forwarder)
Remove f from the list of forwarders. If f is not registered, nothing happens.
Pre
f # NIL 20
PROCEDURE ForwardVia (target: BOOLEAN; VAR msg: Views.CtrlMessage)
Send msg to either target or front focus.
PROCEDURE SetCurrentPath (target: BOOLEAN)
Set path to target and push the previous path value onto a stack. Must be balanced by a call to ResetCurrentPath, otherwise a trap will occur (in Controllers.BalanceCheckAction.Do).
PROCEDURE ResetCurrentPath
Reset path to the value it had before the last call of SetCurrentPath. Calls of ResetCurrentPath must exactly balance the calls of SetCurrentPath.
PROCEDURE PollSection (VAR msg: PollSectionMsg)
Poll the current focus view's scroll state.
PROCEDURE PollOps (VAR msg: PollOpsMsg)
Poll the current focus view's currently valid editing operations.
PROCEDURE PollCursor (x, y: INTEGER; OUT cursor: INTEGER)
Poll the current focus view's currently desired cursor.
PROCEDURE Transfer (x, y: INTEGER; source: Views.Frame; sourceX, sourceY: INTEGER;
VAR msg: TransferMessage)
PROCEDURE PollDrop (x, y: INTEGER; source: Views.Frame; sourceX, sourceY: INTEGER;
mark, show: BOOLEAN; type: Stores.TypeName;
isSingle: BOOLEAN; w, h, rx, ry: INTEGER;
OUT dest: Views.Frame; OUT destX, destY: INTEGER)
PROCEDURE Drop (x, y: INTEGER; source: Views.Frame; sourceX, sourceY: INTEGER;
view: Views.View; isSingle: BOOLEAN; w, h, rx, ry: INTEGER)
PROCEDURE PasteView (view: Views.View; w, h: INTEGER; clipboard: BOOLEAN)
| System/Docu/Controllers.odc |
Controls
DEFINITION Controls;
IMPORT Meta, Dialog, Views, Properties;
CONST
opt0 = 0; opt1 = 1; opt2 = 2; opt3 = 3; opt4 = 4;
link = 5; label = 6; guard = 7; notifier = 8; level = 9;
default = opt0; cancel = opt1;
left = opt0; right = opt1; multiLine = opt2; password = opt3;
sorted = opt0;
haslines = opt1; hasbuttons = opt2; atroot = opt3; foldericons = opt4;
TYPE
Control = POINTER TO ABSTRACT RECORD (Views.View)
item-: Meta.Item;
disabled-, undef-, readOnly-, customFont-: BOOLEAN;
font-: Fonts.Font;
label-: Dialog.String;
prop-: Prop;
(c: Control) Internalize- (VAR rd: Stores.Reader);
(c: Control) Externalize- (VAR wr: Stores.Writer);
(c: Control) CopyFromSimpleView- (source: Views.View);
(c: Control) HandleViewMsg- (f: Views.Frame; VAR msg: Views.Message);
(c: Control) HandleCtrlMsg (f: Views.Frame; VAR msg: Views.CtrlMessage;
VAR focus: Views.View);
(c: Control) HandlePropMsg- (VAR msg: Views.PropMessage);
(c: Control) Internalize2- (VAR rd: Stores.Reader), NEW, EMPTY;
(c: Control) Externalize2- (VAR wr: Stores.Writer), NEW, EMPTY;
(c: Control) CopyFromSimpleView2- (source: Control), NEW, EMPTY;
(c: Control) HandleViewMsg2- (f: Views.Frame; VAR msg: Views.Message), NEW, EMPTY;
(c: Control) HandleCtrlMsg2- (f: Views.Frame; VAR msg: Views.CtrlMessage;
VAR focus: Views.View), NEW, EMPTY;
(c: Control) HandlePropMsg2- (VAR p: Views.PropMessage), NEW, EMPTY;
(c: Control) CheckLink- (VAR ok: BOOLEAN), NEW, EMPTY;
(c: Control) Update- (f: Views.Frame; op, from, to: INTEGER), NEW, EMPTY;
(c: Control) UpdateList- (f: Views.Frame), NEW, EMPTY
END;
Directory = POINTER TO ABSTRACT RECORD
(d: Directory) NewPushButton (p: Prop): Control, NEW, ABSTRACT;
(d: Directory) NewCheckBox (p: Prop): Control, NEW, ABSTRACT;
(d: Directory) NewRadioButton (p: Prop): Control, NEW, ABSTRACT;
(d: Directory) NewListBox (p: Prop): Control, NEW, ABSTRACT;
(d: Directory) NewSelectionBox (p: Prop): Control, NEW, ABSTRACT;
(d: Directory) NewField (p: Prop): Control, NEW, ABSTRACT;
(d: Directory) NewUpDownField (p: Prop): Control, NEW, ABSTRACT;
(d: Directory) NewDateField (p: Prop): Control, NEW, ABSTRACT;
(d: Directory) NewTimeField (p: Prop): Control, NEW, ABSTRACT;
(d: Directory) NewTreeControl (p: Prop): Control, NEW, ABSTRACT;
(d: Directory) NewColorField (p: Prop): Control, NEW, ABSTRACT;
(d: Directory) NewComboBox (p: Prop): Control, NEW, ABSTRACT;
(d: Directory) NewCaption (p: Prop): Control, NEW, ABSTRACT;
(d: Directory) NewGroup (p: Prop): Control, NEW, ABSTRACT
END;
Prop = POINTER TO RECORD (Properties.Property)
opt: ARRAY 5 OF BOOLEAN;
link, label, guard, notifier: Dialog.String;
level: INTEGER;
(p: Prop) IntersectWith (q: Properties.Property; OUT equal: BOOLEAN)
END;
DefaultsPref = RECORD (Properties.Preference)
disabled, undef, readOnly: BOOLEAN
END;
PropPref = RECORD (Properties.Preference)
valid: SET
END;
VAR
dir-, stdDir-: Directory;
par-: Control;
PROCEDURE Notify (c: Control; f: Views.Frame; op, from, to: INTEGER);
PROCEDURE OpenLink (c: Control; p: Prop);
PROCEDURE Relink;
PROCEDURE DepositPushButton;
PROCEDURE DepositCheckBox;
PROCEDURE DepositRadioButton;
PROCEDURE DepositListBox;
PROCEDURE DepositSelectionBox;
PROCEDURE DepositField;
PROCEDURE DepositUpDownField;
PROCEDURE DepositDateField;
PROCEDURE DepositTimeField;
PROCEDURE DepositTreeControl;
PROCEDURE DepositColorField;
PROCEDURE DepositComboBox;
PROCEDURE DepositCaption;
PROCEDURE DepositGroup;
PROCEDURE DepositCancelButton;
PROCEDURE SetDir (d: Directory);
END Controls.
Module Controls provides a variety of standard user interface elements, so-called controls. In BlackBox, a control is an extended view. As every view, a control can be embedded in any general container (-> Containers), such as forms (-> FormModels) but also texts (-> TextModels). Usually, controls are put into forms.
The standard controls provided by BlackBox are: command buttons (push buttons), check boxes, radio buttons, list boxes, selection boxes, (text, date, time and color) fields, combo boxes, tree controls, captions, and groups.
Unlike other views, these BlackBox controls can be linked to a program variable, or more exactly: to any field accessible through a globally declared variable. When the control is opened, BlackBox tries to link the control to its variable, using the advanced metaprogramming capabilities of the BlackBox Meta module. In this way, the link between control and variable can be built up automatically when a dialog is newly created or loaded from a file, and correct linking (i.e., correct typing) can be guaranteed even after a dialog layout had been edited or otherwise manipulated.
Controls may take on different states at run-time. Depending on the control and on the underlying user interface, these states may be represented in visually distinct ways:
enabled/disabled
Only enabled controls may be modified interactively.
To disable a control, its guard should set par.disabled to TRUE.
A control which cannot be linked to its variable is always disabled.
defined/undefined
Illegal or otherwise undefined values may be hilighted as such.
To mark a control as undefined, its guard should set par.undef to TRUE.
normal/read-only
Controls may be denoted as read-only, i.e., under program control only.
To mark a control as read-only, its guard should set par.readOnly to TRUE.
Controls which are linked to read-only variables are always read-only.
Note that the above states are temporary, i.e., determined wholly at run-time; they are never externalized or internalized.
All controls have the following persistent properties, which are externalized when the controls are written to files:
link
This is the name of a global variable, to which the control is linked, e.g.,
TextCmds.find.replace.
label
This is the displayed name of the control and, optionally, serves to define the keyboard shortcut.
The keyboard shortcut must be marked by a preceding "&" character.
It will be underlined in the displayed name.
If you want "&" to appear in the displayed name, use the escape sequence "&&".
Controls that do not have a displayed name, for example text fields, use this property only for defining
the keyboard shortcut.
guard
This optional command name denotes a guard procedure which allows to disable/enable a
control selectively, and to set the undef and readOnly states as well.
notifier
This optional command name denotes a notifier procedure which allows to do something
whenever the value of a control was changed interactively.
light font
A field may either be displayed in the standard font for this purpose, or in a more
discreet ("light") font. On some platforms, this property may be interpreted only in fields and captions.
These properties, as well as further control-specific properties (see below) can be set interactively using a suitable tool (-> DevInspector), or programmatically using the Properties.SetMsg.
Command Button
Pressing a command button (also called a push button) invokes the linked BlackBox "Command". A Command is frequently an exported parameterless Component Pascal procedure, but it may be any sequence of procedure calls that comply with the "Command" syntax described in the Docu for StdInterpreter. The individual procedures called may be either constant (or normal) procedures, or procedure variables.
Additional properties:
default The button is activated when the user presses return or enter.
cancel The button is activated when the user presses escape.
Check Box
A check box lets the user toggle between two states, checked and unchecked. A check box is linked to a BOOLEAN field or variable.
Alternatively, a check box can also be linked to a SET field or variable. The level property then specifies to which entry of the set the control is linked to. The control is checked if the inspected element is in the set. A check box can also be linked to a Dialog.Selection field or variable. The level property then indicates which element of the val set of the selection is inspected.
Additional property:
level if a check box is linked to a set or to a Dialog.Selection variable, then the level field
indicates which set element is displayed by the control.
Radio Button
Radio buttons let the user choose between several alternatives. Each alternative is represented as a radio button. At any time, exactly one of the radio buttons is "on", while all others are "off".
All radio buttons which belong to one selection are linked to the same integer field. Each radio button is "on" for another value of the integer field. This value can be configured with the level property.
Additional property:
level a radio button is "on" when the value of the variable to which the button is
bound is equal to the level value.
List Box
A list box presents a list of strings to the user. From this list, at most one entry can be selected. List boxes are linked to a Dialog.List.
Selection Box
A selection box presents a list of strings to the user. From this list, an arbitrary number of entries can be selected. Selection boxes are linked to a Dialog.Selection.
Field
A text field lets the user type in a string. Fields are either linked to ARRAY n OF CHAR, BYTE, SHORTINT, INTEGER, LONGINT, SHORTREAL, REAL, Dialog.Combo or Dialog.Currency fields. Fields perform some basic checks, such as for the maximum permissible string length, or for the permissible character set (for numbers, only digits and a few characters like "-" or "." make sense).
Additional property:
multi line The field linked to ARRAY n OF CHAR may display several lines.
A carriage return character is accepted on input.
password Don't display the characters that have been typed in.
UpDownField
The UpDownField is a special text field linked to a BYTE, SHORTINT or INTEGER variable. The value of the integer can be incremented and decremented through arrows, or by using the mouse wheel. If the <Ctrl> key is depressed the value is multiplied or divided by 10 rather than being incremented or decremented by 1.
DateField
A date field lets the user specify a date. Date fields are linked to variables of type Dates.Date. On input, date fields only allow valid dates.
Time Field
A time field lets the user specify a time. Time fields are linked to variables of type Dates.Time. On input, time fields only allow valid times.
Tree Control
A tree control presents a tree of strings to the user. From this tree, at most one node can be selected. Tree Controls are linked to a Dialog.Tree.
Additional properties:
Sorted Nodes with the same parent are displayed in alphabetical order
rather than in the order they were added to the tree.
Lines Lines are drawn between nodes in the tree.
Buttons A button with a "+" or a "-" sign is drawn in front of nodes that have children.
Lines/Buttons at Root Lines and buttons are drawn also at the root level in the tree.
Folder Icons Icons are used to show nodes as folders or leafs.
Color Field
A color field lets the user specify a color. Color fields are linked to variables of type Dialog.Color or of type Ports.Color.
Combo Box
A combo box is a combination of a text field with a list box. Like a list box, it presents a list of strings from which can be chosen. Additionally, it provides a field in which a value may be typed in. This value may be one in the list, or another value altogether. Combo boxes are linked to a Dialog.Combo.
Caption
A caption is a static string, which cannot be manipulated by the user. Typically, a field is accompanied by a caption which tells what the meaning of the field is. Captions may either be unlinked, or linked to the same record field as their corresponding field. Captions are not completely passive in that they may be enabled or disabled (e.g., "greyed out") as other controls.
Group
A group is a rectangular frame with a label in it. It allows to logically group several controls together.
Guard commands can be associated with a control. Such a command has the following signature:
PROCEDURE Guard (VAR par: Dialog.Par)
The main purpose of a guard command is to disable a control when necessary. This is done in the following way:
PROCEDURE Guard (VAR par: Dialog.Par);
BEGIN
par.disabled := condition
END Guard;
Controls which are always enabled need no guard. Besides disabling a control, guards may also set a control to an undefined or read-only state (par.undef, par.readOnly).
Notifier commands can be associated with a control. Such a command has the signature of Dialog.NotifierProc, i.e.,
PROCEDURE Notifier (op, from, to: INTEGER)
The purpose of a notifier command is to give a program the opportunity to customize the behavior of a control when its state is being modified by the user. For example, a status message may be shown when the user clicks onto a command button, and remove again when the user releases the button again (this can be done using the Dialog.ShowStatus procedure). Or, a notifier may perform some checks after each character typed into a text field. Another example are selection boxes: for each item / item range which is selected/deselected, a notification is produced. This makes it possible to e.g. update the count of currently selected items of this selection box.
Examples:
ObxControlsdocu the use of guards and notifiers
ObxDialogdocu the use of selection boxes and combo boxes
ObxButtonsdocu control not extended from Controls.Control shows how to handle control properties
ObxCtrls slider control, extended from Controls.Control
ObxFldCtrls special-purpose text field control, extended from Controls.Control
CONST opt0, opt1, opt2, opt3, opt4
Elements of a control property's valid set. They determine whether their corresponding optN fields are valid.
CONST link
Element of a control property's valid set. It determines whether the link field is valid.
CONST label
Element of a control property's valid set. It determines whether the label field is valid.
CONST guard
Element of a control property's valid set. It determines whether the guard field is valid.
CONST notifier
Element of a control property's valid set. It determines whether the notifier field is valid.
CONST level
Element of a control property's valid set. It determines whether the level field is valid.
CONST default, cancel
Aliases of opt0 and opt1, used for command buttons.
CONST left, right, multiLine, password
Aliases of opt0 to opt3 used for text entry fields
CONST sorted
Alias of opt0 used for list-structured controls (list/selection/combo boxes/tree control).
CONST haslines
Alias of opt1 used for tree control.
CONST hasbuttons
Alias of opt2 used for tree control.
CONST atroot
Alias of opt3 used for tree control.
CONST foldericons
Alias of opt4 used for tree control.
TYPE Control (Views.View)
ABSTRACT
Base type for controls that can be linked to global variables or procedures via metaprogramming. Such a control has no separate model, the item to which it is linked takes the role of a model.
item-: Meta.Item
This item describes the variable or procedure to which the control is linked.
disabled-, undef-, readOnly-: BOOLEAN
The current temporary state of any control.
customFont-: BOOLEAN
This flag determines whether the control's font is taken from the operating system configuration, or from the font variable below.
font-: Fonts.Font font # NIL -> customFont
The control's custom font (customFont must be TRUE when font is used, i.e., when it is not NIL).
label-: Dialog.String
The control's label.
prop-: Prop prop # NIL
The control attributes of this control.
PROCEDURE (c: Control) Internalize2- (VAR rd: Stores.Reader), NEW, EMPTY;
PROCEDURE (c: Control) Externalize2- (VAR wr: Stores.Writer), NEW, EMPTY;
PROCEDURE (c: Control) CopyFromSimpleView2- (source: Control), NEW, EMPTY;
PROCEDURE (c: Control) HandleViewMsg2- (f: Views.Frame; VAR msg: Views.Message)
PROCEDURE (c: Control) HandleCtrlMsg2- (f: Views.Frame; VAR msg: Views.CtrlMessage;
VAR focus: Views.View)
PROCEDURE (c: Control) HandlePropMsg2- (VAR p: Views.PropMessage)
NEW, EMPTY
Extension hooks for Internalize, Externalize, CopyFromSimpleView, HandleCtrlMsg, HandlePropMsg, HandlePropMsg. These methods are made final, and call their new empty extension hooks.
PROCEDURE (c: Control) CheckLink- (VAR ok: BOOLEAN)
NEW, EMPTY
This hook procedure allows a control to check whether the item to which it is linked is acceptable. For example, a checkbox control would accept a link to a Boolean item, but not to an integer item.
PROCEDURE (c: Control) Update- (f: Views.Frame; op, from, to: INTEGER)
NEW, EMPTY
Update the display of a control. For list-structured controls, the list is not changed.
PROCEDURE (c: Control) UpdateList- (f: Views.Frame)
NEW, EMPTY
Update the display of a list-structured control, including a rebuilding of its list elements.
TYPE Directory
ABSTRACT
Directory type for standard controls.
PROCEDURE (d: Directory) NewPushButton (p: Prop): Control
NEW, ABSTRACT
Allocates and returns a new command button.
PROCEDURE (d: Directory) NewCheckBox (p: Prop): Control
NEW, ABSTRACT
Allocates and returns a new check box.
PROCEDURE (d: Directory) NewRadioButton (p: Prop): Control
NEW, ABSTRACT
Allocates and returns a new radio button.
PROCEDURE (d: Directory) NewListBox (p: Prop): Control
NEW, ABSTRACT
Allocates and returns a new list box.
PROCEDURE (d: Directory) NewSelectionBox (p: Prop): Control
NEW, ABSTRACT
Allocates and returns a new selection box.
PROCEDURE (d: Directory) NewField (p: Prop): Control
NEW, ABSTRACT
Allocates and returns a new text field.
PROCEDURE (d: Directory) NewUpDownField (p: Prop): Control
NEW, ABSTRACT
Allocates and returns a new text field with up and down arrows.
PROCEDURE (d: Directory) NewDateField (p: Prop): Control
NEW, ABSTRACT
Allocates and returns a new date field.
PROCEDURE (d: Directory) NewTimeField (p: Prop): Control
NEW, ABSTRACT
Allocates and returns a new time field.
PROCEDURE (d: Directory) NewTreeControl (p: Prop): Control
NEW, ABSTRACT
Allocates and returns a new tree control.
PROCEDURE (d: Directory) NewColorField (p: Prop): Control
NEW, ABSTRACT
Allocates and returns a new color field.
PROCEDURE (d: Directory) NewComboBox (p: Prop): Control
NEW, ABSTRACT
Allocates and returns a new combo box.
PROCEDURE (d: Directory) NewCaption (p: Prop): Control
NEW, ABSTRACT
Allocates and returns a new text caption.
PROCEDURE (d: Directory) NewGroup (p: Prop): Control
NEW, ABSTRACT
Allocates and returns a new group.
TYPE Prop (Properties.Property)
A property object describes various attributes of a control. There are messages which allow to poll or set the control properties of a control (-> Properties, -> Controllers).
opt: ARRAY 5 OF BOOLEAN;
Up to five Boolean options. Their meaning depends on the control's type.
link: Dialog.String
Name of the field or procedure to which control is linked, e.g., "TextCmds.find.replace".
label: Dialog.String
Displayed name and keyboard shortcut of the control.
guard: Dialog.String
Optional name of guard command.
notifier: Dialog.String
Optional name of notifier command.
level: INTEGER only valid for radio buttons.
Determines for which value of the bound variable the control is "on".
TYPE DefaultsPref (Properties.Preference)
This preference message allows to override the general defaults of a control's temporary state.
disabled, undef, readOnly: BOOLEAN
State of the control. It is being determined in three steps:
1) general default:
disabled := ~c.item.Valid()
undef := FALSE
readOnly := c.item.vis = Meta.readOnly
2) control-specific default:
by handling the DefaultsPref message, the general default can be overwritten.
For example, with buttons: disabled := link = ""
3) guard call:
If there is a guard, the guard result is used, otherwise the default.
TYPE PropPref (Properties.Preference)
Preference message which allows to specify the valid properties of the receiving control.
{link, label, guard, notifier, customFont} is the default. By handling the PropPref message, elements of the valid set can be added or removed.
valid: SET
VAR dir-, stdDir-: Directory dir # NIL & stdDir # NIL
Directories for the lookup of standard controls.
VAR par-: Control
Before a control's guard or notifier procedure is called, and before any controller message is sent to it, the control is assigned to par. Afterwards, it is reset to its previous value. This variable can be used in a command to determine the currently active control.
PROCEDURE Notify (c: Control; f: Views.Frame; op, from, to: INTEGER)
Used internally.
PROCEDURE OpenLink (c: Control; p: Prop)
Try to link control c according to control property p.
Pre
c # NIL 20
p # NIL 21
PROCEDURE Relink
Force a re-evaluation of the control's link.
PROCEDURE DepositPushButton
Allocate a new command button using dir.NewPushButton and deposit it.
PROCEDURE DepositCheckBox
Allocate a new check box using dir.NewCheckBox and deposit it.
PROCEDURE DepositRadioButton
Allocate a new radio button using dir.NewRadioButton and deposit it.
PROCEDURE DepositListBox
Allocate a new list box using dir.NewListBox and deposit it.
PROCEDURE DepositSelectionBox
Allocate a new selection box using dir.NewSelectionBox and deposit it.
PROCEDURE DepositField
Allocate a new field using dir.NewField and deposit it.
PROCEDURE DepositUpDownField
Allocate a new up-down-field using dir.NewUpDownField and deposit it.
PROCEDURE DepositDateField
Allocate a new date field using dir.NewDateField and deposit it.
PROCEDURE DepositTimeField
Allocate a new time field using dir.NewTimeField and deposit it.
PROCEDURE DepositTreeControl
Allocate a new tree control using dir.NewTreeControl and deposit it.
PROCEDURE DepositColorField
Allocate a new color field using dir.NewColorField and deposit it.
PROCEDURE DepositComboBox
Allocate a new combo box using dir.NewComboBox and deposit it.
PROCEDURE DepositCaption
Allocate a new caption using dir.NewCaption and deposit it.
PROCEDURE DepositGroup
Allocate a new group using dir.NewGroup and deposit it.
PROCEDURE DepositCancelButton
Allocate a new command button using dir.NewPushButton and deposit it. The button's link property is initialized to "StdCmds.CloseDialog" and its cancel-property is set to TRUE.
PROCEDURE SetDir (d: Directory)
Assigns directory.
SetDir is used in configuration routines.
Pre
d # NIL 20
Post
stdDir' = NIL
stdDir = d
stdDir' # NIL
stdDir = stdDir'
dir = d
| System/Docu/Controls.odc |
Converters
DEFINITION Converters;
IMPORT Stores, Files, Dialog;
CONST importAll = 0;
TYPE
Importer = PROCEDURE (f: Files.File; OUT s: Stores.Store);
Exporter = PROCEDURE (s: Stores.Store; f: Files.File);
Converter = POINTER TO RECORD
next*: Converter;
imp-, exp-: Dialog.String;
storeType-: Stores.TypeName;
fileType-: Files.Type;
opts-: SET
END;
VAR list-: Converter;
PROCEDURE Register (imp, exp: Dialog.String; storeType: Stores.TypeName; fileType: Files.Type;
opts: SET);
PROCEDURE Import (loc: Files.Locator; name: Files.Name; VAR conv: Converter; OUT s: Stores.Store);
PROCEDURE Export (loc: Files.Locator; name: Files.Name; conv: Converter; s: Stores.Store);
END Converters.
Module Converters allows the definition and registration of file converters. A file converter is an importer which translates a file into a store (usually some view type), or an exporter which translates a store into a file, or it is both an importer and an exporter simultaneously. For a given pair (file type, store type) there may be several file converters registered, e.g. a text view may be translated into an ASCII file with or without carriage returns at the end of lines.
Example: ObxConvdocu
CONST importAll
Set element for the opts set of procedure Register. It indicates that the importer is able to import all file types (e.g., an importer that displays the file contents as a hex dump).
TYPE Importer
This procedure type is the signature of an importer command. An importer translates a given file f into a store s.
Pre
f # NIL 20
f has correct type 22
Post
s # NIL
TYPE Exporter
This procedure type is the signature of an exporter command. An exporter translates a given store s into the contents of a file f. File f is already set up as an empty new (i.e., writable) file.
Pre
s # NIL 20
f # NIL 21
f.Length() = 0 22
s has correct type 23
Post
f.Length() >= 0
TYPE Converter
A converter object represents a file converter. It consists of an import and an export command, one of which may be empty. A converter converts between a file and a store.
next*: Converter
Next converter in the list. Converters are sorted by their registration time: later registration means further back in the list.
imp-, exp-: Dialog.String imp # "" OR exp # ""
Strings for the import/export commands, e.g.,
"StdTextConv.ImportText" or
"StdTextConv.ExportText".
storeType-: Stores.TypeName exp # "" -> storeType # ""
Store type of the converter, e.g., "TextViews.TextView".
fileType-: Files.Type fileType # ""
File type of the converter, e.g., "TXT".
opts-: SET
Set of options, e.g., {} or {importAll}.
VAR list-: Converter
List of registered converters. Converters are sorted by their registration time: later registration means further back in the list. The first element of the list, i.e., list, is always the document converter, i.e., the converter used for standard BlackBox document files.
PROCEDURE Register (imp, exp: Dialog.String; storeType: Stores.TypeName;
fileType: Files.Type; opts: SET)
Register an importer which translates a file of type fileType into a store of type storeType (e.g., "TextViews.View"), an exporter which translates a store of type storeType into a file of type fileType, or both.
imp is the name of an importer command, which must have the signature of Importer.
exp is the name of an exporter command, which must have the signature of Exporter.
opts allows to express a set of options; currently only the element importAll is defined. Normally, opts is empty.
Register does not yet load the modules which contain the import/export commands. They are loaded only when needed.
The standard document converter is already installed by the BlackBox core. Converters that should be available at startup of BlackBox should be registered in the StdConfig module, e.g., converters for ASCII files, Unicode files, or picture files. StdConfig.Setup is executed upon startup of BlackBox to allow the establishment of custom configurations, such as the set of available converters. As a result of Register, a new converter is appended to list, with fields corresponding to the parameters passed.
For each registered importer or exporter, there optionally may be a corresponding string mapping; to make the display of a list of importers/exporters more user-friendly. For example, the importer "StdTextConv.ImportText" could be mapped to the more telling name "Ascii" (in the standard file open dialog). The mapping is done in the Strings file in the Rsrc directory of the importer's subsystem, e.g., there may be the following lines in the Std/Rsrc/Strings text:
StdTextConv.ImportText Ascii
StdTextConv.ExportText Ascii
Pre
imp # "" OR exp # "" 20
fileType # "" 21
PROCEDURE Import (loc: Files.Locator; name: Files.Name; VAR conv: Converter; OUT s: Stores.Store)
Converts the contents of the file specified by (loc, name) into store s, using converter conv. Internally it calls the converter's import command. If conv = NIL, the first suitable converter in list is used and returned in the VAR parameter.
Pre
loc # NIL 20
name # "" 21
conv = NIL OR conv.imp # "" 22
File type of (loc, name) = converter's file type 23
PROCEDURE Export (loc: Files.Locator; name: Files.Name; conv: Converter; s: Stores.Store)
Convert store s to a new file (loc, name) using converter conv. Internally it calls the converter's export command. Success or failure is reported in the locator's res field.
Pre
s # NIL 20
~ s IS Stores.Alien 21
loc # NIL 22
name # "" 23
conv = NIL OR conv.exp # "" 24
TypeOf(s) = converter's store type 25
| System/Docu/Converters.odc |
Dates
DEFINITION Dates;
CONST
monday = 0; tuesday = 1; wednesday = 2; thursday = 3; friday = 4; saturday = 5; sunday = 6;
short = 0; long = 1; abbreviated = 2; plainLong = 3; plainAbbreviated = 4;
TYPE
Date = RECORD
year, month, day: INTEGER
END;
Time = RECORD
hour, minute, second: INTEGER
END;
PROCEDURE DateToString (IN d: Date; format: INTEGER; OUT str: ARRAY OF CHAR);
PROCEDURE Day (IN d: Date): INTEGER;
PROCEDURE DayOfWeek (IN d: Date): INTEGER;
PROCEDURE DayToDate (n: INTEGER; OUT d: Date);
PROCEDURE GetDate (OUT d: Date);
PROCEDURE GetDateTime (OUT d: Date; OUT t: Time);
PROCEDURE GetEasterDate (year: INTEGER; OUT d: Date);
PROCEDURE GetTime (OUT t: Time);
PROCEDURE GetUTCBias (OUT bias: INTEGER);
PROCEDURE GetUTCDate (OUT d: Date);
PROCEDURE GetUTCDateTime (OUT d: Date; OUT t: Time);
PROCEDURE GetUTCTime (OUT t: Time);
PROCEDURE TimeToString (IN t: Time; OUT str: ARRAY OF CHAR);
PROCEDURE ValidDate (IN d: Date): BOOLEAN;
PROCEDURE ValidTime (IN t: Time): BOOLEAN;
END Dates.
Module Dates provides basic procedures to work with dates. It covers the Julian calendar up to 10/4/1582 and the Gregorian calendar starting at 10/15/1582. Module Dates can deal with dates from 1/1/1 up to 12/31/9999. The types Date and Time are known to the framework and can be displayed by suitable controls.
CONST monday, tuesday, wednesday, thursday, friday, saturday, sunday
Possible return value of procedure DayOfWeek.
CONST short, long, abbreviated, plainLong, plainAbbreviated
Possible value for parameter format of DateToString to specify the format.
TYPE Date
Date information.
year: INTEGER 0001 <= year <= 9999
month: INTEGER 1 <= month <= 12
day: INTEGER 1 <= day <= 31
TYPE Time
Time information.
hour: INTEGER 0 <= hour <= 23
minute: INTEGER 0 <= minute <= 59
second: INTEGER 0 <= second <= 59
PROCEDURE DateToString (IN d: Date; format: INTEGER; OUT s: ARRAY OF CHAR);
Convert the date d into string s. The format of the conversion is specified through the operation system, usually depending on country and language.
format example
short 01/02/92
abbreviated Thu, Jan 2, 1992
long Thursday, January 2, 1992
plainAbbreviated Jan 2, 1992
plainLong January 2, 1992
Pre
ValidDate(d) (not explicitly checked)
format IN {short, abbreviated, long, plainAbbreviated, longAbbreviated} 20
PROCEDURE Day (d: Date): INTEGER;
For date d, return the number of days since 1/1/1. Day(1/1/1) = 1.
The difference between two dates in days can be computed with Day(d2) - Day(d1).
Pre
ValidDate(d) (not explicitly checked)
Post
(result > 0) & (result < 3652062)
PROCEDURE DayOfWeek (IN d: Date): INTEGER
Return the weekday of date d.
Pre
ValidDate(d) (not explicitly checked)
Post
result IN {monday .. sunday}
PROCEDURE DayToDate (n: INTEGER; OUT d: Date);
Convert the number of days since 1/1/1 into a date.
DayToDate(Day(d1), d2) => d1=d2
Pre
(n > 0) & (n < 3652062) (not explicitly checked)
Post
ValidDate(d) & Day(d) = n
PROCEUDRE GetDate (OUT d: Date)
Get the current date.
PROCEUDRE GetDateTime (OUT d: Date; OUT t: Time)
Get the current date and time by one atomic operation.
PROCEDURE GetEasterDate (year: INTEGER; OUT d: Date)
Get the Easter date of year.
Pre
(year > 1582) & (year < 2300) 20
PROCEDURE GetTime (OUT t: Time)
Get the current time.
PROCEDURE GetUTCBias (OUT bias: INTEGER);
Returns the current bias, in minutes, for local time translation on this computer. The bias is the difference, in minutes, between Coordinated Universal Time (UTC) and local time. All translations between UTC and local time are based on the following formula: UTC = local time + bias
UTC = Coordinated Universal Time, also known as Greenwich Mean time (GMT).
PROCEDURE GetUTCDate (OUT d: Date);
Get the UTC date.
PROCEUDRE GetUTCDateTime (OUT d: Date; OUT t: Time)
Get the UTC date and time by one atomic operation.
PROCEDURE GetUTCTime (OUT t: Time);
Get the UTC time.
PROCEDURE TimeToString (IN t: Time; OUT s: ARRAY OF CHAR);
Convert the time t into string s. The format of the conversion is specified through the operating system.
Pre
ValidTime(t) (not explicitly checked)
PROCEDURE ValidDate (IN d: Date): BOOLEAN
Test whether d is a valid date according to the Julian (before 1582) or Gregorian (after 1582) calendar. Dates between 10/5/1582 and 10/14/1582 did not exist and are not valid.
PROCEDURE ValidTime (IN t: Time): BOOLEAN
Test whether time t is valid. | System/Docu/Dates.odc |
Dialog
DEFINITION Dialog;
IMPORT Files;
CONST
cancel = 4;
changed = 3;
excluded = 6;
exitWithoutWindows = TRUE;
firstPos = 0;
included = 5;
lastPos = -1;
linux = 30;
macOS = 21;
macOSX = 22;
no = 3;
nonPersistent = FALSE;
ok = 1;
persistent = TRUE;
pressed = 1;
released = 2;
set = 7;
tru64 = 40;
windows2000 = 15;
windows32s = 11;
windows7 = 19;
windows8 = 10;
windows95 = 12;
windows98 = 16;
windowsNT3 = 13;
windowsNT4 = 14;
windowsVista = 18;
windowsXP = 17;
yes = 2;
TYPE
LangNotifier = POINTER TO ABSTRACT RECORD
(n: LangNotifier) Notify-, NEW, ABSTRACT
END;
TreeNode = POINTER TO LIMITED RECORD
(tn: TreeNode) Data (): ANYPTR, NEW;
(tn: TreeNode) GetName (OUT name: String), NEW;
(tn: TreeNode) IsExpanded (): BOOLEAN, NEW;
(tn: TreeNode) IsFolder (): BOOLEAN, NEW;
(tn: TreeNode) NofChildren (): INTEGER, NEW;
(tn: TreeNode) SetData (data: ANYPTR), NEW;
(tn: TreeNode) SetExpansion (expanded: BOOLEAN), NEW;
(tn: TreeNode) SetName (name: String), NEW;
(tn: TreeNode) ViewAsFolder (isFolder: BOOLEAN), NEW
END;
Color = RECORD
val: INTEGER
END;
Combo = RECORD
item: String;
len-: INTEGER;
(IN c: Combo) GetItem (index: INTEGER; OUT item: String), NEW;
(VAR c: Combo) SetItem (index: INTEGER; IN item: ARRAY OF CHAR), NEW;
(VAR c: Combo) SetLen (len: INTEGER), NEW;
(VAR c: Combo) SetResources (IN key: ARRAY OF CHAR), NEW
END;
Currency = RECORD
val: LONGINT;
scale: INTEGER
END;
GuardProc = PROCEDURE (VAR par: Par);
Language = ARRAY 3 OF CHAR;
List = RECORD
index, len-: INTEGER;
(IN l: List) GetItem (index: INTEGER; OUT item: String), NEW;
(VAR l: List) SetItem (index: INTEGER; IN item: ARRAY OF CHAR), NEW;
(VAR l: List) SetLen (len: INTEGER), NEW;
(VAR l: List) SetResources (IN key: ARRAY OF CHAR), NEW
END;
NotifierProc = PROCEDURE (op, from, to: INTEGER);
Par = RECORD
disabled, checked, undef, readOnly: BOOLEAN;
label: String
END;
Selection = RECORD
len-: INTEGER;
(VAR s: Selection) Excl (from, to: INTEGER), NEW;
(IN s: Selection) GetItem (index: INTEGER; OUT item: String), NEW;
(IN s: Selection) In (index: INTEGER): BOOLEAN, NEW;
(VAR s: Selection) Incl (from, to: INTEGER), NEW;
(VAR s: Selection) SetItem (index: INTEGER; IN item: ARRAY OF CHAR), NEW;
(VAR s: Selection) SetLen (len: INTEGER), NEW;
(VAR s: Selection) SetResources (IN key: ARRAY OF CHAR), NEW
END;
String = ARRAY 256 OF CHAR;
Tree = RECORD
(IN t: Tree) Child (node: TreeNode; pos: INTEGER): TreeNode, NEW;
(VAR t: Tree) Delete (node: TreeNode): INTEGER, NEW;
(VAR t: Tree) DeleteAll, NEW;
(VAR t: Tree) Move (node, parent: TreeNode; pos: INTEGER), NEW;
(VAR t: Tree) NewChild (parent: TreeNode; pos: INTEGER; name: String): TreeNode, NEW;
(IN t: Tree) Next (node: TreeNode): TreeNode, NEW;
(IN t: Tree) NofNodes (): INTEGER, NEW;
(IN t: Tree) NofRoots (): INTEGER, NEW;
(IN t: Tree) Parent (node: TreeNode): TreeNode, NEW;
(IN t: Tree) Prev (node: TreeNode): TreeNode, NEW;
(VAR t: Tree) Select (node: TreeNode), NEW;
(IN t: Tree) Selected (): TreeNode, NEW
END;
VAR
appName: ARRAY 32 OF CHAR;
appVersion: ARRAY 32 OF CHAR;
beep: BOOLEAN;
caretPeriod: INTEGER;
commandLinePars: String;
language-: Language;
mapRes: INTEGER;
memInStatus: BOOLEAN;
metricSystem: BOOLEAN;
platform: INTEGER;
serverMode: BOOLEAN;
showsStatus: BOOLEAN;
thickCaret: BOOLEAN;
user: ARRAY 32 OF CHAR;
version: INTEGER;
PROCEDURE Beep;
PROCEDURE Call (IN proc, errorMsg: ARRAY OF CHAR; OUT res: INTEGER);
PROCEDURE FlushMappings;
PROCEDURE GetColor (in: INTEGER; OUT out: INTEGER; OUT set: BOOLEAN);
PROCEDURE GetExtSpec (defName: Files.Name; defType: Files.Type; VAR loc: Files.Locator; OUT name: Files.Name);
PROCEDURE GetIntSpec (defType: Files.Type; VAR loc: Files.Locator; OUT name: Files.Name);
PROCEDURE GetOK (IN str, p0, p1, p2: ARRAY OF CHAR; form: SET; OUT res: INTEGER);
PROCEDURE IsLinux (): BOOLEAN;
PROCEDURE IsMac (): BOOLEAN;
PROCEDURE IsWindows (): BOOLEAN;
PROCEDURE IsWine (): BOOLEAN;
PROCEDURE MapParamString (in, p0, p1, p2: ARRAY OF CHAR; OUT out: ARRAY OF CHAR);
PROCEDURE MapString (in: ARRAY OF CHAR; OUT out: ARRAY OF CHAR);
PROCEDURE Notify (id0, id1: INTEGER; opts: SET);
PROCEDURE OpenExternal (IN fileName: ARRAY OF CHAR);
PROCEDURE RegisterLangNotifier (notifier: LangNotifier);
PROCEDURE RemoveLangNotifier (notifier: LangNotifier);
PROCEDURE ResetLanguage;
PROCEDURE RunExternal (IN exeName: ARRAY OF CHAR);
PROCEDURE SetLanguage (lang: Language; persistent: BOOLEAN);
PROCEDURE ShowMsg (IN str: ARRAY OF CHAR);
PROCEDURE ShowParamMsg (IN str, p0, p1, p2: ARRAY OF CHAR);
PROCEDURE ShowParamStatus (IN str, p0, p1, p2: ARRAY OF CHAR);
PROCEDURE ShowStatus (IN str: ARRAY OF CHAR);
PROCEDURE Update (IN x: ANYREC);
PROCEDURE UpdateBool (VAR x: BOOLEAN);
PROCEDURE UpdateByte (VAR x: BYTE);
PROCEDURE UpdateChar (VAR x: CHAR);
PROCEDURE UpdateInt (VAR x: INTEGER);
PROCEDURE UpdateLInt (VAR x: LONGINT);
PROCEDURE UpdateList (IN x: ANYREC);
PROCEDURE UpdateReal (VAR x: REAL);
PROCEDURE UpdateSChar (VAR x: SHORTCHAR);
PROCEDURE UpdateSInt (VAR x: SHORTINT);
PROCEDURE UpdateSReal (VAR x: SHORTREAL);
PROCEDURE UpdateSString (IN x: ARRAY OF SHORTCHAR);
PROCEDURE UpdateSet (VAR x: SET);
PROCEDURE UpdateString (IN x: ARRAY OF CHAR);
END Dialog.
Module Dialog provides a variety of auxiliary services to simplify user interaction of a program. In particular, the output of messages, e.g. error messages, is supported. Furthermore, various base types are provided: List, Selection, Combo, Currency, Tree, etc. These types are known to the framework (more exactly: they are known to module Controls) and can be displayed by suitable controls, i.e. views which display not a normal model, but instead a variable of one of the mentioned types.
CONST pressed
This value may be passed to the op field of a notifier procedure. It notifies about a mouse-down event, i.e. the primary mouse key has just been pressed.
CONST released
This value may be passed to the op field of a notifier procedure. It notifies about a mouse-up event, i.e. the primary mouse key has just been released.
CONST changed
This value may be passed to the op field of a notifier procedure. It notifies about some change of an interactor field's value. For a Selection, the more specific constants included, excluded, or set are used.
CONST included
This value may be passed to the op field of a notifier procedure. It notifies about an inclusion of the range [from..to] in a Selection. Before the operation, this range was not included in the set.
CONST excluded
This value may be passed to the op field of a notifier procedure. It notifies about an exclusion of the range [from..to] in a Selection. Before the operation, this range was included in the set.
CONST set
This value may be passed to the op field of a notifier procedure. It notifies about a change in a Selection or SET, resulting in a set {from..to}. Any previous selection was cleared.
CONST ok
This value may be used as an element of the form set parameter of procedure GetOK. It indicates that the user has pressed the OK button.
CONST yes
This value may be used as an element of the form set parameter of procedure GetOK. It indicates that the user has pressed the Yes button.
CONST no
This value may be used as an element of the form set parameter of procedure GetOK. It indicates that the user has pressed the No button.
CONST cancel
This value may be used as an element of the form set parameter of procedure GetOK. It indicates that the user has pressed the Cancel button.
CONST windows32s
This is a possible value of variable platform. It indicates that BlackBox is running on Windows 3.1 (Win32s). This platform is not supported anymore.
CONST windows95
This is a possible value of variable platform. It indicates that BlackBox is running on Windows 95, Windows 98, Windows 98SE, or Windows 98 ME.
CONST windowsNT3
This is a possible value of variable platform. It indicates that BlackBox is running on Windows NT 3.x.
CONST windowsNT4
This is a possible value of variable platform. It indicates that BlackBox is running on Windows NT 4.x.
CONST windows2000
This is a possible value of variable platform. It indicates that BlackBox is running on Windows 2000 (formerly called Windows NT 5.0).
CONST windows98
This is a possible value of variable platform. It indicates that BlackBox is running on one of the Windows 98 flavors (original Windows 98, Windows 98 SE, or Windows 98 ME).
CONST windowsXP
This is a possible value of variable platform. It indicates that BlackBox is running on Windows XP.
CONST windowsVista
This is a possible value of variable platform. It indicates that BlackBox is running on Windows Vista.
CONST windows7
This is a possible value of variable platform. It indicates that BlackBox is running on Windows 7.
CONST windows8
This is a possible value of variable platform. It indicates that BlackBox is running on Windows 8.
CONST macOS
This is a possible value of variable platform. It indicates that BlackBox is running on Mac OS 7.x, 8.x, or 9.x. This platform is not supported anymore.
CONST macOSX
This is a possible value of variable platform. It indicates that BlackBox is running on Mac OS X. This platform is currently not supported.
CONST linux
This is a possible value of variable platform. It indicates that BlackBox is running on Linux. This platform is currently not supported.
CONST tru64
This is a possible value of variable platform. It indicates that BlackBox is running on Compaq Tru64 Unix. This platform is currently not supported.
CONST firstPos
This value may be used in calls to Tree variables. It indicates that the first child of a node is requested.
CONST lastPos
This value may be used in calls to Tree variables. It indicates that the last child of a node is requested.
CONST persistent
This value may be used in calls to SetLanguage variables. It indicates that the setting is to be stored in a persistent registry and used again when BlackBox is started the next time.
CONST nonPersistent
This value may be used in calls to SetLanguage variables. It indicates that the setting is not to be stored in a persistent registry and thus will not affect BlackBox the next time it is started.
CONST exitWithoutWindows
This value may be passed to RequestExit to allow the application to exit once all windows are closed by the user.
TYPE String
String type for various names to be displayed for the user, or to be entered by the user.
TYPE List
A list type defines a sub range of the INTEGER type, and an item name (a string) for each element of this range. All valid names can be enumerated by indexing from 0 upwards until len - 1.
index: INTEGER index >= -1 & index < len
Currently selected item of the list. If index = -1 then no element of the list is selected, which may happen e.g. if len = 0.
len-: INTEGER len >= 0
Number of elements in the list.
PROCEDURE (VAR l: List) SetLen (len: INTEGER)
NEW
Makes sure that the list has at least len elements available. If len > l.len, then the size of the existing list is increased as much as necessary. Note that SetItem also increases the list size if necessary, so SetLen is strictly necessary only to shorten the list. SetLen should be called when the size of the list to be constructed is known in advance, to avoid unnecessary allocations and copying in SetItem.
If len > l.len, the existing l.len elements are not affected by SetLen.
Pre
len >= 0 20
Post
l.len = len
PROCEDURE (VAR l: List) SetItem (index: INTEGER; IN item: String)
NEW
Given an index index, the corresponding item name is set, or overwritten if it had been set earlier. If index >= l.len then the length is increased as much as necessary
Pre
index >= 0 20
item # "" 21
Post
index <l.len'
l.len = l.len'
index >= l.len'
l.len = index + 1
PROCEDURE (VAR l: List) GetItem (index: INTEGER; OUT item: String)
NEW
Given an index index, the corresponding item name is returned. If index is outside of the valid index range, the empty string "" is returned.
Post
name # "" iff index is in 0 .. l.len - 1
PROCEDURE (VAR l: List) SetResources (IN key: ARRAY OF CHAR)
NEW
Set up the item list according to entries in a string resource file. For example, key = "#System:colors" would build up an item list (red, green, blue), assuming that resource file System/Rsrc/Strings contains the entries
key[0] red
key[1] green
key[2] blue
Pre
key # "" 20
TYPE Selection
A selection is similar to a List, except that not only one value can be represented, but between 0 and an arbitrary number of values instead, i.e., a selection is a potentially large set of integers. In this context, the term "list" denotes all selectable elements, not only the selected ones.
len-: INTEGER len >= 0
Number of elements in the list.
PROCEDURE (VAR s: Selection) SetLen (len: INTEGER)
NEW
Makes sure that the list has at least len elements available. If len > l.len, then the size of the existing list is increased as much as necessary. Note that SetItem also increases the list size if necessary, so SetLen is strictly necessary only to shorten the list. SetLen should be called when the size of the list to be constructed is known in advance, to avoid unnecessary allocations and copying in SetItem.
If len > l.len, the existing l.len elements are not affected by SetLen.
Pre
len >= 0 20
Post
s.len = len
PROCEDURE (VAR s: Selection) SetItem (index: INTEGER; IN item: String)
NEW
Given an index index, the corresponding item name is set, or overwritten if it had been set earlier. If index >= s.len then the length is increased as much as necessary
Pre
index >= 0 20
item # "" 21
Post
index <s.len'
s.len = s.len'
index >= s.len'
s.len = index + 1
PROCEDURE (VAR s: Selection) GetItem (index: INTEGER; OUT item: String)
NEW
Given an index index, the corresponding item name is returned. If index is outside of the valid index range, the empty string "" is returned.
Post
name # "" iff index is in 0 .. s.len - 1
PROCEDURE (VAR s: Selection) SetResources (IN key: ARRAY OF CHAR)
NEW
Set up the item list according to entries in a string resource file. For example, key = "#System:colors" would build up an item list (red, green, blue), assuming that resource file System/Rsrc/Strings contains the entries
key[0] red
key[1] green
key[2] blue
Pre
key # "" 20
PROCEDURE (VAR s: Selection) Incl (from, to: INTEGER)
NEW
Include the range [from..to] intersected with [0..s.len - 1] into the selection. If from > to, this is regarded as an empty range.
PROCEDURE (VAR s: Selection) Excl (from, to: INTEGER)
NEW
Exclude the range [from..to] intersected with [0..s.len - 1] into the selection. If from > to, this is regarded as an empty range.
PROCEDURE (VAR s: Selection) In (index: INTEGER): BOOLEAN
NEW
Determine whether element index is in the selection. If index is outside of the range [0..s.len-1], then FALSE is returned.
TYPE Combo
A combo is similar to a List, except that it also accepts other values than the predefined ones of a list. Typically, a combo is represented on the screen as a combo box control. Such a control is a mixture of a list box or popup box (where one of the listed values can be chosen) and a text field (in which non-standard values can be typed in).
item: String
Current value of the combo.
len-: INTEGER len >= 0
Number of elements in the list.
PROCEDURE (VAR c: Combo) SetLen (len: INTEGER)
NEW
Makes sure that the list has at least len elements available. If len > l.len, then the size of the existing list is increased as much as necessary. Note that SetItem also increases the list size if necessary, so SetLen is strictly necessary only to shorten the list. SetLen should be called when the size of the list to be constructed is known in advance, to avoid unnecessary allocations and copying in SetItem.
If len > l.len, the existing l.len elements are not affected by SetLen.
Pre
len >= 0 20
Post
c.len = len
PROCEDURE (VAR c: Combo) SetItem (index: INTEGER; IN item: String)
NEW
Given an index index, the corresponding item name is set, or overwritten if it had been set earlier. If index >= c.len then the length is increased as much as necessary
Pre
index >= 0 20
item # "" 21
Post
index <c.len'
c.len = c.len'
index >= c.len'
c.len = index + 1
PROCEDURE (VAR c: Combo) GetItem (index: INTEGER; OUT item: String)
NEW
Given an index index, the corresponding item name is returned. If index is outside of the valid index range, the empty string "" is returned.
Post
name # "" iff index is in 0 .. c.len - 1
PROCEDURE (VAR c: Combo) SetResources (IN key: ARRAY OF CHAR)
NEW
Set up the item list according to entries in a string resource file. For example, key = "#System:colors" would build up an item list (red, green, blue), assuming that resource file System/Rsrc/Strings contains the entries
key[0] red
key[1] green
key[2] blue
Pre
key # "" 20
TYPE TreeNode
Holds information about a node in a Tree. A TreeNode is part of one and only one Tree.
PROCEDURE (tn: TreeNode) SetName (name: String)
NEW
Sets the name of tn. This is the text that is displayed when a Tree is bound to a tree control.
PROCEDURE (tn: TreeNode) GetName (OUT name: String)
NEW
Retrieves the name of tn.
PROCEDURE (tn: TreeNode) SetData (data: ANYPTR), NEW;
Associates some data with node tn. This can be used to associate some application defined data with each node in a Tree.
PROCEDURE (tn: TreeNode) Data (): ANYPTR
NEW
Returns the data associated with the tn by an earlier call to SetData. Returns NIL if no call to SetData has been made.
PROCEDURE (tn: TreeNode) NofChildren (): INTEGER
NEW
Returns the number of immediate children to tn, i.e. all nodes, n, in tree, t, such that t.Parent(n) = tn.
PROCEDURE (tn: TreeNode) SetExpansion (expanded: BOOLEAN)
NEW
Marks tn as expanded or collapsed. When the tree is displayed in a Tree Control the node corresponding to tn will be expanded or collapsed according to the value of expanded.
PROCEDURE (tn: TreeNode) IsExpanded (): BOOLEAN
NEW
Returns TRUE if tn has been expanded by a Tree Control or by an explicit call to SetExpansion. Otherwise FALSE is returned.
PROCEDURE (tn: TreeNode) ViewAsFolder (isFolder: BOOLEAN)
NEW
When a Tree Control has the option "Folder Icons" set, it automatically displays nodes that have children as folders. If node tn should be viewed as a folder even if it has no children, tn.ViewAsFolder(TRUE) should be called. If node tn has children it will be viewed as a folder even if tn.ViewAsFolder(FALSE) is called. ViewAsFolder only provides a way to make leafs look like folders, not the other way around.
PROCEDURE (tn: TreeNode) IsFolder (): BOOLEAN
NEW
Returns TRUE if tn has children or if tn.ViewAsFolder(TRUE) has been called, otherwise it returns FALSE.
TYPE Tree
Defines a tree structure for storing TreeNodes. Normally a Tree is bound to a Tree Control in the user interface. Each tree can have several roots. It is possible to navigate up and down in the tree as well as between siblings. All operations on a tree t that require a TreeNode tn have the precondition that tn was created using t.NewChild and that tn is still part of t, i.e., tn is a node in t and not in any other tree and tn has not been deleted from t.
Note:Tree controls look different under Windows NT and other Windows versions. The background of a tree control is not set to gray when the control is disabled or read only under Windows NT.
See PlatformSpecificIssues for more information.
PROCEDURE (VAR t: Tree) NofNodes (): INTEGER
NEW
Returns the total number of nodes in the tree.
Post
Returned value is greater than or equal to 0.
PROCEDURE (VAR t: Tree) NofRoots (): INTEGER
NEW
The total number of roots in the tree. A node, tn, is a root if tn.Parent() = NIL.
Post
Returned value is greater than or equal to 0.
PROCEDURE (VAR t: Tree) NewChild (parent: TreeNode; pos: INTEGER; name: String): TreeNode
NEW
Creates a new node in a tree. The new node is inserted at positions pos among the children of parent. If parent has no children or pos = firstPos then the new node is inserted as the first child of parent. If parent has fewer children than the value of pos or pos = lastPos, then the new node is inserted as the last child of parent. If parent is NIL then the new node is added as a new root in the tree at position pos.
Pre
(pos >= 0) OR (pos = firstPos) OR (pos = lastPos)
Post
t.NofNodes() = t.NofNodes()' + 1
PROCEDURE (VAR t: Tree) Delete (node: TreeNode): INTEGER
NEW
Removes node and all its children from the tree.
Pre
node # NIL
Post
t.NofNodes < t.NofNodes()'
PROCEDURE (VAR t: Tree) DeleteAll
NEW
Removes all nodes from the tree.
Post
t.NofNodes() = 0
t.NofRoots() = 0
PROCEDURE (VAR t: Tree) Move (node, parent: TreeNode; pos: INTEGER)
NEW
Moves a node in a tree from its current place to the place specified by parent and pos. The interpretation of parent and pos is the same as in NewChild.
Pre
node # NIL
(pos >= 0) OR (pos = firstPos) OR (pos = lastPos)
Post
t.NofNodes() = t.NofNodes()'
PROCEDURE (VAR t: Tree) Parent (node: TreeNode): TreeNode
NEW
Returns the parent node of node. If node is a root then NIL is returned.
Pre
node # NIL
PROCEDURE (VAR t: Tree) Child (node: TreeNode; pos: INTEGER): TreeNode
NEW
Returns the child at position pos of node. If node is NIL the root at position pos is returned. The constants firstPos and lastPos can be used to retrieve the first and last child of a node. If node has no children or if it has fewer children than the value of pos, then NIL is returned.
Pre
(pos >= 0) OR (pos = firstPos) OR (pos = lastPos)
PROCEDURE (VAR t: Tree) Next (node: TreeNode): TreeNode
NEW
Returns the next node at the same level and with the same parent as node i.e. If node is at position pos then the returned node is at position pos + 1. If node is the last child of its parent then NIL is returned.
Pre
node # NIL
PROCEDURE (VAR t: Tree) Prev (node: TreeNode): TreeNode
NEW
Returns the previous node at the same level and with the same parent as node. If node is at position pos then the returned node is at position pos - 1. If node is the first child of its parent then NIL is returned.
Pre
node # NIL
PROCEDURE (VAR t: Tree) Select (node: TreeNode)
NEW
Makes node become the selected node in the tree. If node is NIL then there is no selection in the tree.
PROCEDURE (VAR t: Tree) Selected (): TreeNode
NEW
Returns the selected node in a tree. If no node is currently selected then NIL is returned.
TYPE Color
Type for colors.
val: INTEGER
Current color value (in the same format as Ports.Color).
TYPE Currency
Type for money values.
val: LONGINT
The fixed-point value of the currency. The true value is val / 10^scale.
scale: INTEGER scale > 0
Scale factor for val. For example, val = 12475 and scale = 2 is the representation for 124.75. If the currency denotes US dollars, then scale = 2 means that values can be displayed and entered with cent precision. A value of 3 would increase precision to 1/10 of a cent.
TYPE Par
Values of this parameter type are used to set up the names of menu items, and to disable or check menu items. A procedure of type GuardProc has a variable parameter of type Par.
disabled: BOOLEAN
Initially set to FALSE, this field can be set to TRUE by guard commands, to disable a menu item or a control.
checked: BOOLEAN
Initially set to FALSE, this field can be set to TRUE to show a check mark for a menu item.
undef: BOOLEAN
Initially set to FALSE, this field can be set to TRUE to set the undef state of a control.
readOnly: BOOLEAN
Initially set to FALSE, this field can be set to TRUE to set the readOnly state of a control.
label: String
For menu items or controls which show different labels depending on the current context, the current string can be deposited here.
TYPE GuardProc = PROCEDURE (VAR par: Par)
Menu guard or control guard commands must have this signature (or the extended version described below). They can set the fields of the par parameter to suitable values. Guard commands are called to determine the current state (in particular to find out whether the item is currently enabled) of a menu item or a control.
For menu items, the guard commands are specified in the respective subsystem's /Rsrc/Menus text, or in System/Rsrc/Menus. Menu guard commands are called after the user clicks in the menu bar, and before the menu appears.
For controls, the guard commands are specified in the inspector dialog which allows to set the various control properties. Control guard commands are called after the user interactively changed the state of a control, or after a program calls the procedure Update or UpdateList (or one of the other update procedures).
Note that when the user clicks in a menu bar, possibly all menu guard commands may be executed. After the contents of an interactor has been changed and Update or UpdateList (or one of the other update procedures) has been called, all control guards are executed. This means two things. First, a guard command must be efficient. And second, the module which contains the guard is loaded as soon as the guard is evaluated for the first time. In this respect, menu commands are a certain pitfall during development: when a module has been unloaded, it is reloaded as soon as the user tries to execute a menu command.
Guard commands may only modify fields of their par parameters, they must not modify any other state of the system, e.g., global variables. This means that the evaluation of a guard is similar to a function call without side-effects. Avoiding side-effects is particularly important since guards may be called by the framework at relatively unpredictable times.
An extended version of GuardProc can be used as an alternative, with the following signature:
PROCEDURE (n: INTEGER; VAR par: Par)
An actual parameter for n must be a constant.
TYPE NotifierProc = PROCEDURE (op, from, to: INTEGER)
A notifier procedure must have one of the following signatures:
PROCEDURE (op, from, to: INTEGER)
PROCEDURE (n, op, from, to: INTEGER)
Through calls of notification procedures, an application can be notified of manipulations of a control. op determines the kind of manipulation:
op = pressed: A mouse-down event has occurred.
op = released: A mouse-up event has occurred.
op = changed: The value of a control (not bound to a SET or a Selection) has been changed.
op = included: Range [from..to] has been included in a SET or a Selection. It wasn't included before.
op = excluded: Range [from..to] has been excluded from a SET or a Selection. It was included before.
op = set: Range [from..to] has been set in a SET or a Selection after clearing the previous selection.
An actual parameter for n must be a constant.
TYPE LangNotifier = POINTER TO ABSTRACT RECORD END;
Objects of this type can be registered and unregistered using RegisterLangNotifier and RemoveLangNotifier.
PROCEDURE (n: LangNotifier) Notify-
NEW, ABSTRACT
This method is called for all registered LangNotifiers whenever the language is changed. The order in which the language notifiers are called is undefined.
VAR metricSystem: BOOLEAN
This variable indicates whether sizes should be measured in metric units or in inches.
VAR showsStatus: BOOLEAN
Indicates whether status messages are currently displayed. If showsStatus = FALSE, the procedures ShowParamStatus and ShowStatus will have no visible effect.
VAR version: INTEGER
Indicates the current major version of BlackBox.
10 = version 1.0
11 = version 1.1
12 = version 1.2
13 = version 1.3
14 = version 1.4
15 = version 1.5
16 = version 1.6
17 = version 1.7
VAR platform: INTEGER
Indicates on which host operating system the application is running.
VAR appName: ARRAY 32 OF CHAR
Gives the name of the application program which is currently running; the default is "BlackBox".
VAR appVersion: ARRAY 32 OF CHAR
Gives the version of the application program which is currently running; the default is taken from the System property 'appVersion'.
VAR language-: Language
Current language in ISO 639 codes. See SetLanguage for more information about language support.
VAR user: ARRAY 32 OF CHAR
Login name of current user. Currently not used.
VAR thickCaret: BOOLEAN
Determines whether the text subsystem uses a Word-like thick caret or a normal thin caret.
VAR caretPeriod: INTEGER
Determines the blinking period that the text subsystem uses for caret blinking. The period is given in ticks (1/1000 second). The default is 500, i.e., half a second.
VAR beep: BOOLEAN
If not checked, Dialog.Beep is silent.
VAR serverMode: BOOLEAN
Optimizes BlackBox for operating as a server:
(1) background task processing while mouse tracking,
(2) shortest possible idle periods in main Windows thread (needs a restart of BlackBox in order to be effective).
Warning about possible side-effects caused by background task processing in server mode.
Note the potential CPU overhead in server mode caused by a smaller idlePeriod.
For compatible with the BlackBox 1.6 switch off the serverMode.
VAR commandLinePars: String
Command line parameters that have been passed when starting BlackBox. Variable commandLinePars contains the string entered on the command line following the /PAR option. The string can be specified enclosed in either single or double quotes. Quotes may be omitted if no white space is contained in the string. If no /PAR option is present on the command line, commandLinePars contains the empty string.
Examples:
/PAR test
/PAR "parameter string"
/PAR 'A string containing a " can be entered like this'
VAR mapRes: INTEGER
Result of the last MapString operation:
0 — ok
6 — result is not fit into target array, clipped
5 — requested string is not mapped (not found in a strings file)
4 — strings file isn't loaded (not found or error)
1..3 — request syntax error
PROCEDURE IsLinux (): BOOLEAN;
Returns TRUE if and only if the application is runing under any Linux version. Note that in case of using the Windows emulator Wine IsLinux returns FALSE.
PROCEDURE IsMac (): BOOLEAN;
Returns TRUE if and only if the application is runing under any MacOS version.
PROCEDURE IsWindows (): BOOLEAN;
Returns TRUE if and only if the application is runing under any Windows verson. Note that also in case of using the Windows emulator Wine IsWindows returns TRUE.
PROCEDURE IsWine (): BOOLEAN;
Returns TRUE if and only if the application is runing under the Windows emulator Wine. Note that IsWine() implies IsWindows().
PROCEDURE Update (IN x: ANYREC)
This procedure should be called after one or several fields of the interactor x have been modified by a program (it is called automatically when a field has been modified interactively via a control). It causes all controls which are bound to fields of this interactor to be updated, and then guards are evaluated.
PROCEDURE UpdateList (IN x: ANYREC)
For list-structured controls (list boxes, selection boxes, combo boxes, tree controls), the lists are re-created. For efficiency reasons, this is not done after a call to Update.
Note that UpdateList also includes the functionality of Update, thus for efficiency reasons you shouldn't call UpdateList(rec); Update(rec).
PROCEDURE UpdateBool (VAR x: BOOLEAN)
Similar to Update, except that it accepts a BOOLEAN parameter.
PROCEDURE UpdateByte (VAR x: BYTE)
Similar to Update, except that it accepts a BYTE parameter.
PROCEDURE UpdateChar (VAR x: CHAR)
Similar to Update, except that it accepts a CHAR parameter.
PROCEDURE UpdateInt (VAR x: INTEGER)
Similar to Update, except that it accepts an INTEGER parameter.
PROCEDURE UpdateLInt (VAR x: LONGINT)
Similar to Update, except that it accepts a LONGINT parameter.
PROCEDURE UpdateReal (VAR x: REAL)
Similar to Update, except that it accepts a REAL parameter.
PROCEDURE UpdateSChar (VAR x: SHORTCHAR)
Similar to Update, except that it accepts a SHORTCHAR parameter.
PROCEDURE UpdateSInt (VAR x: SHORTINT)
Similar to Update, except that it accepts a SHORTINT parameter.
PROCEDURE UpdateSReal (VAR x: SHORTREAL)
Similar to Update, except that it accepts a SHORTREAL parameter.
PROCEDURE UpdateSString (IN x: ARRAY OF SHORTCHAR)
Similar to Update, except that it accepts an ARRAY OF SHORTCHAR parameter.
PROCEDURE UpdateSet (VAR x: SET)
Similar to Update, except that it accepts a SET parameter.
PROCEDURE UpdateString (IN x: ARRAY OF CHAR)
Similar to Update, except that it accepts an ARRAY OF CHAR parameter.
PROCEDURE MapParamString (in, p0, p1, p2: ARRAY OF CHAR; OUT out: ARRAY OF CHAR)
Translates string in into string out. Strings in of the form "#Subsystem:message" with non-empty Subsystem and message are translated if there is a corresponding entry in the "Strings" resource file for this subsystem (in the subsystem's "Rsrc" directory). Otherwise, the "#Subsystem:" prefix is stripped away.
As an example, "#System:Cancel" may be translated to "Cancel" in the USA, and to "Abbrechen" in Germany; or to "Cancel" if the resource file or the appropriate entry is missing.
The form "#SubsystemModule:message" addresses to module's strings-resource file "ModuleStrings" for subsystem Subsystem.
Three additional input parameters can be spliced into the in parameter. These parameters are inserted where "^0", "^1", or "^2" occur in in. The parameters are not mapped, but merely substituted.
MapParamString allows to remove country- and language-specific strings from a program source text, while at the same time providing a default string in the program source text such that the program always works, even if string resources are missing.
Post
mapRes IN {0..6}
PROCEDURE MapString (in: ARRAY OF CHAR; OUT out: ARRAY OF CHAR)
This is a simplified version of MapParamString which has no additional input parameters.
Except for performance, equivalent to:
MapParamString(in, "", "", "", out)
PROCEDURE RegisterLangNotifier (notifier: LangNotifier)
Adds notifier to the list of LangNotifiers to be called every time the language is changed.
Pre
notifier # NIL 20
PROCEDURE RemoveLangNotifier (notifier: LangNotifier)
Removes notifier from the list of LangNotifiers called every time the language is changed.
Pre
notifier # NIL, 20
PROCEDURE SetLanguage (lang: ARRAY OF CHAR; persistent: BOOLEAN)
Sets the current language to lang, specified in ISO 639 code. This indicates that String resources are not read from the Rsrc-directory directly but from a subdirectory within the Rsrc-directory with the same name as the language code. It also sets the value of the global variable language.
For example, if lang = "de" the String resources are read from the directory "Rsrc/de". If no such directory exists or the requested resource does not exist then the resources are read from the normal Rsrc-directory. An empty string implies that no particular language has been selected and resources are read from the Rsrc-directory.
The persistent parameter indicates whether the setting is being used again when BlackBox is started the next time. persistent = nonPersistent causes a non-permanent change, i.e. the change is effective for this particular instance of BlackBox only. With persistent = persistent the change is registered in a registry and the language will be set immediately when BlackBox starts up next time.
For information on how to do software that needs to be notified whenever the value of the global variable language is changing, see RegisterLangNotifier.
Pre
(lang = "") OR (LEN(lang$) = 2) 20
PROCEDURE ResetLanguage
Resets the current language to the value of the last persistent setting. See also SetLanguage.
PROCEDURE ShowParamMsg (IN str, p0, p1, p2: ARRAY OF CHAR)
Presents str as a message to the user. The string str is mapped. The additional input parameters p0, p1, and p2 are not mapped. This procedure is used to present urgent messages to the user, typically alerting the user that some action has failed. It shouldn't be used for casual success messages. If a log window is present it is assumed that the user prefers these kind of messages in the log. Therefore the message is printed in the log if one exists, otherwise the message is displayed in a separately opened dialog box.
Pre
LEN(str$) # 0 20
PROCEDURE ShowMsg (IN str: ARRAY OF CHAR)
This is a simplified version of ShowParamMsg which has no additional input parameters.
Except for performance, equivalent to:
ShowParamMsg(str, "", "", "")
Pre
LEN(str$) # 0 20
PROCEDURE ShowParamStatus (IN str, p0, p1, p2: ARRAY OF CHAR)
Presents str as a message to the user. The string str is mapped. The additional input parameters p0, p1, and p2 are not mapped. In contrast to ShowParamMsg, ShowParamStatus is used for shorter-lived and less urgent messages; e.g., messages produced and updated during a lengthy process. This procedure should not be used for vital messages, because on some platforms there may be no status area to display status messages, or the message mechanism may be switched off. These conditions are indicated by the global variable showsStatus.
PROCEDURE ShowStatus (IN str: ARRAY OF CHAR)
This is a simplified version of ShowParamStatus which has no additional input parameters.
Except for performance, equivalent to:
ShowParamStatus(str, "", "", "")
PROCEDURE FlushMappings
String mappings are cached in internal tables for efficiency reasons. This procedure flushes all string mapping tables. This forces a reload of these tables from the string resource files as soon as the mappings are performed again.
PROCEDURE GetOK (IN str, p0, p1, p2: ARRAY OF CHAR; form: SET; OUT res: INTEGER)
Modal dialog
Presents a mapped string, with the optional parameters p0 to p2, in a modal dialog box. form indicates the set of buttons of the dialog box. Only meaningful combinations are allowed:
{ok}
{ok, cancel}
{yes, no}
{yes, no, cancel}
res indicates which button has been pressed by the user.
Pre
((yes IN form) = (no IN form)) & ((yes IN form) # (ok IN form)) 20
Post
res IN form
PROCEDURE GetIntSpec (defType: Files.Type; VAR loc: Files.Locator; OUT name: Files.Name)
Modal dialog
Ask the user for a file specification (loc, name). defType indicates which file type is desired ("" stands for any file type; other types are platform-specific, e.g., "txt" for Windows Ascii files). loc # NIL indicates a valid file specification.
Pre
defType = "" OR defType is legal type name on this platform 20
PROCEDURE GetExtSpec (defName: Files.Name; defType: Files.Type; VAR loc: Files.Locator;
OUT name: Files.Name)
Modal dialog
Ask the user for a file specification for externalizing a file. defName is the default name presented to the user. defType is the file type which should be used as default type. loc # NIL indicates a valid file specification.
Pre
defType = "" OR defType is legal type name on this platform 20
PROCEDURE GetColor (in: INTEGER; OUT out: LONGINT; OUT set: BOOLEAN)
Modal dialog
Ask the user for a color. in is the default color presented to the user.
PROCEDURE Call (IN cmd, errorMsg: ARRAY OF CHAR; OUT res: INTEGER)
Call executes a sequence of BlackBox commands denoted by cmd. If the corresponding modules are not yet loaded, Call tries to load them. If some error occurs, command execution terminates and res is returned with a value # 0. If errorMsg = "", Call does not display error messages. If errorMsg # "", Call displays errorMsg in case of an error, appended with a short description of the particular error having occurred.
The syntax for commands with parameters is explained in the documentation of module StdInterpreter.
PROCEDURE Beep
Emit a short beep sound.
PROCEDURE Notify
Used internally.
PROCEDURE RunExternal (IN exeName: ARRAY OF CHAR)
Run any external application.
exeName is the command string, which includes the name of an external ".exe" filename, possibly including its full path, and any command line parameters that this application needs.
Windows OS specific documentation:
Some applications may close their "Run environment" window before their output can be read. This window can be kept open by adding the string "cmd /k " to the beginning of exeName before calling RunExternal.
Opening this window can be avoided, with the default ExtCallHook, by setting WinDialog.hideExtRunWindow to TRUE before calling RunExternal, which then resets it to FALSE.
PROCEDURE OpenExternal (IN fileName: ARRAY OF CHAR)
Open fileName in external application associated with such file type.
URLs will be opened in default browser application.
PROCEDURE RequestExit* (allow: BOOLEAN)
Allow or forbid exit from the application once all windows are closed by the user. See module Loop for a discussion of the main loop and application kinds supported by the framework.
| System/Docu/Dialog.odc |
Documents
This module has a private interface, it is only used internally.
| System/Docu/Documents.odc |
Files
DEFINITION Files;
CONST
exclusive = FALSE; shared = TRUE;
dontAsk = FALSE; ask = TRUE;
readOnly = 0; hidden = 1; system = 2; archive = 3; stationery = 4;
TYPE
Name = ARRAY 256 OF CHAR;
Type = ARRAY 16 OF CHAR;
FileInfo = POINTER TO RECORD
next: FileInfo;
name: Name;
length: INTEGER;
type: Type
modified: RECORD
year, month, day, hour, minute, second: INTEGER
END;
attr: SET
END;
LocInfo = POINTER TO RECORD
next: LocInfo;
name: Name;
attr: SET
END;
Locator = POINTER TO ABSTRACT RECORD
res: INTEGER;
(l: Locator) This (IN path: ARRAY OF CHAR): Locator, NEW, ABSTRACT
END;
File = POINTER TO ABSTRACT RECORD
type-: Type;
(f: File) Length (): INTEGER, NEW, ABSTRACT;
(f: File) NewReader (old: Reader): Reader, NEW, ABSTRACT;
(f: File) NewWriter (old: Writer): Writer, NEW, ABSTRACT;
(f: File) Flush, NEW, ABSTRACT;
(f: File) Register (name: Name; type: Type; ask: BOOLEAN;
OUT res: INTEGER), NEW, ABSTRACT;
(f: File) Close, NEW, ABSTRACT;
(f: File) InitType (type: Type), NEW
END;
Reader = POINTER TO ABSTRACT RECORD
eof: BOOLEAN;
(r: Reader) Base (): File, NEW, ABSTRACT;
(r: Reader) Pos (): INTEGER, NEW, ABSTRACT;
(r: Reader) SetPos (pos: INTEGER), NEW, ABSTRACT;
(r: Reader) ReadByte (OUT x: BYTE), NEW, ABSTRACT;
(r: Reader) ReadBytes (VAR x: ARRAY OF BYTE; beg, len: INTEGER), NEW, ABSTRACT
END;
Writer = POINTER TO ABSTRACT RECORD
(w: Writer) Base (): File, NEW, ABSTRACT;
(w: Writer) Pos (): INTEGER, NEW, ABSTRACT;
(w: Writer) SetPos (pos: INTEGER), NEW, ABSTRACT;
(w: Writer) WriteByte (x: BYTE), NEW, ABSTRACT;
(w: Writer) WriteBytes (IN x: ARRAY OF BYTE; beg, len: INTEGER), NEW, ABSTRACT
END;
Directory = POINTER TO ABSTRACT RECORD
(d: Directory) This (IN path: ARRAY OF CHAR): Locator, NEW, ABSTRACT;
(d: Directory) Temp (): File, NEW, ABSTRACT;
(d: Directory) New (loc: Locator; ask: BOOLEAN): File, NEW, ABSTRACT;
(d: Directory) Old (loc: Locator; name: Name; shared: BOOLEAN): File, NEW, ABSTRACT;
(d: Directory) Delete (loc: Locator; name: Name), NEW, ABSTRACT;
(d: Directory) Rename (loc: Locator; old, new: Name; ask: BOOLEAN), NEW, ABSTRACT;
(d: Directory) SameFile (loc0: Locator; name0: Name;
loc1: Locator; name1: Name): BOOLEAN, NEW, ABSTRACT;
(d: Directory) FileList (loc: Locator): FileInfo, NEW, ABSTRACT;
(d: Directory) LocList (loc: Locator): LocInfo, NEW, ABSTRACT;
(d: Directory) GetFileName (name: Name; type: Type; OUT filename: Name), NEW, ABSTRACT
END;
VAR
dir-, stdDir-: Directory;
docType-, objType-, symType-: Type;
PROCEDURE SetDir (d: Directory);
END Files.
Most programmers never need to deal with files directly, instead they can use readers and writers (of module -> Stores) which are set up already by BlackBox!
Module Files provides the abstractions necessary to handle most aspects of a hierarchical file system. A file is a sequence of bytes. Several access paths can be open simultaneously on the same file, possibly at different positions.
A file and its access paths are modeled as separate data structures, namely as File and Reader/Writer. Where a statement applies both to readers and writers, the term "rider" will be used. An open rider is never closed explicitly, and an application can create as many riders as it needs.
Figure 1: File with three riders
Each file resides at some location in the file hierarchy (i.e., in a subdirectory). In BlackBox, a location is described by a locator object. A directory object provides a procedure which creates a locator, given a path name in the host platform's file name syntax. Most other directory operations take a locator as parameter, to find the specific subdirectory where the operation should be performed.
For temporary files, a system-specific (implicit) location is used. Temporary files are used as scratch files, and cannot be registered in the file directory. Module Dialog provides further sources for file locators, via standard file dialogs.
A file itself is specified by a location and a name. The name is the file's local name at the given location, i.e., it cannot be a path name.
A directory object provides three procedures to access a file: New, Temp, and Old. New creates a new file. This file already has a particular location, but is anonymous, i.e., it has no name (yet). When the file's contents are written, the file can be registered under a given name, possibly replacing an already existing file which in turn becomes anonymous itself. File registration is an atomic action, which reduces the danger that a file is replaced by a new, but incomplete or corrupted, file.
Anonymous files for which no more riders exist are automatically deleted by the garbage collector, at an appropriate time.
Temp creates a temporary file. Such a file is never registered, and thus remains anonymous.
Old looks up and opens an existing file, given its name and location. The file may either be opened in shared or in exclusive mode. "shared" means that it may be looked up and opened by several programs simultaneously, but that none may alter it (immutable file). Even if a file has been opened, its entry in the file directory is replaced when a new file is registered at the same location and under the same name. In this case, the old file remains accessible through the existing file readers. However, looking up this file with procedure Old yields the most recently registered file version. When no more riders on an older file version exist, the disk space occupied by the file is reclaimed by the garbage collector eventually.
Opening a file in shared mode is the rule in BlackBox; opening a file in exclusive mode is an infrequent exception. "exclusive" means that at most one program may open a file. As long as the file is not closed again, other programs remain locked out, i.e., Old on the same file fails. An exclusively opened file may be modified (mutable file), which is useful for simple data base applications. Registering a new file under the same name as an exclusively opened file has the same effect as for shared files, i.e., the existing file becomes anonymous, and is garbage collected eventually.
A file can be opened in exclusive mode, closed, and then be opened again in shared mode, for example. However, it can never be open in exclusive and in shared mode simultaneously.
Open files for which no more riders exist are automatically closed by the garbage collector at an appropriate time. For files opened in exclusive mode, it is recommended that they be closed explicitly, in order to make them accessible again to other programs as early as possible.
A directory object represents all accessible files (not just one subdirectory), independent of their location in the file hierarchy. There is exactly one file hierarchy. However, every BlackBox service may implement its own file directory object. Such an object represents exactly the same file hierarchy, but may provide different ways to look up files, e.g., by applying default search paths, or it may define a current directory relative to which path names are evaluated, etc.
Files are typed. This means that each file has a type attribute which is a string, typically of length 3. On some platforms, the host file system knows about file types (Mac OS), while on others file types are simulated by using file suffixes as extensions (Windows). File types are useful to tell the system which operations are permissible on files and which aren't. For example, it is possible to install file converters (-> Converters) in BlackBox which translate between file and memory data structures.
Example: ObxAsciidocu
CONST exclusive, shared
Values which can be passed to the Directory.Old.shared parameter, to determine whether a file should be opened in shared or in exclusive mode.
CONST ask, dontAsk
Values which can be passed to the Directory.New, Directory.Rename, and File.Register methods.
CONST readOnly
Possible value for FileInfo.attr. Indicates that the file can be accessed only for reading.
CONST hidden
Possible value for FileInfo.attr. Indicates that the file is not displayed when the user lists the available file.
CONST system
Possible value for FileInfo.attr. Indicates that the file belongs to the operating system.
CONST archive
Possible value for FileInfo.attr. Indicates that the file is an archive.
CONST stationery
Possible value for FileInfo.attr. Indicates that the file is a stationery (i.e., a template).
TYPE Name
String type for file names.
TYPE Type
String type for file type names. Under Windows, file type names correspond to the three-character file name extensions, e.g., file XYZ.txt has type txt.
TYPE Locator
ABSTRACT
A file locator identifies a location in the file system.
File locators are used internally, and sometimes in commands which operate on non-BlackBox files.
File locators are extended internally.
res: INTEGER
Directory operations return their results in the locator's res field.
The following result codes are predefined:
res = 0 no error
res = 1 invalid parameter (name or locator)
res = 2 location or file not found
res = 3 file already exists
res = 4 write-protection
res = 5 io error
res = 6 access denied
res = 7 illegal file type
res = 8 cancelled
res = 80 not enough memory
res = 81 not enough system resources (disk space, file handles, etc.)
A particular BlackBox implementation may return additional, platform-specific, error codes. These error codes always have negative values.
PROCEDURE (l: Locator) This (IN path: ARRAY OF CHAR): Locator
NEW, ABSTRACT
This evaluates a relative path starting from the location specified by l.
Post
result # NIL
result.res = 0 no error
result.res # 0 illegal locator
TYPE FileInfo
This record represents information about a file.
next: FileInfo
Next entry in the list of file descriptors. No particular ordering is defined.
name: Name name # ""
The file's name.
length: INTEGER length >= 0
The file's length in bytes.
type: Type type # ""
The file's type.
modified: RECORD year, month, day, hour, minute, second: INTEGER END
Date and time of most recent modification of the file.
attr: SET
Indicates various optional attributes of a file (readOnly, hidden, system, archive, stationery).
TYPE LocInfo
This record represents information about a location.
next: LocInfo
Next entry in the list of location descriptors. No particular ordering is defined.
name: Name name # ""
The file's name.
attr: SET
Indicates various optional attributes of a location (readOnly, hidden, system, archive).
TYPE File
ABSTRACT
A file is a carrier for a linear sequence of bytes, which typically resides on a hard disk or similar device.
Files are allocated by file directories.
Files are used by commands which operate on non-BlackBox files.
Files are extended internally.
type-: Type type # ""
This file's file type.
PROCEDURE (f: File) Length (): INTEGER
NEW, ABSTRACT
Returns the current length of the file in bytes.
Post
result >= 0
PROCEDURE (f: File) NewReader (old: Reader): Reader
NEW, ABSTRACT
Returns a reader which has the appropriate type (for this file type). If old = NIL, then a new reader is allocated. If old # NIL and old has the appropriate type, old is returned. Otherwise, a new reader is allocated. The returned reader is connected to f, its eof field is set to FALSE, and its position is somewhere on the file. If an old reader is passed as parameter, the old position will be retained if possible.
If an old reader is passed as parameter, it is the application's responsibility to guarantee that it is not in use anymore. Passing an unused old reader is recommended because it avoids unnecessary allocations.
Post
result # NIL
~result.eof
old # NIL & old.Base() = f
result.Pos() = old.Pos()
old = NIL OR old.Base() # f
result.Pos() = 0
PROCEDURE (f: File) NewWriter (old: Writer): Writer
NEW, ABSTRACT
Returns a writer which has the appropriate type (for this file type). If old = NIL, then a new writer is allocated. If old # NIL and old has the appropriate type, old is returned. Otherwise, a new writer is allocated. The returned writer is connected to f, and its position is somewhere on the file. If an old writer is passed as parameter, the old position will be retained if possible.
If an old writer is passed as parameter, it is the application's responsibility to guarantee that it is not in use anymore. Passing an unused old writer is recommended because it avoids unnecessary allocations.
Read-only files allow no writers at all.
Post
result # NIL
old # NIL & old.Base() = f
result.Pos() = old.Pos()
old = NIL OR old.Base() # f
result.Pos() = f.Length()
PROCEDURE (f: File) Flush
NEW, ABSTRACT
To guarantee consistency of the file, Flush should be called after the last writer operation. Superfluous calls of Flush have no effect.
Close may call Flush internally.
PROCEDURE (f: File) Register (name: Name; type: Type; ask: BOOLEAN; OUT res: INTEGER)
NEW, ABSTRACT
Register makes an anonymous file permanently available. If a file with the same name at the same location already exists, it is deleted first. If the deletion does not work, i.e. when the file is write protected, the parameter ask determines whether a platform specific error message is displayed or not. Pass either the constant ask or dontAsk.
Register can be considered as an atomic action.
Only files opened with procedure New may be registered. Trying to register a file opened with Old results in a precondition violation error.
If an already existing file is deleted during Register, only its entry in the file directory is removed. The file's contents are still available to existing file riders. The space occupied by a file is reclaimed at an unspecified time after no more riders on it exist anymore.
The file f and the riders operating on file f are not valid anymore after registering f, i.e., no more file or rider operations may be performed on it. This also implies that Register may only be executed once. However, the registered file can be retrieved by procedure Old again.
Register may call Flush internally, and closes the file.
Each registered file has a file type, which is passed to Register in the type parameter.
Pre
f is anonymous and not temporary 20
name # "" 21
name is a file name 22
Post
res = 0 no error
res = 1 invalid parameter (name or locator)
res = 2 location or file not found
res = 3 file already exists
res = 4 write-protection
res = 5 io error
res = 6 access denied
res = 7 illegal file type
res = 8 cancelled
res = 80 not enough memory
res = 81 not enough system resources (disk space, file handles, etc.)
A particular BlackBox implementation may return additional, platform-specific, error codes. These error codes always have negative values.
PROCEDURE (f: File) Close
NEW, ABSTRACT
Closes an open file. Close does nothing if the file is not open. If a call to New or Old is not balanced by a call to Close, the Close is later performed automatically, at an unspecified time. If it is known that a file won't be used again, it is recommended to call its Close procedure.
The file f and the riders operating on file f are not valid anymore after closing f, i.e., no more file or rider operations may be performed on it. However, the closed file can be retrieved and opened again by procedure Old.
Close may call Flush internally.
Close should (but need not necessarily) be called explicitly after a file is not needed anymore.
PROCEDURE (f: File) InitType (type: Type)
Initializes the file's type field.
Pre
type # "" 20
f.type = "" OR f.type = type 21
TYPE Reader
ABSTRACT
Reading access path to a file carrier.
Readers are allocated by their base files.
Readers are used by commands which read non-BlackBox files and operate at the byte level.
Readers are extended internally.
eof: BOOLEAN
Set when it has been attempted to read the byte after the end of the file (by ReadByte or ReadBytes). Reset when the reader is generated or positioned.
PROCEDURE (r: Reader) Base (): File
NEW, ABSTRACT
Returns the file to which the reader is currently connected.
Post
result # NIL
PROCEDURE (r: Reader) Pos (): INTEGER
NEW, ABSTRACT
Returns the reader's current position.
Post
0 <= result <= r.Base().Length()
PROCEDURE (r: Reader) SetPos (pos: INTEGER)
NEW, ABSTRACT
Sets the reader's current position to pos and clears the eof flag.
Pre
pos >= 0 20
pos <= r.Base().Length() 21
Post
r.Pos() = pos
~r.eof
PROCEDURE (r: Reader) ReadByte (OUT x: BYTE)
NEW, ABSTRACT
Attempts to read the byte after the current position. If successful, it increments the position by one. If the current position (before reading) is at the end of the available data, i.e., Pos equals the carrier data's length, then r.eof is set.
ReadByte internally may call SetPos.
Post
r.Pos()' < r.Base().Length()
r.Pos() = r.Pos()' + 1
~r.eof
x = byte after r.Pos()'
r.Pos()' = r.Base().Length()
r.Pos() = r.Base().Length()
r.eof
x = 0H
PROCEDURE (r: Reader) ReadBytes (VAR x: ARRAY OF BYTE; beg, len: INTEGER)
NEW, ABSTRACT
Attempts to read len bytes after the current position. It increments the position by the number of bytes which have been read successfully. If reading is continued beyond the file's length, then r.eof is set. The data are transferred to the array x starting at element beg.
ReadBytes internally may call SetPos.
Pre
beg >= 0 20
len >= 0 21
beg + len <= LEN(x) 22
Post
r.Pos()' <= r.Base().Length() - len
r.Pos() = r.Pos()' + len
~r.eof
len bytes read after r.Pos()' and transferred into x
r.Pos()' > r.Base().Length() - len
r.Pos() = r.Base().Length()
r.eof
r.Base().Length() - r.Pos()' bytes read after r.Pos()' and transferred into x
TYPE Writer
ABSTRACT
Writing access path to a file carrier.
Writers are allocated by their base files.
Writers are used by commands which write non-BlackBox files and operate at the byte level.
Writers are extended internally.
PROCEDURE (w: Writer) Base (): File
NEW, ABSTRACT
Returns the file to which the writer is currently connected.
Post
result # NIL
PROCEDURE (w: Writer) Pos (): INTEGER
NEW, ABSTRACT
Returns the writer's current position.
Post
0 <= result <= w.Base().Length()
PROCEDURE (w: Writer) SetPos (pos: INTEGER)
NEW, ABSTRACT
Sets the writer's current position to pos.
Pre
pos >= 0 20
pos <= w.Base().Length() 21
Post
w.Pos() = pos
PROCEDURE (w: Writer) WriteByte (x: BYTE)
NEW, ABSTRACT
Writes a byte after the current position, then increments the current position. If the current position is at the end of the carrier data, the writer's length is incremented also.
WriteByte internally may call SetPos.
Post
x written at w.Pos()'
w.Pos() = w.Pos()' + 1
w.Pos()' < w.Base().Length()'
w.Base().Length() = w.Base().Length()'
x has overwritten old value after w.Pos()'
w.Pos()' = w.Base().Length()'
w.Base().Length() = w.Base().Length()' + 1
x was appended
PROCEDURE (w: Writer) WriteBytes (IN x: ARRAY OF BYTE; beg, len: INTEGER)
NEW, ABSTRACT
Writes len bytes after the current position and increments the position accordingly. If necessary the stream's length is increased. The data are transferred from array x starting with element beg.
WriteBytes internally may call SetPos.
Pre
beg >= 0 20
len >= 0 21
beg + len <= LEN(x) 22
Post
len bytes transferred from variable x to carrier
w.Pos() = w.Pos()' + len
w.Pos()' + len <= w.Base().Length()'
w.Base().Length() = w.Base().Length()'
w.Pos()' + len > w.Base().Length()'
w.Base().Length() = w.Pos()' + len
TYPE Directory
ABSTRACT
Directory for the lookup in and manipulation of file directories.
File directories are allocated by BlackBox.
File directories are used by commands which operate on non-BlackBox files.
File directories are extended internally.
PROCEDURE (d: Directory) This (IN path: ARRAY OF CHAR): Locator
NEW, ABSTRACT
Returns a locator, given an absolute or relative path name in the host platform's syntax.
This may perform some validity checks, e.g., whether the syntax of the path name is correct. A relative path (including an empty path) is evaluated starting from the directory's default location. With the standard BlackBox configuration the directory denoted by Files.dir uses the BlackBox startup directory as the default. This does not check if the specified path exists.
Post
result # NIL
result.res = 0 no error
result.res = 1 invalid name
result.res = 5 io error
PROCEDURE (d: Directory) Temp (): File
NEW, ABSTRACT
Returns a temporary file. This file is anonymous, i.e., not registered in a directory. (In host file systems where anonymous files are not directly supported, they may appear under temporary names in a suitable subdirectory.) Registration is not possible on a temporary file.
A temporary file always has both read and write capabilities (mutable file).
Post
result # NIL
PROCEDURE (d: Directory) New (loc: Locator; ask: BOOLEAN): File
NEW, ABSTRACT
Returns a new file object (or NIL if this is not possible). This file is anonymous, i.e., not yet registered in the directory. (In host file systems where anonymous files are not directly supported, they may appear under temporary names in subdirectory loc.) If the file is registered later, it will appear in the subdirectory specified by loc.
If loc indicates a location that does not yet exist, the necessary location(s) (i.e., directories) must be created first. Parameter ask determines whether the user is asked for the permission to do so. Pass either the constant ask or dontAsk.
A new file always has both read and write capabilities (mutable file).
If location loc does not exist, the user may be asked whether the location should be created (loc.res = 0) or not (loc.res = 8).
Pre
loc # NIL 20
Post
result # NIL
loc.res = 0 no error
result = NIL
loc.res = 1 invalid name
loc.res = 2 location not found
loc.res = 4 write-protection
loc.res = 5 io error
loc.res = 8 cancelled
PROCEDURE (d: Directory) Old (loc: Locator; name: Name; shared: BOOLEAN): File
NEW, ABSTRACT
Looks up and opens a file with name name at location loc. It returns this file (or NIL if this is not possible). Parameter shared determines whether the returned file is in shared or in exclusive mode. A shared file provides read-only access. This means that several applications may read the file simultaneously, but it may not be modified. An exclusively opened file provides exclusive read and write access. This means that both read and write access are denied to any other application. Note however, that the application may pass on the file pointer to wherever it likes. The point is, another application cannot gain access to the file solely via the file directory, without cooperation of the application which currently has access. Moreover, "exclusive" access does not imply that only one rider may be active on the file.
A file is usually opened in shared mode. To change its contents, a new file is generated and then registered under the old name. If only a small part of the data is actually changed, it may be more appropriate to use the exclusive mode instead, e.g. when implementing simple data bases. In this case, the file should be closed explicitly as soon as it isn't needed anymore.
Pre
loc # NIL 20
name # "" 21
Post
result # NIL
loc.res = 0 no error
result = NIL
loc.res = 1 invalid name
loc.res = 2 location or file not found
loc.res = 6 access denied
PROCEDURE (d: Directory) Delete (loc: Locator; name: Name)
NEW, ABSTRACT
Deletes the file specified by loc and name.
Pre
loc # NIL 20
Post
loc.res = 0 no error
loc.res = 1 invalid parameter (name or locator)
loc.res = 2 location or file not found
loc.res = 4 write-protection
loc.res = 5 io error
PROCEDURE (d: Directory) Rename (loc: Locator; old, new: Name; ask: BOOLEAN)
NEW, ABSTRACT
Rename the file specified by loc and new to the local name new. If a file with name new already exists, it must be deleted first. Parameter ask determines whether the user is asked for the permission to do so. Pass either the constant ask or dontAsk.
Pre
loc # NIL 20
Post
loc.res = 0 no error
loc.res = 1 invalid parameter (locator or name)
loc.res = 2 location or file not found
loc.res = 3 file already exists
loc.res = 4 write-protection
loc.res = 5 io error
PROCEDURE (d: Directory) SameFile (loc0: Locator; name0: Name;
loc1: Locator; name1: Name): BOOLEAN
NEW, ABSTRACT
Determines whether two (locator, name) pairs denote the same file.
Pre
loc0 # NIL 20
name0 # "" 21
loc1 # NIL 22
name1 # "" 23
PROCEDURE (d: Directory) FileList (loc: Locator): FileInfo
NEW, ABSTRACT
Returns information about the files at a given location. The result is a linear list of file descriptions, in no particular order. The procedure may alter loc.res.
Pre
loc # NIL 20
PROCEDURE (d: Directory) LocList (loc: Locator): LocInfo
NEW, ABSTRACT
Returns information about subdirectories at a given location. The result is a linear list of location (subdirectory) descriptions, in no particular order. The procedure may alter loc.res.
Pre
loc # NIL 20
PROCEDURE (d: Directory) GetFileName (name: Name; type: Type; OUT filename: Name)
NEW, ABSTRACT
Make a file name out of a file and its type.
filename = name + "." + type
VAR dir-, stdDir-: Directory (dir # NIL) & (stdDir # NIL)
Directories for the lookup of files.
PROCEDURE SetDir (d: Directory)
Assigns directory.
SetDir is used in configuration routines.
Pre
d # NIL 20
Post
stdDir' = NIL
stdDir = d
stdDir' # NIL
stdDir = stdDir'
dir = d
VAR docType-, objType-, symType-: Type (docType # NIL) & (objType # NIL) & (symType # NIL)
File types of BlackBox documents (docType), of BlackBox code files (objType), and of BlackBox symbol files (symType).
| System/Docu/Files.odc |
Files64
DEFINITION Files64;
IMPORT Files;
CONST
exclusive = FALSE; shared = TRUE;
dontAsk = FALSE; ask = TRUE;
readOnly = 0; hidden = 1; system = 2; archive = 3; stationery = 4;
TYPE
Name = Files.Name;
Type = Files.Type;
FileInfo = POINTER TO RECORD
next: FileInfo;
name: Files.Name;
length: LONGINT;
type: Files.Type;
modified: RECORD
year, month, day, hour, minute, second: INTEGER
END;
attr: SET
END;
LocInfo = Files.LocInfo;
Locator = Files.Locator;
File = POINTER TO ABSTRACT RECORD
type-: Files.Type;
(f: File) Length (): LONGINT, NEW, ABSTRACT;
(f: File) NewReader (old: Reader): Reader, NEW, ABSTRACT;
(f: File) NewWriter (old: Writer): Writer, NEW, ABSTRACT;
(f: File) Flush, NEW, ABSTRACT;
(f: File) Register (name: Files.Name; type: Files.Type; ask: BOOLEAN; OUT res: INTEGER),
NEW, ABSTRACT;
(f: File) Close, NEW, ABSTRACT;
(f: File) InitType (type: Files.Type), NEW;
END;
Reader = POINTER TO ABSTRACT RECORD
eof: BOOLEAN;
(r: Reader) Base (): File, NEW, ABSTRACT;
(r: Reader) Pos (): LONGINT, NEW, ABSTRACT;
(r: Reader) SetPos (pos: LONGINT), NEW, ABSTRACT
(r: Reader) ReadByte (OUT x: BYTE), NEW, ABSTRACT;
(r: Reader) ReadBytes (VAR x: ARRAY OF BYTE; beg, len: INTEGER), NEW, ABSTRACT;
END;
Writer = POINTER TO ABSTRACT RECORD
(w: Writer) Base (): File, NEW, ABSTRACT;
(w: Writer) Pos (): LONGINT, NEW, ABSTRACT;
(w: Writer) SetPos (pos: LONGINT), NEW, ABSTRACT;
(w: Writer) WriteByte (x: BYTE), NEW, ABSTRACT;
(w: Writer) WriteBytes (IN x: ARRAY OF BYTE; beg, len: INTEGER), NEW, ABSTRACT
END;
Directory = POINTER TO ABSTRACT RECORD
(d: Directory) This (IN path: ARRAY OF CHAR): Files.Locator, NEW, ABSTRACT
(d: Directory) Temp (): File, NEW, ABSTRACT;
(d: Directory) New (loc: Files.Locator; ask: BOOLEAN): File, NEW, ABSTRACT;
(d: Directory) Old (loc: Files.Locator; name: Files.Name; shared: BOOLEAN): File,
NEW, ABSTRACT;
(d: Directory) Delete (loc: Files.Locator; name: Files.Name), NEW, ABSTRACT;
(d: Directory) Rename (loc: Files.Locator; old, new: Files.Name; ask: BOOLEAN),
NEW, ABSTRACT;
(d: Directory) SameFile (loc0: Files.Locator; name0: Files.Name;
loc1: Files.Locator; name1: Files.Name): BOOLEAN, NEW, ABSTRACT;
(d: Directory) FileList (loc: Files.Locator): FileInfo, NEW, ABSTRACT;
(d: Directory) LocList (loc: Files.Locator): Files.LocInfo, NEW, ABSTRACT;
(d: Directory) GetFileName (name: Files.Name; type: Files.Type; OUT filename: Files.Name),
NEW, ABSTRACT;
END;
VAR
dir-, stdDir: Directory;
docType-, objType-, symType-: Files.Type;
PROCEDURE SetDir (d: Directory);
END Files64.
Module Files64 is identical to Files except that it uses the 64-bit LONGINT type instead of the 32-bit INTEGER type for the file length and positions within a file.
Note: This module may be removed in a later BlackBox release when 64-bit file length support is added to the module Files. | System/Docu/Files64.odc |
In
DEFINITION In;
VAR Done-: BOOLEAN;
PROCEDURE Open;
PROCEDURE Char (OUT ch: CHAR);
PROCEDURE Int (OUT i: INTEGER);
PROCEDURE LongInt (OUT l: LONGINT);
PROCEDURE Real (OUT x: REAL);
PROCEDURE Name (OUT name: ARRAY OF CHAR);
PROCEDURE String (OUT str: ARRAY OF CHAR);
END In.
This module is provided for compatibility with the book "Programming in Oberon" by Reiser/Wirth. It is useful when learning the language. It is not recommended for use in production programs.
VAR Done
This variable indicates whether the most recent input operation has succeeded. It is set to TRUE by a successful Open, and set to FALSE by the first unsuccessful input operation. Once set to FALSE, it remains FALSE until the next Open.
PROCEDURE Open
This procedure opens the input stream. In BlackBox, the input stream is opened onto the target focus' text. If there is no target focus, or if it doesn't contain text, Done is set to FALSE. If there is a target focus containing text, the input stream is connected to the beginning of the text if there is no selection, otherwise to the beginning of the selection.
Post
Done
input stream was opened successfully
~Done
input stream couldn't be opened
PROCEDURE Char (OUT ch: CHAR)
If Done holds, this procedure attempts to read a character, otherwise it does nothing.
Post
Done
ch has been read
~Done
no character could be read
PROCEDURE Int (OUT i: INTEGER)
If Done holds, this procedure attempts to read an integer, otherwise it does nothing.
Post
Done
i has been read
~Done
no integer could be read
PROCEDURE LongInt (OUT l: LONGINT)
If Done holds, this procedure attempts to read a long integer, otherwise it does nothing.
Post
Done
l has been read
~Done
no long integer could be read
PROCEDURE Real (OUT x: REAL)
If Done holds, this procedure attempts to read a real number, otherwise it does nothing.
Post
Done
x has been read
~Done
no real number could be read
PROCEDURE Name (OUT name: ARRAY OF CHAR)
If Done holds, this procedure attempts to read a name, otherwise it does nothing. A name is a sequence of legal Component Pascal identifiers concatenated by periods, e.g., "Dialog.Beep".
Post
Done
x has been read
~Done
no name could be read
PROCEDURE String (OUT str: ARRAY OF CHAR)
If Done holds, this procedure attempts to read a string, otherwise it does nothing. A string is a sequence of characters delimited by white space (i.e., blanks, carriage returns, tabulators) or by double quotes (").
Post
Done
str has been read
~Done
no string could be read
| System/Docu/In.odc |
Init
This module has a private interface, it is only used internally.
| System/Docu/Init.odc |
Integers
DEFINITION Integers;
IMPORT Files;
TYPE Integer = POINTER;
PROCEDURE Abs (x: Integer): Integer;
PROCEDURE Compare (x, y: Integer): INTEGER;
PROCEDURE ConvertFromString (IN s: ARRAY OF CHAR; OUT x: Integer);
PROCEDURE ConvertToString (x: Integer; OUT s: ARRAY OF CHAR);
PROCEDURE Difference (x, y: Integer): Integer;
PROCEDURE Digits10Of (x: Integer): INTEGER;
PROCEDURE Entier (x: REAL): Integer;
PROCEDURE Externalize (w: Files.Writer; x: Integer);
PROCEDURE Float (x: Integer): REAL;
PROCEDURE GCD (x, y: Integer): Integer;
PROCEDURE Internalize (r: Files.Reader; OUT x: Integer);
PROCEDURE Long (x: LONGINT): Integer;
PROCEDURE Power (x: Integer; exp: INTEGER): Integer;
PROCEDURE Product (x, y: Integer): Integer;
PROCEDURE QuoRem (x, y: Integer; OUT quo, rem: Integer);
PROCEDURE Quotient (x, y: Integer): Integer;
PROCEDURE Remainder (x, y: Integer): Integer;
PROCEDURE Short (x: Integer): LONGINT;
PROCEDURE Sign (x: Integer): INTEGER;
PROCEDURE Sum (x, y: Integer): Integer;
PROCEDURE ThisDigit10 (x: Integer; exp10: INTEGER): CHAR;
END Integers.
Module Integer implements an abstract data type Integer to represent arbitrary precision integer numbers. It also offers the most important arithmetical operations on such numbers and a variety of conversion operations. The arithmetical operations include summation, multiplication, powering, computations of quotients, remainders, and greatest common divisors.
With respect to assignment and procedure parameters, variables of type Integers.Integer can be used in the same way as variables of the numerical types built into the language. Of course, to perform operations with such variables, special procedures have to be called. The "operators" +, -, *, DIV, MOD, etc. cannot be used . The same holds for comparisons.
Note: Though the language syntax allows two variables of type Integers.Integer to be compared using the "="-operator, the result is not what you would expect. Instead of values, pointers to objects representing the values are compared. Thus, the comparison may yield the result FALSE, although the values of the variables are equal. Hence, use the Integers.Compare-function instead of the "="-operator.
The individual values are represented by objects on the heap rather than the stack. Clients of module Integers will use references to these objects only. Values of existing objects cannot be changed (they are immutable). Thus, copying such values is completely safe; it is not possible to inadvertantly change a value via an alias pointer.
The space needed to represent a small integer is that of the minimum object size of your Component Pascal implementation. To represent a large value, the required memory is proportional to the number of decimal digits in the value. Each of the operations offered by module Integers allocates memory necessary to represent its result, but no extra memory will be allocated beyond that (space for intermediate results is allocated on the stack).
Examples of client modules:
ObxFactdocu calculate factorials
ObxFractdocu calculatior/simplifier for rational numbers
TYPE Integer
Opaque
Opaque type to represent integers of arbitrary size. Values of this type are allocated on the heap. The required memory size depends on the number of decimals to be represented. The objects are immutable.
PROCEDURE Long (x: LONGINT): Integer
Long generates a new Integer from a LONGINT variable.
PROCEDURE Entier (x: REAL): Integer
Entier generates a new Integer from a REAL variable. Entier rounds similar to the ENTIER-function of the Component Pascal programming language; both implement the floor-function.
PROCEDURE Short (x: Integer): LONGINT
Short converts a value of type Integer into a LONGINT.
Pre
MIN(LONGINT) <= x <= MAX(LONGINT)
PROCEDURE Float (x: Integer): REAL
Float converts a value of type Integer into a REAL.
Pre
MIN(REAL) <= x <= MAX(REAL)
PROCEDURE Sum (x, y: Integer): Integer
PROCEDURE Difference (x, y: Integer): Integer
PROCEDURE Product (x, y: Integer): Integer
PROCEDURE Quotient (x, y: Integer): Integer
PROCEDURE Remainder (x, y: Integer): Integer
PROCEDURE QuoRem (x, y: Integer; VAR quo, rem: Integer)
PROCEDURE Power (x: Integer; exp: INTEGER): Integer
PROCEDURE GCD (x, y: Integer): Integer
PROCEDURE Abs (x: Integer): Integer
The arithmetic operations Sum, Difference, Product, Quotient, Remainder, Power, GCD (= greatest common divisor), and Abs (= absolute value) are defined as to be expected. In particular, Quotient and Remainder are defined according the Component Pascal rules for DIV and MOD. If both quotient and remainder need to be computed, for performance reasons the procedure QuoRem should be called instead of the individual functions Quotient and Remainder. Power requires the exponent to be non-negative.
Pre (Quotient, Remainder, QuoRem)
y # 0
Pre (Power)
exp >= 0
PROCEDURE Compare (x, y: Integer): INTEGER
Compares the values of x and y. With this function, all comparison relations can be built: to compute the value of (x op y) write (Compare(x, y) op 0), where op is one of =, #, <, <=, >, >=.
Post
x < y
result < 0
x = y
result = 0
x > y
result > 0
PROCEDURE Sign (x: Integer): INTEGER
The sign of x.
Post
x > 0
result = 1
x = 0
result = 0
x < 0
result = -1
PROCEDURE Digits10Of (x: Integer): INTEGER
The number of decimal digits needed to represent x.
Exception: for x = 0 the result is the value 0.
PROCEDURE ThisDigit10 (x: Integer; exp10: INTEGER): CHAR
This Digit10 returns a single decimal digit as a character.
Pre
exp10 >= 0 20
Post
"0" <= result <= "9"
exp10 >= Digits10Of(x)
result = "0"
PROCEDURE ConvertFromString (IN s: ARRAY OF CHAR; OUT x: Integer)
PROCEDURE ConvertToString (x: Integer; OUT s: ARRAY OF CHAR)
ConvertFromString and ConvertToString are used to read an Integer from a string resp. to write an Integer to a string. ConvertToString requires that the string is long enough to represent the Integer.
Pre (ConvertToString)
(Sign(x) >= 0) & (LEN(s) >= Digits10Of(x) + 1)
OR
(Sign(x) < 0) & (LEN(s) >= Digits10Of(x) + 2)
PROCEDURE Internalize (r: Files.Reader; OUT x: Integer)
PROCEDURE Externalize (w: Files.Writer; x: Integer)
Internalize and Externalize are used to read from resp. to write to files.
| System/Docu/Integers.odc |
Kernel
Module Kernel provides the runtime support for BlackBox applications.
Facilities include memory management, garbage collection, module loading, symbolic debugging using meta information, exception handling, and various other low-level support facilities.
The Kernel documentation is provided to support Framework development. Application developers are advised to use higher level facilities. Kernel routine interfaces and functionality may change between BlackBox releases.
Green color means COM-specific text.
??? indicates missing content.
DEFINITION Kernel (* nonportable (i386) *);
IMPORT SYSTEM, WinApi;
CONST
commNotFound = 7;
commSyntaxError = 8;
cyclicImport = 5;
docType = "odc";
done = 0;
fileNotFound = 1;
illegalFPrint = 4;
littleEndian = TRUE;
moduleNotFound = 9;
nameLen = 256;
noMem = 6;
objNotFound = 3;
objType = "ocf";
processor = 10;
symType = "osf";
syntaxError = 2;
timeResolution = 1000;
TYPE
Directory = POINTER TO RECORD [untagged]
num-: INTEGER;
obj-: ARRAY OF ObjDesc
END;
ExcpFramePtr = POINTER TO ExcpFrame;
ExcpFrame = EXTENSIBLE RECORD [untagged]
link: ExcpFramePtr;
handler: PROCEDURE (excpRec: WinApi.PtrEXCEPTION_RECORD; estFrame: ExcpFramePtr;
context: WinApi.PtrCONTEXT; dispCont: INTEGER): INTEGER
END;
ItemExt = POINTER TO ABSTRACT RECORD
(e: ItemExt) BaseTyp (): INTEGER, NEW, ABSTRACT;
(e: ItemExt) BoolVal (): BOOLEAN, NEW, ABSTRACT;
(e: ItemExt) Call (OUT ok: BOOLEAN), NEW, ABSTRACT;
(e: ItemExt) CharVal (): CHAR, NEW, ABSTRACT;
(e: ItemExt) Deref (VAR ref: ANYREC), NEW, ABSTRACT;
(e: ItemExt) GetSStringVal (OUT x: ARRAY OF SHORTCHAR; OUT ok: BOOLEAN), NEW, ABSTRACT;
(e: ItemExt) GetStringVal (OUT x: ARRAY OF CHAR; OUT ok: BOOLEAN), NEW, ABSTRACT;
(e: ItemExt) Index (index: INTEGER; VAR elem: ANYREC), NEW, ABSTRACT;
(e: ItemExt) IntVal (): INTEGER, NEW, ABSTRACT;
(e: ItemExt) Len (): INTEGER, NEW, ABSTRACT;
(e: ItemExt) LongVal (): LONGINT, NEW, ABSTRACT;
(e: ItemExt) Lookup (name: ARRAY OF CHAR; VAR i: ANYREC), NEW, ABSTRACT;
(e: ItemExt) PtrVal (): ANYPTR, NEW, ABSTRACT;
(e: ItemExt) PutBoolVal (x: BOOLEAN), NEW, ABSTRACT;
(e: ItemExt) PutCharVal (x: CHAR), NEW, ABSTRACT;
(e: ItemExt) PutIntVal (x: INTEGER), NEW, ABSTRACT;
(e: ItemExt) PutLongVal (x: LONGINT), NEW, ABSTRACT;
(e: ItemExt) PutPtrVal (x: ANYPTR), NEW, ABSTRACT;
(e: ItemExt) PutRealVal (x: REAL), NEW, ABSTRACT;
(e: ItemExt) PutSStringVal (IN x: ARRAY OF SHORTCHAR; OUT ok: BOOLEAN), NEW, ABSTRACT;
(e: ItemExt) PutSetVal (x: SET), NEW, ABSTRACT;
(e: ItemExt) PutStringVal (IN x: ARRAY OF CHAR; OUT ok: BOOLEAN), NEW, ABSTRACT;
(e: ItemExt) RealVal (): REAL, NEW, ABSTRACT;
(e: ItemExt) SetVal (): SET, NEW, ABSTRACT;
(e: ItemExt) Size (): INTEGER, NEW, ABSTRACT;
(e: ItemExt) Valid (): BOOLEAN, NEW, ABSTRACT
END;
Module = POINTER TO RECORD [untagged]
next-: Module;
opts-: SET;
refcnt-: INTEGER;
compTime-, loadTime-: ARRAY 6 OF SHORTINT;
ext-: INTEGER;
term-: Command;
nofimps-, nofptrs-, csize-, dsize-, rsize-, code-, data-, refs-, procBase-, varBase-: INTEGER;
names-: POINTER TO ARRAY [untagged] OF SHORTCHAR;
ptrs-: POINTER TO ARRAY [untagged] OF INTEGER;
imports-: POINTER TO ARRAY [untagged] OF Module;
export-: Directory;
name-: Utf8Name
END;
Object = POINTER TO ObjDesc;
ObjDesc = RECORD [untagged]
fprint-, offs-, id-: INTEGER;
struct-: Type
END;
Reducer = POINTER TO ABSTRACT RECORD
(r: Reducer) Reduce (full: BOOLEAN), NEW, ABSTRACT
END;
Signature = POINTER TO RECORD [untagged]
retStruct-: Type;
num-: INTEGER;
par-: ARRAY OF RECORD [untagged]
id-: INTEGER;
struct-: Type
END
END;
TrapCleaner = POINTER TO ABSTRACT RECORD
(c: TrapCleaner) Cleanup, NEW, EMPTY
END;
Type = POINTER TO RECORD [untagged]
size-: INTEGER;
mod-: Module;
id-: INTEGER;
base-: ARRAY 16 OF Type;
fields-: Directory;
ptroffs-: ARRAY OF INTEGER
END;
Command = PROCEDURE;
Handler = PROCEDURE;
Identifier = ABSTRACT RECORD
typ: INTEGER;
obj-: ANYPTR;
(VAR id: Identifier) Identified (): BOOLEAN, NEW, ABSTRACT
END;
ItemAttr = RECORD
obj, vis, typ, adr: INTEGER;
mod: Module;
desc: Type;
ptr: SYSTEM.PTR;
ext: ItemExt
END;
Name = ARRAY 256 OF CHAR;
TryHandler = PROCEDURE (a, b, c: INTEGER);
Utf8Name = ARRAY 256 OF SHORTCHAR;
VAR
err-: INTEGER;
fp-: INTEGER;
mainWnd: INTEGER;
modList-: Module;
pc-: INTEGER;
sp-: INTEGER;
stack-: INTEGER;
trapCount-: INTEGER;
val-: INTEGER;
watcher: PROCEDURE (event: INTEGER);
PROCEDURE AddRef (p: INTEGER): INTEGER;
PROCEDURE AllocModMem (descSize, modSize: INTEGER; VAR descAdr, modAdr: INTEGER);
PROCEDURE Allocated (): INTEGER;
PROCEDURE Beep;
PROCEDURE Call (adr: INTEGER; sig: Signature; IN par: ARRAY OF INTEGER; n: INTEGER): LONGINT;
PROCEDURE Cleanup;
PROCEDURE Collect;
PROCEDURE DeallocModMem (descSize, modSize, descAdr, modAdr: INTEGER);
PROCEDURE FastCollect;
PROCEDURE FatalError (id: INTEGER; str: ARRAY OF CHAR);
PROCEDURE GetLoaderResult (OUT res: INTEGER; OUT importing, imported, object: ARRAY OF CHAR);
PROCEDURE GetModName (mod: Module; OUT name: Name);
PROCEDURE GetObjName (mod: Module; obj: Object; OUT name: Name);
PROCEDURE GetRefProc (VAR ref: INTEGER; OUT adr: INTEGER; OUT name: Utf8Name);
PROCEDURE GetRefVar (VAR ref: INTEGER; OUT mode, form: SHORTCHAR; OUT desc: Type;
OUT adr: INTEGER; OUT name: Utf8Name);
PROCEDURE GetTypeName (t: Type; OUT name: Name);
PROCEDURE InstallCleaner (p: Command);
PROCEDURE [code] InstallExcp (VAR e: ExcpFrame);
PROCEDURE InstallReducer (r: Reducer);
PROCEDURE InstallTrapChecker (h: Handler);
PROCEDURE InstallTrapViewer (h: Handler);
PROCEDURE InterfaceTrapHandler (excpRec, estFrame, context, dispCont: INTEGER): INTEGER;
PROCEDURE IsAlpha (ch: CHAR): BOOLEAN;
PROCEDURE IsLower (ch: CHAR): BOOLEAN;
PROCEDURE IsReadable (from, to: INTEGER): BOOLEAN;
PROCEDURE IsUpper (ch: CHAR): BOOLEAN;
PROCEDURE LevelOf (t: Type): SHORTINT;
PROCEDURE LoadDll (IN name: ARRAY OF CHAR; VAR ok: BOOLEAN);
PROCEDURE LoadMod (IN name: ARRAY OF CHAR);
PROCEDURE Lower (ch: CHAR): CHAR;
PROCEDURE MakeFileName (VAR name: ARRAY OF CHAR; type: ARRAY OF CHAR);
PROCEDURE NewArr (eltyp, nofelem, nofdim: INTEGER): INTEGER;
PROCEDURE NewObj (VAR o: SYSTEM.PTR; t: Type);
PROCEDURE NewRec (typ: INTEGER): INTEGER;
PROCEDURE PopTrapCleaner (c: TrapCleaner);
PROCEDURE PushTrapCleaner (c: TrapCleaner);
PROCEDURE Quit (exitCode: INTEGER);
PROCEDURE RegisterMod (mod: Module);
PROCEDURE Release (p: INTEGER): INTEGER;
PROCEDURE Release2 (p: INTEGER): INTEGER;
PROCEDURE RemoveCleaner (p: Command);
PROCEDURE [code] RemoveExcp (VAR e: ExcpFrame);
PROCEDURE Root (): INTEGER;
PROCEDURE SearchProcVar (var: INTEGER; VAR m: Module; VAR adr: INTEGER);
PROCEDURE SetTrapGuard (on: BOOLEAN);
PROCEDURE SourcePos (mod: Module; codePos: INTEGER): INTEGER;
PROCEDURE SplitName (name: ARRAY OF CHAR; VAR head, tail: ARRAY OF CHAR);
PROCEDURE Start (code: Command);
PROCEDURE StringToUtf8 (IN in: ARRAY OF CHAR; OUT out: ARRAY OF SHORTCHAR;
OUT res: INTEGER);
PROCEDURE ThisCommand (mod: Module; IN name: ARRAY OF CHAR): Command;
PROCEDURE ThisDesc (mod: Module; fprint: INTEGER): Object;
PROCEDURE ThisDllObj (mode, fprint: INTEGER; IN dll, name: ARRAY OF CHAR): INTEGER;
PROCEDURE ThisField (rec: Type; IN name: ARRAY OF CHAR): Object;
PROCEDURE ThisFinObj (VAR id: Identifier): ANYPTR;
PROCEDURE ThisLoadedMod (IN name: ARRAY OF CHAR): Module;
PROCEDURE ThisMod (IN name: ARRAY OF CHAR): Module;
PROCEDURE ThisObject (mod: Module; IN name: ARRAY OF CHAR): Object;
PROCEDURE ThisType (mod: Module; IN name: ARRAY OF CHAR): Type;
PROCEDURE Time (): LONGINT;
PROCEDURE Try (h: TryHandler; a, b, c: INTEGER);
PROCEDURE TypeOf (IN rec: ANYREC): Type;
PROCEDURE UnloadMod (mod: Module);
PROCEDURE Upper (ch: CHAR): CHAR;
PROCEDURE Used (): INTEGER;
PROCEDURE Utf8ToString (IN in: ARRAY OF SHORTCHAR; OUT out: ARRAY OF CHAR;
OUT res: INTEGER);
PROCEDURE WouldFinalize (): BOOLEAN;
END Kernel.
It is generally advised that applications avoid calling Kernel routines directly where possible. There are usually higher level ways of accessing the required functionality; for example use Services.Ticks rather than Kernel.Time.
This document has been reverse engineered by people who were not involved with designing or implementing it. Hence it may contain errors and omissions. Please report any deficiencies to the Community Forum:
BlackBox Component Builder Forums http://community.blackboxframework.org
Main area BLACKBOX COMPONENT BUILER SUPPOPRT
Group BlackBox Framework
Topic Documentation issues.
CONST done, fileNotFound, syntaxError, objNotFound, illegalFPrint, cyclicImport, noMem, commNotFound, commSyntaxError, moduleNotFound
Error codes used by the loader.
CONST docType, symType, objType
The files extensions for BlackBox documents, symbol files, and code files.
CONST littleEndian = TRUE
Specifies the byte ordering within computer words.
Little-endian gives lower addresses to the lower numbered bits in the word, big-endian gives lower addresses to the higher numbered bits.
Intel x86 processors are little-endian.
CONST nameLen = 256
Specifies the length of type Name.
CONST processor = 10
The current hardware platform. The value of 10 corresponds to the platform x86.
CONST timeResolution = 1000;
Number of ticks of the system timer, corresponding to one second.
TYPE Directory
[untagged]
Type used to give external access to objects.
num-: INTEGER
The number of objects made available.
obj-: ARRAY OF ObjDesc
An array giving access to the objects.
TYPE ExcpFramePtr
POINTER TO ExcpFrame
TYPE ExcpFrame
EXTENSIBLE
[untagged]
Type used to implement a list of exception handlers.
link: ExcpFramePtr
Pointer to the next exception handler
handler: PROCEDURE
The exception handler procedure.
TYPE ItemExt
ABSTRACT
Type that can be used to make the type Item defined in module Meta effectively extensible.
The following ABSTRACT procedures define the interfaces of that type that can be extended.
For the functionality of these procedures refer to the documentation for Meta.Item.
PROCEDURE (e: ItemExt) BaseTyp (): INTEGER
PROCEDURE (e: ItemExt) BoolVal (): BOOLEAN
PROCEDURE (e: ItemExt) Call (OUT ok: BOOLEAN)
PROCEDURE (e: ItemExt) CharVal (): CHAR
PROCEDURE (e: ItemExt) Deref (VAR ref: ANYREC)
PROCEDURE (e: ItemExt) GetSStringVal (OUT x: ARRAY OF SHORTCHAR; OUT ok: BOOLEAN)
PROCEDURE (e: ItemExt) GetStringVal (OUT x: ARRAY OF CHAR; OUT ok: BOOLEAN)
PROCEDURE (e: ItemExt) Index (index: INTEGER; VAR elem: ANYREC)
PROCEDURE (e: ItemExt) IntVal (): INTEGER
PROCEDURE (e: ItemExt) Len (): INTEGER
PROCEDURE (e: ItemExt) LongVal (): LONGINT
PROCEDURE (e: ItemExt) Lookup (name: ARRAY OF CHAR; VAR i: ANYREC)
PROCEDURE (e: ItemExt) PtrVal (): ANYPTR
PROCEDURE (e: ItemExt) PutBoolVal (x: BOOLEAN)
PROCEDURE (e: ItemExt) PutCharVal (x: CHAR)
PROCEDURE (e: ItemExt) PutIntVal (x: INTEGER)
PROCEDURE (e: ItemExt) PutLongVal (x: LONGINT)
PROCEDURE (e: ItemExt) PutPtrVal (x: ANYPTR)
PROCEDURE (e: ItemExt) PutRealVal (x: REAL)
PROCEDURE (e: ItemExt) PutSStringVal (IN x: ARRAY OF SHORTCHAR; OUT ok: BOOLEAN)
PROCEDURE (e: ItemExt) PutSetVal (x: SET)
PROCEDURE (e: ItemExt) PutStringVal (IN x: ARRAY OF CHAR; OUT ok: BOOLEAN)
PROCEDURE (e: ItemExt) RealVal (): REAL
PROCEDURE (e: ItemExt) SetVal (): SET
PROCEDURE (e: ItemExt) Size (): INTEGER
PROCEDURE (e: ItemExt) Valid (): BOOLEAN
TYPE Module
[untagged]
Type used to implement a list of records containing information about Modules.
next-: Module
The next Module in the list.
opts-: SET
Elements 0..15 are reserved for compiler options, 16..31 for kernel flags.
Element 16: Module has been initialised.
Element 17: Module has been dynamically loaded.
Element 24: The module is a DLL.
Element 30: The module has pointers to COM objects.
refcnt-: INTEGER
The number of other modules that import this module. If refcnt < 0 this module is not valid.
compTime-, loadTime-: ARRAY 6 OF SHORTINT
The times when this module was compiled and loaded into memory.
The time format is Year [0], Month [1], Day [2], Hour [3], Minute [0], & Second [5].
ext-: INTEGER
Currently not used.
term-: Command
Procedure called when the module is unloaded.
nofimps-: INTEGER
Number of modules imported by this module.
nofptrs-: INTEGER
Number of global pointers used by this module.
csize-, dsize-, rsize-: INTEGER
Sizes of the module's code section, data section, and symbol information sections.
code-, data-, refs-: INTEGER
Pointer to the start of the code section, data section, and symbol information section, respectively.
(The BlackBox variables in the data section are arranged in the reverse order of their declaration in the source code).
procBase-, varBase-: INTEGER
Meta base address for calculating the displacement of procedures and variables, respectively.
names-: POINTER TO ARRAY OF SHORTCHAR
[untagged]
ptrs-: POINTER TO ARRAY OF INTEGER
[untagged]
List of offsets, relative to varBase, to specify pointers to objects.
It is used by the garbage collector, and the COM compiler additions.
imports-: POINTER TO ARRAY OF Module
[untagged]
List of modules directly imported by this module.
export-: Directory
List of objects exported by this module. The list is sorted in ascending order by object name.
name-: Utf8Name
The name of this module in UTF-8 format.
TYPE Object = POINTER TO ObjDesc
TYPE ObjDesc
[untagged]
Contains information about objects.
fprint-: INTEGER
Object fingerprint used to implement version control.
offs-: INTEGER
Fingerprint for record types.
id-: INTEGER
Object properties in packaged form.
struct-: Type
Id of basic type, or pointer to typedesc / signature.
TYPE Reducer
ABSTRACT
List of objects used to (try to) reduce the amount of heap memory used.
PROCEDURE (r: Reducer) Reduce (full: BOOLEAN)
ABSTRACT
The procedure called to perform the reduction. It is called when new memory blocks are required, but there is not sufficient memory immediately available.
The first time it is called in each block allocation full is set FALSE.
If sufficient memory is still not available it may be called again with full set TRUE.
TYPE Signature
[untagged]
Record containing information about an object.
retStruct-: Type
Id of basic type, or pointer to typedesc, or 0
num-: INTEGER
Number of parameters
par-: ARRAY OF RECORD
[untagged]
Parameters
id-: INTEGER
Name index * 256 + kind
struct-: Type
Id of basic type or pointer to typedesc.
TYPE TrapCleaner
ABSTRACT
Base type for trap cleaners.
PROCEDURE (c: TrapCleaner) Cleanup
EMPTY
Performs cleanup operations as part of the trap handler.
TYPE Type
[untagged]
Information about a Component Pascal TYPE.
The pointer to the type's n-th method is at negative offset −4 * (n+1).
size-: INTEGER
The size of a RECORD, the number of elements in an ARRAY, 0 for a dynamic ARRAY, or the signature fingerprint for a PROCEDURE.
Multi-dimensional static ARRAYs are treated as one-dimensional arrays of ARRAYs.
mod-: Module
The type's module.
id-: INTEGER
Name index * 256 + Level * 16 + Attributes * 4 + Form.
Form: 1 = record, 2 = array, 3 = pointer.
Attributes: 0 = final, 1 = EXTENSIBLE, 2 = LIMITED, 3 = ABSTRACT.
Level: For RECORDs the extension level, for dynamic ARRAYs the number of dimensions
Name index: its start position in mod.names.
base-: ARRAY 16 OF Type
For records: Array of pointers to descriptors of its ancestor types.
For arrays: base[0] points to the descriptor of its element's type, or the code of a basic CP type.
For pointers: base[0] points to the descriptor of its target type
fields-: Directory
List of fields in declaration order.
ptroffs-: ARRAY OF INTEGER
For records: The list of fields of displacement-pointers. It is used by the garbage collector. The end of the list is indicated by a negative value.
TYPE Command
Procedure type used by several facilities.
TYPE Handler
Procedure type.
TYPE Identifier
ABSTRACT
Search criteria for ThisFinObj.
typ: INTEGER
The search is restricted to objects with this type tag.
obj-: ANYPTR
Set to point to objects found matching this type tag.
PROCEDURE (VAR id: Identifier) Identified (): BOOLEAN
ABSTRACT
Called successively for objects matching this type tag. It should return TRUE when the desired one is found.
TYPE ItemAttr
Item attributes. Used by module Meta to support meta programming.
obj, vis, typ, adr: INTEGER
mod: Module
desc: Type
ptr: SYSTEM.PTR
ext: ItemExt
Refer to module Meta for more information.
TYPE Name
String type used for names. Contents must be null (0X) terminated.
TYPE TryHandler = PROCEDURE (a, b, c: INTEGER)
The type of procedure that can be called with a local trap handler by means of Try.
TYPE Utf8Name
Short string type used for names. Contents is in UTF-8 format and null (0X) terminated.
VAR err-, val-: INTEGER
Information about the last exception; an error code err and possibly additional information in val.
err val Comment
< 0 Exception # |err| e.g. DLL error
129 Invalid WITH
130 Invalid CASE
131 Function without RETURN
132 Type guard
133 Implied type guard
134 Value out of range
135 Index out of range
136 String too long
137 Stack overflow
138 Integer overflow
139 Division by zero
140 Infinite REAL result
141 REAL underflow
142 REAL overflow
143 Undefined REAL result FPU CW, FPU SW
144 Not a number
200 Keyboard interrupt
201 NIL dereference
202 Illegal instruction The instruction code
203 Illegal memory read The illegal address
204 Illegal memory write The illegal address
205 Illegal execution The illegal address
257 Out of memory
10001H Bus error
10002H Address error
10007H FPU error
fp-: INTEGER
Pointer to the stack frame when the last exception occurred.
mainWnd: INTEGER
Handle of the main Window.
modList-: Module
Root of the list of modules that have been loaded.
It contains descriptors of the modules, including those already unloaded.
pc-: INTEGER
Instruction pointer (program counter) when the last exception occurred.
sp-: INTEGER
Stack pointer when the last exception occurred.
stack-: INTEGER
Pointer to the beginning of the stack when the last exception occurred.
trapCount-: INTEGER
The number of exceptions that have occurred since the application started.
watcher: PROCEDURE (event: INTEGER);
Procedure used for watching the memory management if the internal flag debug is set.
event = 1: Collect
event = 2: FastCollect
event = 3: allocate memory
PROCEDURE AddRef (p: INTEGER): INTEGER
Adds a reference to p.
PROCEDURE AllocModMem (descSize, modSize: INTEGER; VAR descAdr, modAdr: INTEGER)
Asks the operating system for memory blocks for a loadable module.
descSize is the size of the description section, modSize is the size of the data section and the code.
descAdr & modAdr are set to pointers to these memory blocks.
PROCEDURE Allocated (): INTEGER
Returns the amount of memory allocated to the BlackBox heap, in bytes.
PROCEDURE Beep
Emit a short beep sound. (Use Dialog.Beep!)
PROCEDURE Call (adr: INTEGER; sig: Signature; IN par: ARRAY OF INTEGER; n: INTEGER): LONGINT
Calls the procedure with the specified address adr, signature sig, and parameters par and returns the result cast into a LONGINT. The length of the parameter array is specified in n.
PROCEDURE Cleanup
Executes the do Commands of all the registered TrapCleaners.
PROCEDURE Collect
Performs a garbage collection.and calls the Finalizers of unreachable finalizable objects. Garbage collection uses the mark-and-sweep approach with refinements for oject finalization, and COM support.
The sequence of steps performed by Collect is:
(1) mark all global variables. The information for the global roots is precisely available from the module list. The information for pointers inside of records and arrays is available from the related type descriptor. Marking is done using a non-recursive algorithm. The chain for returning to the parent(s) of a referenced block is maintained by pointer reversals inside the marked blocks. When marking finishes, all pointer reversals are reset and the reachable memory blocks have a mark flag set (ODD(typeTag)).
(2) mark all local (stack based) variables. Since there are no type descriptors available for stack frames, this phase uses a so-called conservative approach. It marks all memory blocks reachable from any local variable no matter if it is a pointers or not. In order to avoid memory corruption, it collects the possible candidates first in an auxiliary array and scans the memory for deciding if a candidate is a heap block or not. By sorting the candidate array by ascending addresses it is possible to check the whole array in one scan. This approach guarantees that all blocks reachable via local variables are marked indeed but it can lead to marking blocks of memory that in reality cannot be reached. That's why this approach is called conservative.
(3) check for finalizable objects: scans the list of finalizable objects for unmarked objects and moves them to the list of objects that can be finalized now (hotFinalizers). This list is then marked in order to keep the finalizable objects (and everything reachable from them) from being freed in the following sweep phase.
(4) sweep: sequential scan over the whole memory for resetting the mark flag of reachable blocks and inserting unreachable blocks into the free list. This phase also merges adjacent free blocks into bigger blocks. The objects in hotFinalizers are not yet freed since they are marked. After sweeping the memory is again in a consistent state ready for executing arbitrary user programs.
(5) call finalizers: calls the FINALIZE method for all entries in hotFinalizers (unless the related module has been unloaded). A FINALIZE method is not restricted in any way by the needs of the memory managament. It can even re-establishes a reference to itself or anything reachable from itself in a global variable. It will, however, only be finalized once. In addition this phase calls Release for all affected COM interface records. This decrements the reference count of the COM interface object to zero and releases it.
The efficiency of garbage collection depends on the number of roots and reachable blocks during the mark phase, the stack size and number of candidates encountered when marking local variables, the number of reachable, unreachable and free blocks visited in the sweep phase and the efficiency of the finalizers.
PROCEDURE DeallocModMem (descSize, modSize, descAdr, modAdr: INTEGER)
Deallocates the memory blocks for a loaded module.
descSize is the size of the description section, modSize is the size of the data section and the code.
descAdr & modAdr are the pointers to these memory blocks.
PROCEDURE FastCollect
Performs a garbage collection without calling any Finalizers.
Objects with Finalizers are not deallocated, but remain queued until the next Collect.
PROCEDURE FatalError (id: INTEGER; str: ARRAY OF CHAR)
Immediately terminates the application process in the case of a fatal error.
The error number is id, and str is the associated comment.
PROCEDURE GetLoaderResult (OUT res: INTEGER; OUT importing, imported, object: ARRAY OF CHAR)
Returns the result of the last attempt to load the module (for the current thread).
res is set to one of the loader constants defined above.
PROCEDURE GetModName (mod: Module; OUT name: Name)
Sets name to the name of the module mod.
PROCEDURE GetObjName (mod: Module; obj: Object; OUT name: Name)
Returns the name, in name, of the object obj in the module mod.
PROCEDURE GetRefProc (VAR ref: INTEGER; OUT adr: INTEGER; OUT name: Utf8Name)
Returns the symbol information of the next procedures in a module and sets ref to the next symbol.
To scan all the module's procedures initialize ref with mod.refs and call GetRefProc until adr = 0.
For each procedure adr is set to the offset from the module's code section (mod.code), and name is set to the procedure's name.
PROCEDURE GetRefVar (VAR ref: INTEGER; OUT mode, form: SHORTCHAR; OUT desc: Type; OUT adr: INTEGER; OUT name: Utf8Name)
Returns the symbol information of the next variable in a module or the next local variable in a stack frame and sets ref to the next symbol.
mode: 1X = global variable, local variable, value parameter; 3X = reference parameter (VAR, IN, OUT)
form: cf. DevDebug.WriteName
desc: type descriptor for structured types
adr: address relative to module data or stack frame.
To scan all global variables of a module set ref to mod.refs and call GetRefVar while mode = 1X.
To scan all local variables of a procedure use ref as returned by GetRefProc and call GetRefVar until mode = 0X.
??? needs to be checked and completed
PROCEDURE GetTypeName (t: Type; VAR name: Name)
Returns the name of the type t.
PROCEDURE InstallCleaner (p: Command)
Registers a Command p, which will be assigned to the do Command of a new Cleaner, and added to the Cleaners list.
These Commands are invoked when Cleanup is called.
A Cleaner Command might reset database pointers for example.
PROCEDURE [code] InstallExcp (VAR e: ExcpFrame)
Installs an exception handler for the current stack frame.
PROCEDURE InstallReducer (r: Reducer)
Adds r to the Reducers list.
Reducers are only used once, then they are removed from the list (they may re-register themselves).
PROCEDURE InstallTrapChecker (h: Handler)
Sets h to be the trap checker. It will be called when a Command Traps.
Used by module Views to invalidate views that initiate traps.
PROCEDURE InstallTrapViewer (h: Handler)
Sets h to be the trap checker. It will be called when a Command Traps.
This is the procedure that implements the trap Window and any associated functionality.
Simple and more advanced viewers are registered by the modules StdDebug & DevDebug.
PROCEDURE InterfaceTrapHandler (excpRec, estFrame, context, dispCont: INTEGER): INTEGER
[specific to Direct-To-COM]
Used for exception handling in COM. Access to it is generated by the BlackBox compiler. Not intended for use by developers.
PROCEDURE IsAlpha (ch: CHAR): BOOLEAN
Checks if ch is an alphabetical character, rather than a digit or symbol.
PROCEDURE IsLower (ch: CHAR): BOOLEAN
Checks if ch is a lower case alphabetical character.
PROCEDURE IsReadable (from, to: INTEGER): BOOLEAN
Check whether the memory between from (inclusive) and to (exclusive) may be read.
PROCEDURE IsUpper (ch: CHAR): BOOLEAN
Checks if ch is an upper case alphabetical character.
PROCEDURE LevelOf (t: Type): SHORTINT
Returns the extension level (i.e. the number of basic types in the hierarchy) to type t.
PROCEDURE LoadDll (IN name: ARRAY OF CHAR; VAR ok: BOOLEAN)
Loads into memory the dynamic library named name. ok reports if this was successful.
PROCEDURE LoadMod (IN name: ARRAY OF CHAR)
Loads into memory the module named name.
PROCEDURE Lower (ch: CHAR): CHAR
Returns the lower case character corresponding to ch.
PROCEDURE MakeFileName (VAR name: ARRAY OF CHAR; type: ARRAY OF CHAR)
(Usually) Ensures that the file name name includes an extension.
If name already has a non-empty extension it is unaltered.
If name has an empty extension (i.e. its first "." is its last character) it is truncated prior to this ".".
If type is "" it is given the extension "odc", otherwise it is given the extension type, which should not include the leading "." - not checked.
Uppercase letters in type are converted to lower case.
Pre
LEN (type$) ≤ 7. Not explicitly checked.
PROCEDURE NewArr (eltyp, nofelem, nofdim: INTEGER): INTEGER
Supports the NEW operation for dynamic arrays.
Creates a new array with the base elements of type eltyp, with total number of elements nofelem (defined as the product of the lengths of all dimensions of the array), and with nofdim dimensions.
If the element type is a COM interface pointer or if it contains COM interface pointers (ODD(eltyp)) the allocated memory block is inserted into the list of finalizable objects, which means that an additional memory block is allocated.
The values for eltyp are:
eltyp Type Comment
-1 COM Interface pointer Supports the COM compiler
0 POINTER
1 SHORTCHAR
2 SHORTINT
3 BYTE
4 INTEGER
5 BOOLEAN
6 SET
7 SHORTREAL
8 REAL
9 CHAR
10 LONGINT
11 PROCEDURE
12 Untagged POINTER
ELSE Element Type ODD(eltyp) if COM interface pointers inside
PROCEDURE NewObj (VAR o: SYSTEM.PTR; t: Type)
Supports the Meta.Item.New operation for RECORDs.
Based on calling NewRec o is set to a pointer to the new object of type t.
If t.size = −1 or if the memory is exhausted o is set to NIL.
If t contains any COM interface pointers, calls NewRec with t + 1, i.e. ODD(t).
PROCEDURE NewRec (typ: INTEGER): INTEGER
Supports the NEW operation for RECORDs.
Creates a new record of type typ, and returns the address of the data section.
The address of the record's type descriptor is at offset -4.
If the memory is exhausted it returns 0.
If the record provides a FINALIZEr or if it contains COM interface pointers (ODD(typ)),
the allocated record is inserted into the list of finalizable objects,
which means that an additional memory block is allocated.
PROCEDURE PopTrapCleaner (c: TrapCleaner)
Deletes all the TrapCleaners on the TrapCleaner list prior to c.
PROCEDURE PushTrapCleaner (c: TrapCleaner)
Inserts c to the front of the TrapCleaner list.
Pre
20 c is not already on the list.
PROCEDURE Quit (exitCode: INTEGER)
Exits the application.
Calls the terminators of all the modules on the module list.
Calls all the 'hot' Finalizers, then all the other Finalizers.
Calls WinApi.ExitProcess with parameter exitCode.
PROCEDURE RegisterMod (mod: Module)
Initialises the module mod after it has been loaded into memory.
PROCEDURE Release (p: INTEGER): INTEGER
Removes a reference to p.
PROCEDURE Release2 (p: INTEGER): INTEGER
???
PROCEDURE RemoveCleaner (p: Command)
Removes a previously registered Cleaner (the one with do Command equal to p) from the Cleaners list.
PROCEDURE [code] RemoveExcp (VAR e: ExcpFrame)
Removes the specified exception handler.
PROCEDURE Root (): INTEGER
Returns the pointer to the root of the of the clusters comprising heap BlackBox's heap.
PROCEDURE SearchProcVar (var: INTEGER; VAR m: Module; VAR adr: INTEGER)
Returns the module m, and relative address offset adr (from m.code) of the symbol with address var.
PROCEDURE SetTrapGuard (on: BOOLEAN)
If called with on = TRUE subsequent TRAP displays are inhibited.
PROCEDURE SourcePos (mod: Module; codePos: INTEGER): INTEGER
Returns the position in the source code of Module mod for the instruction at address codePos.
PROCEDURE SplitName (name: ARRAY OF CHAR; VAR head, tail: ARRAY OF CHAR)
Splits the input name into two parts head and tail.
name is scanned for either a lower case to upper case transition, or for a ".".
The text before the transition or "." is copied to head, the text after is copied to tail (the "." is discarded).
If this leaves tail empty then the text in head is moved to tail.
PROCEDURE Start (code: Command)
Called upon start of a BlackBox application.
Defines the stack base and initiates the Command code, which must never return.
The stack base is used by the garbage collector and by the trap handler.
PROCEDURE StringToUtf8 (IN in: ARRAY OF CHAR; OUT out: ARRAY OF SHORTCHAR; OUT res: INTEGER)
Copies the string from in to out while converting it from 16-bit Unicode to UTF-8 format.
Sets res to 0 if successful, or to 1 if the output needed to be truncated.
PROCEDURE ThisCommand (mod: Module; IN name: ARRAY OF CHAR): Command
Returns a pointer the Command (a parameterless PROCEDURE) in the module mod with name name.
PROCEDURE ThisDesc (mod: Module; fprint: INTEGER): Object
Returns a pointer to the object with fingerprint fprint in the module mod.
PROCEDURE ThisDllObj (mode, fprint: INTEGER; IN dll, name: ARRAY OF SHORTCHAR): INTEGER
Returns the address of the procedure called name in the DLL dll.
Currently mode must be set to 4 to indicate a procedure (rather than constant = 1, type = 2, variable = 3, or field = 5) or 0 is returned.
Currently fprint is ignored.
PROCEDURE ThisField (rec: Type; IN name: ARRAY OF CHAR): Object
Returns a pointer to the object within rec called name.
PROCEDURE ThisFinObj (VAR id: Identifier): ANYPTR
Searches the list of Finalizers until one contains a Block recognized by the Identifier id.
If found, the Block's last element is returned.
PROCEDURE ThisLoadedMod (IN name: ARRAY OF CHAR): Module
Returns a pointer to the module named name, provided it is already loaded. Otherwise it returns NIL.
PROCEDURE ThisMod (IN name: ARRAY OF CHAR): Module
Returns a pointer to the module named name. If the module is not loaded, it loads it.
PROCEDURE ThisObject (mod: Module; IN name: ARRAY OF CHAR): Object
Returns a pointer to the object in the module mod called name.
PROCEDURE ThisType (mod: Module; IN name: ARRAY OF CHAR): Type
Returns a pointer to the type in the module mod called name.
PROCEDURE Time (): LONGINT
Returns the current time since the system (the PC) was started in clock ticks.
These ticks have a resolution of timeResolution (1000) ticks per second.
PROCEDURE Try (h: TryHandler; a, b, c: INTEGER)
Calls the procedure h with parameters a, b, and c with a local trap handler.
If a trap occurs inside h a trap window is displayed and h is terminated but the execution is continued as if Try proceeded normally.
PROCEDURE TypeOf (IN rec: ANYREC): Type
Returns a pointer to the type descriptor of the record rec.
PROCEDURE UnloadMod (mod: Module)
Unloads the module mod, provided than no other loaded modules import it.
PROCEDURE Upper (ch: CHAR): CHAR
Returns the upper case character corresponding to ch.
PROCEDURE Used (): INTEGER
Returns the amount of memory allocated to the system heap, in bytes.
PROCEDURE Utf8ToString (IN in: ARRAY OF SHORTCHAR; OUT out: ARRAY OF CHAR; OUT res: INTEGER)
Copies the string from in to out while converting it from UTF-8 format to 16-bit Unicode.
Sets res to 0 if successful, or to 1 if the output needed to be truncated.
If a format error is detected in in, it is copied to out and res is set to 2.
PROCEDURE WouldFinalize (): BOOLEAN
Indicates if there are any objects that are ready to be deallocated, but have not yet had their Finalizers called.
This module has a private interface, it is only used internally. | System/Docu/Kernel.odc |
Librarian
DEFINITION Librarian;
IMPORT Files;
CONST
OK = 0;
TYPE
Librarian = POINTER TO ABSTRACT RECORD
res: INTEGER;
(lib: Librarian) GetExtSpec (IN mod, cat: ARRAY OF CHAR;
OUT loc: Files.Locator; OUT name: Files.Name), NEW, ABSTRACT;
(lib: Librarian) GetIntSpec (IN mod, cat: ARRAY OF CHAR;
OUT loc: Files.Locator; OUT name: Files.Name), NEW, ABSTRACT;
(lib: Librarian) SplitName (IN name: ARRAY OF CHAR;
VAR head, tail: ARRAY OF CHAR), NEW, ABSTRACT
END;
VAR
lib-: Librarian;
stdLib-: Librarian;
PROCEDURE NewStdLibrarian (loc: Files.Locator): Librarian;
PROCEDURE SetLib (librarian: Librarian);
END Librarian.
Module Librarian defines layer from module names to files specifications of modules, documentation, resources and artefatcs of compilation (code and symbol files).
CONST OK
This constant can be compared with Librarian.res variable to define is last GetSpec proceed correctly.
TYPE Librarian
Librarians providing access to file specifications (locator, file name and file type) based on subsystem and name of the file. The subsystem name and name of the file also can be provided from module bame by SplitName procedure.
PROCEDURE (lib: Librarian) SplitName* (IN name: ARRAY OF CHAR; VAR head, tail: ARRAY OF CHAR), NEW, ABSTRACT;
Return subsystem name head and fine name tail for the module name.
PROCEDURE (lib: Librarian) GetExtSpec* (IN mod, cat: ARRAY OF CHAR; OUT loc: Files.Locator; OUT name: Files.Name), NEW, ABSTRACT;
PROCEDURE (lib: Librarian) GetIntSpec* (IN mod, cat: ARRAY OF CHAR; OUT loc: Files.Locator; OUT name: Files.Name), NEW, ABSTRACT;
Returns locator loc and file name name for module of name mod with required resource categoty cat.
Standard librarian supports "Mod", "Code", "Sym", "Rsrc" for cat argument.
GetExtSpec procedure should be used for saving (extranalizing) and GetIntSpec for loading (internalizing) resource from disk.
Post:
loc = NIL
=> .res # 0, constituent not found, fname and ftype undefined
loc # NIL
.res = 0
loc and name identify the file of the requested constituent
PROCEDURE NewStdLibrarian* (loc: Files.Locator): Librarian;
Returns a standard filesystem-based librarian based at loc. This direcrory will be used to obtain source files, documentation and resources and put results of compilation there.
Pre
loc # NIL, 20
Post
RESULT = NIL => impossible to create a standard librarian for the given location
RESULT # NIL => standard librarian for location loc created successfully
| System/Docu/Librarian.odc |
Log
Module Log provides an abstract interface for logging. It can be used for logging in low-level modules that cannot import StdLog directly due to cyclic imports. The logging features are the same as for StdLog except that any logging before the installation of the logging hook is silently ignored. During the normal startup of BlackBox StdLog is loaded and installs a logging hook. In principle, it would also be possible to support other logging devices such as a console, a file, or a remote server by means of appropriate implementations of the logging hook.
This module has a private interface, it is only used internally. | System/Docu/Log.odc |
Loop
DEFINITION Loop;
TYPE
ExitGuard = PROCEDURE (): BOOLEAN;
VAR
quantum: LONGINT;
PROCEDURE Start (eventIterator, viewsValidator: PROCEDURE; exitGuard: ExitGuard);
END Loop.
Module Loop provides the main event loop for event-driven applications.
The BlackBox framework, as of 2.0, supports the development of two kinds of applications:
* Event-loop applications (window applications, server applications, or a combination thereof)
* Batch aplications
Event-loop applications do have an event loop, which is implemented in module Loop; the loop ends normally (thus the application exits) once exit conditions have been met. In principle, the loop is:
REPEAT
ObtainEvent;
ProcessEvent;
InvokeImmediateActions;
ValidateViews;
InvokeDueActions
UNTIL ExitAllowed()
Events are usually obtained from the host platform; they may be user input events, timer events, network events, etc. For window applications, the exit condition is that all windows have been closed; for server applications, the exit condition is that the server app has somehow received a signal to exit. A combination is possible, when a server app starts 'in the background' (without any windows); but may at some point present some windows; for such apps, the exit condition may be a conjunction of 'all windows closed' and 'exit signal received'.
The main event loop is started with Loop.Start; it should be provided with three procedures: eventIterator to obtain and process a host platform event; exitGuard to establish the exit condition; and viewsValidator (optional) to validate (restore) views. Normally, Start is called from WinInit/LinInit.
Simple server apps may call Dialog.RequestExit(~Dialog.exitWithoutWindows) to tell the framework NOT to exit even if there are no (more) windows; or Dialog.RequestExit(Dialog.exitWithoutWindows) to tell the framework that the server has received an exit signal and is ready to exit. If your server app requires a more complicated exit condition, you will need to provide (and statically link) your own <App>Init module that will call Loop.Start and provide it with your own exit guard procedure.
Batch applications do not have an event loop and should not invoke Loop.Start; they require a (statically linked) <App>Init module. The latter should invoke all required input processing from it's BEGIN section. Once such processing is complete, and the BEGIN section returns control, the batch application exits normally.
TYPE ExitGuard = PROCEDURE (): BOOLEAN
Type of procedure used in Start to check whether the main event loop should exit.
VAR quantum: INTEGER
At least quantum milliseconds are guaranteed to have elapsed between consecutive invocations of scheduled actions.
That is, If all due actions had been invoked at t0, and actions A0..An are due at t0 + delta, it is guaranteed that A0..An won't be invoked until t0 + quantum.
PROCEDURE Start (eventIterator, viewsValidator: PROCEDURE; exitGuard: ExitGuard);
Starts the main event loop of application (typically called in LinInit/WinInit or a custom <App>Init module). When exitGuard returns TRUE, the event loop exits, and Start returns control. eventIterator is called to let the host platform process/dispatch/deliver an event. If viewsValidator is provided, it's called to validate (restore) views (may be NIL).
Pre
eventIterator # NIL 20
exitGuard # NIL 21
Post
exitGuard has just returned TRUE
| System/Docu/Loop.odc |
Math
DEFINITION Math;
PROCEDURE Pi (): REAL;
PROCEDURE Eps (): REAL;
PROCEDURE Sqrt (x: REAL): REAL;
PROCEDURE Exp (x: REAL): REAL;
PROCEDURE Ln (x: REAL): REAL;
PROCEDURE Log (x: REAL): REAL;
PROCEDURE Power (x, y: REAL): REAL;
PROCEDURE IntPower (x: REAL; n: INTEGER): REAL;
PROCEDURE Sin (x: REAL): REAL;
PROCEDURE Cos (x: REAL): REAL;
PROCEDURE SinCos (x: REAL; OUT s, c: REAL);
PROCEDURE Tan (x: REAL): REAL;
PROCEDURE ArcSin (x: REAL): REAL;
PROCEDURE ArcCos (x: REAL): REAL;
PROCEDURE ArcTan (x: REAL): REAL;
PROCEDURE ArcTan2 (y, x: REAL): REAL;
PROCEDURE Sinh (x: REAL): REAL;
PROCEDURE Cosh (x: REAL): REAL;
PROCEDURE Tanh (x: REAL): REAL;
PROCEDURE ArcSinh (x: REAL): REAL;
PROCEDURE ArcCosh (x: REAL): REAL;
PROCEDURE ArcTanh (x: REAL): REAL;
PROCEDURE Sign (x: REAL): REAL;
PROCEDURE Floor (x: REAL): REAL;
PROCEDURE Ceiling (x: REAL): REAL;
PROCEDURE Trunc (x: REAL): REAL;
PROCEDURE Frac (x: REAL): REAL;
PROCEDURE Mod1 (x: REAL): REAL;
PROCEDURE Round (x: REAL): REAL;
PROCEDURE Mantissa (x: REAL): REAL;
PROCEDURE Exponent (x: REAL): INTEGER;
PROCEDURE Real (m: REAL; e: INTEGER): REAL;
PROCEDURE SignBit (x: REAL): BOOLEAN;
PROCEDURE CopySign (x, y: REAL): REAL;
END Math.
Module Math is a basic library for numerical computations. It offers the most frequently used functions and constants. For some additional functions, a transformation in terms of functions available in module Math is given below.
Note: the normal arithmetic operations of the language Component Pascal and the other operations implemented in this module never produce a not-a-number value (NaN, IEEE 754-2008) but generate an undefined real result trap instead.
Constants
PROCEDURE Pi (): REAL
Returns an approximation of the value of pi.
Post
result = 3.141592...
PROCEDURE Eps (): REAL
Returns the machine epsilon for REAL. The machine epsilon eps is the smallest floating point number such that the sum 1.0+eps can be represented exactly in a REAL variable. Usually, the machine epsilon is 2-m where m is the number of digits used to represent the mantissa of a floating point number. Note, that Eps() is not necessarily the smallest floating point number with the property that its sum with 1.0 is greater than 1.0, and note also, that most floating point processors offer a higher internal precision than what can be represented within REAL variables.
Powers and logarithms
PROCEDURE Sqrt (x: REAL): REAL
Returns the square root of x.
Pre
x >= 0.0
Post
result >= 0.0
x = INF
result = INF
PROCEDURE Exp (x: REAL): REAL
Returns ex.
Post
result > 0.0
x = INF
result = INF
x = -INF
result = 0.0
PROCEDURE Ln (x: REAL): REAL
Returns the natural logarithm of x.
Pre
x >= 0.0
Post
x = 0.0
result = -INF
x = INF
result = INF
PROCEDURE Log (x: REAL): REAL
Returns the logarithm to the basis 10 of x.
Pre
x >= 0.0
Post
x = 0.0
result = -INF
x = INF
result = INF
PROCEDURE Power (x, y: REAL): REAL
Returns xy.
Pre
20 x >= 0.0
21 x # 0.0 OR y # 0.0
22 x # INF OR y # 0.0
23 x # 1.0 OR ABS(y) # INF
Post
x = 0.0 & y < 0.0
result = INF
x = 0.0 & y > 0.0
result = 0.0
x = INF & y > 0.0
result = INF
x = INF & y < 0.0
result = 0.0
x > 1.0 & y = INF
result = INF
x > 1.0 & y = -INF
result = 0.0
x < 1.0 & y = INF
result = 0.0
x < 1.0 & y = -INF
result = INF
PROCEDURE IntPower (x: REAL; n: INTEGER): REAL
Returns xn. The procedure is optimized for integer values of n. IntPower(0, 0) yields 1. If the result is too large, INF is returned.
Trigonometric and hyperbolic functions
The arguments for all trigonometric and hyperbolic functions must be given in radians, and the inverse trigonometric and hyperbolic functions are calculated in radians (1 radian = 180/pi degrees). At the end of this section, a transformation table for additional trigonometric and hyperbolic functions is given which do not belong to the interface of the Math module, but which can easily be written in terms of the exported functions.
PROCEDURE Sin (x: REAL): REAL
Returns the sine of x.
Pre
ABS(x) # INF
Post
-1.0 <= result <= 1.0
PROCEDURE Cos (x: REAL): REAL
Returns the cosine of x.
Pre
ABS(x) # INF
Post
-1.0 <= result <= 1.0
PROCEDURE SinCos (x: REAL; OUT s, c: REAL);
Returns the sine & cosine of x.
Pre
ABS(x) # INF
Post
-1.0 <= s, c <= 1.0
PROCEDURE Tan (x: REAL): REAL
Returns the tangent of x. The Tan can be computed for all possible REAL arguments except INF.
Pre
ABS(x) # INF
PROCEDURE ArcSin (x: REAL): REAL
Returns the arcus sine of x.
Pre
-1.0 <= x <= 1.0
Post
-pi/2.0 <= result <= pi/2.0
PROCEDURE ArcCos (x: REAL): REAL
Returns the arcus cosine of x.
Pre
-1.0 <= x <= 1.0
Post
0.0 <= result <= pi
PROCEDURE ArcTan (x: REAL): REAL
Returns the arcus tangent of x.
Post
-pi/2.0 <= result <= pi/2.0
x = INF
result = pi/2.0
x = -INF
result = -pi/2.0
PROCEDURE ArcTan2 (y, x: REAL): REAL
Returns the argument (angle) of the complex number x + iy measured anti-clockwise from the positive real axis.
All input pairs, including (0., 0.), are valid.
Post
-pi <= result <= pi
The following table lists the IEEE 754-2008 "special values" of the function:
y x result
0 +0, fin, INF 0
fin INF 0
INF INF pi / 4
fin 0 pi / 2
INF -fin, 0, fin pi / 2
INF -INF 3 pi / 4
0 -INF, -fin, -0 pi
fin -INF pi
Key:
+0 The zero with a positive sign bit (0)
-0 The zero with a negative sign bit (1)
0 A zero with any sign bit (0 or 1)
fin Any finite positive number in (0 ... INF)
+ or -, but both occurances in a line are the same.
PROCEDURE Sinh (x: REAL): REAL
Returns the hyperbolic sine of x.
Post
x = INF
result = INF
x = -INF
result = -INF
PROCEDURE Cosh (x: REAL): REAL
Returns the hyperbolic cosine of x.
Post
1.0 <= result
x = INF
result = INF
x = -INF
result = INF
PROCEDURE Tanh (x: REAL): REAL
Returns the hyperbolic tangent of x.
Post
-1.0 <= result <= 1.0
x = INF
result = 1.0
x = -INF
result = -1.0
PROCEDURE ArcSinh (x: REAL): REAL;
Returns the inverse hyperbolic sine of x.
Post
x = INF
result = INF
x = -INF
result = -INF
PROCEDURE ArcCosh (x: REAL): REAL;
Returns the inverse hyperbolic cosine of x.
Pre
1.0 <= x
Post
0.0 <= result
x = INF
result = INF
PROCEDURE ArcTanh (x: REAL): REAL;
Returns the inverse hyperbolic tangent of x.
Pre
-1.0 <= x <= 1.0
Post
x = 1.0
result = INF
x = -1.0
result = -INF
Below you find the definition of additional trigonometric and hyperbolic functions in terms of the exported functions. Their pre and post conditions can be induced from the pre and post conditions of the involved functions.
Cot (x) = 1.0 / Math.Tan(x)
Csc (x) = 1.0 / Math.Sin(x)
Sec (x) = 1.0 / Math.Cos(x)
ArcCot (x) = Math.ArcTan(1.0 / x)
ArcCsc (x) = Math.ArcSin(1.0 / x)
ArcSec (x) = Math.ArcCos(1.0 / x)
Coth (x) = 1.0 / Math.Tanh(x)
Csch (x) = 1.0 / Math.Sinh(x)
Sech (x) = 1.0 / Math.Cosh(x)
ArcCoth (x) = Math.ArcTanh(1.0 / x)
ArcCsch (x) = Math.ArcSinh(1.0 / x)
ArcSech (x) = Math.ArcCosh(1.0 / x)
Miscellaneous functions
You could in principle implement the functions Sign, Floor, Ceiling, Trunc, Frac, Mod1, and Round yourself, using the ENTIER standard function. They are provided here for convenience, and in versions which return REAL typed results, so that no conversions between reals and integers become necessary if they are used in REAL expressions.
PROCEDURE Sign (x: REAL): REAL
Returns the sign um function of x, that is 1 if x > 0, -1 if x < 0 and 0 with the sign of x if x = 0. It also returns +1 or -1 for NaNs according to their sign bit.
Post
result IN {-1, 0, 1}
PROCEDURE Floor (x: REAL): REAL
Returns the greatest integer less than or equal to x. This function is identical to ENTIER, except that it returns a REAL type value and it does not generate an integer overflow.
Post
x = INF
result = INF
x = -INF
result = -INF
PROCEDURE Ceiling (x: REAL): REAL
Returns the smallest integer greater than or equal to x.
Post
x = INF
result = INF
x = -INF
result = -INF
PROCEDURE Trunc (x: REAL): REAL
Trunc truncates its argument to the next nearest integer towards zero.
Post
x = INF
result = INF
x = -INF
result = -INF
PROCEDURE Frac (x: REAL): REAL
Frac is the fractional part of the argument.
The following equation holds: x = Trunc(x) + Frac(x).
Pre
x # INF & x # -INF
Post
-1 < result < 1
PROCEDURE Mod1 (x: REAL): REAL
Mod1 is the fractional part of the argument modulo 1.
The following equation holds: x = Floor(x) + Mod1(x).
Pre
x # INF & x # -INF
Post
0 ≤ result < 1
PROCEDURE Round (x: REAL): REAL
Same as Floor(x + 0.5).
PROCEDURE Mantissa (x: REAL): REAL
Returns the mantissa of x.
Post
1.0 <= ABS(result) < 2.0 OR result = 0.0
x = INF
result = 1.0
x = -INF
result = -1.0
x = NaN
ABS(result) > 1.0
PROCEDURE Exponent (x: REAL): INTEGER
Returns the exponent of x such that x = Mantissa(x) * 2Exponent(x). If x represents INF or if x is NaN, then MAX(INTEGER) is returned.
PROCEDURE Real (m: REAL; e: INTEGER): REAL
Returns m * 2e. If the argument e is MAX(INTEGER), then INF or NaN is returned where INF is returned if m = 1.0 and NaN otherwise. Thus for any real x the equation
x = Real(Mantissa(x), Exponent(x))
holds.
Note: this is the only function that can produce NaN and only if explicitly requested.
Note: Real(0, 0) = 0.
Pre
20 (1.0 <= ABS(m) < 2.0) OR (m = 0.0)
Post
m = 0.0
result = 0.0
PROCEDURE SignBit (x: REAL): BOOLEAN
Returns TRUE if and only if x has negative sign. This applies to zeros and NaNs as well.
PROCEDURE CopySign (x, y: REAL): REAL
Returns x with the sign bit of y. This can be used, for example, for converting the sign bit of a number z into +1 or -1 with CopySign(1, z).
Post
SignBit(result) = SignBit(y) & ABS(result) = ABS(x)
| System/Docu/Math.odc |
Mechanisms
This module has a private interface, it is only used internally.
| System/Docu/Mechanisms.odc |
Meta
DEFINITION Meta;
CONST
undef = 0;
typObj = 2; varObj = 3; procObj = 4; fieldObj = 5; modObj = 6; parObj = 7;
boolTyp = 1; sCharTyp = 2; charTyp = 3;
byteTyp = 4; sIntTyp = 5; intTyp = 6; longTyp = 10; sRealTyp = 7; realTyp = 8;
setTyp = 9; anyRecTyp = 11; anyPtrTyp = 12; sysPtrTyp = 13;
procTyp = 16; recTyp = 17; arrTyp = 18; ptrTyp = 19;
final = 0; extensible = 1; limited = 2; abstract = 3;
hidden = 1; readOnly = 2; exported = 4;
value = 10; in = 11; out = 12; var = 13;
TYPE
Name = ARRAY 256 OF CHAR;
Value = ABSTRACT RECORD END;
Item = RECORD (Value)
obj-, typ-, vis-, adr-: INTEGER;
(IN i: Item) Valid (): BOOLEAN, NEW;
(IN i: Item) GetTypeName (OUT mod, type: Name), NEW;
(IN i: Item) BaseTyp (): INTEGER, NEW;
(IN i: Item) Level (): INTEGER, NEW;
(IN i: Item) Size (): INTEGER, NEW;
(IN arr: Item) Len (): INTEGER, NEW;
(IN in: Item) Lookup (IN name: ARRAY OF CHAR; VAR i: Item), NEW;
(IN i: Item) GetBaseType (VAR base: Item), NEW;
(IN rec: Item) GetThisBaseType (level: INTEGER; VAR base: Item), NEW;
(IN proc: Item) NumParam (): INTEGER, NEW;
(IN proc: Item) GetParam (n: INTEGER; VAR par: Item), NEW;
(IN proc: Item) GetParamName (n: INTEGER; OUT name: Name), NEW;
(IN proc: Item) GetReturnType (VAR type: Item), NEW;
(IN rec: Item) Is (IN type: Value): BOOLEAN, NEW;
(IN ptr: Item) Deref (VAR ref: Item), NEW;
(IN arr: Item) Index (index: INTEGER; VAR elem: Item), NEW;
(IN proc: Item) Call (OUT ok: BOOLEAN), NEW;
(IN proc: Item) ParamCall (IN par: ARRAY OF Item; VAR dest: Item;
OUT ok: BOOLEAN), NEW;
(IN proc: Item) ParamCallVal (IN par: ARRAY OF POINTER TO Value; VAR dest: Item;
OUT ok: BOOLEAN), NEW;
(IN var: Item) GetVal (VAR x: Value; OUT ok: BOOLEAN), NEW;
(IN var: Item) PutVal (IN x: Value; OUT ok: BOOLEAN), NEW;
(IN var: Item) GetStringVal (OUT x: ARRAY OF CHAR; OUT ok: BOOLEAN), NEW;
(IN var: Item) GetSStringVal (OUT x: ARRAY OF SHORTCHAR; OUT ok: BOOLEAN), NEW;
(IN var: Item) PutStringVal (IN x: ARRAY OF CHAR; OUT ok: BOOLEAN), NEW;
(IN var: Item) PutSStringVal (IN x: ARRAY OF SHORTCHAR; OUT ok: BOOLEAN), NEW;
(IN var: Item) PtrVal (): ANYPTR, NEW;
(IN var: Item) PutPtrVal (x: ANYPTR), NEW;
(IN var: Item) IntVal (): INTEGER, NEW;
(IN var: Item) PutIntVal (x: INTEGER), NEW;
(IN var: Item) RealVal (): REAL, NEW;
(IN var: Item) PutRealVal (x: REAL), NEW;
(IN var: Item) LongVal (): LONGINT, NEW;
(IN var: Item) PutLongVal (x: LONGINT), NEW;
(IN var: Item) CharVal (): CHAR, NEW;
(IN var: Item) PutCharVal (x: CHAR), NEW;
(IN var: Item) BoolVal (): BOOLEAN, NEW;
(IN var: Item) PutBoolVal (x: BOOLEAN), NEW;
(IN var: Item) SetVal (): SET, NEW;
(IN var: Item) PutSetVal (x: SET), NEW;
(IN type: Item) New (): ANYPTR, NEW;
(IN val: Item) Copy (): ANYPTR, NEW;
(IN rec: Item) CallWith (proc: PROCEDURE (VAR rec, par: ANYREC); VAR par: ANYREC), NEW
END;
Scanner = RECORD
this-: Item;
eos-: BOOLEAN;
(VAR s: Scanner) ConnectToMods, NEW;
(VAR s: Scanner) ConnectTo (IN obj: Item), NEW;
(VAR s: Scanner) Scan, NEW;
(VAR s: Scanner) GetObjName (OUT name: Name), NEW;
(VAR s: Scanner) Level (): INTEGER, NEW
END;
LookupFilter = PROCEDURE (IN path: ARRAY OF CHAR; OUT i: Item; OUT done: BOOLEAN)
PROCEDURE Lookup (IN name: ARRAY OF CHAR; OUT mod: Item);
PROCEDURE LookupPath (IN path: ARRAY OF CHAR; OUT i: Item);
PROCEDURE GetItem (obj: ANYPTR; OUT i: Item);
PROCEDURE InstallFilter (filter: LookupFilter);
PROCEDURE UninstallFilter (filter: LookupFilter);
PROCEDURE GetThisItem (IN attr: ANYREC; OUT i: Item);
END Meta.
Meta provides access to Component Pascal run-time type information. Meta is restricted to public information, i.e., it doesn't allow access to non-exported items of a module. Meta is safe, it doesn't allow to change data which is not exported as modifiable. Generally, Meta only allows to do with a module what could be done by a normal client module also. The difference is that Meta is more dynamic; it allows inspection and modification of data depending on run-time decisions, without static import of the inspected or modified module.
Constants are not accessible via Meta, they are not represented at run-time in order to minimize space overhead.
Examples:
ObxCtrls slider control, extended from Controls.Control
ObxFldCtrls special-purpose text field control, extended from Controls.Control
How to call procedures using Meta:
In order to call an arbitrary procedure (methods are not possible) whose signature is statically known, the following must be done: first, an item must be created that describes the function:
Meta.Lookup(moduleName, item);
IF item.obj = Meta.modObj THEN
item.Lookup(procedureName, item);
IF item.obj = Meta.procObj THEN
item.GetVal(item0, ok);
IF ok THEN
item0.fun(x)
...
The item item is a normal, non-extended Meta.Item item. In contrast, item0 must be an extension of Meta.Value that contains as one additional field a procedure variable of the correct type:
item0: RECORD (Meta.Value)
fun: PROCEDURE (x: REAL): REAL
END;
CONST undef
Possible result code for object classes, type classes, visibility classes.
CONST typObj, varObj, procObj, fieldObj, modObj, parObj
Object classes.
CONST boolTyp, sCharTyp, charTyp, byteTyp, sintTyp, intTyp, longTyp,
sRealTyp, realTyp, setTyp, anyRecTyp, anyPtrTyp, procTyp, recTyp, arrTyp, ptrTyp,
sysPtrTyp
Type classes.
CONST final, extensible, limited, abstract
Record attributes.
CONST hidden, readOnly, exported
Visibility classes.
CONST value, in, out, var
Parameter kinds.
TYPE Name
String type for meta item names.
TYPE Value
ABSTRACT
A value may be extended exactly once, with a single field.
TYPE Item (Value)
obj-: INTEGER
typ-: INTEGER
vis-: INTEGER
adr-: INTEGER
Properties of the object represented by the item. The meaning of the fields depends on the class of the object as follows:
Class: Type Variable Procedure Field Module Parameter
obj: typObj varObj procObj fieldObj modObj parObj
typ: type class type class undef type class undef type class
vis: undef visibility visibility visibility undef kind
adr: 0 address address offset 0 number
PROCEDURE (IN i: Item) Valid (): BOOLEAN
NEW
Determines whether the item is valid, i.e., initialized, set to a defined type, and its module is still loaded.
PROCEDURE (IN i: Item) GetTypeName (OUT mod, type: Name)
NEW
Get the item's type name and the name of this type's module.
Pre
i.Valid() 20
i.typ >= recTyp 21
module of type is still loaded 24
PROCEDURE (IN i: Item) BaseTyp (): INTEGER
NEW
Returns the item's base type.
Pre
i.Valid() 20
i.typ IN {arrTyp, recTyp, ptrTyp} 21
PROCEDURE (IN i: Item) Level (): INTEGER
NEW
Returns the item's level.
Pre
i.Valid() 20
i.typ IN {recTyp, arrTyp} 21
PROCEDURE (IN i: Item) Size (): INTEGER
NEW
Returns the item's size in bytes.
Pre
i.Valid() 20
i.typ # undef 21
PROCEDURE (IN arr: Item) Len (): INTEGER
NEW
Returns the array's length.
Pre
i.Valid() 20
i.typ = arrTyp 21
PROCEDURE (IN in: Item) Lookup (IN name: ARRAY OF CHAR; VAR i: Item)
NEW
Lookup an item in a module or a field in a record.
Pre
in.Valid() 20
in.obj = modObj OR in.typ = recTyp 21
Post
i.obj # undef
lookup was successful
i.obj = undef
lookup was not successful
PROCEDURE (IN i: Item) GetBaseType (VAR base: Item)
NEW
Assign i's base type to base.
Pre
i.Valid() 20
i.typ IN {recTyp, arrTyp, ptrTyp} 21
PROCEDURE (IN rec: Item) GetThisBaseType (level: INTEGER; VAR base: Item)
NEW
Assign i's level-th base type to base. If the level does not exist, i.obj is set to undef.
Pre
rec.Valid() 20
rec.typ IN {recTyp, arrTyp} 21
level >= 0 & level < 16 28
PROCEDURE (IN proc: Item) NumParam (): INTEGER
NEW
Returns the number of parameters of a procedure or procedure type.
Pre
proc.Valid() 20
proc.obj = procObj OR proc.typ = procTyp 21
PROCEDURE (IN proc: Item) GetParam (n: INTEGER; VAR par: Item)
NEW
Assigns the n-th parameter of proc to par. n must be in the range 0..proc.NumParam()-1. par.obj is set to parObj, par.vis reflects the kind of the parameter (value, in, out, or var), and par.typ its type.
Pre
proc.Valid() 20
proc.obj = procObj OR proc.typ = procTyp 21
PROCEDURE (IN proc: Item) GetParamName (n: INTEGER; OUT name: Name)
NEW
Assigns the name of the n-th parameter of proc to name. If the parameter does not exist, name is set to "".
Pre
proc.Valid() 20
proc.obj = procObj OR proc.typ = procTyp 21
PROCEDURE (IN proc: Item) GetReturnType (VAR type: Item)
NEW
Assigns the return type of a procedure or procedure type to type. For proper procedures type.typ is set to undef.
Pre
proc.Valid() 20
proc.obj = procObj OR proc.typ = procTyp 21
PROCEDURE (IN rec: Item) Is (IN type: Value): BOOLEAN
NEW
Perform a type test rec IS type.
Pre
rec.Valid() 20
rec.typ = recTyp 21
type IS Item
type.Valid() 20
type.typ = recTyp 21
~(type IS Item)
type.Level() = 1 25
number of fields of type = 1 26
PROCEDURE (IN ptr: Item) Deref (VAR ref: Item)
NEW
Dereference pointer ptr and assign the result to ref.
Pre
ptr.typ IN {ptrTyp, anyPtrTyp, sysPtrTyp} 21
ref must be a level 1 record 25
ref must have exactly one field 26
PROCEDURE (IN arr: Item) Index (index: INTEGER; VAR elem: Item)
NEW
Assign the index-th element of array arr to elem.
Pre
arr.Valid() 20
arr.typ = arrTyp 21
arr.obj = varObj 22
PROCEDURE (IN proc: Item) Call (OUT ok: BOOLEAN)
NEW
Call a parameterless procedure.
Pre
proc.Valid() 20
proc.obj = procObj OR proc.obj = varObj & proc.typ = procTyp 22
PROCEDURE (IN proc: Item) ParamCall (IN par: ARRAY OF Item; VAR dest: Item;
OUT ok: BOOLEAN)
NEW
Call a procedure with a given set of parameters. par must contain a valid variable of appropriate type for each parameter of the procedure. Depending on the parameter kind, either the variable itself or its actual value is passed to the call. If the procedure returns a value, it is assigned to variable dest.
Pre
proc.Valid() 20
proc.obj = procObj OR proc.obj = varObj & proc.typ = procTyp 22
LEN(par) >= proc.NumParam() 32
par[i].Valid() 20
par[i].obj = varObj 22
proc.GetParam(i).vis IN {out, var}
par[i].vis = exported 27
proc.GetReturnType() valid
dest.Valid() 20
dest.obj = varObj 22
dest.vis = exported 27
PROCEDURE (IN proc: Item) ParamCallVal (IN par: ARRAY OF POINTER TO Value; VAR dest: Value;
OUT ok: BOOLEAN)
NEW
Call a procedure with a given set of parameters. par must contain a valid variable item or a value record of appropriate type for each parameter of the procedure. Depending on the parameter kind, either the variable itself or its actual value is passed to the call. If the procedure returns a value, it is assigned to the variable item or value record dest.
Pre
proc.Valid() 20
proc.obj = procObj OR proc.obj = varObj & proc.typ = procTyp 22
LEN(par) >= proc.NumParam() 32
par[i] IS Item
par[i].Valid() 20
par[i].obj = varObj 22
par[i] IS Item & proc.GetParam(i).vis IN {out, var}
par[i].vis = exported 27
~(par[i] IS Item)
par[i] is extension of Value 25
par[i] contains a single field 26
proc.GetReturnType() valid & dest IS Item
dest.Valid() 20
dest.obj = varObj 22
dest.vis = exported 27
proc.GetReturnType() valid & ~(dest IS Item)
dest is extension of Value 25
dest contains a single field 26
PROCEDURE (IN var: Item) GetVal (VAR x: Value; OUT ok: BOOLEAN)
NEW
Assigns the value of var to x. The actual type of x must either be Item or a custom extension of Value containing a single field of any type. In the former case the item denotes the assigned variable, in the latter the value is assigned directly to the field.
Pre
var.Valid() 20
var.obj IN {varObj, procObj} 22
x IS Item
x.Valid() 20
x.obj = varObj 22
x.vis = exported 27
~(x IS Item)
x is extension of Value 25
x contains a single field 26
PROCEDURE (IN var: Item) PutVal (IN x: Value; OUT ok: BOOLEAN)
NEW
Assigns the value of x to var. The actual type of x must either be Item or a custom extension of Value containing a single field of any type. In the former case the item denotes the value, in the latter the value is read directly from to the field.
Pre
var.Valid() 20
var.obj = varObj 22
var.vis = exported 27
x IS Item
x.Valid() 20
x.obj IN {varObj, procObj} 22
~(x IS Item)
x is extension of Value 25
x contains a single field 26
PROCEDURE (IN var: Item) GetStringVal (OUT x: ARRAY OF CHAR; OUT ok: BOOLEAN)
NEW
Reads a string value from an item.
Pre
var.Valid() 20
var.typ = arrTyp & var.BaseTyp() = charTyp 21
var.obj = varObj 22
PROCEDURE (IN var: Item) GetSStringVal (OUT x: ARRAY OF SHORTCHAR; OUT ok: BOOLEAN)
NEW
Reads a short string value from an item.
Pre
var.Valid() 20
var.typ = arrTyp & var.BaseTyp() = sCharTyp 21
var.obj = varObj 22
PROCEDURE (IN var: Item) PtrVal (): ANYPTR
NEW
Reads a pointer value from an item.
Pre
var.Valid() 20
var.typ IN {anyPtrTyp, ptrTyp} 21
var.obj = varObj 22
PROCEDURE (IN var: Item) IntVal (): INTEGER
NEW
Reads a integer value from an item.
Pre
var.Valid() 20
var.typ IN {sCharTyp, charTyp, byteTyp, sIntTyp, intTyp} 21
var.obj = varObj 22
PROCEDURE (IN var: Item) RealVal (): REAL
NEW
Reads a real value from an item.
Pre
var.Valid() 20
var.typ IN {sRealTyp, realTyp} 21
var.obj = varObj 22
PROCEDURE (IN var: Item) LongVal (): LONGINT
NEW
Reads a long value from an item.
Pre
var.Valid() 20
var.typ = longTyp 21
var.obj = varObj 22
PROCEDURE (IN var: Item) CharVal (): CHAR
NEW
Reads a character value from an item.
Pre
var.Valid() 20
var.typ IN {sCharTyp, charTyp} 21
var.obj = varObj 22
PROCEDURE (IN var: Item) BoolVal (): BOOLEAN
NEW
Reads a boolean value from an item.
Pre
var.Valid() 20
var.typ = boolTyp 21
var.obj = varObj 22
PROCEDURE (IN var: Item) SetVal (): SET
NEW
Reads a set value from an item.
Pre
var.Valid() 20
var.typ = setTyp 21
var.obj = varObj 22
PROCEDURE (IN var: Item) PutStringVal (IN x: ARRAY OF CHAR; OUT ok: BOOLEAN)
NEW
Writes a string value to an item.
Pre
var.Valid() 20
var.typ = arrTyp & var.BaseTyp() = charTyp 21
var.obj = varObj 22
var.vis = exported 27
PROCEDURE (IN var: Item) PutSStringVal (IN x: ARRAY OF SHORTCHAR; OUT ok: BOOLEAN)
NEW
Writes a short string value to an item.
Pre
var.Valid() 20
var.typ = arrTyp & var.BaseTyp() = sCharTyp 21
var.obj = varObj 22
var.vis = exported 27
PROCEDURE (IN var: Item) PutPtrVal (x: ANYPTR)
NEW
Writes a pointer value to an item.
Pre
var.Valid() 20
var.typ IN {anyPtrTyp, ptrTyp} 21
var.obj = varObj 22
var.vis = exported 27
PROCEDURE (IN var: Item) PutIntVal (x: INTEGER)
NEW
Writes an integer value to an item.
Pre
var.Valid() 20
var.typ IN {sCharTyp, charTyp, byteTyp, sIntTyp, intTyp} 21
var.obj = varObj 22
var.vis = exported 27
PROCEDURE (IN var: Item) PutRealVal (x: REAL)
NEW
Writes a real value to an item.
Pre
var.Valid() 20
var.typ IN {sRealTyp, realTyp} 21
var.obj = varObj 22
var.vis = exported 27
PROCEDURE (IN var: Item) PutLongVal (x: LONGINT)
NEW
Writes a long value to an item.
Pre
var.Valid() 20
var.typ = longTyp 21
var.obj = varObj 22
var.vis = exported 27
PROCEDURE (IN var: Item) PutCharVal (x: CHAR)
NEW
Writes a character value to an item.
Pre
var.Valid() 20
var.typ IN {sCharTyp, charTyp} 21
var.obj = varObj 22
var.vis = exported 27
PROCEDURE (IN var: Item) PutBoolVal (x: BOOLEAN)
NEW
Writes a boolean value to an item.
Pre
var.Valid() 20
var.typ = boolTyp 21
var.obj = varObj 22
var.vis = exported 27
PROCEDURE (IN var: Item) PutSetVal (x: SET)
NEW
Writes a set value to an item.
Pre
var.Valid() 20
var.typ = setTyp 21
var.obj = varObj 22
var.vis = exported 27
PROCEDURE (IN type: Item) New (): ANYPTR
NEW
Generates a new empty heap object. The item must be a record or a pointer type. The type of the new object is the same as the pointer, or a pointer to the record described by the item.
Pre
type.Valid() 20
type.typ IN (recTyp, ptrTyp) 21
PROCEDURE (IN val: Item) Copy (): ANYPTR
NEW
The same as New, but also copies the contents byte by byte. The item must be a record variable.
Pre
val.Valid() 20
val.typ = recTyp 21
val.obj = varObj 22
PROCEDURE (IN rec: Item) CallWith (proc: PROCEDURE (VAR rec, par: ANYREC); VAR par: ANYREC)
NEW
Call procedure proc with the parameters rec (i.e., the item itself, the "self" parameter) and parameter par.
Pre
rec.Valid() 20
rec.typ = recTyp 21
rec.obj = varObj 22
TYPE Scanner
A scanner allows to iterate over all modules, all items in a module, or all fields in a record.
this-: Item
The result of the most recent Scan operation.
eos-: BOOLEAN
This flag tells whether the most recent Scan operation has attempted to read beyond the last item.
PROCEDURE (VAR s: Scanner) ConnectToMods
NEW
Each invocation of s.Scan will return another module.
Post
s.this.obj = undef
~s.eos
PROCEDURE (VAR s: Scanner) ConnectTo (IN obj: Item)
NEW
Connect the scanner to a particular module or record.
Pre
obj.Valid() 20
obj.obj = modObj OR obj.typ = recTyp 21
PROCEDURE (VAR s: Scanner) Scan
Scan a new item. The result is put into s.this. If an attempt was made to scan beyond the last item, s.eos is set, otherwise it is cleared.
Pre
s is connected 20
PROCEDURE (VAR s: Scanner) GetObjName (OUT name: Name)
NEW
Get the name of the most recently scanned item.
Pre
s.this.Valid() 20
PROCEDURE (VAR s: Scanner) Level (): INTEGER
NEW
Returns the scanned record's extension level.
Pre
s.this.Valid() 20
s connecte to record variable 22
TYPE LookupFilter = PROCEDURE (IN path: ARRAY OF CHAR; OUT i: Item; OUT done: BOOLEAN)
Type used for extension hook that allows Meta to operate remotely, for example.
PROCEDURE Lookup (IN name: ARRAY OF CHAR; OUT mod: Item)
Set up an item to a module.
Post
mod.obj = modObject
lookup was successful
mod.obj = undef
lookup was not successful
PROCEDURE LookupPath (IN path: ARRAY OF CHAR; OUT i: Item)
Lookup an item via a whole designator, starting with a module name.
PROCEDURE GetItem (obj: ANYPTR; OUT i: Item)
Create an item out of a pointer variable.
PROCEDURE InstallFilter (filter: LookupFilter)
Install an extension hook.
PROCEDURE UninstallFilter (filter: LookupFilter);
Uninstall an extension hook.
PROCEDURE GetThisItem (IN attr: ANYREC; OUT i: Item)
Used internally in extension hooks (creates an item out of a record variable). Use Lookup, LookupPath, or GetItem instead.
| System/Docu/Meta.odc |
Models
DEFINITION Models;
IMPORT Stores;
CONST clean = 0; notUndoable = 1; invisible = 2;
TYPE
Model = POINTER TO ABSTRACT RECORD (Stores.Store)
PROCEDURE (m: Model) Domain (): Stores.Domain, NEW
END;
Context = POINTER TO ABSTRACT RECORD
(c: Context) ThisModel (): Model, NEW, ABSTRACT;
(c: Context) GetSize (OUT w, h: INTEGER), NEW, ABSTRACT;
(c: Context) SetSize (w, h: INTEGER), NEW, EMPTY;
(c: Context) Normalize (): BOOLEAN, NEW, ABSTRACT;
(c: Context) Consider (VAR p: Proposal), NEW, EMPTY;
(c: Context) MakeVisible (l, t, r, b: INTEGER), NEW, EMPTY
END;
Proposal = ABSTRACT RECORD END;
Message = ABSTRACT RECORD
model-: Model;
era-: INTEGER
END;
UpdateMsg = EXTENSIBLE RECORD (Message) END;
NeutralizeMsg = RECORD (Message) END;
PROCEDURE CopyOf (m: Model): Model;
PROCEDURE Broadcast (model: Model; VAR msg: Message);
PROCEDURE Domaincast (d: Stores.Domain; VAR msg: Message);
PROCEDURE BeginModification (type: INTEGER; m: Model);
PROCEDURE EndModification (type: INTEGER; m: Model);
PROCEDURE BeginScript (m: Model; name: Stores.OpName; OUT script: Stores.Operation);
PROCEDURE EndScript (m: Model; script: Stores.Operation);
PROCEDURE Do (m: Model; name: Stores.OpName; op: Stores.Operation);
PROCEDURE LastOp (m: Model): Stores.Operation;
PROCEDURE Bunch (m: Model);
PROCEDURE StopBunching (m: Model);
PROCEDURE Era (m: Model): INTEGER;
END Models.
Figure 1. Model-View-Controller Separation
A model is one part of a Model-View-Controller triple. A model represents some data, without knowing how these data may be represented. Representation is performed by a view. There may be several views displaying the same model simultaneously, and possibly in different ways.
After a model has been modified, a model message is broadcast in the domain to which this model belongs (e.g., the domain of the document of which the model is a part). Model messages are received by the appropriate views, such that these views can update the display according to the model modification which was performed.
A modification of a model may be permanent, or reversible. To indicate a permanent modification, the procedures BeginModification/EndModification must be called before/after the modification(s). Reversible modifications ("undoable" operations) are implemented as Stores.Operation objects. Several operations on the same model can be combined into one (i.e., as a whole undoable/redoable) operation with the BeginScript/EndScript pair of procedures.
A model may be a container, i.e., contain embedded views. An embedded view can communicate with the model in which it is embedded via a Context. A container model provides a context for each embedded view. Using its context, a view can inquire its current size, or it can try to change its size.
All models in a document share the same domain, i.e., their domain fields are either NIL (when the document is not displayed in some window) or refer to the same domain. Different displayed documents have different domains.
Examples:
ObxLinesdocu
ObxGraphsdocu
ObxCapsdocu/sources compound commands (undoable scripts)
CONST clean
Possible value for parameter type of BeginModification/EndModification. Indicates an operation that does not make its document "dirty". Example: modifying a text in a way that is considered as "unimportant", such as collapsing or expanding a text fold (-> StdFolds).
CONST invisible
Possible value for parameter type of BeginModification/EndModification. Indicates an operation that "folds together" with the previous operation, i.e., does not itself become visible in the Undo/Redo menu items. Invisible operations can be used for operations that by themselves may not be expected to appear in an Undo/Redo menu. Example: setting options in a controller. When executing a Redo operation, after a (visible) operation, all invisible operations executed. When executing an Undo operation, first all invisible operations are undone and afterwards the visible operations.
CONST notUndoable
Possible value for parameter type of BeginModification/EndModification. Indicates an operation that cannot be reversed ("undone"). This is important for operations where the undo feature would be too expensive.
TYPE Model (Stores.Store)
ABSTRACT
A model represents data, which may be presented by a view.
Models are allocated by specific model directories, e.g., by Texts.dir.
Models are used by commands which can operate on the data that is represented by the model.
Models are extended whenever new kinds of displayable data need to be represented.
A model's domain delineates the boundaries of the document in which it is embedded.
A model's Internalize, Externalize, and CopyFrom procedures must be implemented if the store contains persistent state.
PROCEDURE (m: Model) Domain (): Stores.Domain
NEW
Returns the domain of the model, usually representing one document. If the domain is NIL, the model is not displayed. The domain is set up by the procedure Stores.InitDomain.
TYPE Context
ABSTRACT
A context object is part of the model-view recursion scheme of BlackBox. A context is generated and maintained by a container model, and there is one context for every view embedded in the model. The context is carried by the view, so the view can communicate with its context (i.e., with the model in which it is embedded).
A Context allows a contained view to communicate with its container.
A Context is extended for every container model.
PROCEDURE (c: Context) ThisModel (): Model
NEW, ABSTRACT
Returns the context's model. NIL may be returned if the context doesn't want to disclose its identity.
ThisModel may be narrowed in an extension.
PROCEDURE (c: Context) GetSize (OUT w, h: INTEGER)
NEW, ABSTRACT
Returns the width and height of the contained view in its container, in universal units.
Post
w >= 0 & h >= 0
PROCEDURE (c: Context) SetSize (w, h: INTEGER)
NEW, EMPTY
Requests the container to adapt the size of c's view to the given width and height. The container may or may not grant this request.
PROCEDURE (c: Context) Normalize (): BOOLEAN
NEW, ABSTRACT
Determines whether the contained view should normalize its persistent state upon externalization, and whether it should not make a modification of this state undoable.
As an example, consider the scroll position of a text view: if the view is in a root context, i.e., in the outermost view level, it should write out position 0 (i.e., "normalized") as its current scroll position upon externalization, and it shouldn't make scroll operations undoable. However, if embedded in a non-root context, it should write out its current scroll position, and should make a scroll operation undoable.
Normalize is called in a view's Externalize procedure and when it must be determined whether an operation needs to be undoable or not.
PROCEDURE (c: Context) Consider (VAR p: Proposal)
NEW, EMPTY
If an embedded view wants its container to do something, it must ask for such a change by sending the container a Proposal via the Consider procedure. The container may, but need not, cooperate in an appropriate way. BlackBox currently doesn't predefine proposals of its own.
PROCEDURE (c: Context) MakeVisible (l, t, r, b: INTEGER)
NEW, EMPTY
Scroll the container of c's view such that the rectangle (l, t, r, b) becomes at least partially visible.
TYPE Proposal
ABSTRACT
Base type for all proposals. A proposal is a message which a view can send to the container (via its context object) in which it is embedded.
TYPE Message
ABSTRACT
Base type for all model messages.
Messages are used to transmit information from a model to all views which display this model, typically about changes that have occurred in a model.
Messages are extended to describe specific kinds of information to be transmitted.
model: Model model # NIL
The model that has been changed.
era-: INTEGER
Used internally.
TYPE UpdateMsg (Message)
EXTENSIBLE
All model messages which notify about a model modification must be extensions of UpdateMsg. A basic (unextended) UpdateMsg indicates that the message's model has changed in some unspecified way.
UpdateMsgs are used to notify all views displaying a given model about a change of this model.
UpdateMsgs are extended in order to update the display in more specific ways than to redraw the whole view (i.e., faster and with less screen flicker), i.e., to allow partial updates.
TYPE NeutralizeMsg (Message)
Extension
This message is sent by the framework to indicate that marks (selection marks and the like) should be removed.
PROCEDURE CopyOf (m: Model): Model
Returns a (deep) copy of the model. Internally, it clones m and calls its CopyFrom method.
Pre
m # NIL 20
Post
result # NIL
PROCEDURE Broadcast (model: Model; VAR msg: Message)
Broadcast msg for model. Before broadcasting, parameter model is assigned to the message's model-field. The broadcast is actually performed only if model.domain # NIL.
Broadcast is called by models whenever models need to transmit information to the views by which they are displayed. In contrast to Domaincast, Broadcast sends msg only to the views which have model as their model.
The handler of a model message may not recursively broadcast another model message.
Pre
model # NIL 20
no recursion 21
Post
msg.model = model
PROCEDURE Domaincast (d: Stores.Domain; VAR msg: Message)
This procedure sends a message to a particular domain, or does nothing if the domain is NIL. Every view in the domain receives the message. Normally, you'll use Broadcast to notify only the views on a particular model. Domaincast is only necessary if the contents of one view (e.g., a text ruler) influences something outside of the view itself (e.g., the formatting of the text below the ruler). The domaincast is actually performed only if d # NIL.
A domaincast may not be performed if another one is still in progress for this domain (no recursion).
Pre
no recursion 20
Post
msg.model = NIL
PROCEDURE BeginModification (type: INTEGER; m: Model)
If model m is modified in a way that cannot be undone, the modification(s) must be bracketed by calls to BeginModification and EndModification with parameter type set to notUndoable.
Pre
m # NIL 20
type IN {clean, notUndoable, invisible} 21
PROCEDURE EndModification (type: INTEGER; m: Model)
If model m is modified in a way that cannot be undone, the modification(s) must be bracketed by calls to BeginModification and EndModification with parameter type set to notUndoable.
Pre
m # NIL 20
type IN {clean, notUndoable, invisible} 21
PROCEDURE BeginScript (m: Model; name: Stores.OpName; OUT script: Stores.Operation)
To make a sequence of undoable operations undoable as a whole, the sequence should be bracketed by calls to BeginScript and EndScript.
Pre
m # NIL 20
Post
script # NIL
PROCEDURE EndScript (m: Model; script: Stores.Operation)
To make a sequence of undoable operations undoable as a whole, the sequence should be bracketed by calls to BeginScript and EndScript. The same script which has been returned in BeginScript must be passed to EndScript.
Pre
m # NIL 20
script # NIL 21
PROCEDURE Do (m: Model; name: Stores.OpName; op: Stores.Operation)
This procedure is called to execute an operation on a model. The operation's Do procedure is called, and the operation is recorded for a later undo.
Pre
m # NIL 20
op # NIL 21
Post
op.inUse
PROCEDURE LastOp (m: Model): Stores.Operation
This procedure returns the most recently executed operation on the given model. It can be used to decide whether to bunch several successive operations into one single atomic operation, e.g., if a character is typed into a text, it may be bunched with the previously inserted character; such that an undo operates on the whole text typed in, and not on one character per undo.
Pre
m # NIL 20
PROCEDURE Bunch (m: Model)
Notify model that another action was bunched to the most recently executed operation. After it has been determined that the new operation can be merged into the most recent operation (using LastOp for the test), the previous operation can be modified (e.g., a character appended to its string of characters that were typed in) and this modification made known to the framework by calling Bunch.
Pre
m # NIL 20
PROCEDURE StopBunching (m: Model)
Prevents any further bunching on this model's current operation.
Pre
m # NIL 20
PROCEDURE Era (m: Model): INTEGER
Called internally.
Pre
m # NIL 20
| System/Docu/Models.odc |
Out
DEFINITION Out;
PROCEDURE Open;
PROCEDURE Char (ch: CHAR);
PROCEDURE Ln;
PROCEDURE Int (i: LONGINT; n: INTEGER);
PROCEDURE Real (x: REAL; n: INTEGER);
PROCEDURE String (str: ARRAY OF CHAR);
END Out.
This module is provided for compatibility with the book "Programming in Oberon" by Reiser/Wirth. It is useful when learning the language. It is not recommended for use in production programs.
PROCEDURE Open
Brings open log window to the top. If no log window is open, a new one is opened.
PROCEDURE Char (ch: CHAR)
Writes a character into the log.
PROCEDURE Ln
Writes a carriage return into the log.
PROCEDURE Int (i: LONGINT; n: INTEGER)
Writes an integer number into the log, with n digits. If n is too small (e.g., 0) to represent the number correctly, the necessary minimal number of digits is used.
PROCEDURE Real (x: REAL; n: INTEGER)
Writes a real number into the log, with n digits. If n is too small (e.g., 0) to represent the number correctly, the necessary minimal number of digits is used.
PROCEDURE String (str: ARRAY OF CHAR)
Writes a string into the log.
| System/Docu/Out.odc |
Ports
DEFINITION Ports;
IMPORT Fonts;
CONST
black = 00000000H; white = 00FFFFFFH;
grey6 = 00F0F0F0H; grey12 = 00E0E0E0H; grey25 = 00C0C0C0H;
grey50 = 00808080H; grey75 = 00404040H;
red = 000000FFH; green = 0000FF00H; blue = 00FF0000H;
defaultColor = 01000000H;
mm = 36000; point = 12700; inch = 914400;
fill = -1;
openPoly = 0; closedPoly = 1; openBezier = 2; closedBezier = 3;
invert = 0; hilite = 1; dim25 = 2; dim50 = 3; dim75 = 4;
hide = FALSE; show = TRUE;
arrowCursor = 0; textCursor = 1; graphicsCursor = 2; tableCursor = 3; bitmapCursor = 4; refCursor = 5;
keepBuffer = FALSE; disposeBuffer = TRUE;
TYPE
Color = INTEGER;
Point = RECORD
x, y: INTEGER
END;
Port = POINTER TO ABSTRACT RECORD
unit-: INTEGER;
(p: Port) Init (unit: INTEGER; printerMode: BOOLEAN), NEW;
(p: Port) GetSize (OUT w, h: INTEGER), NEW, ABSTRACT;
(p: Port) SetSize (w, h: INTEGER), NEW, ABSTRACT;
(p: Port) NewRider (): INTEGER, NEW, ABSTRACT;
(p: Port) OpenBuffer (l, t, r, b: INTEGER), NEW, ABSTRACT;
(p: Port) CloseBuffer, NEW, ABSTRACT
END;
Rider = POINTER TO ABSTRACT RECORD
(rd: Rider) SetRect (l, t, r, b: INTEGER), NEW, ABSTRACT;
(rd: Rider) GetRect (OUT l, t, r, b: INTEGER), NEW, ABSTRACT;
(rd: Rider) Base (): Port, NEW, ABSTRACT;
(rd: Rider) Move (dx, dy: INTEGER), NEW, ABSTRACT;
(rd: Rider) SaveRect (l, t, r, b: INTEGER; OUT res: INTEGER), NEW, ABSTRACT;
(rd: Rider) RestoreRect (l, t, r, b: INTEGER; dispose: BOOLEAN), NEW, ABSTRACT;
(rd: Rider) DrawRect (l, t, r, b, s: INTEGER; col: Color), NEW, ABSTRACT;
(rd: Rider) DrawOval (l, t, r, b, s: INTEGER; col: Color), NEW, ABSTRACT;
(rd: Rider) DrawLine (x0, y0, x1, y1, s: INTEGER; col: Color), NEW, ABSTRACT;
(rd: Rider) DrawPath (IN p: ARRAY OF Point; n, s: INTEGER; col: Color;
path: INTEGER), NEW, ABSTRACT;
(rd: Rider) MarkRect (l, t, r, b, s: INTEGER; mode: INTEGER; show: BOOLEAN), NEW, ABSTRACT;
(rd: Rider) Scroll (dx, dy: INTEGER), NEW, ABSTRACT;
(rd: Rider) SetCursor (cursor: INTEGER), NEW, ABSTRACT;
(rd: Rider) Input (OUT x, y: INTEGER; OUT modifiers: SET;
OUT isDown: BOOLEAN), NEW, ABSTRACT;
(rd: Rider) DrawSpace (x, y, w: INTEGER; col: Color; font: Fonts.Font), NEW, ABSTRACT;
(rd: Rider) DrawString (x, y: INTEGER; col: Color; IN s: ARRAY OF CHAR;
font: Fonts.Font), NEW, ABSTRACT;
(rd: Rider) DrawSString (x, y: INTEGER; col: Color; IN s: ARRAY OF SHORTCHAR;
font: Fonts.Font), NEW, ABSTRACT;
(rd: Rider) CharIndex (x, pos: INTEGER; IN s: ARRAY OF CHAR;
font: Fonts.Font): INTEGER, NEW, ABSTRACT;
(rd: Rider) SCharIndex (x, pos: INTEGER; IN s: ARRAY OF SHORTCHAR;
font: Fonts.Font): INTEGER, NEW, ABSTRACT;
(rd: Rider) CharPos (x, index: INTEGER; IN s: ARRAY OF CHAR;
font: Fonts.Font): INTEGER, NEW, ABSTRACT;
(rd: Rider) SCharPos (x, index: INTEGER; IN s: ARRAY OF SHORTCHAR;
font: Fonts.Font): INTEGER, NEW, ABSTRACT
END;
Frame = POINTER TO ABSTRACT RECORD
unit-: INTEGER;
dot-: INTEGER;
rider-: Rider;
gx-, gy-: INTEGER;
(f: Frame) ConnectTo (p: Port), NEW, EXTENSIBLE;
(f: Frame) SetOffset (gx, gy: INTEGER), NEW, EXTENSIBLE;
(f: Frame) SaveRect (l, t, r, b: INTEGER; OUT res: INTEGER), NEW;
(f: Frame) RestoreRect (l, t, r, b: INTEGER; dispose: BOOLEAN), NEW;
(f: Frame) DrawRect (l, t, r, b, s: INTEGER; col: Color), NEW;
(f: Frame) DrawOval (l, t, r, b, s: INTEGER; col: Color), NEW;
(f: Frame) DrawLine (x0, y0, x1, y1, s: INTEGER; col: Color), NEW;
(f: Frame) DrawPath (IN p: ARRAY OF Point; n, s: INTEGER; col: Color; path: INTEGER), NEW;
(f: Frame) MarkRect (l, t, r, b, s: INTEGER; mode: INTEGER; show: BOOLEAN), NEW;
(f: Frame) Scroll (dx, dy: INTEGER), NEW;
(f: Frame) SetCursor (cursor: INTEGER), NEW;
(f: Frame) Input (OUT x, y: INTEGER; OUT modifiers: SET; OUT isDown: BOOLEAN), NEW;
(f: Frame) DrawSpace (x, y, w: INTEGER; col: Color; font: Fonts.Font), NEW;
(f: Frame) DrawString (x, y: INTEGER; col: Color; IN s: ARRAY OF CHAR;
font: Fonts.Font), NEW;
(f: Frame) DrawSString (x, y: INTEGER; col: Color; IN s: ARRAY OF SHORTCHAR;
font: Fonts.Font), NEW;
(f: Frame) CharIndex (x, pos: INTEGER; IN s: ARRAY OF CHAR;
font: Fonts.Font): INTEGER, NEW;
(f: Frame) SCharIndex (x, pos: INTEGER; IN s: ARRAY OF SHORTCHAR;
font: Fonts.Font): INTEGER, NEW;
(f: Frame) CharPos (x, index: INTEGER; IN s: ARRAY OF CHAR;
font: Fonts.Font): INTEGER, NEW;
(f: Frame) SCharPos (x, index: INTEGER; IN s: ARRAY OF SHORTCHAR;
font: Fonts.Font): INTEGER, NEW
END;
VAR background, dialogBackground: Color;
PROCEDURE IsPrinterPort (p: Port): BOOLEAN;
PROCEDURE RGBColor (red, green, blue: INTEGER): Color;
END Ports.
Ports are carriers for pixel data. Examples of ports are screen and printer ports.
Riders are access paths to ports. The drawing operations of a rider are performed in a coordinate system with positive x-axis and negative y-axis, i.e., x values increase towards the right, while y values increase towards the bottom. This coordinate system is the same for every rider on a port, with the origin at the upper-left corner of the port. Points are coordinate pairs (in device coordinates) which denote the upper-left corner of a pixel:
Figure 1. Drawing Plane
A rider occupies a rectangle within the port area. Each rider acts as a clipping rectangle, to which all its drawing operations are clipped.
Frames are port mappers, which provide port output operations and input from mouse and keyboard. Frame coordinates are scaled and translated such that they are independent of the frame's position on a port, and independent of the port's spacial resolution. For this reason, all frame operations use universal units (-> Fonts) for coordinates, while all port and rider operations use pixel coordinates.
CONST black, white, grey6, grey12, grey25, grey50, grey75, red, green, blue
RGB values for several important colors.
CONST defaultColor
This is a pseudo color which is substituted by the currently set default foreground color for drawing.
CONST mm, point, inch
Three important distance measures in universal units.
CONST fill
This value may be passed to the procedures DrawRect, DrawOval, DrawPath, and MarkRect as size parameter, to cause the drawing of a filled shape, instead of the shape's outline only.
CONST openPoly, closedPoly, openBezier, closedBezier
These values may be passed to the procedure DrawPath as path parameter. They causes the drawing of a polyline, a polygon, an open Bezier curve, or of a closed Bezier curve. Note that with Bezier curves, only every third point lies on the curve.
Figure 2. Various Path Examples
CONST invert, hilite, dim25, dim50, dim75
These values may be passed as mode-parameter to procedure MarkRect. They cause the marked rectangle to become inverted, hilighted, or dimmed. The exact interpretation of these modes is platform-dependent.
In the simplest case, all three modes are implemented the same way, namely by inverting each bit in the color value which represents a pixel. Ideally, hilite should replace an area's background color with a user-selectable hilight-color, and vice versa. The three dimming modes, applied to a white background, deliver light, medium, and dark grey values, respectively.
CONST hide, show
These values may be passed as show-parameter of the MarkRect procedures. hide means that an existing mark should be removed, and show means that the mark should be drawn. In some implementations, the operation may be identical for hide and show, but this is not guaranteed.
CONST arrowCursor
The default shape of the cursor.
CONST textCursor, graphicsCursor, tableCursor, bitmapCursor
Cursor shapes which correspond to the type of data currently being manipulated: sequential, large shapes, regularly arranged objects, small shapes.
CONST refCursor
Cursor shape for indicating references, such as hyperlinks.
CONST keepBuffer, disposeBuffer
These constants may be passed to the dispose parameters of procedures Rider.RestoreRect and Frame.RestoreRect.
TYPE Color = INTEGER
A color is a four-byte value where the least significant byte (interpreted as unsigned integer) specifies the red-intensity of an RGB triple. The next byte specifies the green-intensity, the third byte represents the blue-intensity. The most significant byte must be set to zero.
TYPE Point
This type is used to construct paths for the DrawPath procedure. A path consists of an array of points, where points are coordinate pairs.
Points are used in drawing routines that call DrawPath.
x, y: INTEGER
Coordinate pair.
TYPE Port
ABSTRACT
Carrier for pixel data.
Ports are allocated and used internally.
Ports are implemented internally.
unit-: INTEGER unit > 0
The size of a pixel in universal units.
PROCEDURE (p: Port) Init (unit: INTEGER; printerMode: BOOLEAN)
Sets the spacial resolution (in universal units per pixel). Parameter printerMode determines whether the port acts as a printing object.
Pre
p.unit = 0 OR p.unit = unit 20
unit > 0 21
Post
p.unit = unit
PROCEDURE (p: Port) GetSize (OUT w, h: INTEGER)
NEW, ABSTRACT
Get the port's current size (in pixels).
Post
w >= 0
h >= 0
PROCEDURE (p: Port) SetSize (w, h: INTEGER)
NEW, ABSTRACT
Sets the port's size (in pixels).
Pre
w >= 0 20
h >= 0 21
PROCEDURE (p: Port) NewRider (): Rider
NEW, ABSTRACT
Returns a rider that has the appropriate type for this port implementation.
PROCEDURE (p: Port) OpenBuffer (l, t, r, b: INTEGER)
NEW, ABSTRACT
Opens an off-screen buffer for port p. The buffer is initialized with the contents of p's rectangle (l, t, r, b). OpenBuffer must be followed by a call to CloseBuffer. Calls to OpenBuffer must not be nested.
Used internally, for restoring a window flicker-free in the background. Not to be used for other purposes.
PROCEDURE (p: Port) CloseBuffer
NEW, ABSTRACT
Copy back the contents of the port's off-screen buffer, and release the buffer. OpenBuffer must have been called before.
Used internally, for restoring a window flicker-free in the background. Not to be used for other purposes.
TYPE Rider
ABSTRACT
Access path to a port (i.e., to a pixel carrier). A rider uses the same coordinate system as its port, with the origin being the upper-left corner of the port. All coordinates used for a rider are in device coordinates, i.e., in pixels. Riders also contain a clipping rectangle. Normally, it is manipulated automatically by the framework, but in special circumstances, it can be useful also for view programmers.
Riders are allocated by ports.
Riders are used internally (by frames, see below) and implemented internally.
PROCEDURE (rd: Rider) SetRect (l, t, r, b: INTEGER)
NEW, ABSTRACT
Sets the rider's clipping rectangle on the port (in pixels). Normally, this method is called by the framework only. If you use it explicitly, you should restore the old clipping rectangle after you are done. The framework sets up the clipping rectangle before a view's Restore method is called (-> Views.View.Restore). This ensures that drawing never occurs outside of the drawing area that belongs to the view, as long as the clipping rectangle is not modified by the view.
The clipping rectangle must never be made larger than the size set up by the framework, it may only be made smaller. Otherwise, the results are unpredictable.
Pre
0 <= l <= r & 0 <= t <= b 20
PROCEDURE (rd: Rider) GetRect (OUT l, t, r, b: INTEGER)
NEW, ABSTRACT
Gets the rider's clipping rectangle on the port (in pixels).
Post
0 <= l <= r & 0 <= t <= b
PROCEDURE (rd: Rider) Base (): Port
NEW, ABSTRACT
Returns the port to which rd is connected.
Post
result # NIL
PROCEDURE (rd: Rider) Move (dx, dy: INTEGER)
NEW, ABSTRACT
Used internally.
PROCEDURE (rd: Rider) SaveRect (l, t, r, b: INTEGER; OUT res: INTEGER)
NEW, ABSTRACT
Saves a rectangle (parallel to the coordinate axes) of width r - l and of height b - t in a background buffer, from where it can be restored later using RestoreRect. SaveRect must be balanced by RestoreRect(l, t, r, b, disposeBuffer). All coordinates are in pixels.
Calls to SaveRect may not be nested, and they may not occur during restoration of a view (-> Views.View.Restore). The purpose of SaveRect/RestoreRect is to act as temporary buffering mechanism during mouse tracking (->Views.View.HandleCtrlMsg).
res = 0 means that the call was successful, otherwise RestoreRect must not be called.
Pre
(l <= r) & (t <= b) 20
PROCEDURE (rd: Rider) RestoreRect (l, t, r, b: INTEGER; dispose: BOOLEAN)
NEW, ABSTRACT
After a successful call to SaveRect, the same rectangle, i.e., its pixelmap contents as it was upon saving, can be restored with RestoreRect. All coordinates are in pixels. RestoreRect can be called several times in succession; the last time with dispose = disposeBuffer and all other times with dispose = keepBuffer.
Pre
(l <= r) & (t <= b) 20
PROCEDURE (rd: Rider) DrawRect (l, t, r, b, s: INTEGER; col: Color)
NEW, ABSTRACT
Draws a rectangle (parallel to the coordinate axes) of width r - l and of height b - t. All coordinates are in pixels. If s < 0, the rectangle is filled with color col. Otherwise, the rectangle is drawn as an outline of thickness s. The outline is drawn inside of the rectangle. If s = 0, a very thin outline (hairline) is used.
Pre
(l <= r) & (t <= b) 20
(s >= 0) OR (s = fill) 21
PROCEDURE (rd: Rider) DrawOval (l, t, r, b, s: INTEGER; col: Color)
NEW, ABSTRACT
Draws an ellipse (parallel to the coordinate axes) of width r - l and of height b - t. All coordinates are in pixels. If s < 0, the ellipse is filled with color col. Otherwise, the ellipse is drawn as an outline of thickness s. The outline is drawn inside of the rectangle. If s = 0, a very thin outline (hairline) is used.
Pre
(l <= r) & (t <= b) 20
(s >= 0) OR (s = fill) 21
PROCEDURE (rd: Rider) DrawLine (x0, y0, x1, y1, s: INTEGER; col: Color)
NEW, ABSTRACT
Draws a line from the point (x0, y0) to the point (x1, y1) of thickness s in color col: All coordinates are in pixels.
Note that if you need to draw strictly horizontal or vertical lines, you could use DrawRect with fill instead of DrawLine. The advantage of DrawRect is that it is clearer which pixels are really drawn, it's the pixels that are strictly inside the bounding rectangle.
Figure 3: Line
If s = 0, a very thin outline (hairline) is used.
Pre
s >= 0 20
PROCEDURE (rd: Rider) DrawPath (IN p: ARRAY OF Point; n, s: INTEGER; col: Color;
path: INTEGER)
NEW, ABSTRACT
Draws the path consisting of points p[0] .. p[n - 1] in color col. The nature of the path is given by parameter path. It can either be a polyline, a polygon, an open Bezier curve, or a closed Bezier curve. The polyline is the same that a sequence of DrawLine operations would generate. For a polygon, the n points define the mathematical region which will be outlined or filled. An open path with n points results in n - 1 path pieces, a closed path with n points results in n path pieces. All coordinates in the point array are in pixels.
Pre
n >= 0 20
n <= LEN(p) 21
(s = fill) => (path = closedPoly) OR (path = closedBezier) 22
(s >= 0) OR (s = fill) 23
path IN {closedPoly, openPoly, closedBezier, openBezier} 25
path = openPoly
n >= 2 20
path = closedPoly
n >= 2 20
path = openBezier
n >= 4 20
n MOD 3 = 1 24
path = closedBezier
n >= 3 20
n MOD 3 = 0 24
PROCEDURE (rd: Rider) MarkRect (l, t, r, b, s: INTEGER; mode: INTEGER; show: BOOLEAN)
NEW, ABSTRACT
Marks a rectangle (parallel to the coordinate axes) of width r - l and of height b - t. All coordinates are in pixels. If s < 0, the rectangle is filled in some way dependent on mode. Otherwise, the rectangle is drawn as an outline of thickness s. The outline is drawn inside of the rectangle. If s = 0, a very thin outline (hairline) is used.
The meaning of mode is implementation-dependent, but it must change the marked area in a visible way. show indicates whether the mark should be drawn or removed. Calling MarkRect with show and then directly afterwards with hide (otherwise with the same parameters) should re-establish exactly the state before the first call.
Pre
(l <= r) & (l <= t) 20
s >= 0 21
mode IN {invert, hilite, dim25, dim50, dim75} 22
PROCEDURE (rd: Rider) Scroll (dx, dy: INTEGER)
NEW, ABSTRACT
Shifts the rider's contents by vector (dx, dy). The translation vector is given in pixels. Shifting occurs completely within the rider's rectangle, ie., pixels outside of it are neither written nor read. The part of the rectangle that becomes newly exposed is undefined.
The purpose of Scroll is to speed up scrolling operations by reusing existing pixel data instead of making the application redraw everything.
However, under special circumstances, this procedure may not actually copy pixel data, but cause the application to restore part of the rectangle instead anyway.
Warning: this operation may only be used on interactive ports, in order to update the screen display after a user manipulation.
Figure 4. Effect of Scroll Operation
PROCEDURE (rd: Rider) SetCursor (cursor: INTEGER)
NEW, ABSTRACT
Sets the cursor to the given value.
Pre
cursor IN {arrowCursor..refCursor} 20
PROCEDURE (rd: Rider) Input (OUT x, y: INTEGER; OUT modifiers: SET; OUT isDown: BOOLEAN)
NEW, ABSTRACT
Polls the current mouse location and tells whether the mouse button is currently pressed. All coordinates are in pixels. In modifiers, the currently pressed modifier keys are returned, like Controllers.doubleClick, Controllers.extend, Controllers.modify, Controllers.popup, Controllers.pick, and possibly additional platform-specific modifiers. For the mapping of platform specific keys see platform specific modifiers.
PROCEDURE (rd: Rider) DrawSpace (x, y, w: INTEGER; col: Color; font: Fonts.Font)
NEW, ABSTRACT;
Draws a space character of width w.
The horizontal position is specified by x, the vertical baseline by y, the color by col, and the font attributes by font. All coordinates are in pixels. This method allows for drawing spaces decorated with underline or strike out.
Pre
font # NIL
PROCEDURE (rd: Rider) DrawString (x, y: INTEGER; col: Color; IN s: ARRAY OF CHAR;
font: Fonts.Font)
NEW, ABSTRACT
Draws string s in color col and font font with the base line at y. All coordinates are in pixels.
Pre
font # NIL 20
PROCEDURE (rd: Rider) DrawSString (x, y: INTEGER; col: Color; IN s: ARRAY OF SHORTCHAR;
font: Fonts.Font)
NEW, ABSTRACT
Draws short string s in color col and font font with the base line at y. All coordinates are in pixels.
Pre
font # NIL 20
PROCEDURE (rd: Rider) CharIndex (x, pos: INTEGER; IN s: ARRAY OF CHAR;
font: Fonts.Font): INTEGER
NEW, ABSTRACT
Given string s at position x, CharIndex determines the index of the character which lies at position pos. All coordinates are in pixels. Result = 0 means pos is at or left of the first character in s, result = n - 1, where n is the number of characters in string s, means pos is right of the last character in s.
Pre
font # NIL 20
PROCEDURE (rd: Rider) LCharIndex (x, pos: INTEGER; IN s: ARRAY OF SHORTCHAR;
font: Fonts.Font): INTEGER
NEW, ABSTRACT
Given string s at position x, CharIndex determines the index of the character which lies at position pos. All coordinates are in pixels. Result = 0 means pos is at or left of the first character in s, result = n - 1, where n is the number of characters in string s, means pos is right of the last character in s.
Pre
font # NIL 20
PROCEDURE (rd: Rider) CharPos (x, index: INTEGER; IN s: ARRAY OF CHAR;
font: Fonts.Font): INTEGER
NEW, ABSTRACT
Given string s at position x, CharPos determines the position of character index in s. All coordinates are in pixels. The position of the left margin of the character is returned.
Pre
font # NIL 20
PROCEDURE (rd: Rider) LCharPos (x, index: INTEGER; IN s: ARRAY OF SHORTCHAR;
font: Fonts.Font): INTEGER
NEW, ABSTRACT
Given string s at position x, CharPos determines the position of character index in s. All coordinates are in pixels. The position of the left margin of the character is returned.
Pre
font # NIL 20
TYPE Frame
ABSTRACT
A Frame is a mapper for a port. Every frame has its own coordinate system. All coordinates used for a frame are measured in universal units. Most frame operations forward to the frame's rider, i.e., they call the frame rider's corresponding procedure, and perform the necessary coordinate transformations (scaling between universal units and pixels, and a translation by the frame's origin).
A frame f translates from local universal coordinates to global pixel coordinates using the following transformation:
x := (f.gx + x) DIV f.unit; y := (f.gy + y) DIV f.unit; (* frame -> rider coordinates *)
The opposit transformation is:
x := x * f.unit - f.gx; y := y * f.unit - f.gy; (* rider -> frame coordinates *)
The rider's clipping rectangle is always set up such that drawing cannot occur outside of the frame, i.e., outside of the drawing view. Be careful if you change the rider's clipping rectangle (using the rider's SetRect method), since this introduces mutable state that you have to manage.
Frames are allocated by views.
Frames are used by views, for drawing and for mouse polling.
Frames are extended internally (Views.Frame).
unit-: INTEGER unit > 0
The size of a pixel in universal units.
dot-: INTEGER dot = point - point MOD unit
This value can be used as an approximation of point, rounded to a pixel. By using dot instead of point, ugly rounding errors can be avoided. For example, if you used point as the thickness of a line, and a pixel were slightly larger than point, the line might disappear altogether. Moreover, you may want to use a very thin line on the screen (about one pixel) as a hairline, but not have it become too small on a laser printer (where the frame's unit is much smaller than on screen). In these cases, dot comes handy.
rider-: Ports.Rider
Rider which links the frame to a port.
gx-, gy-: INTEGER [units]
The frame's origin in global coordinates (i.e., relative to the port's upper-left corner), but in units instead of pixels. This is an exception from the rule that riders use pixels, while frames use units.
PROCEDURE (f: Frame) ConnectTo (p: Port)
NEW, EXTENSIBLE
Connects the frame to a port. All other frame procedures require a connected frame, i.e., rider # NIL. This precondition is not checked explicitly.
ConnectTo is used internally.
Post
p = NIL
f.unit = 0
f.rider = NIL
p # NIL
f.unit = p.unit
f.rider # NIL & f.rider.Base() = p
f.dot = point - point MOD p.unit
PROCEDURE (f: Frame) SetOffset (gx, gy: INTEGER)
NEW, EXTENSIBLE
Sets the frame's origin, in global coordinates (i.e., relative to the port's upper-left corner), but in units instead of pixels. All local coordinates are relative to this origin. This method is only for internal use in the framework.
SetOffset is used internally.
Pre
f.rider # NIL 20
Post
f.gx = gx & f.gy = gy
PROCEDURE (f: Frame) SaveRect (l, t, r, b: INTEGER; OUT res: INTEGER)
NEW
Saves a rectangle (parallel to the coordinate axes) of width r - l and of height b - t in a background buffer, from where it can be restored later using RestoreRect. SaveRect must be balanced by RestoreRect(l, t, r, b, disposeBuffer).
Calls to SaveRect may not be nested, and they may not occur during restoration of a view (-> Views.View.Restore). The purpose of SaveRect/RestoreRect is to act as temporary buffering mechanism during mouse tracking (->Views.View.HandleCtrlMsg).
res = 0 means that the call was successful, otherwise RestoreRect must not be called.
Pre
(l <= r) & (t <= b) 20
PROCEDURE (f: Frame) RestoreRect (l, t, r, b: INTEGER; dispose: BOOLEAN)
NEW
After a successful call to SaveRect, the same rectangle, i.e., its pixelmap contents as it was upon saving, can be restored with RestoreRect. RestoreRect can be called several times in succession; the last time with dispose = disposeBuffer and all other times with dispose = keepBuffer.
Pre
(l <= r) & (t <= b) 20
PROCEDURE (f: Frame) DrawRect (l, t, r, b, s: INTEGER; col: Color)
NEW
Draws a rectangle (parallel to the coordinate axes) of width r - l and of height b - t. If s < 0, the rectangle is filled with color col. Otherwise, the rectangle is drawn as an outline of thickness s. The outline is drawn inside of the rectangle. If s = 0, a very thin outline (hairline) is used.
Pre
(l <= r) & (t <= b) 20
(s >= 0) OR (s = fill) 21
PROCEDURE (f: Frame) DrawOval (l, t, r, b, s: INTEGER; col: Color)
NEW
Draws an ellipse (parallel to the coordinate axes) of width r - l and of height b - t. If s < 0, the ellipse is filled with color col. Otherwise, the ellipse is drawn as an outline of thickness s. The outline is drawn inside of the rectangle. If s = 0, a very thin outline (hairline) is used.
Pre
(l <= r) & (t <= b) 20
(s >= 0) OR (s = fill) 21
PROCEDURE (f: Frame) DrawLine (x0, y0, x1, y1, s: INTEGER; col: Color)
NEW
Draws a line from the point (x0, y0) to the point (x1, y1) of thickness s in color col:
Figure 5. Line
If s = 0, a very thin outline (hairline) is used.
Pre
s >= 0 20
PROCEDURE (f: Frame) DrawPath (IN p: ARRAY OF Point; n, s: INTEGER; col: Color;
path: INTEGER)
NEW
Draws the path consisting of points p[0] .. p[n - 1] in color col. The nature of the path is given by parameter path. It can either be a polyline, a polygon, an open Bezier curve, or a closed Bezier curve. The polyline is the same that a sequence of DrawLine operations would generate. For a polygon, the n points define the mathematical region which will be outlined or filled. An open path with n points results in n - 1 path pieces, a closed path with n points results in n path pieces.
Pre
n >= 0 20
n <= LEN(p) 21
(s = fill) => (path = closedPoly) OR (path = closedBezier) 22
(s >= 0) OR (s = fill) 23
path IN {closedPoly, openPoly, closedBezier, openBezier} 25
path = openPoly
n >= 2 20
path = closedPoly
n >= 2 20
path = openBezier
n >= 4 20
n MOD 3 = 1 24
path = closedBezier
n >= 3 20
n MOD 3 = 0 24
PROCEDURE (f: Frame) MarkRect (l, t, r, b, s: INTEGER; mode: INTEGER; show: BOOLEAN)
NEW
Marks a rectangle (parallel to the coordinate axes) of width r - l and of height b - t. If s < 0, the rectangle is filled in some way, dependent on mode. Otherwise, the rectangle is drawn as an outline of thickness s. If s = 0, a very thin outline (hairline) is used. The outline is drawn inside of the rectangle.
The meaning of mode is implementation-dependent, but it must change the marked area in a visible way. show indicates whether the mark should be drawn or removed. Calling MarkRect with show and then directly afterwards with hide (otherwise with the same parameters) should re-establish exactly the state before the first call.
Pre
(l <= r) & (t <= b) 20
s >= 0 21
mode IN {invert, hilite, dim25, dim50, dim75} 22
PROCEDURE (f: Frame) Scroll (dx, dy: INTEGER)
NEW
Shifts the frame's area by vector (dx, dy). Shifting occurs completely within the frame's rectangle, i.e., pixels outside of it are neither written nor read. The part of the rectangle which becomes newly exposed should be considered as undefined.
The purpose of Scroll is to speed up scrolling and editing operations by reusing existing pixel data instead of making the application redraw everything.
However, under special circumstances, this procedure may not actually copy pixel data, but cause the application to restore part of the rectangle instead anyway.
Warning: this operation may only be used on interactive ports, in order to update the screen display after a user manipulation.
Figure 6. Effect of Scroll Operation
PROCEDURE (f: Frame) SetCursor (cursor: INTEGER)
NEW
Sets the cursor to the given value.
SetCursor is used in polling loops during mouse tracking.
Pre
cursor IN {arrowCursor..refCursor} 20
PROCEDURE (f: Frame) Input (OUT x, y: INTEGER; OUT modifiers: SET; OUT isDown: BOOLEAN)
NEW
Polls the current mouse location and tells whether the mouse button is currently pressed.
Input is used in polling loops during mouse tracking. In modifiers, the currently pressed modifier keys are returned, like Controllers.doubleClick, Controllers.extend, Controllers.modify, Controllers.popup, Controllers.pick, and possibly additional platform-specific modifiers. For the mapping of platform specific keys see platform specific modifiers.
PROCEDURE (f: Frame) DrawSpace (x, y, w: INTEGER; col: Color; font: Fonts.Font)
NEW;
Draws a space character of width w.
The horizontal position is specified by x, the vertical baseline by y, the color by col and the font attributes by font. This method allows for drawing spaces decorated with underline or strike out.
Pre
font # NIL
PROCEDURE (f: Frame) DrawString (x, y: INTEGER; col: Color; IN s: ARRAY OF CHAR;
font: Fonts.Font)
NEW
Draws string s in color col and font font with the base line at y.
Pre
font # NIL 20
PROCEDURE (f: Frame) DrawSString (x, y: INTEGER; col: Color; IN s: ARRAY OF SHORTCHAR;
font: Fonts.Font)
NEW
Draws short string s in color col and font font with the base line at y.
Pre
font # NIL 20
PROCEDURE (f: Frame) CharIndex (x, pos: INTEGER; IN s: ARRAY OF CHAR;
font: Fonts.Font): INTEGER
NEW
Given string s at position x, CharIndex determines the index of the character which lies at position pos. Result = 0 means pos is at or left of the first character in s, result = n - 1, where n is the number of characters in string s, means pos is right of the last character in s.
Pre
font # NIL 20
PROCEDURE (f: Frame) SCharIndex (x, pos: INTEGER; IN s: ARRAY OF SHORTCHAR;
font: Fonts.Font): INTEGER
Given short string s at position x, CharIndex determines the index of the character which lies at position pos. Result = 0 means pos is at or left of the first character in s, result = n - 1, where n is the number of characters in string s, means pos is right of the last character in s.
Pre
font # NIL 20
PROCEDURE (f: Frame) CharPos (x, index: INTEGER; IN s: ARRAY OF CHAR;
font: Fonts.Font): INTEGER
Given string s at position x, CharPos determines the position of character index in s. The position of the left margin of the character is returned.
Pre
font # NIL 20
PROCEDURE (f: Frame) SCharPos (x, index: INTEGER; IN s: ARRAY OF SHORTCHAR;
font: Fonts.Font): INTEGER
Given short string s at position x, CharPos determines the position of character index in s. The position of the left margin of the character is returned.
Pre
font # NIL 20
VAR background: Color background >= 0
This variable denotes the color which is used for the background of a window.
VAR dialogBackground: Color dialogBackground >= 0
This variable denotes the color which is used for the background of a dialog.
PROCEDURE IsPrinterPort (p: Port): BOOLEAN
Determines whether a port represents a printer.
PROCEDURE RGBColor (red, green, blue: INTEGER): Color
Constructs a Color out of the red, green, and blue components.
Pre
0 <= red < 256 20
0 <= green < 256 21
0 <= blue < 256 22
Post
result = blue * 65536 + green * 256 + red
| System/Docu/Ports.odc |
Printers
This module has a private interface, it is only used internally.
| System/Docu/Printers.odc |
Printing
DEFINITION Printing;
IMPORT Fonts, Views, Dates;
TYPE
Par = POINTER TO LIMITED RECORD
page: PageInfo;
header, footer: Banner;
copies-: INTEGER
END;
Banner = RECORD
font: Fonts.Font;
gap: INTEGER;
left, right: ARRAY 128 OF CHAR
END;
PageInfo = RECORD
first, from, to: INTEGER;
alternate: BOOLEAN;
title: Views.Title
END;
ExpandHook = PROCEDURE (IN s: ARRAY OF CHAR; printView: Views.View;
IN date: Dates.Date; IN time: Dates.Time; IN title: Views.Title; pno: INTEGER; printing: BOOLEAN;
OUT sx: ARRAY OF CHAR);
VAR par: Par;
expandHook-: ExpandHook;
PROCEDURE NewPar (IN page: PageInfo; IN header, footer: Banner; copies: INTEGER): Par;
PROCEDURE NewDefaultPar (title: Views.Title): Par;
PROCEDURE PrintView (view: Views.View; p: Par);
PROCEDURE Current (): INTEGER;
PROCEDURE PrintBanner (f: Views.Frame; IN p: PageInfo; IN b: Banner; IN date: Dates.Date;
IN time: Dates.Time; x0, x1, y: INTEGER);
PROCEDURE SetExpandHook (p: ExpandHook);
END Printing.
This module allows to print a document, including headers and footers.
TYPE Par
Specification of the print job. Is passed as parameter to the function PrintView. During printing, it can be accessed via the global variable par. During printing, its state can be changed.
page: PageInfo
Information about the area of the pages to be printed; about page numbers; and whether printing of left and right pages is treated differently.
header, footer: Banner
Header/footer line to be printed on every page.
copies-: INTEGER copies >= 1
Number of copies to be printed.
TYPE Banner
Describes a header or a footer line.
font: Fonts.Font
Font of the header/footer line. Only one font is possible.
gap: INTEGER
Distance to next base line. Currently ignored for footers.
left, right: ARRAY 128 OF CHAR
Text of the header/footer line. In this string the following abbreviations may occur:
&p - replaced by current page number as arabic numeral
&r - replaced by current page number as roman numeral
&R - replaced by current page number as capital roman numeral
&a - replaced by current page number as alphanumeric character
&A - replaced by current page number as capital alphanumeric character
&d - replaced by printing date
&t - replaced by printing time
&&- replaced by & character
&; - specifies split point
&f - title
The text is centered, except if a split point occurs. A split point acts like a spring: it "presses" the items to the left and right apart. For example, "&;&p" presses an arabic page number to the right page border.
TYPE PageInfo
Information about the pages to be printed.
first: INTEGER
Page number of the first page to be printed. Page number of the currently printed page is Current() + first. May be changed during printing.
from, to: INTEGER (from >= 0) & (to >= from)
Range of pages to be printed. Specification is not in page numbers, but in absolute number. The first page of the document is number 0. There will be to - from + 1 pages printed.
alternate: BOOLEAN
Determines whether left and right pages are treated differntly. If ~alternate, then every page will be printed with the banners specified for right pages. Otherwise, pages with odd page number use the right banners, while pages with even page numbers use the left banners. The page number of the current page is first + Current().
title: Views.Title
Title of the document.
TYPE ExpandHook
The procedure type for the custom tag expansions hook. A custom tag expander maps an input string s to an expanded output string sx where custom specific tags are replaced by an actual value with appropriate formatting.
VAR par: Par
This variable is set during printing of the document and may be changed by a printed view. However, this variable should not be used to determine whether the document is printed or displayed (-> Views.IsPrinterFrame).
VAR expandHook: ExpandHook;
The most recently installed custom tag expander or NIL if none has been installed.
PROCEDURE NewPar (IN page: PageInfo; IN header, footer: Banner; copies: INTEGER): Par
Allocates and initializes a new printing parameters object.
Post
result.page = page
result.header = header
result.footer = footer
result.copies = copies
header.font # NIL => result.header.font = header.font
header.font = NIL => result.header.font = Fonts.dir.Default()
footer.font # NIL => result.footer.font = footer.font
footer.font = NIL => result.footer.font = Fonts.dir.Default()
PROCEDURE NewDefaultPar (title: Views.Title): Par
Allocates and initializes a new printing parameters object.
Post
result.page.first = 1
result.page.from = 0
result.page.to = 9999
result.page.alternate = FALSE
result.copies = 1
result.header.gap = 0
result.header.left = ""
result.header.right = ""
result.header.font = Fonts.dir.Default()
result.footer.gap = 0
result.footer.left = ""
result.footer.right = ""
result.footer.font = Fonts.dir.Default()
PROCEDURE Current (): INTEGER
Returns the page number of the page currently being printed.
Post
result >= 0
PROCEDURE PrintView (view: Views.View; par: Par)
Prints view on the (current) printer, provided that a printer is available.
For the parameter par, NIL can be passed. In this case, a default par parameter is generated. It is initialized
with
copies := 1;
page.first := 1, page.from := 0, page.to := 9999, page.alternate := FALSE; page.title := title;
header.gap := 0; header.left := ""; header.right := "";
header.font := Fonts.dir.Default();
footer.gap := 0; footer.left := ""; footer.right := "";
footer.font := Fonts.dir.Default();
otherwise
par.title is overwritten by title.
Actually, not the view view is printed, but a copy of it. PrintView makes a shallow copy of the view that is being printed, in order to avoid the original view to be changed by pagination, scrolling, or similar modifications that may be performed during printing.
Pre
view # NIL 20
par # NIL =>
par.page.first >= 0 23
par.page.from >= 0 24
par.page.to >= par.page.from 25
par.copies > 0 25
PROCEDURE PrintBanner (f: Views.Frame; IN p: PageInfo; IN b: Banner;
IN date: Dates.Date; IN time: Dates.Time; x0, x1, y: INTEGER)
Used internally.
PROCEDURE SetExpandHook* (p: ExpandHook);
Sets procedure p as custom tag expander. Custom tags are tags that modify or extend the set of standard tags as defined for Banner.left/right. The result of the custom tag expansion is the input for standard tag expansion.
Post
Printing.expandHook = p
| System/Docu/Printing.odc |
Properties
DEFINITION Properties;
IMPORT Fonts, Ports, Views, Controllers, Dialog;
CONST
color = 0; typeface = 1; size = 2; style = 3; weight = 4;
width = 0; height = 1;
maxVerbs = 16;
noMark = FALSE; mark = TRUE;
hide = FALSE; show = TRUE;
TYPE
Property = POINTER TO ABSTRACT RECORD
next-: Property;
known: SET;
readOnly: SET;
valid: SET;
(p: Property) IntersectWith (q: Property; OUT equal: BOOLEAN)
END;
StdProp = POINTER TO RECORD (Property)
color: Dialog.Color;
typeface: Fonts.Typeface;
size: INTEGER;
style: RECORD
val, mask: SET
END;
weight: INTEGER
END;
SizeProp = POINTER TO RECORD (Property)
width, height: INTEGER
END;
Message = Views.PropMessage;
PollMsg = RECORD (Message)
prop: Property
END;
SetMsg = RECORD (Message)
old, prop: Property
END;
Preference = ABSTRACT RECORD (Message) END;
ResizePref = RECORD (Preference)
fixed: BOOLEAN;
horFitToPage: BOOLEAN;
verFitToPage: BOOLEAN;
horFitToWin: BOOLEAN;
verFitToWin: BOOLEAN;
END;
SizePref = RECORD (Preference)
w, h: INTEGER;
fixedH, fixedW: BOOLEAN
END;
BoundsPref = RECORD (Preference)
w, h: INTEGER
END;
FocusPref = RECORD (Preference)
atLocation: BOOLEAN;
x, y: INTEGER;
hotFocus: BOOLEAN;
setFocus: BOOLEAN
END;
ControlPref = RECORD (Preference)
char: CHAR;
focus: Views.View;
getFocus: BOOLEAN;
accepts: BOOLEAN
END;
PollVerbMsg = RECORD (Message)
verb: INTEGER;
label: ARRAY 64 OF CHAR;
disabled, checked: BOOLEAN
END;
DoVerbMsg = RECORD (Message)
verb: INTEGER;
frame: Views.Frame
END;
CollectMsg = RECORD (Controllers.Message)
poll: PollMsg
END;
EmitMsg = RECORD (Controllers.RequestMessage)
set: SetMsg
END;
PollPickMsg = RECORD (Controllers.TransferMessage)
mark: BOOLEAN;
show: BOOLEAN;
dest: Views.Frame
END;
PickMsg = RECORD (Controllers.TransferMessage)
prop: Property
END;
VAR era-: INTEGER;
PROCEDURE IncEra;
PROCEDURE CollectProp (OUT prop: Property);
PROCEDURE CollectStdProp (OUT prop: StdProp);
PROCEDURE EmitProp (old, prop: Property);
PROCEDURE PollPick (x, y: INTEGER; source: Views.Frame;
sourceX, sourceY: INTEGER; mark, show: BOOLEAN;
OUT dest: Views.Frame; OUT destX, destY: INTEGER);
PROCEDURE Pick (x, y: INTEGER; source: Views.Frame; sourceX, sourceY: INTEGER;
OUT prop: Property);
PROCEDURE Insert (VAR list: Property; x: Property);
PROCEDURE CopyOf (p: Property): Property;
PROCEDURE CopyOfList (p: Property): Property;
PROCEDURE Merge (VAR base, override: Property);
PROCEDURE Intersect (VAR list: Property; x: Property; OUT equal: BOOLEAN);
PROCEDURE IntersectSelections (a, aMask, b, bMask: SET; OUT c, cMask: SET;
OUT equal: BOOLEAN);
PROCEDURE PreferredSize (v: Views.View; minW, maxW, minH, maxH,
defW, defH: INTEGER; VAR w, h: INTEGER);
PROCEDURE ProportionalConstraint (scaleW, scaleH: INTEGER;
fixedW, fixedH: BOOLEAN; VAR w, h: INTEGER);
PROCEDURE GridConstraint (gridX, gridY: INTEGER; VAR x, y: INTEGER);
PROCEDURE ThisType (view: Views.View; type: Stores.TypeName): Views.View;
END Properties.
Practically every view has some state, and for much of that state it is desirable that the user can change it interactively. However, in an extensible system this means that for every new view at least one, or more likely several, new dialog boxes would have to be created, and would have to be learned by the user.
It is more economical for both programmer and user to have a generic and extensible way to deal with such state. Properties are provided for exactly this purpose, to communicate internal state to the user, and to communicate back any desired changes. They are the hooks for a general property editor.
Of course, some interactions are optimized for convenience, thus the most important editing operations are also accessible in a more direct way: via typing or direct manipulation with the mouse. Furthermore, combinations of often-used properties can still be handled by a custom-tailored dialog, instead of a less specific general property editor. However, except where there are standard messages already defined by lower levels of the BlackBox framework, properties are the preferred way to implement such interactions.
Properties are communicated via property messages. A particularly light-weight version of a property message is called a Preference: preferences inquire about a view's current preference, e.g., what its preferred size is. Preferences are normally used for the internal communication of an embedded view with its container, rather than with the user. Preferences are static message records, and a receiver should never change its state upon reception of such a message. These restrictions make preferences efficient and side-effect free, and thus easy to use.
As with all message records in BlackBox, property messages may, but need not, be handled.
CONST color, typeface, size, style, weight
When the focus view returns a StdProp property in the CollectMsg, the StdProp.known, the StdProp.readOnly, and the StdProp.valid sets may contain one or more of the above elements. If one of these elements is set in StdProp.known, the focus view knows about the corresponding property. If one of these elements is set in both StdProp.valid and StdProp.known, the focus view currently has an opinion about what the current value of this property is. These current values are returned in the other fields of StdProp. If one of these elements is set in both StdProp.valid and StdProp.readOnly, the focus view currently doesn't allow this property to be changed.
CONST width, height
When the focus view returns a SizeProp property in the CollectMsg, the SizeProp.known and the SizeProp.valid sets may contain one or more of these elements. If one of these elements is set in both SizeProp.valid and SizeProp.known, the SizeProp property contains the focus view's current width and height in the width and height fields.
CONST noMark, mark
These values may be passed to the mark parameter of procedure PollPick. They denote whether the target feedback during drag & pick should be drawn or not.
CONST maxVerbs
Maximum number of verbs in a context menu.
CONST hide, show
These values may be passed to the show parameter of procedure PollPick. They denote whether the target feedback during drag & pick should be shown or hidden. This parameter is only relevant if mark holds.
TYPE Property
ABSTRACT
Properties are a general mechanism to get and set attributes of a view from its environment. A view may know about attributes such as font, color, size, and arbitrary other attributes. Properties may be extended only once.
next-: Property
Properties are connected in a list, implemented by the next field.
known: SET
Each property record may describe up to 32 different attributes. These attributes are numbered from 0..31. The known field tells which of these attributes are known to the view which responds to the CollectMsg.
readOnly: SET readOnly - known = {}
Each known attribute may currently be read-only, i.e., not modifiable. The readOnly field tells which of the attributes are currently read-only.
The readOnly set must be a subset of the known set, i.e., no attribute can be read-only and unknown simultaneously.
valid: SET valid - known = {}
Each known attribute may currently be undefined. This happens particularly when properties of multiple objects are collected together and some attributes differ from object to object (property with mixed values).
The valid field tells which of the attributes are currently defined. Their current values should be represented by further fields of the specific property record, e.g., field color in StdProp corresponds to element 0 in the valid set, field typeface to the element 1, etc.
The valid set must be a subset of the known set; i.e., no attribute can be valid and unknown simultaneously.
Additionally valid is used to specify which attributes should change if a property record is sent to an object.
PROCEDURE (p: Property) IntersectWith (q: Property; OUT equal: BOOLEAN)
A property record p must be able to compare itself with another property record q. If all attributes in p have the same values as in q, equal should be set to TRUE. Otherwise p should be set to the intersection of p and q and equal should be set to FALSE. The intersection is built by excluding all differing attributes from the valid set. It can be assumed that the type of p is exactly the same as the type of q.
IntersectWith must maintain the Property invariant that valid is a subset of known; otherwise it is not interested in known.
As an example, see the implementation of StdProp.IntersectWith below.
TYPE StdProp (Property)
These are the standard attributes known to any BlackBox implementation. They encompass font attributes as well as color.
color: Dialog.Color valid iff constant color IN StdProp.valid
Current color.
typeface: Fonts.Typeface valid iff constant typeface IN StdProp.valid
Current typeface.
size: INTEGER valid iff constant size IN StdProp.valid
Current size. It usually, but not necessarily, refers to a font's size.
style: RECORD valid iff constant style IN StdProp.valid
style IN StdProp.valid => StdProp.style.mask # {}
StdProp.style.val - StdProp.style.mask = {} (* val is subset of mask *)
Current style. Field style.mask denotes which style flags are valid, style.val denotes which of the valid flags are currently set.
weight: INTEGER valid iff constant weight IN StdProp.valid
Current font weight.
PROCEDURE (p: StdProp) IntersectWith* (q: Property; OUT equal: BOOLEAN);
VAR valid: SET; c, m: SET; eq: BOOLEAN;
BEGIN
WITH q: StdProp DO
equal := TRUE;
valid := p.valid * q.valid;
IF p.color.val # q.color.val THEN EXCL(valid, color) END;
IF p.typeface # q.typeface THEN EXCL(valid, typeface) END;
IF p.size # q.size THEN EXCL(valid, size) END;
IntersectSelections(p.style.val, p.style.mask, q.style.val, q.style.mask, c, m, eq);
IF m = {} THEN
EXCL(valid, style)
ELSIF (style IN valid) & ~eq THEN
p.style.mask := m; equal := FALSE
END;
IF p.weight # q.weight THEN EXCL(valid, weight) END;
IF p.valid # valid THEN p.valid := valid; equal := FALSE END
END
END IntersectWith;
TYPE SizeProp (Property)
This property record represents the size of a rectangular area, e.g., of a view.
width: INTEGER valid iff constant width IN SizeProp.valid
The current width in universal units.
height: INTEGER valid iff constant height IN SizeProp.valid
The current height in universal units.
TYPE Message
ABSTRACT
Base type of all property messages.
TYPE PollMsg (Message)
This message is sent to get the receiving view's properties. The receiver should return the properties of all its contents, not only the selection.
prop: Property
The list of returned properties which may be modified. No property exists twice in such a list.
TYPE SetMsg (Message)
This message is sent to set the receiving view's properties. The properties' known and readOnly fields are not used and thus not defined in this case. The receiver should set the properties of all its contents, not only the selection.
old: Property
This list is provided for modifications of the kind "replace old by new", e.g., "replace typeface Helvetica by Times". Can be NIL.
prop: Property
The list of properties to be changed. No property may exist twice in the list.
TYPE Preference (Message)
ABSTRACT
Preferences are special property messages. They are normally used for the communication between an embedded view and its container. They should operate as functions, i.e. the receiver should return values, but never change its state.
TYPE ResizePref (Preference)
The receiver of this message can indicate that it doesn't wish to be resized, by setting fixed to TRUE. A fixed size view doesn't show resize handled when it is selected as a singleton.
For the root view in a document or window the fields horFitToPage, verFitToPage, horFitToWin, and verFitToWin can be used to enforce automatic adaptation of the view size to the actual window or page size. For embedded views, these four flags have no effect, in contrast to fixed.
fixed: BOOLEAN fixed => ~horFitToPage & ~verFitToPage & ~horFitToWin & ~verFitToWin
(view => caller, preset to FALSE)
Can be set to indicate that the receiver's size should remain the same.
horFitToPage: BOOLEAN horFitToPage => ~horFitToWin
(view => caller, preset to FALSE)
Can be set to indicate that the receiver's width should be adapted to the actual page width.
verFitToPage: BOOLEAN verFitToPage => ~verFitToWin
(view => caller, preset to FALSE)
Can be set to indicate that the receiver's height should be adapted to the actual page height.
horFitToWin: BOOLEAN horFitToWin => ~horFitToPage
(view => caller, preset to FALSE)
Can be set to indicate that the receiver's width should be adapted to the actual window width.
verFitToWin: BOOLEAN verFitToWin => ~verFitToPage
(view => caller, preset to FALSE)
Can be set to indicate that the receiver's height should be adapted to the actual window height.
TYPE SizePref (Preference)
The sender of this message proposes a size for the receiving view; the size may be Views.undefined. The receiving view may override the proposal, e.g., in order to establish constraints between its width and height. The procedures ProportionalConstraint and GridConstraint are useful standard implementations of constraints.
Procedure PreferredSize implements the caller's side of the protocol, i.e., fills out, sends, and interprets a SizeMsg.
w, h: INTEGER (w = Views.undefined) = (h = Views.undefined)
(view => caller, preset to Views.undefined if view is new or to caller's preference otherwise)
Desired width and height. Either both values are preset to Views.undefined, or none of them.
fixedH, fixedW: BOOLEAN
(caller => view)
These values are set up when the message is sent, to indicate whether height or width of the view should remain fixed. This can be used e.g. to keep a view's proportions, by adapting the width if the height is fixed, and vice versa. (See procedure ProportionalConstraint)
TYPE BoundsPref (Preference)
The receiving view should compute its bounding box, or, if this is too expensive to do, it should return an approximation of or a suggested substitute for the true bounding box.
Views that can display part of their contents, e.g., by supporting scrolling in one or both directions, will handle BoundsPref very differently from SizePref. While SizePref relates to constraints and preferences of the size of the current view onto the model, BoundsPref should compute the size the view would need to take to just fully display all of the model. For very large or complex models (such as uncast text running over many pages) this can be a very costly operation and therefore it is anticipated that views may return an approximation of a bounding size, or an alternate suggestion, such as a size that is "quite big" but no bigger than the model.
w, h: INTEGER
(view => caller, preset to Views.undefined)
Preferred width and height.
TYPE FocusPref (Preference)
A view can indicate if it doesn't want to become focus permanently, e.g., a button. It may even decide so depending on where the mouse has been clicked.
atLocation: BOOLEAN
(caller => view)
This flag is set if the receiver would become focus through a mouse click.
x, y: INTEGER [units]
(caller => view, valid iff atLocation)
Position of mouse click relative to the receiving view's top-left corner.
hotFocus: BOOLEAN
(view => caller, preset to FALSE)
The receiver can set this flag to indicate that the view should release its focus immediately after the mouse is released. Command buttons are typical hot foci.
setFocus: BOOLEAN
(view => caller, preset to FALSE)
The receiver can set this flag to indicate that the view should become focus when the mouse is clicked inside (otherwise the view may become selected immediately, e.g., to be dragged & dropped). setFocus should be set for all true editors, such that context-sensitive menu commands can be attached to the view.
TYPE ControlPref (Preference)
A view can indicate its preferred behavior if it is embedded in a dialog (i.e., a container in mask mode, -> Containers) and a key is pressed.
The ControlPref message is sent first to the actual focus view and then to all other views in the container until one of the views sets either the getFocus or the accepts bit or both. If none of the views respond to the message, the character is forwarded to the focus view.
char: CHAR
(caller => view)
The key which was pressed.
focus: Views.View
(caller => view)
The actual focus view.
getFocus: BOOLEAN
(view => caller, valid if (view # focus), preset to (char = tab) )
Indicates that the view wants to become the focus view.
accepts: BOOLEAN
(view => caller, preset to ((view = focus) & (char # tab)) )
This flag should be set if the receiver would accept and interpret char to invoke some action.
The character is sent to the view in a separate Edit message.
TYPE PollVerbMsg (Message)
Message used to ask a view whether it supports custom verbs. A verb is some kind of action that the user can apply to a view and that is shown in a popup-menu.
verb: INTEGER verb >= 0 (IN)
(caller => view)
The index of the verb to be polled.
label: ARRAY 64 OF CHAR
(view => caller, preset to "")
Displayed label of the verb.
disabled: BOOLEAN
(view => caller, preset to FALSE)
Indicates whether verb is enabled or disabled.
checked: BOOLEAN
(view => caller, preset to FALSE)
Indicates whether verb is unchecked or checked.
TYPE DoVerbMsg (Message)
Execute a particular custom verb.
verb: INTEGER
(caller => view)
The verb to be executed.
frame: Views.Frame
(caller => verb)
The frame of the view where the verb was invoked by the user.
TYPE CollectMsg (Controllers.Message)
This controller message is sent along the focus path, to poll the properties of the innermost focus view's selection or caret, i.e., unlike PollMsg it does not return the properties of the whole contents.
poll: PollMsg
TYPE EmitMsg (Controllers.RequestMessage)
This controller message is sent along the focus path, to set the properties of the innermost focus view's selection or caret, i.e., unlike SetMsg it does not set the properties of the whole contents.
set: SetMsg
TYPE PollPickMsg (Controllers.TransferMessage)
While an item is being dragged around for the purpose of picking properties (BlackBox's Drag & Pick mechanism), PollPickMsgs are sent to enable feedback about the pick target. Note that this is similar to the role of Controllers.PollDropMsg for Drag & Drop.
mark: BOOLEAN
A container which supports pick feedback should show (hide) its feedback mark when mark is set (cleared). You don't need to deal with the view's border mark (the rectangular outline of the view which is drawn while you are dragging over a view), this is handled completely by BlackBox itself through its container abstraction.
show: BOOLEAN
Indicates whether the mark should be drawn or removed.
dest: Views.Frame
The receiver should set dest to its own frame, if it would accept a pick.
TYPE PickMsg (Controllers.TransferMessage)
Extension
This message is used if properties are to be picked from the cursor's location. Note that this is similar to the Controllers.DropMsg for Drag & Drop.
prop: Property
The receiver should set prop to the properties at the cursor's location.
VAR era-: INTEGER propEra >= 0
This variable is used by BlackBox to determine whether the focus view's properties may have changed.
PROCEDURE IncEra
Increments era. This procedure should be called whenever one or several properties of a view have changed. As a response, the system will eventually send a PollMsg to get the new properties, e.g., to reflect them in the menus or in a property editor.
Post
era = era' + 1
PROCEDURE CollectProp (OUT prop: Property)
Poll focus view's properties.
PROCEDURE CollectStdProp (OUT prop: StdProp)
Poll focus view's standard properties.
PROCEDURE EmitProp (old, prop: Property)
Set focus view's properties to prop. If old is not NIL, only the properties corresponding to old are replaced by their prop counterparts.
PROCEDURE PollPick (x, y: INTEGER; source: Views.Frame;
sourceX, sourceY: INTEGER; mark, show: BOOLEAN;
OUT dest: Views.Frame; OUT destX, destY: INTEGER)
Control pick feedback at location (x, y) relative to the coordinates of source, by sending a PollPickMsg msg. Presets msg.dest to NIL, msg.mark to mark, msg.show to show, and calls Controllers.Transfer(x, y, source, sourceX, sourceY, msg). Returns msg.dest, msg.destX, and msg.destY in dest, destX, and destY, respectively.
Pre
source # NIL 20
PROCEDURE Pick (x, y: INTEGER; source: Views.Frame;
sourceX, sourceY: INTEGER; OUT prop: Property)
Pick properties at location (x, y) relative to the coordinates of source, by sending a PickMsg msg. Presets msg.prop to NIL and calls Controllers.Transfer(x, y, source, sourceX, sourceY, msg). Returns msg.prop in prop.
PROCEDURE Insert (VAR list: Property; x: Property)
Insert new property record x in list list. A property whose type is already in the list replaces the property in the list. The dynamic type of x must be a direct extension of type Property.
Pre
x # NIL 20
x.next = NIL 21
x # list 22
x.valid - x.known = {} 23
list # NIL
list.valid - list.known = {} 24
extension-level(list) = 1 25
extension-level(x) = 1 26
PROCEDURE CopyOf (p: Property): Property
Returns a copy of the property p (not of the entire list!). The dynamic types of every property inp must be a direct extension of type Property.
Pre
extension-level(p) = 1 20
PROCEDURE CopyOfList (p: Property): Property
Returns a copy of the property list p. The dynamic types of every property inp must be a direct extension of type Property.
Pre
all x in {p, p.next, p.next.next, ...}: extension-level(x) = 1 20
PROCEDURE Merge (VAR base, override: Property)
Merge two property lists base and override. If the type of a property is in both lists, the attributes of the property in override will be selected for the merged list. The merged list is returned in base.
PROCEDURE Intersect (VAR list: Property; x: Property; OUT same: BOOLEAN)
It reduces the properties in list by all these properties which are not in x, or which have different values in x. Furthermore, it determines whether both lists are the same.
PROCEDURE IntersectSelections (a, aMask, b, bMask: SET; OUT c, cMask: SET;
OUT equal: BOOLEAN)
Support procedure to implement the IntersectWith procedure of properties containing a set. This procedure is equivalent to the following code:
cMask := aMask * bMask - (a / b);
c := a * cMask;
equal := (aMask = bMask) & (bMask = cMask)
PROCEDURE PreferredSize (v: Views.View; minW, maxW, minH, maxH,
defW, defH: INTEGER; VAR w, h: INTEGER)
Sets up a SizePref and uses it to ask view v for its sizing preferences.
[minW, maxW] and [minH, maxH] are the legal ranges of width and height, respectively, that are acceptable to the caller. (defW, defH) is the caller-specified default size, i.e., the size that the caller prefers in the absence of any preferences of v; specifying (Views.undefined, Views.undefined) means "no default". (w, h) can be preset by the caller and will be used to preset the SizePref; normally the caller uses this to pass the current size of a view that is to be resized.
However, if (w < Views.undefined) or (w > maxW), then defW will be used instead of w. Likewise, if (h < Views.undefined) or (h > maxH), then defH will be used instead of h.
If v does not interpret a SizePref or returns w = Views.undefined, then defW overrides the preference of v. Likewise, if the SizePref returns h = Views.undefined, then defH overrides the preference of v.
Finally, (w, h) will be clipped to ([minW, maxW], [minH, maxH]) before returning to the caller. Therefore, if v has no (or no valid) preferences and the caller-specified default (or preset) value is Views.undefined, then the minimum values will be returned.
Pre
Views.undefined < minW 20
minW < maxW 21
Views.undefined < minH 23
minH < maxH 24
Views.undefined <= defW 26
Views.undefiend <= defH 28
PROCEDURE ProportionalConstraint (scaleW, scaleH: INTEGER;
fixedW, fixedH: BOOLEAN; VAR w, h: INTEGER)
Supports proportional resizing of rectangular shapes such as views. (scaleW, scaleH) is the size of a rectangle of the required proportions, e.g., (2,3) represents all rectangles having a ratio width to height of 2:3. (w, h) is the proposed size and ProportionalConstraint modifies this pair to satisfy the proportionality constraint. Normally, ProportionalConstraint performs its function by changing both, w and h, such that the resulting rectangle satisfies the constraint and that the new rectangle's area is as close to the old rectangle's area as possible. By setting fixedW, the constraint is satisfied by only changing h. Likewise, setting fixedH asks for at most changing w. When both, fixedW and fixedH, are set, then this is ignored and again the area-preserving heuristics is used.
Pre
w > Views.undefined 20
h > Views.undefined 21
scaleW > Views.undefined 22
scaleH > Views.undefined 23
~fixedW OR ~fixedH 24
PROCEDURE GridConstraint (gridX, gridY: INTEGER; VAR x, y: INTEGER)
Supports forcing the coordinates of a point, such as one of the corners of a view, to the nearest point of a grid. (gridX, gridY) specifies the resolution of the grid in x and y direction, e.g., (5,3) specifies a grid with valid coordinates being multiples of 5 in the x and multiples of 3 in the y direction.
Pre
gridX > Views.undefined 20
gridY > Views.undefined 21
| System/Docu/Properties.odc |
Sequencers
This module has a private interface, it is only used internally.
| System/Docu/Sequencers.odc |
Services
DEFINITION Services;
CONST
immediately = -1; now = 0;
resolution = 1000;
TYPE
Action = POINTER TO ABSTRACT RECORD
(a: Action) Do-, NEW, ABSTRACT
END;
InsistentAction = POINTER TO ABSTRACT RECORD (Action) END;
SafeAction = ABSTRACT RECORD
trapped-: BOOLEAN;
(VAR a: SafeAction) Do, NEW, ABSTRACT
END;
SafeRecAction = ABSTRACT RECORD (SafeAction)
(VAR a: SafeRecAction) Do;
(VAR a: SafeRecAction) DoRec (VAR rec: ANYREC), NEW, ABSTRACT
END;
VAR
itemsInTheQueue-: INTEGER;
PROCEDURE DoLater (a: Action; notBefore: LONGINT);
PROCEDURE RemoveAction (a: Action);
PROCEDURE Ticks (): LONGINT;
PROCEDURE GetTypeName (IN rec: ANYREC; OUT type: ARRAY OF CHAR);
PROCEDURE SameType (IN ra, rb: ANYREC): BOOLEAN;
PROCEDURE IsExtensionOf (IN ra, rb: ANYREC): BOOLEAN;
PROCEDURE Is (IN rec: ANYREC; IN type: ARRAY OF CHAR): BOOLEAN;
PROCEDURE Extends (IN type, base: ARRAY OF CHAR): BOOLEAN;
PROCEDURE Level (IN type: ARRAY OF CHAR): INTEGER;
PROCEDURE TypeLevel (IN rec: ANYREC): INTEGER;
PROCEDURE AdrOf (IN rec: ANYREC): INTEGER;
PROCEDURE Collect;
PROCEDURE Try (VAR a: SafeAction);
PROCEDURE TryRec (VAR a: SafeRecAction; VAR rec: ANYREC);
END Services.
Green color denote new features for version 2.0.
This module provides a variety of low-level services. Currently, only a timing service, a background processing service, and a reflection service is provided.
Actions are objects whose Do procedures are executed in a delayed fashion, when the system is idle. An action which re-installs itself whenever it is invoked operates as a non-preemptive background task.
The reflection service, unlike module Meta, only works on records, and it is also applicable to temporary variables on the stack (while Meta items typically denote long-lived variables).
Examples:
ObxActionsdocu
ObxCubesdocu
CONST immediately
This value can be passed to DoLater as notBefore parameter, if the action must be executed as part of the currently executing command.
CONST now
This value can be passed to DoLater as notBefore parameter, if the action should be executed as quickly as possible, after the currently executing command.
CONST resolution
Time resolution in ticks per second. The current time can be inquired by procedure Ticks.
VAR actionsInTheQueue- : INTEGER;
Current abount of actions in the queue.
TYPE Action
ABSTRACT
Actions are objects whose Do procedures are called in a deferred way, when the system is idle again.
PROCEDURE (a: Action) Do-
NEW, ABSTRACT
For a registered action a, a.Do is called eventually, depending how it has been registered (see DoLater).
TYPE InsistentAction (Action)
ABSTRACT
Extension of basic Action, wich has higher prioryty then the mouse tracking loop proceed.
This action is not recommended for calling any graphical commands (Views.Update etc), because this can lead to instability of the framework.
TYPE SafeAction
ABSTRACT
SafeActions are objects whose Do procedures can be called in a 'protected' fashion: if a trap occurs during the execution of Do, control returns to the caller (as opposed to terminating the whole running command).
trapped-: BOOLEAN
TRUE if the last execution of Do ended in a trap; FALSE if Do returned successfully.
Valid only after Try.
PROCEDURE (a: SafeAction) Do
NEW, ABSTRACT
Do is called in a protected fashion by Try.
TYPE SafeRecAction
ABSTRACT
SafeRecActions are like SafeActions, but their DoRec procedure has a reference record variable parameter.
trapped-: BOOLEAN
TRUE if the last execution of DoRec ended in a trap; FALSE if DoRec returned successfully.
Valid only after TryRec.
PROCEDURE (a: SafeRecAction) DoRec (VAR rec: ANYREC)
NEW, ABSTRACT
DoRec is called in a protected fashion by TryRec.
PROCEDURE DoLater (a: Action; notBefore: LONGINT)
Register an action. Its Do procedure will be executed once, later when time permits. a.Do is called eventually after Ticks() has reached notBefore, or if notBefore = now. If the action's Do procedure should be executed more than once, it may call DoLater to re-install itself. A particular action can only be registered once; additional attempts have no effect.
Pre
a # NIL 20
PROCEDURE RemoveAction (a: Action)
Remove a registered action. If action a is not registered or NIL, nothing happens.
PROCEDURE Ticks (): LONGINT
Returns the current time in clock ticks. These ticks have a resolution of resolution., i.e., resolution ticks per second.
PROCEDURE GetTypeName (IN rec: ANYREC; OUT type: ARRAY OF CHAR)
Returns the name of a record type, in the form "module.type". If a pointer is passed, its record type is returned. If the record is anonymous, the pointer's type name is returned, e.g., "FormViews.StdView".
PROCEDURE SameType (IN ra, rb: ANYREC): BOOLEAN
Determines whether two record variables have (exactly!) the same type.
PROCEDURE IsExtensionOf (IN ra, rb: ANYREC): BOOLEAN
Determines whether the record type of ra is the same or an extension of the type of rb.
PROCEDURE Is (IN rec: ANYREC; IN type: ARRAY OF CHAR): BOOLEAN
Determines whether the record type of rec is the same or an extension of the type given in type (e.g., as "FormViews.View"). If type type was not found, FALSE is returned.
Pre
type # "" 20
type has form "module.type" 21
PROCEDURE Extends (IN type, base: ARRAY OF CHAR): BOOLEAN
Determines whether the record type type is the same or an extension of the type base. If type type or base was not found, FALSE is returned.
Pre
type # "" & base # "" 20
type and base have form "module.type" 21
PROCEDURE Level (IN type: ARRAY OF CHAR): INTEGER
Determines the extension level of a record type type. A newly introduced type has level 0. If type type was not found, -1 is returned.
Pre
type # "" 20
type has form "module.type" 21
PROCEDURE TypeLevel (IN rec: ANYREC): INTEGER
Determines the extension level of a record variable rec's type. A newly introduced type has level 0.
PROCEDURE AdrOf (IN rec: ANYREC): INTEGER
Returns the address of a record variable.
PROCEDURE Collect
Forces a garbage collection.
PROCEDURE Try (VAR a: SafeAction)
Calls a.Do. Try returns even if a trap occurs during the execution of Do. a.trapped can be analyzed to check if Do trapped or returned successfully.
PROCEDURE TryRec (VAR a: SafeAction; VAR rec: ANYREC)
Calls a.DoRec(rec). TryRec returns even if a trap occurs during the execution of DoRec. a.trapped can be analyzed to check if Do trapped or returned successfully.
| System/Docu/Services.odc |
SMath
Module SMath is identical to Math except that it uses the 32-bit SHORTREAL type instead of the normal 64-bit REAL type.
| System/Docu/SMath.odc |
Stores
DEFINITION Stores;
IMPORT Files;
CONST
alienVersion = 1; alienComponent = 2;
inconsistentVersion = -1; inconsistentType = -2; moduleFileNotFound = -3;
invalidModuleFile = -4; inconsModuleVersion = -5; typeNotFound = -6;
TYPE
TypeName = ARRAY 64 OF CHAR;
TypePath = ARRAY 16 OF TypeName;
OpName = ARRAY 32 OF CHAR;
Domain = POINTER TO LIMITED RECORD
PROCEDURE (d: Domain) GetSequencer (): ANYPTR, NEW;
PROCEDURE (d: Domain) SetSequencer (sequencer: ANYPTR), NEW
END;
Operation = POINTER TO ABSTRACT RECORD
PROCEDURE (op: Operation) Do, NEW, ABSTRACT
END;
Store = POINTER TO ABSTRACT RECORD
PROCEDURE (s: Store) Domain (): Domain, NEW;
PROCEDURE (s: Store) CopyFrom- (source: Store), NEW, EMPTY;
PROCEDURE (s: Store) Internalize- (VAR rd: Reader), NEW, EMPTY;
PROCEDURE (s: Store) Externalize- (VAR wr: Writer), NEW, EMPTY;
PROCEDURE (s: Store) ExternalizeAs- (VAR s1: Store), NEW, EMPTY
END;
Reader = RECORD
rider-: Files.Reader;
cancelled-: BOOLEAN;
readAlien-: BOOLEAN;
(VAR rd: Reader) ConnectTo (f: Files.File), NEW;
(VAR rd: Reader) Pos (): INTEGER, NEW;
(VAR rd: Reader) SetPos (pos: INTEGER), NEW;
(VAR rd: Reader) ReadBool (OUT x: BOOLEAN), NEW;
(VAR rd: Reader) ReadSChar (OUT x: SHORTCHAR), NEW;
(VAR rd: Reader) ReadXChar (OUT x: CHAR), NEW;
(VAR rd: Reader) ReadChar (OUT x: CHAR), NEW;
(VAR rd: Reader) ReadByte (OUT x: BYTE), NEW;
(VAR rd: Reader) ReadSInt (OUT x: SHORTINT), NEW;
(VAR rd: Reader) ReadXInt (OUT x: INTEGER), NEW;
(VAR rd: Reader) ReadInt (OUT x: INTEGER), NEW;
(VAR rd: Reader) ReadLong (OUT x: LONGINT), NEW;
(VAR rd: Reader) ReadSReal (OUT x: SHORTREAL), NEW;
(VAR rd: Reader) ReadXReal (OUT x: REAL), NEW;
(VAR rd: Reader) ReadReal (OUT x: REAL), NEW;
(VAR rd: Reader) ReadSet (OUT x: SET), NEW;
(VAR rd: Reader) ReadSString (OUT x: ARRAY OF SHORTCHAR), NEW;
(VAR rd: Reader) ReadXString (OUT x: ARRAY OF CHAR), NEW;
(VAR rd: Reader) ReadString (OUT x: ARRAY OF CHAR), NEW;
(VAR rd: Reader) ReadStore (OUT x: Store), NEW;
(VAR rd: Reader) ReadVersion (min, max: INTEGER; OUT version: INTEGER), NEW;
(VAR rd: Reader) TurnIntoAlien (cause: INTEGER), NEW
END;
Writer = RECORD
rider-: Files.Writer;
writtenStore-: Store;
(VAR wr: Writer) ConnectTo (f: Files.File), NEW;
(VAR wr: Writer) Pos (): INTEGER, NEW;
(VAR wr: Writer) SetPos (pos: INTEGER), NEW;
(VAR wr: Writer) WriteBool (x: BOOLEAN), NEW;
(VAR wr: Writer) WriteSChar (x: SHORTCHAR), NEW;
(VAR wr: Writer) WriteXChar (x: CHAR), NEW;
(VAR wr: Writer) WriteChar (x: CHAR), NEW;
(VAR wr: Writer) WriteByte (x: BYTE), NEW;
(VAR wr: Writer) WriteSInt (x: SHORTINT), NEW;
(VAR wr: Writer) WriteXInt (x: INTEGER), NEW;
(VAR wr: Writer) WriteInt (x: INTEGER), NEW;
(VAR wr: Writer) WriteLong (x: LONGINT), NEW;
(VAR wr: Writer) WriteSReal (x: SHORTREAL), NEW;
(VAR wr: Writer) WriteXReal (x: REAL), NEW;
(VAR wr: Writer) WriteReal (x: REAL), NEW;
(VAR wr: Writer) WriteSet (x: SET), NEW;
(VAR wr: Writer) WriteSString (IN x: ARRAY OF SHORTCHAR), NEW;
(VAR wr: Writer) WriteXString (IN x: ARRAY OF CHAR), NEW;
(VAR wr: Writer) WriteString (IN x: ARRAY OF CHAR), NEW;
(VAR wr: Writer) WriteStore (x: Store), NEW;
(VAR wr: Writer) WriteVersion (version: INTEGER), NEW
END;
AlienComp = POINTER TO LIMITED RECORD
next-: AlienComp
END;
AlienPiece = POINTER TO LIMITED RECORD (AlienComp)
next-: AlienComp;
pos-, len-: INTEGER
END;
AlienPart = POINTER TO LIMITED RECORD (AlienComp)
next-: AlienComp;
store-: Store
END;
Alien = POINTER TO LIMITED RECORD (Store)
path-: TypePath;
cause-: INTEGER;
file-: Files.File;
comps-: AlienComp
END;
PROCEDURE InitDomain (s: Store);
PROCEDURE CopyOf (s: Store): Store;
PROCEDURE Join (s0, s1: Store);
PROCEDURE Joined (s0, s1: Store): BOOLEAN;
PROCEDURE Unattached (s: Store): BOOLEAN;
PROCEDURE ExternalizeProxy (s: Store): Store;
PROCEDURE Report (IN msg, p0, p1, p2: ARRAY OF CHAR);
END Stores.
Introduction
Module Stores defines a data type Store, which should be used as base type of all storable extensible objects. When storing an object of an extensible type, it is necessary to store not only its contents but also its particular type. The type is needed to create an object of the correct type when reading the data in again.
A variable of (an extension of) type Store is stored in a file. A store must implement the Internalize procedure which takes a Reader as parameter, and the Externalize procedure which takes a Writer as parameter. These procedures read/write the store's persistent state. (A store may also have temporary state which is not internalized/externalized.) Readers and writers are mappers on files. The types Views.View and TextModels.Model are examples of Store extensions.
Stores may form arbitrary graphs. The "boundary" of a graph is determined by its domain. This is an object that represents the whole collection of stores that can be externalized to a file, or be internalized from a file. The stores of a domain are externalized and internalized such that pointers among them are reconstructed correctly upon internalization. In particular, alias pointers are handled correctly: if several stores point to another element of the same domain, this element is read in only once, and all the pointers to it are rebuilt. Arbitrary graphs can be handled this way, e.g., cyclic data structures. Links to stores of other domains are prohibited.
A document consists of a hierarchy of views and models, both of which are stores. Possibly there may occur further stores in a document, such as text attribute objects or controller objects. All stores of a document share the same domain.
The stores of a domain may be manipulated indirectly via operation objects. An operation implements a method Do, which must be auto-inverse (i.e., executing it twice undoes its effect). This is the key to the undo/redo mechanism of the compound document architecture of BlackBox. However, in principle it could also be used by a transaction mechanism to implement transactions on persistent non-document data represented as stores.
The contents of a store is stored in a file. When reading the same file by another BlackBox configuration, it may occur that not all necessary modules are available in this configuration, i.e., the module which defines the store's type cannot be loaded. Yet reading such an "alien" store does not fail completely. Instead of the correct store type, an "alien" object is generated. Obviously such an alien cannot interpret the data it represents, and therefore cannot provide any special behavior. However, it may be copied and stored into another file, such that its contents on the new file are intact and consistent.
To define the set of stores that belong to a domain and to set up an actual domain, two procedures have to be provided by the framework. A first procedure is needed to collect stores in sets and to join store sets, and a second procedure is used to assign an actual domain object to a set of stores. In BlackBox these procedures are Join and InitDomain. They are discussed in more detail below.
Join
Procedure Join is used to join two store sets. This procedure has to be called whenever a link from a store in one set is established to a store in the other set. As arguments, representatives of the two store sets have to be passed. Join is symmetric. If the two stores which are passed as arguments already belong to the same set, Join has no effect. Figure 1 demonstrates the effect of a Join operation on two store sets X and Y.
Figure 1: Effect of a Join operation on two disjoint store sets X and Y.
Join calls have to be added at those places where newly created stores are connected, usually in a factory procedure. All those stores have to be joined with a store s which are written to disk in the Externalize method of store s.
Join calls are not necessary in the Internalize and CopyOf methods where usually also links between stores are established. Module Stores has sufficient information to join these stores itself.
The function Joined allows to test whether two given stores belong to the same store set, i.e., whether they have been joined or not. Joined is symmetric, reflexive and transitive.
InitDomain
In order to assign an actual domain object to a free store or a store set, the procedure InitDomain is called. As parameter a member of the set (or a single store) is passed. The actual domain object is created inside module Stores (Domain is limited) and then assigned to all stores in the set. After a domain has been assigned to a store graph this domain can be accessed with the Domain() method defined in the Store type. If InitDomain is called on a store which is already assigned to a domain object, then the procedure has no effect. The framework calls InitDomain in module Documents only whenever a new document is created. Usually, there is no need for BlackBox programmers to call InitDomain themselves, except when a deep copy of a document is created.
The arguments of Join may or may not be bound to a domain. If only one argument store is bound to a domain, then the effect of Join is that all stores in the other set are bound to the same domain object. If both arguments are bound to a domain then they have to be bound to the same one and Join has no effect, otherwise a precondition trap is raised.
The function Joined can be applied on stores independent of whether they are bound to a domain or not. If store s0 or s1 is bound to a domain, then Joined(s0, s1) is equivalent to s0.Domain() = s1.Domain().
The procedures Join and InitDomain specify the following pre and post conditions.
PROCEDURE Join (s0, s1: Store)
PRE 20 s0 # NIL
PRE 21 s1 # NIL
PRE 22 s0.Domain() = NIL OR s1.Domain() = NIL OR s0.Domain() = s1.Domain()
POST Joined(s0, s1)
PROCEDURE InitDomain (s: Store)
PRE 20 s # NIL
POST s.Domain() # NIL
If two stores have to be joined and precondition 22 is not met, then a deep copy of one of the two stores has to be generated using CopyOf.
Alias pointers and copying
The stores of a domain are externalized and internalized such that pointers among them are reconstructed correctly upon internalization. In particular, alias pointers are handled correctly: if several stores point to a particular element of the same domain, this element is read in only once, and all the pointers to it are rebuilt. Arbitrary graphs can be handled this way, including cyclic data structures.
Cloning of stores is provided by procedure CopyOf. This procedure creates a new object and then calls the CopyFrom method with the original object as parameter. This mechanism can conceptually be regarded as writing the store to a file and then reading it back as a clone.
Alias pointers are handled correctly. Whenever CopyOf is called, all copied stores are stored in a table which is associated with the store's set of joined stores. All recursive calls of CopyOf can access this information. After the top-level call of CopyOf terminates, the table with the copies is discarded.
However, there would be a problem with restoring alias pointers if during a call of CopyOf additional stores are added to the store set which contains the alias information. Therefore, Join(s0, s1) must not be called while a CopyOf operation is active either on s0 or on s1. If such a situation appears, then an implementation trap is raised. This can be avoided by joining the involved stores before copying the store graph.
Additional Remarks
Aliens
Aliens are handled in a special way regarding domains. Since aliens are immutable, they are never copied and can be inserted into any store graph. As a store can only reference one domain, this would violate the rule that a store in a document may not refer to stores that belong to another domain. Therefore, all aliens are assigned a special domain for aliens. Module Stores knows this rule and does not trap if an alien is externalized.
Operations and undo
Calls of Join or InitDomain on stores are not operations, thus these calls cannot be undone! If stores are joined or assigned to a domain as a side effect of an operation and if the operation is undone, then the asignments which were performed on involved stores are not undone. This may require that a deep copy is generated before an operation is applied to a store graph.
Shallow copies
Module Views offers a procedure CopyOf which allows to make shallow copies of views. A shallow copy of a view means that the copy refers to the same model like the original. As models and views are always joined, this implies that a view and its shallow copy are also joined.
Inspecting a store set
A store set cannot be inspected programmatically beyond what is offered by procedure Joined. However, the debugger allows to iterate over all stores in a store set. The stores which belong to the same store set are linked in a circular list. As soon as a domain object is associated to the set, the links are set to NIL and each store in the set refers to the new domain object. To iterate over a store set the debugger has to be called before the store set is bound. Then, the stores can be iterated with the store's next field. Listing 2 shows a simple procedure which generates an empty text view and then opens the debugger. Following the next fields of the view v, you see that the following seven stores are joined in one set: TextModels.Model, TextModels.Attributes, TextRulers.Ruler, TextRulers.Style, TextRulers.Attributes, TextViews.View and TextControllers.Controller.
MODULE Test;
IMPORT TextViews, TextModels;
PROCEDURE Do*;
VAR v: TextViews.View;
BEGIN
v := TextViews.dir.New(TextModels.dir.New());
HALT(0);
END Do;
END Test.
Listing 2: Inspecting the stores in a store set
Unattached
Function Unattached(s) tests whether a store s has been joined to other stores or was bound to a domain. If neither is the case Unattached returns TRUE. This function is only provided by the framework to decide whether a single store can be simply joined to another store graph or whether a deep copy must be generated; e.g., for a store that is kept in a cache and which may be joined to different store graphs.
For this special purpose the following code pattern is used. In this example, store s1 is copied if it is attached. This way an unnecessary copy call in the case that the store is unattached is prevented.
IF ~Stores.Joined(s0, s1) THEN
IF ~Stores.Unattached(s1) THEN s1 := Stores.CopyOf(s1) END;
Stores.Join(s0, s1)
END;
The pattern is not symmetric because it is often known statically that either s0 or s1 should never be copied. It is used for small stores which are generated once and which may be joined to different store sets.
Data types
Stores provides a pair of mapper types, which are used as parameters in a store's Internalize and Externalize procedures. These readers/writers use the following external (little endian) format:
BOOLEAN
1 byte (0 = FALSE, 1 = TRUE)
SHORTCHAR
1 byte in the Latin-1 character set (i.e., Unicode page 0; 00X..0FFX)
CHAR
2 byte in the Unicode character set (0000X..0FFFFX)
BYTE
1 byte (-128..127)
SHORTINT
2 bytes (-32768..32767)
INTEGER
4 bytes (-2147483648..2147483647)
LONGINT
8 bytes (-9223372036854775808..9223372036854775807)
SHORTREAL
4 bytes IEEE format
REAL
8 bytes IEEE format
SET
4 bytes (least significant bit = element 0)
Short String
string in the Latin-1 character set, followed by a 00X
String
string in the Unicode character set, followed by a 0000X
CONST alienVersion
This value is assigned to a Reader's cause field if Reader.ReadVersion read a version outside of the specified range.
CONST alienComponent
This value can be used as cause parameter to Reader.TurnIntoAlien to indicate that the store itself could be read, but that some store contained in it is an alien. As an example, a view may turn itself into an alien if its model is an alien.
CONST inconsistentVersion
This value is assigned to a Reader's cause field if Reader.ReadVersion read a data block which has an inconsistent length, i.e., not all of its data have been read, or it has been attempted to read beyond the end of the data.
CONST inconsistentType
This value is assigned to a Reader's cause field if Reader.ReadVersion detected a change in the type extension hierarchy of the internalized type.
CONST moduleFileNotFound
This value is assigned to a Reader's cause field if Reader.ReadVersion tried to load a module defining an internalized type, and the codefile for this module couldn't be found.
CONST invalidModuleFile
This value is assigned to a Reader's cause field if Reader.ReadVersion tried to load a module defining an internalized type, and the module couldn't be loaded because it imports another module which cannot be loaded for some reason.
CONST inconsModuleVersion
This value is assigned to a Reader's cause field if Reader.ReadVersion tried to load a module defining an internalized type, and the module couldn't be loaded because its version is inconsistent with some already loaded module.
CONST typeNotFound
This value is assigned to a Reader's cause field if Reader.ReadVersion tried to internalize a non-existing type (the module was found, however).
TYPE TypeName
String type for the type name of an object.
TYPE TypePath
Array of type names.
TYPE OpName
String type for the name of an operation.
TYPE Domain
LIMITED
A domain represents a graph of stores which may be saved in a file as a whole. All stores of a domain refer to an object of type Domain.
PROCEDURE (d: Domain) GetSequencer (): ANYPTR
NEW
Used internally.
PROCEDURE (d: Domain) SetSequencer (sequencer: ANYPTR)
NEW
Used internally.
TYPE Operation
ABSTRACT
An operation is an object that represents a command performed on some store(s) of a domain. An operation can be undone (i.e., aborted) and redone.
PROCEDURE (op: Operation) Do
NEW, ABSTRACT
This method implements the actual behavior of the operation. It must be auto-inverse, i.e., if executed an even number of times, it must have no effect. If executed an odd number of times, it should have the same effect.
TYPE Store
ABSTRACT
Storable extensible data types like Views.View or TextModels.Text are derived from Store.
Stores are typically allocated by suitable directories, e.g., Views.Directory or TextModels.Directory.
Stores are used as base types for all objects that must be both extensible and persistent.
PROCEDURE (s: Store) Domain (): Domain
NEW
A store may be associated with a domain. This is done by the procedure InitDomain, which assigns a domain to the store.
Domain may be called by arbitrary clients.
PROCEDURE (s: Store) CopyFrom- (source: Store)
NEW, EMPTY
Copy the contents of source to s. Copying is a deep copy.
Pre
source # NIL guaranteed
TYP(source) = TYP(s) guaranteed
s.Domain() = NIL guaranteed
s is not yet initialized guaranteed
PROCEDURE (s: Store) Internalize- (VAR rd: Reader)
NEW, EMPTY
(For backward compatibility, this method is actually still EXTENSIBLE. This may change in the future.)
Reads the contents of s from reader rd. Internalize must read the same (amount of) data as is written by the corresponding Externalize procedure.
Internalize is called locally.
Internalize is extended by various persistent object types, e.g., models, views, and controllers.
Pre
source.Domain() = NIL guaranteed
source is not yet initialized guaranteed
PROCEDURE (s: Store) Externalize- (VAR wr: Writer)
NEW, EMPTY
(For backward compatibility, this method is actually still EXTENSIBLE. This may change in the future.)
Write the contents of s to writer wr. Externalize must write the same (amount of) data as is read by the corresponding Internalize procedure.
Externalize is called locally.
Externalize is extended by various persistent object types, e.g., models, views, and controllers.
PROCEDURE (s: Store) ExternalizeAs- (VAR s1: Store)
NEW, EMPTY
Before a store's Externalize procedure is called, its ExternalizeAs procedure is called, which gives the store the opportunity to denote another store that should be externalized in its place (a "proxy"). It is also possible to set s1 to NIL, which means that the store should not be externalized at all. This is used e.g. for compiler error markers, which are never stored.
ExternalizeAs is called locally.
Pre
s1 = s guaranteed
TYPE Reader
Reader for Component Pascal values like integers, reals, or sets. A reader contains a Files.Reader, to which it forwards most operations.
Readers are used in the Store.Internalize procedure.
Readers are not extensible.
rider-: Files.Reader
The file rider which links a Reader to a file.
cancelled-: BOOLEAN
Tells whether reading has been canceled by ReadVersion or TurnIntoAlien since the last ConnectTo.
readAlien-: BOOLEAN
Tells whether any alien has been read since the last ConnectTo.
PROCEDURE (VAR rd: Reader) ConnectTo (f: Files.File)
NEW
Connect the reader to a file. All the following operations require connected readers, i.e., rd.rider # NIL. This precondition is not checked explicitly, however. After connecting, the reader's position is at the beginning of the file. If the same reader should be reused on another file, it must first be closed, by connecting it to NIL.
ConnectTo is used internally.
Pre
20 (f = NIL) OR (rd.rider = NIL)
Post
f = NIL
rd.rider = NIL
f # NIL
(rd.rider # NIL) & (rd.rider.Base() = f)
rd.Pos() = 0
PROCEDURE (VAR rd: Reader) Pos (): INTEGER
NEW
Returns the reader's current position.
Post
0 <= result <= rd.rider.Base().Length()
PROCEDURE (VAR rd: Reader) SetPos (pos: INTEGER)
NEW
Sets the reader's current position to pos.
Pre
20 pos >= 0
21 pos <= rd.rider.Base().Length()
Post
rd.Pos() = pos
~rd.rider.eof
PROCEDURE (VAR rd: Reader) ReadBool (OUT x: BOOLEAN)
NEW
Reads a Boolean value.
PROCEDURE (VAR rd: Reader) ReadSChar (OUT x: SHORTCHAR)
NEW
Reads a short character (00X..0FFX).
PROCEDURE (VAR rd: Reader) ReadXChar (OUT x: CHAR)
NEW
Same as ReadSChar, but has a CHAR-type parameter.
This procedure is provided to simplify migration from Release 1.2 to 1.3.
PROCEDURE (VAR rd: Reader) ReadChar (OUT x: CHAR)
NEW
Reads a character (0000X..0FFFFX).
PROCEDURE (VAR rd: Reader) ReadByte (OUT x: BYTE)
NEW
Reads a very short integer (-128..127).
PROCEDURE (VAR rd: Reader) ReadSInt (OUT x: SHORTINT)
NEW
Reads a short integer (-32768..32767).
PROCEDURE (VAR rd: Reader) ReadXInt (OUT x: INTEGER)
NEW
Same as ReadSInt, but has an INTEGER-type parameter.
This procedure is provided to simplify migration from Release 1.2 to 1.3.
PROCEDURE (VAR rd: Reader) ReadInt (OUT x: INTEGER)
NEW
Reads an integer (-2147483648..2147483647).
PROCEDURE (VAR rd: Reader) ReadLong (OUT x: LONGINT)
NEW
Reads a long integer (-9223372036854775808..9223372036854775807).
PROCEDURE (VAR rd: Reader) ReadSReal (OUT x: SHORTREAL)
NEW
Reads a short real (32-bit IEEE number).
PROCEDURE (VAR rd: Reader) ReadXReal (OUT x: REAL)
NEW
Same as ReadSReal, but has a REAL-type parameter.
This procedure is provided to simplify migration from Release 1.2 to 1.3.
PROCEDURE (VAR rd: Reader) ReadReal (OUT x: REAL)
NEW
Reads a real (64-bit IEEE number).
PROCEDURE (VAR rd: Reader) ReadSet (OUT x: SET)
NEW
Reads a set (32 elements).
PROCEDURE (VAR rd: Reader) ReadSString (OUT x: ARRAY OF SHORTCHAR)
NEW
Reads a 0X-terminated short string.
Pre
invalid index LEN(x) > Length(string)
PROCEDURE (VAR rd: Reader) ReadXString (OUT x: ARRAY OF CHAR)
NEW
Same as ReadSString, but has a string-type parameter.
This procedure is provided to simplify migration from Release 1.2 to 1.3.
PROCEDURE (VAR rd: Reader) ReadString (OUT x: ARRAY OF CHAR)
NEW
Reads a 0X-terminated string.
Pre
invalid index LEN(x) > Length(string)
PROCEDURE (VAR rd: Reader) ReadStore (OUT x: Store)
NEW
Reads a store's type, allocates it, and then reads its contents, by calling the store's Internalize procedure. x may also be NIL, or an alien if the store's module cannot be loaded, or if internalization has been cancelled by the Internalize procedure.
If the store has already been read in, a pointer to the same store is returned instead of allocating a new one. This means that arbitrary graphs that have been written with WriteStore are reconstructed correctly, including alias pointers to the same store, cycles, etc.
If the file on which the reader operates does not contain correct input, then an assertion trap will be caused (traps 101 to trap 106).
Pre
20 the reader is at the start position of a new store
Post
empty store on file
x = NIL
non-empty store on file
x # NIL
x IS Alien
x.cause # 0
x.type # ""
x.file # NIL
x.pos >= 0 beginning of store's data
x.len >= 0 length of store's data
alien store contents are on x.file in the range [x.pos .. x.pos + x.len[.
These data include only the store's contents, not its prefix
~(x IS Alien)
x was read successfully
PROCEDURE (VAR rd: Reader) ReadVersion (min, max: INTEGER; OUT version: INTEGER)
NEW
Read a version byte and return it in version. If version is not in the specified range [min .. max], the store currently being read is turned into an alien, with cause = alienVersion.
Pre
20 0 <= min <= max
Post
min <= version <= max
legal version
(version < min) OR (version > max)
illegal version
rd.cause = alienVersion
rd.cancelled
rd.readAlien
PROCEDURE (VAR rd: Reader) TurnIntoAlien (cause: INTEGER)
NEW
A store which is currently being internalized can turn itself into an alien, e.g., if it has read a component store which is an alien.
Pre
20 cause > 0
TYPE Writer
Writer for Component Pascal values like integers, reals, or sets. A writer contains a Files.Writer, to which it forwards most operations.
Writers are used in the Externalize procedure.
Writers are not extensible.
rider-: Files.Writer
A file rider which links a Writer to a file.
writtenStore-: Store
Store which was most recently written as an effect of a call to WriteStore.
PROCEDURE (VAR wr: Writer) ConnectTo (f: Files.File)
NEW
Connect the writer to a file. All the following operations require connected writers, i.e., wr.rider # NIL. This precondition is not checked explicitly, however. After connecting, the writer's position is at the end of the file. If the same writer should be reused on another file, it must first be closed, by connecting it to NIL.
ConnectTo is used internally.
Pre
20 (f = NIL) OR (wr.rider = NIL)
Post
f = NIL
wr.rider = NIL
f # NIL
wr.rider # NIL & wr.rider.Base() = f
wr.Pos() = wr.rider.Base().Length()
PROCEDURE (VAR wr: Writer) Pos (): INTEGER
NEW
Returns the writer's current position.
Post
0 <= result <= wr.rider.Base().Length()
PROCEDURE (VAR wr: Writer) SetPos (pos: INTEGER)
NEW
Sets the writer's current position to pos.
Pre
20 pos >= 0
21 pos <= wr.rider.Base().Length()
Post
wr.Pos() = pos
PROCEDURE (VAR wr: Writer) WriteBool (x: BOOLEAN)
NEW
Writes a Boolean value.
PROCEDURE (VAR wr: Writer) WriteSChar (x: SHORTCHAR)
NEW
Writes a character (00X..0FFX).
PROCEDURE (VAR wr: Writer) WriteXChar (x: CHAR)
NEW
Same as WriteSChar, but has a CHAR-type parameter.
This procedure is provided to simplify migration from Release 1.2 to 1.3.
PROCEDURE (VAR wr: Writer) WriteChar (x: CHAR)
NEW
Writes a character (0000X..0FFFFX).
PROCEDURE (VAR wr: Writer) WriteByte (x: BYTE)
NEW
Writes a very short integer (-128..127).
PROCEDURE (VAR wr: Writer) WriteSInt (x: SHORTINT)
NEW
Writes a short integer (-32768..32767).
PROCEDURE (VAR wr: Writer) WriteXInt (x: INTEGER)
NEW
Same as WriteSInt, but has an INTEGER-type parameter.
This procedure is provided to simplify migration from Release 1.2 to 1.3.
PROCEDURE (VAR wr: Writer) WriteInt (x: INTEGER)
NEW
Writes an integer (-2147483648..2147483647).
PROCEDURE (VAR wr: Writer) WriteLong (x: LONGINT)
NEW
Writes a long integer (-9223372036854775808..9223372036854775807).
PROCEDURE (VAR wr: Writer) WriteSReal (x: SHORTREAL)
NEW
Writes a real (32-bit IEEE number).
PROCEDURE (VAR wr: Writer) WriteXReal (x: REAL)
NEW
Same as WriteSReal, but has a REAL-type parameter.
This procedure is provided to simplify migration from Release 1.2 to 1.3.
PROCEDURE (VAR wr: Writer) WriteReal (x: REAL)
NEW
Writes a long real (64-bit IEEE number).
PROCEDURE (VAR wr: Writer) WriteSet (x: SET)
NEW
Writes a set (32 elements).
PROCEDURE (VAR wr: Writer) WriteSString (IN x: ARRAY OF SHORTCHAR)
NEW
Writes a 0X-terminated short string.
PROCEDURE (VAR wr: Writer) WriteXString (IN x: ARRAY OF CHAR)
NEW
Same as WriteSString, but has a string-type parameter.
This procedure is provided to simplify migration from Release 1.2 to 1.3.
PROCEDURE (VAR wr: Writer) WriteString (IN x: ARRAY OF CHAR)
NEW
Writes a 0X-terminated string.
PROCEDURE (VAR wr: Writer) WriteStore (x: Store)
NEW
Writes the store's type and then its contents, by calling the store's Externalize procedure. x may also be NIL, or an alien. Before Externalize, ExternalizeAs is called in order to give the store the opportunity to denote a proxy which should be stored in its stead. WriteStore writes x and (via Externalize) all the stores that it contains. Cycles are handled correctly, i.e., a store is only written once, even if referenced several times in a complex graph.
All stores that are written using the same writer must have the identical domain.
Pre
20 wr.rider # NIL
21 x # NIL => writer must have no domain, or the same one as x (and as all previously written stores)
PROCEDURE (VAR wr: Writer) WriteVersion (version: INTEGER)
NEW
Writes a version byte.
Pre
20 0 <= version <= 127
TYPE AlienComp, AlienPiece, AlienPart, Alien
LIMITED
These auxiliary types are used internally, to handle alien stores.
PROCEDURE Join (s0, s1: Store)
Join two stores in the same store set. See the explanation at the beginning of this text.
Pre
20 s0 # NIL
21 s1 # NIL
22 s0.Domain() = NIL OR s1.Domain() = NIL OR s0.Domain() = s1.Domain()
Post
Joined(s0, s1)
PROCEDURE Joined (s0, s1: Store): BOOLEAN
Test whether two stores are joined. Joined(x, x) always returns TRUE, i.e., it is reflexive.
Pre
20 s0 # NIL
21 s1 # NIL
PROCEDURE Unattached (s: Store): BOOLEAN
Tests whether s is not attached to a domain and whether it has not been joined with another store.
Rarely used.
Pre
20 s # NIL
PROCEDURE CopyOf (s: Store): Store
Returns the clone of a store, with its contents copied.
CopyOf allocates a new record with the same dynamic type as s, and initializes it by calling its CopyFrom procedure. The copy is a deep copy.
Pre
20 s # NIL
Post
(result # NIL) & (result # s)
TYP(result) = TYP(s)
PROCEDURE InitDomain (s: Store)
Initializes the domain of store s. See the explanation at the beginning of this text.
Pre
20 s # NIL
Post
s.Domain() # NIL
PROCEDURE ExternalizeProxy (s: Store): Store
Causes s to call its ExternalizeAs method, basically doing the following:
IF s # NIL THEN s.ExternalizeAs(s) END;
RETURN s
PROCEDURE Report (IN msg, p0, p1, p2: ARRAY OF CHAR)
When a store encounters a problem during internalization, it can report the problem by calling this procedure. The parameters are similar to Dialog.ShowParamMsg.
| System/Docu/Stores.odc |
Stores64
DEFINITION Stores64;
IMPORT Files, Files64, Stores;
TYPE
Reader = RECORD
rider-: Files64.Reader;
cancelled-, readAlien-: BOOLEAN;
(VAR rd: Reader) ConnectTo (f: Files64.File), NEW;
(VAR rd: Reader) Pos (): LONGINT, NEW;
(VAR rd: Reader) ReadBool (OUT x: BOOLEAN), NEW;
(VAR rd: Reader) ReadByte (OUT x: BYTE), NEW;
(VAR rd: Reader) ReadChar (OUT x: CHAR), NEW;
(VAR rd: Reader) ReadInt (OUT x: INTEGER), NEW;
(VAR rd: Reader) ReadLong (OUT x: LONGINT), NEW;
(VAR rd: Reader) ReadReal (OUT x: REAL), NEW;
(VAR rd: Reader) ReadSChar (OUT x: SHORTCHAR), NEW;
(VAR rd: Reader) ReadSInt (OUT x: SHORTINT), NEW;
(VAR rd: Reader) ReadSReal (OUT x: SHORTREAL), NEW;
(VAR rd: Reader) ReadSString (OUT x: ARRAY OF SHORTCHAR), NEW;
(VAR rd: Reader) ReadSet (OUT x: SET), NEW;
(VAR rd: Reader) ReadStore (OUT x: Stores.Store), NEW;
(VAR rd: Reader) ReadString (OUT x: ARRAY OF CHAR), NEW;
(VAR rd: Reader) ReadXChar (OUT x: CHAR), NEW;
(VAR rd: Reader) ReadXInt (OUT x: INTEGER), NEW;
(VAR rd: Reader) ReadXReal (OUT x: REAL), NEW;
(VAR rd: Reader) ReadXString (OUT x: ARRAY OF CHAR), NEW;
(VAR rd: Reader) SetPos (pos: LONGINT), NEW
END;
Writer = RECORD
rider-: Files64.Writer;
writtenStore-: Stores.Store;
(VAR wr: Writer) ConnectTo (f: Files64.File), NEW;
(VAR wr: Writer) Pos (): LONGINT, NEW;
(VAR wr: Writer) SetPos (pos: LONGINT), NEW;
(VAR wr: Writer) WriteBool (x: BOOLEAN), NEW;
(VAR wr: Writer) WriteByte (x: BYTE), NEW;
(VAR wr: Writer) WriteChar (x: CHAR), NEW;
(VAR wr: Writer) WriteInt (x: INTEGER), NEW;
(VAR wr: Writer) WriteLong (x: LONGINT), NEW;
(VAR wr: Writer) WriteReal (x: REAL), NEW;
(VAR wr: Writer) WriteSChar (x: SHORTCHAR), NEW;
(VAR wr: Writer) WriteSInt (x: SHORTINT), NEW;
(VAR wr: Writer) WriteSReal (x: SHORTREAL), NEW;
(VAR wr: Writer) WriteSString (IN x: ARRAY OF SHORTCHAR), NEW;
(VAR wr: Writer) WriteSet (x: SET), NEW;
(VAR wr: Writer) WriteStore (x: Stores.Store), NEW;
(VAR wr: Writer) WriteString (IN x: ARRAY OF CHAR), NEW;
(VAR wr: Writer) WriteVersion (version: INTEGER), NEW;
(VAR wr: Writer) WriteXChar (x: CHAR), NEW;
(VAR wr: Writer) WriteXInt (x: INTEGER), NEW;
(VAR wr: Writer) WriteXReal (x: REAL), NEW;
(VAR wr: Writer) WriteXString (IN x: ARRAY OF CHAR), NEW
END;
PROCEDURE NewSegment (container: Files64.File; org: LONGINT): Files.File;
END Stores64.
This module provides Reader and Writer objects similar to Stores.Reader and Stores.Writer but for 64-bit files (Files64).
Stores64 read and write operations can be applied to the full file space (MAX(LONGINT)) except for the following limitation. The file space for stores must fit within MAX(INTEGER) bytes because for compatibility reasons the file format being used is the same as for Stores.Store. In order to avoid this limitation, a separate ConnectTo operation (typically followed by SetPos) can be executed. This resets internal data structures and restarts checking the store size limitation with the next WriteStore/ReadStore operation. Stores read resp. written after different ConnectTo operations do not refer to each other but are treated as if they are in different files.
For the documentation of Reader and Writer operations see Stores.
PROCEDURE NewSegment (container: Files64.File; org: LONGINT): Files.File;
Creates and returns a 32-bit file segment backed by a 64-bit container file starting at position org. The returned file segment can be used for connecting a Stores.Reader or Stores.Writer, for example. Segments are also used internally for handling ReadStore and WriteStore. A segment cannot be registered.
Pre
container # NIL 20
~container.Closed() 21
org >= 0 22
| System/Docu/Stores64.odc |
Strings
DEFINITION Strings;
CONST
charCode = -1;
decimal = 10;
digitspace = 8FX;
hexadecimal = -2;
hideBase = FALSE;
roman = -3;
showBase = TRUE;
PROCEDURE Extract (s: ARRAY OF CHAR; pos, len: INTEGER; OUT res: ARRAY OF CHAR);
PROCEDURE Find (IN s: ARRAY OF CHAR; IN pat: ARRAY OF CHAR; start: INTEGER; OUT pos: INTEGER);
PROCEDURE GetDecimalSign (): CHAR;
PROCEDURE IntToString (x: LONGINT; OUT s: ARRAY OF CHAR);
PROCEDURE IntToStringForm (x: LONGINT; form, minWidth: INTEGER; fillCh: CHAR; showBase: BOOLEAN; OUT s: ARRAY OF CHAR);
PROCEDURE IsAlpha (ch: CHAR): BOOLEAN;
PROCEDURE IsAlphaNumeric (ch: CHAR): BOOLEAN;
PROCEDURE IsIdent (ch: CHAR): BOOLEAN;
PROCEDURE IsIdentStart (ch: CHAR): BOOLEAN;
PROCEDURE IsLower (ch: CHAR): BOOLEAN;
PROCEDURE IsNumeric (ch: CHAR): BOOLEAN;
PROCEDURE IsUpper (ch: CHAR): BOOLEAN;
PROCEDURE Lower (ch: CHAR): CHAR;
PROCEDURE RealToString (x: REAL; OUT s: ARRAY OF CHAR);
PROCEDURE RealToStringForm (x: REAL; precision, minW, expW: INTEGER; fillCh: CHAR; OUT s: ARRAY OF CHAR);
PROCEDURE Replace (VAR s: ARRAY OF CHAR; pos, len: INTEGER; IN rep: ARRAY OF CHAR);
PROCEDURE SetDecimalSign (sign: CHAR);
PROCEDURE SetToString (x: SET; OUT str: ARRAY OF CHAR);
PROCEDURE StringToInt (IN s: ARRAY OF CHAR; OUT x, res: INTEGER);
PROCEDURE StringToLInt (IN s: ARRAY OF CHAR; OUT x: LONGINT; OUT res: INTEGER);
PROCEDURE StringToReal (IN s: ARRAY OF CHAR; OUT x: REAL; OUT res: INTEGER);
PROCEDURE StringToSet (IN s: ARRAY OF CHAR; OUT x: SET; OUT res: INTEGER);
PROCEDURE ToLower (IN in: ARRAY OF CHAR; OUT out: ARRAY OF CHAR);
PROCEDURE ToUpper (IN in: ARRAY OF CHAR; OUT out: ARRAY OF CHAR);
PROCEDURE Upper (ch: CHAR): CHAR;
PROCEDURE Valid (IN s: ARRAY OF CHAR): BOOLEAN;
END Strings.
Module Strings is a simple and small string library. Its goal is to provide a few string operations that are both often needed and complicated to implement, in particular routines for conversions between numbers and strings. The library is optimized for convenience, not for efficiency.
This tradeoff is apparent in that some operations, such as Extract, use value parameters instead of IN parameters. This allows to pass the same variable both for input and output purposes, which is often convenient (a variable should never be passed to several IN/OUT/VAR parameters simultaneously, since this may cause interference between them).
It is not a goal to provide operations for all possible circumstances, since string processing in different applications simply varies to much to make this practical. Often it is useful to write a few string operations fully tailored to a particular application, which is usually easy to do. Moreover, such custom string operations can be optimized for speed, which is not possible for too general routines.
Note that the language Component Pascal provides efficient built-in support for string assignment (implicitly or explicitly with the "$" operator), for string concatenation (with the "+" operator), and for counting the number of characters in a string (LEN(string$)).
CONST charCode
Possible value for parameter form of IntToStringForm, asking for formatting integers following the syntax of Component Pascal numerical character literals, e.g., 0DX or 37X.
CONST decimal
Possible value for parameter form of IntToStringForm, asking for formatting integers as decimal literals.
CONST hexadecimal
Possible value for parameter form of IntToStringForm, asking for formatting integers as hexadecimal literals.
CONST roman
Possible value for parameter form of IntToStringForm, asking for formatting integers as roman literals.
CONST digitspace
A digit space has the width of digit zero (0) which is equivalent to the width of all digits in most fonts, thus can be used for number formatting.
CONST hideBase, showBase
Possible values for parameter showBase of IntToStringForm, asking for showing / suppressing the base of the number format.
PROCEDURE Valid (IN s: ARRAY OF CHAR): BOOLEAN
Returns TRUE if and only if the array s contains at least one string terminator 0X.
Post
s contains a 0X character
result = TRUE
s does not contain a 0X character
result = FALSE
PROCEDURE Extract (s: ARRAY OF CHAR; pos, len: INTEGER; OUT res: ARRAY OF CHAR)
Extracts the stretch [pos, MIN(pos+len, Len(s))) from s and returns it in res. The result is truncated if res is not large enough. The same actual parameter may be passed for s and res.
Pre
len >= 0 20
pos >= 0 21
Valid(s) (not checked)
Post
Valid(res)
LEN(res$) = MAX(MIN(len, LEN(s'$)-pos, LEN(res)-1), 0)
PROCEDURE Replace (VAR s: ARRAY OF CHAR; pos, len: INTEGER; IN rep: ARRAY OF CHAR)
Replaces the stretch [pos, MIN(pos+len, Len(s))) in s with the string in rep. The characters after the replaced stretch are moved if necessary. The result is truncated if s is not large enough.
Hint: if len = 0 then rep is inserted in s at position pos. If LEN(rep$) = 0 then the stretch [pos, MIN(pos+len, LEN(s$))) is deleted from s.
Pre
len >= 0 20
pos >= 0 21
Valid(s) & Valid(rep) (not checked)
Post
Valid(s)
PROCEDURE Find (IN s: ARRAY OF CHAR; IN pat: ARRAY OF CHAR; start: INTEGER;
OUT pos: INTEGER);
Searches the first occurrence of the pattern pat in string s after position start. If the pattern is found, the position of the first character of the pattern in s is returned in pos. If the pattern is not found, pos is -1.
Pre
start >= 0 20
Valid(s) & Valid(pat) (not checked)
Post
pattern found
pos is start position of pat in s
pattern not found
pos = -1
PROCEDURE IntToStringForm (x: LONGINT; form, minWidth: INTEGER; fillCh: CHAR;
showBase: BOOLEAN; OUT s: ARRAY OF CHAR)
Convert integer x into string s. If form is charCode or hexadecimal, x is converted to a base 16 representation. The total representation will at least have a width of minWidth characters, where padding (if required) takes place to the left using characters as specified by fillCh.
If showBase is TRUE, a suffix character is appended to the number representation according to the number form. The value form = charCode renders the suffix "X", while form = hexadecimal renders the suffix "H". These values of form also represent negative integers using a base-complement form of width minWidth, i.e., for negative hexadecimal numbers, fillCh is ignored and "F" is used instead (both for form = charCode and form = hexadecimal). For form values in the range 2..16, base-complement representation is not supported.
E.g.
x = -3, form = 16, minWidth = 4, fillCh = " " and showBase = FALSE renders a result of -3
x = -3, form = hexadecimal, minWidth = 4, fillCh = " " and showBase = FALSE renders a result of FFFD
If showBase is TRUE and form is in the range 2..16, then the base is appended to the number, preceded by a "%" sign (e.g., "10111001%2").
If form = roman (roman numbers), then showBase is ignored.
The following conditions imply that s is large enough to hold the resulting string (Pre 23):
form = roman: LEN(s) > MAX(minWidth, 15)
(form = charCode) OR (form = hexadecimal) OR (form >= 2) & (form <= 16):
LEN(s) > MAX(minWidth, 4 + <number of digits>)
Where <number of digits> is 1 + Floor(Logbase(ABS(x))), if ABS(x) >= 1, and 1 otherwise.
Note that these values are non-tight upper bounds of the required string length. In individual cases, actual requirements might be lower but the given bounds guarantee compliance with the precondition.
Pre
(form = charCode) OR (form = hexadecimal) OR (form = roman) OR ((form >= 2) & (form <= 16)) 20
(form # roman) OR (form = roman) & (x > 0) & (x < 3999) 21
minWidth >= 0 22
s is large enough to hold resulting string (see above) 23
Post
Valid(s)
PROCEDURE IntToString (x: LONGINT; OUT s: ARRAY OF CHAR)
Write integer in default format.
Except for performance, equivalent to:
IntToStringForm(x, decimal, 0, digitspace, FALSE, s)
PROCEDURE RealToStringForm (x: REAL; precision, minW, expW: INTEGER;
fillCh: CHAR; OUT s: ARRAY OF CHAR)
Convert real x into string s. The string created to represent the number is either in fixed point or in scientific format, according to expW. precision denotes the number of valid decimal places (usually 7 for short reals and 16 for reals). minW denotes the minimal length in characters. If necessary, preceding fillCh will be inserted. Numbers are always rounded to the last valid and visible digit.
expW > 0: exponential format (scientific) with at least expW digits in the exponent.
expW = 0: fixpoint or floatingpoint format, depending on x.
expW < 0: fixpoint format with -expW digits after the decimal point.
The following conditions imply that s is large enough to hold the resulting string (Pre 23):
(x = inf) OR (x = -inf) OR (x = nan): LEN(s) > MAX(minW, 4)
expW >= 0: LEN(s) > MAX(minW, precision + 7)
expW < 0: LEN(s) > MAX(minW, 3 - expW + <number of digits before the decimal point>)
Where the <number of digits before the decimal point> is 1 + Floor(Log10(ABS(x))), if ABS(x) >= 1,
and 1 otherwise.
Note that these values are non-tight upper bounds of the required string length. In individual cases, actual requirements might be lower but the given bounds guarantee compliance with the precondition.
Pre
precision > 0 20
0 <= minW < LEN(s) 21
-LEN(s) < expW <= 3 22
s is large enough to hold resulting string (see above) 23
Pos
Valid(s)
PROCEDURE RealToString (x: REAL; OUT s: ARRAY OF CHAR)
Write real in default format.
Except for performance, equivalent to:
RealToStringForm(x, 16, 0, 0, digitspace, s)
PROCEDURE SetToString* (x: SET; OUT s: ARRAY OF CHAR)
Convert set x into string s. For example the set {1,2,3,5} will be converted into the string "{1..3, 5}".
Pre
s is large enough to hold resulting string 23
Pos
Valid(s)
PROCEDURE StringToInt (IN s: ARRAY OF CHAR; OUT x, res: INTEGER)
PROCEDURE StringToLInt (IN s: ARRAY OF CHAR; OUT x: LONGINT; res: INTEGER)
Converts the number contained in string s into value x. Legal integer number representations follow the syntax given below. Possible result codes are res = 1 for overflow, res = 2 for syntax error.
Syntax:
number = ( [ "+" | "-" ] dec | hex ) 0X .
dec = digit { digit } .
hex = hexdigit { hexdigit } ("H" | "X") .
hexdigit = digit | "A" | "B" | "C" | "D" | "E" | "F" .
digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" .
Post
s is legal integer number representation
x is converted integer number
res = 0
s is not a legal integer number representation
res # 0
PROCEDURE StringToReal (IN s: ARRAY OF CHAR; OUT x: REAL; OUT res: INTEGER)
Converts string s given in fixed or scientific notation into value x. Possible result codes are res = 1 for overflow, res = 2 for syntax error.
Post
s is legal real number representation
x is converted real number
res = 0
s is not legal real number representation
res # 0
PROCEDURE StringToSet* (IN s: ARRAY OF CHAR; OUT x: SET; OUT res: INTEGER)
Converts string s given as Component Pascal set constant into value x. White space between symbols is allowed. Comments or symbolic names are not allowed. In the syntax below, dec stands for a positive integer number between MIN(SET) and MAX(SET). Possible result codes are res = 1 for overflow, res = 2 for syntax error.
Syntax:
set = "{" [element {"," element}] "}".
element = dec [".." dec].
Post
s is legal set representation
x is converted set
res = 0
s is not legal set representation
res # 0
PROCEDURE SetDecimalSign* (sign: CHAR);
Set decimal sign for RealToString and StringToReal conversions.
Pre
sign = "." OR "," 21
PROCEDURE GetDecimalSign* (): CHAR;
Get current decimal sign for RealToString and StringToReal conversions.
PROCEDURE Upper (ch: CHAR): CHAR
Conversion to uppercase characters. Handles the entire 16-bit Unicode character set. Character values that have no uppercase equivalent are returned unchanged.
PROCEDURE Lower (ch: CHAR): CHAR
Conversion to lowercase characters. Handles the entire 16-bit Unicode character set. Character values that have no lowercase equivalent are returned unchanged.
PROCEDURE IsAlpha (ch: CHAR): BOOLEAN;
Returns TRUE if ch is a letter.
PROCEDURE IsUpper (ch: CHAR): BOOLEAN;
Returns TRUE if ch is an uppercase letter.
PROCEDURE IsLower (ch: CHAR): BOOLEAN;
Returns TRUE if ch is a lowercase letter.
PROCEDURE IsNumeric (ch: CHAR): BOOLEAN;
Returns TRUE if ch is a digit.
PROCEDURE IsAlphaNumeric (ch: CHAR): BOOLEAN;
Returns TRUE if ch is it a letter or a digit.
PROCEDURE IsIdentStart (ch: CHAR): BOOLEAN;
Returns TRUE if ch can be the first character of a Component Pascal identifier.
PROCEDURE IsIdent (ch: CHAR): BOOLEAN;
Returns TRUE if ch can be a second or further character of a Component Pascal identifier.
PROCEDURE ToLower (IN in: ARRAY OF CHAR; OUT out: ARRAY OF CHAR)
Converts string in to lowercase characters and returns the result in out. Handles the entire 16-bit Unicode character set. Character values that have no lowercase equivalent are unchanged. The same actual parameter may be passed for in and out.
Pre
Valid(in) index trap
Post
Valid(out)
PROCEDURE ToUpper (IN in: ARRAY OF CHAR; OUT out: ARRAY OF CHAR)
Converts string in to uppercase characters and returns the result in out. Handles the entire 16-bit Unicode character set. Character values that have no uppercase equivalent are unchanged. The same actual parameter may be passed for in and out.
Pre
Valid(in) index trap
Post
Valid(out)
| System/Docu/Strings.odc |
Map to the BlackBox Core
Miscellaneous
In Out
BlackBox Component Framework
Containers Controls
Properties Controllers Printing
Views
Stores64 Converters Models Ports
Stores Fonts
Loop
BlackBox Component Library
Files64 Integers Dialog
Files Math Dates
Services Meta Console
Utf Unicode Strings | System/Docu/Sys-Map.odc |
Unicode
DEFINITION Unicode;
PROCEDURE IsAlpha (ch: CHAR): BOOLEAN;
PROCEDURE IsAlphaNumeric (ch: CHAR): BOOLEAN;
PROCEDURE IsIdent (ch: CHAR): BOOLEAN;
PROCEDURE IsIdentStart (ch: CHAR): BOOLEAN;
PROCEDURE IsLower (ch: CHAR): BOOLEAN;
PROCEDURE IsNumeric (ch: CHAR): BOOLEAN;
PROCEDURE IsUpper (ch: CHAR): BOOLEAN;
PROCEDURE Lower (ch: CHAR): CHAR;
PROCEDURE ToLower (IN in: ARRAY OF CHAR; OUT out: ARRAY OF CHAR);
PROCEDURE ToUpper (IN in: ARRAY OF CHAR; OUT out: ARRAY OF CHAR);
PROCEDURE Upper (ch: CHAR): CHAR;
END Unicode.
Module Unicode providing identification and upper/lower case transformation for 16-bit Unicode character set.
PROCEDURE Upper (ch: CHAR): CHAR
Conversion to uppercase characters. Handles the entire 16-bit Unicode character set. Character values that have no uppercase equivalent are returned unchanged.
PROCEDURE Lower (ch: CHAR): CHAR
Conversion to lowercase characters. Handles the entire 16-bit Unicode character set. Character values that have no lowercase equivalent are returned unchanged.
PROCEDURE IsAlpha (ch: CHAR): BOOLEAN;
Returns TRUE if ch is a letter.
PROCEDURE IsUpper (ch: CHAR): BOOLEAN;
Returns TRUE if ch is an uppercase letter.
PROCEDURE IsLower (ch: CHAR): BOOLEAN;
Returns TRUE if ch is a lowercase letter.
PROCEDURE IsNumeric (ch: CHAR): BOOLEAN;
Returns TRUE if ch is a digit.
PROCEDURE IsAlphaNumeric (ch: CHAR): BOOLEAN;
Returns TRUE if ch is it a letter or a digit.
PROCEDURE IsIdentStart (ch: CHAR): BOOLEAN;
Returns TRUE if ch can be the first character of a Component Pascal identifier.
PROCEDURE IsIdent (ch: CHAR): BOOLEAN;
Returns TRUE if ch can be a second or further character of a Component Pascal identifier.
PROCEDURE ToLower (IN in: ARRAY OF CHAR; OUT out: ARRAY OF CHAR)
Converts string in to lowercase characters and returns the result in out. Handles the entire 16-bit Unicode character set. Character values that have no lowercase equivalent are unchanged. The same actual parameter may be passed for in and out.
Pre
Valid(in) index trap
Post
Valid(out)
PROCEDURE ToUpper (IN in: ARRAY OF CHAR; OUT out: ARRAY OF CHAR)
Converts string in to uppercase characters and returns the result in out. Handles the entire 16-bit Unicode character set. Character values that have no uppercase equivalent are unchanged. The same actual parameter may be passed for in and out.
Pre
Valid(in) index trap
Post
Valid(out)
| System/Docu/Unicode.odc |
BlackBox Component Builder
User Manual
Contents
1 Overview
2 Installation
3 Serverinstallation
4 Deinstallation
5 DocumentWindows,ToolWindows,AuxiliaryWindows
6 DocumentSize
7 MenuConfiguration
8 StringResources
9 StandardCommands
9.1 FileMenu
9.2 EditMenu
9.3 AttributesMenu
9.4 WindowMenu
10 CustomCommands
Further user manuals
TextSubsystem
FormSubsystem
DevSubsystem
1 Overview
This document serves as a user's guide for BlackBox programmers. It is not intended as a manual for the end user of software written with the BlackBox Component Builder. Knowledge of the underlying platform's user interface guidelines is assumed.
With the BlackBox Component Builder, there are no separate environments for developing programs, for testing and debugging programs, or for the distribution of programs. Instead there is only one, truly integrated, environment for all these purposes. A distribution version of a BlackBox application can be created simply by stripping away all tools which are specific to the development process.
Such a customized BlackBox environment always has the basic capabilities of the BlackBox Component Framework's compound document architecture, and of the standard text and form subsystems. Furthermore, it constitutes a standard Windows application, where the (boot) application can be double-clicked, where documents can be dropped onto the application icon to open them, etc.
"Native" applications which are only developed under, but not based on, the BlackBox Component Builder can be created as well. For this purpose, a linker tool is provided. Normally, Component Pascal modules are linked and loaded dynamically, such that a separate linker is not strictly necessary. However, it is possible even for pure BlackBox applications to link or pack all or some of their modules together, in order to reduce the number of files to distribute. For further information about this topic, refer to the document Platform-SpecificIssues.
On-line documentation:
Text stretches which are blue and underlined are hyperlinks, and can be followed by clicking on them.
When working in the BlackBox Component Builder environment for the first time, the following may be helpful to remember: almost all modifications to BlackBox documents are undoable, making it quite safe to try out a feature. In general, multi-level undo/redo is available, i.e., not only one, but several commands can be undone; as many as memory permits.
An endless loop can be terminated with ctrl-break.
2 Installation
The installation requires a PC with an x86 and Windows XP/2003/Vista/7/8/10/11.
The resulting BlackBox directory contains several files and directories:
Files:
BlackBox.exe The BlackBox Component Framework boot application.
BlackBox.exe.manifest Manifest file for BlackBox.exe.
Remove this file if you want to use Windows XP style GUI controls.
Empty.odc Empty BlackBox Component Builder document.
unins000.dat Data file for BlackBox Component Builder Uninstall.
unins000.exe BlackBox Component Builder Uninstall.
Directories:
Com Direct-To-COM Compiler.
Comm Communications subsystem.
Cons Modules for console applications.
Ctl OLE Automation support.
Dev Development subsystem.
Docu On-line documentation not specific to a particular module or subsystem.
Form Form subsystem with the visual designer.
Obx Obx subsystem, a collection of examples.
Ole OLE compound document support.
Sql Sql subsystem for accessing relational databases.
Std A number of command packages available to the user.
System Core of the BlackBox Component Framework.
Text Text subsystem, with the standard document/program editor.
Win Interface modules for direct Windows API access.
Xhtml Exporter for text to HTML conversion.
3 Server installation
If several developers use BlackBox on the same machine(s), it becomes cumbersome to save one's work and clean up after the end of each session, so that the next developer gets a "clean" system again. It is even more cumbersome to start working with a copy that hasn't been cleaned up correctly by the previous user. To solve this problem, server support is available for BlackBox.
BlackBox can be installed and maintained on one central server, while developers use an arbitrary number of client workstations on a local-area network. Preferably, each developer has his or her own working directory on the server (account).
For the installation, follow these steps:
1) Install BlackBox in a directory on the server machine, using Setup.exe. The directory must be shared on the network but the access may be restricted to read only.
2) For each workstation / user, create a working directory (either on the server or on the client). The user should have read/write access to this directory. The directory may be empty.
3) For each workstation, create a shortcut with the following contents:
Command Line (Target): <BlackBoxDir>\BlackBox.exe /Use <WorkDir>
Working Directory (Start in): <WorkDir>
where <BlackBoxDir> stands for the full path name of the directory where BlackBox is installed (on the server), and <WorkDir> is the path of the working directory of the actual machine (on the client or on the server). The latter must not end with a backslash ("\"). Use double quotation marks to delimit path names that contain spaces.
Example:
Command Line (Target): "C:\Program Files\BlackBox\BlackBox.exe" /Use C:\BlackBox
Working Directory (Start in): C:\BlackBox
These features, originally introduced for situations where multiple users want to develop with BlackBox, can also be useful in a single-user environment. The idea is to have one directory with the original installation of BlackBox, and a separate directory for all the developer-specific files. If the user opens a file, it is first searched in his or her working directory. If it isn't found there, the corresponding file in the "server directory" is opened. When a file is saved, it is always saved in the working directory. This makes it easy to set up entirely separate projects simply by creating separate working directories for them. When an upgrade of BlackBox comes out, only the central "server directory" needs to be upgraded. If you use the server features in this way, without having multiple developers using the same installation simultaneously, then no special license is required.
4 Deinstallation
Go to the Control Panel, choose Add/Remove Programs. In the displayed list, locate the entry called BlackBox and select the Change/Remove button. Follow the instructions on the screen.
5 Document Windows, Tool Windows, Auxiliary Windows
There are three kinds of windows in BlackBox: document windows, tool windows, and auxiliary windows.
A document window may contain e.g. a text or a form layout, or any other kind of visual object ("view"). When the contents of a document window have been modified (made "dirty") and the user tries to close the window (or quit the application), the system asks whether it should save the document.
A tool window allows to invoke actions on some document window underneath it. Typically, tool windows are used for modeless dialog boxes. Tool windows look the same way as dialog boxes.
Auxiliary windows are used mainly to hold temporary data for information purposes, e.g., the output of a browser. The contents of an auxiliary window may be editable, but the system does not ask whether a modified auxiliary window should be stored, i.e., it is temporary in nature. The Log window is an example of an auxiliary window.
A document window is decorated with the BlackBox document icon, while an auxiliary window is decorated with the BlackBox application icon. A tool window is not decorated with an icon.
6 Document Size
The size of a document, or more exactly of its outermost ("root") view, can be updated in several ways. Its width, or independently its height, can be bound either to a fixed size, to the paper as defined in the PageSetup dialog box, or to the window's current size.
For example, text views by default have a width bound to the paper page size, and a height bound to the window size. Documentation texts are often bound to the current window size in both dimensions, so that they automatically resize with the window. Such bindings can be changed with the Tools->Document Size... dialog box.
7 Menu Configuration
The configurable menus can be inspected using Info->Menus. The displayed text can be edited, and the current menu configuration updated accordingly (Info->UpdateMenus). To make changes to the menus permanent, the menu text must be saved to disk. The file System/Rsrc/Menus contains the startup menu configuration, i.e., the text which is opened when Info->Menus is executed.
The menu text consists of a sequence of menu definitions, which themselves consist of sequences of menu items. An example is the following extract of a possible Dev menu definition:
MENU "Dev"
"Compile" "K" "DevCompiler.Compile" "TextCmds.FocusGuard"
"Compile Selection" "" "DevCompiler.CompileSelection" "TextCmds.SelectionGuard"
SEPARATOR
"Unmark Errors" "" "DevMarkers.UnmarkErrors" "TextCmds.FocusGuard"
"Next Error" "E" "DevMarkers.NextError" "TextCmds.FocusGuard"
"Toggle Error Mark" "" "DevMarkers.ToggleCurrent" "TextCmds.FocusGuard"
SEPARATOR
"Insert Commander" "Q" "DevCommanders.Deposit; StdCmds.PasteView" "StdCmds.PasteViewGuard"
"Execute" "" "DevDebug.Execute" "TextCmds.SelectionGuard"
"Unload" "" "DevDebug.Unload" "TextCmds.SelectionGuard"
END
Every menu has a name, in this case it is Dev. Optionally, the menu name can be followed by a menu type, e.g.,
MENU "Text" ("TextViews.View")
A typed menu is only installed in the menu bar as long as the current focus has a matching type, i.e., it is context-sensitive. The other menus are always available.
A menu's type is usually simply the name of a view type. This is only a convention, however. It guarantees that menu types are globally unique, so that no clashes occur.
There are two kinds of menu items: normal items and separators. A separator optically organizes a menu into different groups of items. Normal menu items consist of four strings: a label, a keyboard shortcut, an action command, and a guard command. The label is the string presented to the user in the menu.
An "&" character in the menu name or in a menu label indicates which character should be underlined. This character is used for operating the menu with the keyboard. If you want an "&" to appear, you should write "&&".
The keyboard shortcut, which may be empty, allows to associate a keyboard key to the menu item. The action string contains the command sequence which is activated when the menu item is executed. The guard string, which may be empty, contains a command which is called to determine whether the item is currently enabled or disabled, checked or unchecked, or to set up a current item name which overrides the normal name (e.g., to toggle between ShowXYZ and HideXYZ).
Note: the menu guard is executed for example when the user clicks in the menu bar. This causes the guard's module to become loaded, even if the user never invokes the corresponding command.
Note: if the guard's module cannot be loaded, the menu item remains disabled and the guard is not executed again (for performance reasons). If the module's code becomes available later, e.g., because its module was later compiled, the menu item will remain disabled. To force a re-evaluation of the guard, use the Dev->FlushResources command.
Note: the standard menu configuration uses all letters of the alphabet and the digit "0" as keyboard shortcuts. Digits "1" to "9" are not used. The assignment of keyboard shortcuts, like the whole menu configuration, can easily be adapted to specific needs by appropriately changing the menu text.
The following keyboard shortcuts can be specified in the keyboard shortcut string:
"A".."Z", "0".."9" ctrl + key
"*A".."*Z", "*0".."*9" shift + ctrl + key
"F1".."F12" function key
"^F1".."^F12" ctrl + function key
"*F1".."*F12" shift + function key
"*^F1".."*^F12" shift + ctrl + function key
Context menus (pop-up menus activated by the right mouse button) are specified by giving them the name "*" instead of a true name. At most one context menu may be untyped, all other context menus must be typed.
For example, just add the line
"Open &Module" "" "DevCmds.OpenModuleList" "TextCmds.SelectionGuard"
to the menu MENU "*" ("TextViews.View") in the file Text/Rsrc/Menus. This adds a (text-)context menu item for opening the sources of the module(s) whose name(s) is (are) selected.
It is possible to put all menu specifications in the menu text System/Rsrc/Menus. However, it is a better idea to keep the menu specifications that refer to a subsystem's commands in this subsystem's resource directory. For example, the Text menu could be specified in Text/Rsrc/Menus. In this case, System/Rsrc/Menus needs a so-called include statement that tells the menu configuration mechanism where to look for further menus:
INCLUDE "Text"
The explicit include statements allow to define the exact order in which menus appear in a menu bar. The command
INCLUDE "*"
includes all menus that have not been mentioned explicitly before (directly or via an include statement). It is a "catch all" for menus, and it is recommended to put it at the end of the System/Rsrc/Menus text. For example, a typical System/Rsrc/Menus text may look as follows:
INCLUDE "Dev"
INCLUDE "Text"
INCLUDE "Form"
INCLUDE "Sql"
INCLUDE "Obx"
INCLUDE "*"
Note: when you have edited a menu text execute the command Info->Update Menus for re-installing all menus, starting with the System/Rsrc/Menus as it is done when starting up the application.
A submenu is defined very much like a top-level menu except that its name must start with the character "$". In order to reference such a menu in a menu item, use the name of the submenu including the leading "$" as the action string. Menus can be nested at arbitray depth and it is also possible to reference a submenu multiply. The following example shows the structure of a large menu together with a submenu referenced as $submenu1:
MENU "Large Menu"
...
"Submenu 1" "" "$submenu1" ""
END
MENU "$submenu1"
...
END
Note: if you need a top-level menu name starting with "$" simply put the underlining indicator "&" in front of the name.
For more information see also modules StdMenuTool and StdCmds. The command package modules of all subsystems export commands that may be used in a menu. Consult the various modules' on-line documentation, e.g., Text/Docu/Cmds for module TextCmds.
8 String Resources
String resources are files which define a mapping between strings, e.g., the string "untitled" may be mapped to "sans titre". This is useful to prevent hard-wiring textual messages in the program code, in order to make later editing of these messages possible without requiring a recompilation. From a programmer's point of view, string translation is done in several procedures of module Dialog, e.g., Dialog.MapString. String resource files can be normal BlackBox text documents, which simply consist of the keyword STRINGS followed by a sequence of lines; each line contains a string (the key), a TAB, another string (to which the key is mapped), and a carriage return, e.g.,
STRINGS
untitled sans titre
open ouvre
close ferme
There can be one string resource file per subsystem (cf. Modules and Subsystems).
For example, a call of
Dialog.MapString("#Form:CntrlInstallFailed", resultString)
in a program maps the string "CntrlInstallFailed" according to the table in the Form/Rsrc/Strings file. In the English version, the mapping is "form controller installation failed". In a German version, "CntrlInstallFailed" might be mapped to "Der Form Controller konnte nicht installiert werden".
9 Standard Commands
In this section, the menu items of the standard menus File, Edit, Attributes, and Window(s) are described. For a menu item which is not permanently enabled, the condition for enabling it is specified. Often, such a guard command is one of the commands exported by module StdCmds.
The standard menu items can be configured in the same way as all other menu items, by editing the System/Rsrc/Menus document. Most standard menu items are calls to a command exported by module StdCmds.
9.1 File Menu
New
Command: StdCmds.New
Guard:
Opens a new document window containing an empty text view.
Open...
Command: StdCmds.OpenDialog
Guard:
Opens the standard file Open dialog box.
Open Stationery...
Command: StdCmds.OpenStationery
Guard:
Opens the standard file Open dialog box, through which a stationery (i.e., template) file can be opened.
Save
Command: StdCmds.SaveDialog
Guard: StdCmds.SaveGuard
Saves the front window's contents to a file. If the window's contents has not yet been saved to a file, the user is asked for a file name.
Save As...
Command: StdCmds.SaveAsDialog
Guard: StdCmds.WindowGuard
Saves the front window's contents to a file. The user is always asked for a file name. After the command, you continue working with the new file.
Save Copy As...
Command: StdCmds.SaveCopyAsDialog
Guard: StdCmds.WindowGuard
Saves the front window's contents to a file. The user is always asked for a file name. After the command, you continue working with the old file.
Close
Command: StdCmds.CloseTopDialog
Guard: StdCmds.WindowGuard
Closes the front window. If the window is a primary document window and its contents has been modified ("dirty"), the user is asked whether to save the window's contents in a file.
Page Setup...
Command: StdDialog.OpenPageSetup
Guard: StdCmds.WindowGuard
Asks the user for the page information of the front window's document, for later printing.
In addition to the data which is specific to the current printer driver, the margins can be set (the distances between the paper's edges and the printed area), and a standard header can be switched on or off. The standard header consists of a page number and a date.
Print...
Command: StdCmds.Print
Guard: StdCmds.PrintGuard
Asks the user for printing information, and then creates a print-out accordingly.
Exit
Command: StdCmds.Exit
Guard:
Terminates the application. If windows with modified contents are open, the user is asked whether to save them in files.
9.2 Edit Menu
Undo [...]
Command: StdCmds.Undo
Guard: StdCmds.UndoGuard
Reverses the effect of the most recent modifying operation. Usually, the kind of operation is given behind the word "Undo", e.g., UndoPaste. Undo can be activated several times, until the opening, creation, or most recent saving of the document. Under low-memory conditions, the number of undoable operations may become reduced.
Redo [...]
Command: StdCmds.Redo
Guard: StdCmds.RedoGuard
Restores the effect of the most recently undone operation. Usually, the kind of operation is given behind the word "Redo", e.g., RedoPaste.
Cut
Command: StdCmds.Cut
Guard: StdCmds.CutGuard
Deletes the selection and puts a copy into the clipboard.
Copy
Command: StdCmds.Copy
Guard: StdCmds.CopyGuard
Puts a copy of the selection into the clipboard.
Paste
Command: StdCmds.Paste
Guard: StdCmds.PasteGuard
Pastes a copy of the clipboard's contents at the caret position. If the focus view contains the same kind of data as the clipboard, the data is inserted directly into the focus view's data. Otherwise, and if the focus view is a container, a copy of the whole view containing the clipboard data is inserted into the focus view's data.
Delete
Command: StdCmds.Clear
Guard: StdCmds.CutGuard
Deletes the selection, without putting it into the clipboard.
Copy Properties
Command: StdCommands.CopyProp
Guard: StdCmds.SelectionGuard
Copies the properties of the current selection. This command has no effect on the clipboard contents.
Paste Properties
Command: StdCommands.PasteProp
Guard: StdCmds.SelectionGuard
Pastes the properties that were copied most recently (see CopyProperties).
Paste Object
Command: StdCmds.PasteObject
Guard: StdCmds.PasteObjectGuard
Pastes a copy of the clipboard's contents at the caret position. If the focus view is a container, a copy of the whole view containing the clipboard data is inserted into the focus view's data.
Paste Special...
Command: OleClient.PasteSpecial
Guard: StdCmds.PasteObjectGuard
Opens a dialog box, which allows to choose the data type of the view in the clipboard, if the view supports several possible types.
Paste to Window
Command: StdCmds.PasteToWindow
Guard: StdCmds.PasteToWindowGuard
Opens a copy of the clipboard's contents into a new document window.
Insert Object...
Command: OleClient.PasteSpecial
Guard: StdCmds.PasteViewGuard
Opens a dialog box which shows all installed OLE servers. When one of them is chosen, an object of this type is allocated and inserted into the front window's contents.
Object Properties...
Command: StdCmds.ShowProp
Guard: StdCmds.ShowPropGuard
Opens an appropriate property sheet for the selected view.
Object
Command: StdCmds.ObjectMenu
Guard: StdCmds.ObjectMenuGuard
Shows a submenu with commands for the selected view. These commands, which are determined by the selected view itself, are called "verbs". Usually, the first two verbs are Edit and Open:
Edit
Makes the selected view the current focus view.
Open
Opens a new window showing a second view to the selected view.
+ other verbs defined by the selected view.
Select Document
Command: StdCmds.SelectDocument
Guard: StdCmds.WindowGuard
Selects the root view of the front window's document as a singleton. Note the difference to SelectAll, which selects the latter's contents instead (or rather the contents of whatever view is currently the focus).
Select All
Command: StdCmds.SelectAll
Guard: StdCmds.SelectAllGuard
Selects the whole focus view's contents.
Select Next Object
Command: StdCmds.SelectNextView
Guard: StdCmds.ContainerGuard
If a view in the container is selected: select the next view.
If the last view is selected or there is no singleton selection: select the first view.
Preferences...
Command: StdDialog.OpenPrefDialog
Guard:
Allows to define several parameters: whether TrueType metrics are used (for best printing results), whether screen updates are performed during scrolling, the font used as default for texts, the font used as default for controls, and whether the status bar is visible or not.
9.3 Attributes Menu
Available: style/size/color-carrying selection or caret in focus view in front window
The following commands work on the selection; if there is no selection, the caret's current attributes are affected instead. These attributes are used as defaults when typing in new text.
For colors, there is a system-wide color (default color) which can be modified by the user. The default color can be changes using an operating-system utility. Everything drawn in the default color will be updated accordingly.
Regular
Command: StdCmds.Plain
Guard: StdCmds.PlainGuard
Checked: if text to the left and to the right of the caret is plain, or if selection is homogeneously plain (i.e., non-bold, non-italicized, non-underlined, and non-striked-out).
Removes all style attributes (bold, italic, underline, strikeout) from the selection.
Bold
Command: StdCmds.Bold
Guard: StdCmds.BoldGuard
Checked: if text to the left and to the right of the caret is bold, or if selection is homogeneously bold.
If the selection is homogeneously bold, it is made non-bold, otherwise it is made bold.
Italic
Command: StdCmds.Italic
Guard: StdCmds.ItalicGuard
Checked: if text to the left and to the right of the caret is italic, or if selection is homogeneously italic.
If the selection is homogeneously italic, it is made non-italic, otherwise it is made italic.
Underline
Command: StdCmds.Underline
Guard: StdCmds.UnderlineGuard
Checked: if text to the left and to the right of the caret is underlined, or if selection is homogeneously underlined.
If the selection is homogeneously underlined, it is made non-underlined, otherwise it is made underlined.
8 point, 9, 10, 12, 16, 20, 24
Command: StdCmds.Size(size)
Guard: StdCmds.SizeGuard(size)
Checked: if text to the left and to the right of the caret has the given size, or if the selection is homogeneously of the given size.
The selection is set to the given point size.
Size...
Command: StdCmds.InitSizeDialog; StdCmds.OpenToolDialog('Std/Rsrc/Cmds', 'Size')
Guard: StdCmds.SizeGuard(-1)
Checked: if none of the other sizes apply
A tool dialog box is opened, which allows to enter a particular font size in points, and then to set the selection to this size.
Default Color
Command: StdCmds.Color(1000000H)
Guard: StdCmds.ColorGuard(1000000H)
Checked: if text to the left and to the right of the caret has the default color, or if the selection is homogeneously of the default color
Sets the selection's color to the default color.
Black
Command: StdCmds.Color(0000000H)
Guard: StdCmds.ColorGuard(0000000H)
Checked: if text to the left and to the right of the caret is black, or if the selection is homogeneously black
Sets the selection's color to black.
Red
Command: StdCmds.Color(00000FFH)
Guard: StdCmds.ColorGuard(00000FFH)
Checked: if text to the left and to the right of the caret is red, or if the selection is homogeneously red
Sets the selection's color to red.
Green
Command: StdCmds.Color(000AF00H)
Guard: StdCmds.ColorGuard(000AF00H)
Checked: if text to the left and to the right of the caret is green, or if the selection is homogeneously green
Sets the selection's color to green.
Blue
Command: StdCmds.Color(0FF0000H)
Guard: StdCmds.ColorGuard(0FF0000H)
Checked: if text to the left and to the right of the caret is blue, or if the selection is homogeneously blue
Sets the selection's color to blue.
Color...
Command: StdDialog.ColorDialog
Guard: StdCmds.ColorGuard(-1)
Checked: if none of the other colors apply
Asks the user for a color, to which it then sets the selection.
Default Font
Command: StdCmds.DefaultFont
Guard: StdCmds.DefaultFontGuard
Sets the selection to the default font.
Font...
Command: StdDialog.FontDialog
Guard: StdCmds.TypefaceGuard
Opens the standard font dialog box and applies the chosen font attributes to the selection.
Typeface...
Command: StdDialog.TypefaceDialog
Guard: StdCmds.TypefaceGuard
Opens the standard font dialog box and applies the chosen font attributes to the selection. In contrast to the Font... command, only the typeface (the name of the font) is changed, but not the other attributes like size or weight (bold/normal).
9.4 Window Menu (for MDI version)
New Window
Command: StdCmds.NewWindow
Guard: StdCmds.WindowGuard
Opens a new window on the same document as the front window. The window is of the same kind as the front window. The window's title is put between "<" and ">" parentheses.
Cascade
Command: MdiMenus.Cascade
Guard: StdCmds.WindowGuard
Arrange document windows in an overlapping fashion.
Tile Horizontal
Command: MdiMenus.TileHorizontal
Guard: StdCmds.WindowGuard
Arrange windows from left to right in a non-overlapping fashion. This command does not affect non-resizable windows, and it ignores some windows when there are too many open windows for a reasonable tiling. The front window becomes the left-most window.
Tile Vertical
Command: MdiMenus.TileVertical
Guard: StdCmds.WindowGuard
Arrange windows from top to bottom in a non-overlapping fashion. This command does not affect non-resizable windows, and it ignores some windows when there are too many open windows for a reasonable tiling. The front window becomes the top-most window.
Arrange Icons
Command: MdiMenus.ArrangeIcons
Guard: StdCmds.WindowGuard
Arrange icons (minimized windows) at the bottom of the application window.
{window}
Command: MdiMenus.WindowList
Guard:
Here the list of open windows is appended. The front window is checked.
10 Custom Commands
Not all commands are visible in the default configuration of the menus. The following is a list of modules from the Std subsystem. These modules contain many useful commands but not all of them appear in the menus. For more information about the commands in the modules, please consult the corresponding module documentation.
StdClocks analog clock views
StdCmds cmds of std menus
StdCoder ASCII coder
StdDebug minimal debugger
StdFolds fold views
StdHeaders headers / footers
StdLinks hyperlink views
StdLog standard output
StdMenuTool menu tool
StdStamps date stamp views
StdTables table controls
StdTabViews tabbed folder views
StdViewSizer set size of a view | System/Docu/User-Man.odc |
Utf
DEFINITION Utf;
PROCEDURE StringToUtf8 (IN in: ARRAY OF CHAR;
OUT out: ARRAY OF SHORTCHAR; OUT res: INTEGER);
PROCEDURE Utf8ToString (IN in: ARRAY OF SHORTCHAR;
OUT out: ARRAY OF CHAR; OUT res: INTEGER);
END Utf.
Module Utf providing conversion for Utf8 format. | System/Docu/Utf.odc |
Views
DEFINITION Views;
IMPORT Files, Fonts, Stores, Ports, Converters, Models;
CONST
undefined = 0;
transparent = 0FF000000H;
deep = FALSE; shallow = TRUE;
keepFrames = FALSE; rebuildFrames = TRUE;
dontAsk = FALSE; ask = TRUE;
clean = 0; notUndoable = 1; invisible = 2;
TYPE
View = POINTER TO ABSTRACT RECORD (Stores.Store)
context-: Models.Context;
(v: View) InitContext (context: Models.Context), NEW, EXTENSIBLE;
(v: View) GetBackground (VAR color: Ports.Color), NEW, EMPTY;
(v: View) Neutralize, NEW, EMPTY;
(v: View) ConsiderFocusRequestBy- (view: View), NEW, EMPTY;
(v: View) GetNewFrame (VAR frame: Frame), NEW, EMPTY;
(v: View) Restore (f: Frame; l, t, r, b: INTEGER), NEW, ABSTRACT;
(v: View) RestoreMarks (f: Frame; l, t, r, b: INTEGER), NEW, EMPTY;
(v: View) HandleViewMsg- (f: Frame; VAR msg: Message), NEW, EMPTY;
(v: View) HandleCtrlMsg (f: Frame; VAR msg: CtrlMessage; VAR focus: View), NEW, EMPTY;
(v: View) HandlePropMsg- (VAR p: PropMessage), NEW, EMPTY;
(v: View) HandleModelMsg- (VAR msg: Models.Message), NEW, EMPTY;
(v: View) CopyFrom- (source: View);
(v: View) CopyFromSimpleView- (source: View), NEW, EMPTY;
(v: View) CopyFromModelView- (source: View; model: Models.Model), NEW, EMPTY;
(v: View) ThisModel (): Models.Model, NEW, EXTENSIBLE
END;
Alien = POINTER TO LIMITED RECORD (View)
store-: Stores.Alien
END;
Message = ABSTRACT RECORD
view-: View
END;
NotifyMsg = EXTENSIBLE RECORD (Message)
id0, id1: INTEGER;
opts: SET
END;
Frame = POINTER TO ABSTRACT RECORD (Ports.Frame)
l-, t-, r-, b-: INTEGER;
view-: View;
front-, mark-: BOOLEAN;
(f: Frame) Close, NEW, EMPTY
END;
RootFrame = POINTER TO RECORD (Frame)
flags-: SET
END;
PropMessage = ABSTRACT RECORD END;
CtrlMessage = ABSTRACT RECORD END;
CtrlMsgHandler = PROCEDURE (op: INTEGER; f, g: Frame; VAR msg: CtrlMessage;
VAR mark, front, req: BOOLEAN);
Title = ARRAY 64 OF CHAR;
UpdateCachesMsg = EXTENSIBLE RECORD (Message) END;
ScrollClassMsg = RECORD (Message)
allowBitmapScrolling: BOOLEAN
END;
VAR HandleCtrlMsg-: CtrlMsgHandler;
PROCEDURE Broadcast (v: View; VAR msg: Message);
PROCEDURE Domaincast (domain: Stores.Domain; VAR msg: Message);
PROCEDURE Omnicast (VAR msg: ANYREC);
PROCEDURE HandlePropMsg (v: View; VAR msg: PropMessage);
PROCEDURE Era (v: View): INTEGER;
PROCEDURE BeginModification (type: INTEGER; v: View);
PROCEDURE EndModification (type: INTEGER; v: View);
PROCEDURE BeginScript (v: View; name: Stores.OpName; OUT script: Stores.Operation);
PROCEDURE EndScript (v: View; script: Stores.Operation);
PROCEDURE Do (v: View; name: Stores.OpName; op: Stores.Operation);
PROCEDURE LastOp (v: View): Stores.Operation;
PROCEDURE Bunch (v: View);
PROCEDURE StopBunching (v: View);
PROCEDURE ForwardCtrlMsg (f: Frame; VAR msg: CtrlMessage);
PROCEDURE Update (v: View; rebuild: BOOLEAN);
PROCEDURE UpdateIn (v: View; l, t, r, b: INTEGER; rebuild: BOOLEAN);
PROCEDURE ReadView (VAR rd: Stores.Reader; OUT v: View);
PROCEDURE WriteView (VAR wr: Stores.Writer; v: View);
PROCEDURE CopyOf (v: View; shallow: BOOLEAN): View;
PROCEDURE CopyWithNewModel (v: View; m: Models.Model): View;
PROCEDURE ReadFont (VAR rd: Stores.Reader; OUT f: Fonts.Font);
PROCEDURE WriteFont (VAR wr: Stores.Writer; f: Fonts.Font);
PROCEDURE IsPrinterFrame (f: Frame): BOOLEAN;
PROCEDURE InstallFrame (host: Frame; view: View; x, y, level: INTEGER; focus: BOOLEAN);
PROCEDURE ThisFrame (host: Frame; view: View): Frame;
PROCEDURE FrameAt (host: Frame, x, y: INTEGER): Frame;
PROCEDURE Old (ask: BOOLEAN; VAR loc: Files.Locator; VAR name: Files.Name;
VAR conv: Converters.Converter): View;
PROCEDURE OldView (loc: Files.Locator; name: Files.Name): View;
PROCEDURE Register (view: View; ask: BOOLEAN; VAR loc: Files.Locator; VAR name: Files.Name;
VAR conv: Converters.Converter; OUT res: INTEGER);
PROCEDURE RegisterView (view: View; loc: Files.Locator; name: Files.Name);
PROCEDURE Open (view: View; loc: Files.Locator; name: Files.Name; conv: Converters.Converter);
PROCEDURE OpenView (view: View);
PROCEDURE OpenAux (view: View; title: Title);
PROCEDURE Deposit (view: View);
PROCEDURE RestoreDomain (domain: Stores.Domain);
PROCEDURE Scroll (v: View; dx, dy: INTEGER);
PROCEDURE SetDir (d: Directory);
PROCEDURE MarkBorders (root: RootFrame);
PROCEDURE MarkBorder (host: Frame; v: View; l, t, r, b: INTEGER);
PROCEDURE Fetch (OUT view: View);
PROCEDURE Available (): INTEGER;
PROCEDURE ClearQueue;
PROCEDURE RemoveFrame (host, f: Frame);
PROCEDURE RemoveFrames (host: Frame; l, t, r, b: INTEGER);
PROCEDURE BroadcastModelMsg (f: Frame; VAR msg: Models.Message);
PROCEDURE BroadcastViewMsg (f: Frame; VAR msg: Message);
PROCEDURE HandleCtrlMsg (op: INTEGER; f, g: Frame; VAR msg: CtrlMessage;
VAR target, front: BOOLEAN);
PROCEDURE SetRoot (root: RootFrame; view: View; front: BOOLEAN; flags: SET);
PROCEDURE AdaptRoot (root: RootFrame);
PROCEDURE RootOf (f: Frame): RootFrame;
PROCEDURE HostOf (f: Frame): Frame;
PROCEDURE UpdateRoot (root: RootFrame; l, t, r, b: INTEGER; rebuild: BOOLEAN);
PROCEDURE RestoreRoot (root: RootFrame; l, t, r, b: INTEGER);
PROCEDURE ValidateRoot (root: RootFrame);
PROCEDURE InitCtrl (p: CtrlMsgHandler);
PROCEDURE IsInvalid (v: View): BOOLEAN;
PROCEDURE RevalidateView (v: View);
END Views.
Figure 1. Model-View-Controller Separation
A view is a rectangular display object which provides visual presentation of data. Views are storable, and may be embedded recursively.
A view often contains a Models.Model which represents some data, and sometimes a Controllers.Controller which provides interaction of the view with the user. There may be several views for each model simultaneously, but at most one controller per view.
If several views share the same model, every change of the model must cause all its views to update their contents accordingly. Module Models provides a messaging mechanism through which visible views can be notified of model modifications, and thus re-establish the display's consistency.
It is possible to implement views which do not contain a model. These views cannot use the messaging mechanism of module Models. Therefore, such views usually don't share data and are independent from each other. Typically, these views are simple controls which implement a very specific functionality that relies on cooperation with the control's container, e.g., a form view container.
It is also possible to implement views which do not contain a controller. This is possible because all messages to a controller are sent to the controller's view, not directly to the controller itself. Thus a view can decide whether to handle these messages itself, or whether to forward them to a controller. Simple views don't contain a controller.
Because a view is an extension of a Stores.Store, it can be embedded in a model, such that it is externalized and internalized as part of this model. This makes it possible to realize compound documents, which contain views containing views containing views...
When a view needs to draw to the screen (or printer), it can do this through a frame. A frame is an access path (a mapper) to the port on which the view is presented. Since several windows may show the same document with its hierarchy of views, one and the same view may be visible several times simultaneously. This results in several frames for the same view simultaneously, and therefore in the need to update a view change in several frames.
In general, the reaction to a model modification happens in two steps. In the first step, the nature of the model's change is broadcast to all visible views, using the model broadcast mechanism of module Models. This causes every visible view to update its own state, if necessary. In the second step, every view which has changed its state uses the view broadcast mechanism of module Views, to notify all frames for this view. In fact, since frames are usually not extended, the view itself performs the update for each of its frames. This second broadcast step is normally invisible to the programmer, because he merely needs to determine the view's region which needs updating. The actual update of this region in each of its frames is done by the framework.
A view may behave differently depending on the model in which it is embedded, i.e., depending on its context. For this purpose, a variable of type Models.Context is carried by a view, as a link to its container.
For every user interaction, e.g., the press of a key, a view must be defined which should handle this interaction, i.e., a so-called focus. BlackBox doesn't know which view is the current focus. BlackBox only provides a strategy which decides which window is focus. Since a window may contain a hierarchy of views, a view which has received an interaction message a controller message must decide on its own whether it is the focus itself, or whether it contains another view which might be focus instead. In the former case, it handles the messages itself, in the latter case, it forwards the message to this view.
Every window contains a tree of frames. This tree corresponds to the visible views of the window. Every view may only draw inside its own borders, drawing outside of its borders must be prevented. Frames provide the necessary clipping facility. The management of the frame tree and of clipping is largely transparent to the view programmer.
Examples:
ObxPatternsdocu views without models
ObxCalcdocu
ObxOmosidocu
ObxButtonsdocu
ObxLinesdocu views with models
ObxGraphsdocu
ObxBlackBoxdocu
ObxWrappersdocu wrapper
ObxTwinsdocu special container
Formsubsystemmap general container
CONST undefined
This value can be used to denote the width or height of a view as currently undefined.
CONST transparent
A view may be asked for its background color. In this case, the view may either return a Ports.Color value, or the value transparent. The latter value means that the view's container must find another source for a background color, i.e., for the color which is used to erase the background before the foreground is restored (use Update or UpdateIn to restore a view's area in all its frames). Transparency is useful if several views are superimposed on each other, which naturally occurs in a compound document.
CONST deep, shallow
There are two ways that a view can be copied: deep or shallow. This distinction arises from the fact that a view can carry two types of data: data that it owns completely, and data that it can share with other views. The most important example of the latter is the view's model, if it has one.
When a view is copied, it must be decided whether shareable state should actually be shared with the copy (shallow copy), or whether an independent copy of this state should be created (deep copy). These constants can be passed to a parameter of the CopyModel or the CopyOf procedure.
CONST keepFrames, rebuildFrames
When part of a view's area must be restored (in every frame on it), there are two possible kinds of restoration: a frame may be kept as it is and only its contents be redrawn, or it may be rebuilt, i.e., newly allocated, set up, and redrawn. The latter is less efficient than the former, and only necessary if the following holds: the view must be a container, and the operation which changed the view might have modified a subview's bounding box (and thus invalidated its subframes). In the rare case where frames are extended, it could sometimes also become necessary to rebuild the frames on a view.
CONST dontAsk, ask
Theses constants may be passed to the Old and Register procedures. They determine whether these procedures allow the user to interactively change loc, name, or conv used for the operation.
CONST clean
Possible value for parameter type of BeginModification/EndModification. Indicates an operation that does not make its document "dirty". Example: modifying a text in a way that is considered as "unimportant", such as collapsing or expanding a text fold (-> StdFolds).
CONST invisible
Possible value for parameter type of BeginModification/EndModification. Indicates an operation that "folds together" with the previous operation, i.e., does not itself become visible in the Undo/Redo menu items. Invisible operations can be used for operations that by themselves may not be expected to appear in an Undo/Redo menu. Example: setting options in a controller. When executing a Redo operation, after a (visible) operation, all invisible operations are executed. When executing an Undo operation, first all invisible operations are undone and afterwards the visible operations.
CONST notUndoable
Possible value for parameter type of BeginModification/EndModification. Indicates an operation that cannot be reversed ("undone"). This is important for operations where the undo feature would be too expensive.
TYPE View (Stores.Store)
ABSTRACT
A view is a storable object which may contain a model, possibly maintains a scroll position in this model, and generates frames for its display when needed. A view can be regarded as a special editor, and advanced views (containers) are able to contain arbitrary other views as part of their editable data (i.e., of their model).
Views are allocated by specific view directories, e.g., TextViews.dir.
Views are used by commands which manipulate the visual presentation of data.
Views are extended for new kinds of data to be presented visually. Besides the implementation of new commands, the implementation of new view extensions is the central activity of BlackBox programming.
Restore is the only procedure which necessarily must be implemented in an extension of View. It is called by the framework when the view must be redrawn on a screen or on a printer.
Internalize, Externalize must be implemented in views which contain persistent mutable data. In this case, a view without model should also implement the CopyFromSimpleView procedure, while a view with a model should implement the CopyFromModelView procedure instead. Internalize / Externalize is called by the framework when the user opens / saves a document. CopyFromSimpleView / CopyFromModelView should also be implemented by views with mutable state that should be printable. The reason is that the framework makes a shallow copy of a view that is being printed, in order to avoid the original view to be changed by pagination, scrolling, or similar modifications that may be performed during printing.
ThisModel must be implemented in views which contain models. It is called by the framework to find out whether this view should receive model messages for this model.
ConsiderFocusRequestBy should be implemented in container views. It can be called by an embedded view that wants to become focus itself.
GetBackground must be implemented in views which have non-transparent background colors. It is called by the framework as part of the restore mechanism.
RestoreMarks and Neutralize must be implemented in views which may contain marks like selections or carets. RestoreMarks is called by the framework as part of the restore mechanism, after its corresponding Restore has been called.
HandleModelMsg must be implemented in views which support partial view updates after a model change. It is called by the framework in order to deliver notifications about changes to the view's model.
HandleViewMsg must be implemented in views which support marks, or which don't use the delayed update mechanism for some other reason. It is called by the framework to deliver view messages via all currently visible paths (i.e., via frames) to this view.
HandleCtrlMsg must be implemented in editable views. It is called by the surrounding container if it considers the receiving view to be the current focus.
HandlePropMsg must be implemented in views which support preferences and properties (-> Properties). It is called by the surrounding container to find out about the way that the embedded view would like to be treated.
InitContext and GetNewFrame are usually not extended.
A view's domain is the same as the domain of its container and of all embedded views and models. The domain identifies the document in which the view, its context, and its contents are embedded. The view's PropagateDomain procedure propagates the assigned domain to its model, if there is one.
context-: Models.Context
The view's context links the view to its container. Communication between view and container occurs via the context. A context belongs (and is managed by) the container, but carried by the view.
PROCEDURE (v: View) InitContext (context: Models.Context)
NEW, EXTENSIBLE
Assigns context to v.context.
InitContext is called by v's container, when v is being embedded in it (which means that the container creates a suitable context for v).
InitContext is usually not extended, only view wrappers need to extend it in order to forward a context.
Pre
context # NIL 21
v.context = NIL OR v.context = context 22
Post
v.context = context
PROCEDURE (v: View) GetBackground (VAR color: Ports.Color)
NEW, EMPTY
This procedure may return a background color of the view. Upon input, color = transparent.
GetBackground is called internally.
GetBackground is implemented if a view needs a non-transparent background color.
PROCEDURE (v: View) Neutralize
NEW, EMPTY
This procedure should remove all marks that a view carries.
Neutralize is called by the framework.
Neutralize is implemented by views which may contain marks.
PROCEDURE (v: View) ConsiderFocusRequestBy- (view: View)
NEW, EMPTY
A subview of v may request to become focus. Its container may or may not grant this request.
ConsiderFocusRequestBy is called by a subview.
ConsiderFocusRequestBy is implemented in a container view.
PROCEDURE (v: View) GetNewFrame (VAR f: Frame)
NEW, EMPTY
The procedure may generate a frame for the view. Upon entry, f = NIL.
This procedure is rarely implemented (mainly in native controls).
GetNewFrame is called internally.
GetNewFrame is implemented in views which need specialized extended view frames.
PROCEDURE (v: View) Restore (f: Frame; l, t, r, b: INTEGER)
NEW, ABSTRACT
A view implementation must implement this procedure, to draw all or part of its contents. For drawing, a frame is passed to the view, whose drawing procedures can be called in the Restore procedure.
Only the rectangle (l, t, r, b), which is given in universal coordinates, needs to be restored. Since drawing is clipped to this rectangle automatically, it is sometimes the best solution to simply restore the whole view's contents. However, often it is significantly faster to restore only the contents of the rectangle.
If necessary, the size of the view can be determined by calling v.context.GetSize. Consistent with the frame drawing operations (as described in the documentation of module Ports), the origin for drawing is the view's top-left corner, with positive x-values to the right, and positive y-values to the bottom.
For drawing at screen pixel resolutions without rounding errors, the frame's f.dot field is useful. The value f.unit can be inspected to obtain the size of a pixel in universal coordinates (see the documentation of module Fonts). For example, this allows to adapt to the different resolutions during screen display and during printing.
If drawing should be done in different ways depending on whether the view is being displayed on screen or whether it is being printed, then Views.IsPrinterFrame(f) can be used to determine whether it is being printed or displayed on screen.
Restore is called internally by the framework, whenever some part of the view becomes newly visible, or after someone has called Views.Update or Views.UpdateIn for this view. Restore is rarely called directly by a view itself. No assumptions are allowed of when Restore is called, how often, in which order, etc. Restore should simply draw everything within the given rectangle, it must not assume that something is still on screen from the last time it was called.
Since views may be nested, a container must be drawn before the views contained in it are draw. The framework calls Restore methods in the correct order, from the "back" to the "front". An embedded view thus lies always "above" its container. As an exception of the back-to-front drawing rule, BlackBox allows to draw marks (in particular: selections) of a container on top of the contained views. This can be achieved by moving the restoration of marks to the view's RestoreMarks method. This is only necessary for view containers, however.
Restore must be implemented in every view extension. It is the only view procedure whose implementation is mandatory, not optional.
Pre
f # NIL 20
f.view = v 21
v.context # NIL 22
0 <= f.l <= l <= r <= f.r <= width of view 23
0 <= f.t <= t <= b <= f.b <= height of view 24
PROCEDURE (v: View) RestoreMarks (f: Frame; l, t, r, b: INTEGER)
NEW, EMPTY
Restore all marks (in particular any selection) of view v via frame f. Only the rectangle (l, t, r, b), which is given in universal coordinates, needs to be restored. A frame contains the method MarkRect which is provided particularly for the drawing of marks.
RestoreMarks is called locally by the framework as part of the restore mechanism, after its corresponding Restore has been called.
RestoreMarks is implemented in views which support any kind of marks, e.g., selection, caret, or focus marks.
Pre
f # NIL 20
f.view = v 21
v.context # NIL 22
PROCEDURE (v: View) HandleViewMsg- (f: Frame; VAR msg: Message)
NEW, EMPTY
Message handler for view messages.
HandleViewMsg is called locally.
HandleViewMsg is implemented in views which support marks (e.g., selection marks), and in views which support different frame contents for the same view (a rare case).
Pre
f # NIL guaranteed
f.view = v guaranteed
v.context # NIL guaranteed
msg.view = v OR msg.view = NIL guaranteed
PROCEDURE (v: View) HandleCtrlMsg (f: Frame; VAR msg: CtrlMessage; VAR focus: View)
NEW, EMPTY
Message handler for messages to the focus.
HandleCtrlMsg is called by the view's container, indirectly via ForwardCtrlMsg. If a controller message needs to be forwarded to an embedded view, set focus to this view. The framework will perform forwarding after HandleCtrlMsg returns. In the rare cases where this is not an adequate solution, ForwardCtrlMsg must be used; the embedded view's HandleCtrlMsg must never be called directly. After ForwardCtrlMsg, focus must be set to NIL, so that the message is not forwarded twice.
During mouse tracking (i.e., when handling a Controllers.TrackMsg), drawing should only occur in frame f. This also implies that during mouse tracking, no update messages should be sent. If necessary, an update model message should be sent after the mouse button was released.
HandleCtrlMsg is extended in editable views.
Pre
f # NIL 20
f.view = v 21
v.context # NIL 22
focus = NIL 23
PROCEDURE (v: View) HandlePropMsg- (VAR p: PropMessage)
NEW, EMPTY
Property messages can be passed to a view via its HandlePropMsg procedure.
HandlePropMsg is called by the view's container. The global procedure HandlePropMsg (see further below) is used to send a property message to a view.
HandlePropMsg is called locally.
HandlePropMsg is implemented in views which support properties (not described here).
PROCEDURE (v: View) HandleModelMsg- (VAR msg: Models.Message)
NEW, EMPTY
Message handler for model messages.
HandleModelMsg is called locally.
HandleModelMsg is implemented in views with a model which support updates after a model modification.
Pre
msg.model # NIL 20
msg.model = v.ThisModel() 21
PROCEDURE (v: View) CopyFrom- (source: Stores.Store)
This method has become final. It calls the CopyFromSimpleView or CopyFromModelView, respectively. It checks that these procedures don't change the view context.
PROCEDURE (v: View) CopyFromSimpleView- (source: View)
NEW, EMPTY
The procedure should be implemented in views which have no model. It should copy view-specific data from source. CopyFromSimpleView is called as part of module Views' copy operations (CopyOf, CopyWithNewModel).
Note: it is not permissible to implement both CopyFromModelView and CopyFromSimpleView simultaneously!
Pre
source # NIL guaranteed
TYP(source) = TYP(v) guaranteed
CopyFromModelView must not be implemented 20
PROCEDURE (v: View) CopyFromModelView- (source: View; model: Models.Model)
NEW, EMPTY
The procedure must be implemented in views which have a model, and only in them. The major exception where a view without model may still implement CopyFromModelView instead of CopyFromSimpleView are wrapper views: using CopyFromModelView they can be implemented flexibly enough to wrap arbitrary views, whether they have models or not.
The procedure should initialize its model to model. If necessary, it can copy view-specific data from source. CopyFromModelView is called as part of module Views' copy operations (CopyOf, CopyWithNewModel).
Note that if model = source.ThisModel(), then a shallow copy is being performed.
Note: it is not permissible to implement both CopyFromModelView and CopyFromSimpleView simultaneously!
Pre
source # NIL guaranteed
TYP(source) = TYP(v) guaranteed
model # NIL => TYP(model) = TYP(source.ThisModel()) guaranteed
CopyFromSimpleView must not be implemented 20
Post
v.ThisModel() = model
PROCEDURE (v: View) ThisModel (): Models.Model
NEW, EXTENSIBLE
Returns the view's model, if it has one. The default implementation returns NIL.
ThisModel is called internally.
ThisModel is replaced by views which contain models. A view with a model must always return the same model, i.e., the one which was assigned to it upon initialization.
TYPE Alien (View)
LIMITED
If the internalization of a view fails, either because its implementing module(s) cannot be loaded, or because it cancelled internalization (e.g., because of a version conflict), an alien is produced instead (this happens in procedure ReadView). An alien is immutable and doesn't contain a model. It contains an alien store which can be inspected to determine the type of the alien, and the cause for it to be an alien.
Every container must be able to operate even if one or several of its embedded views are aliens. If the view's model is an alien store, the view may turn itself into an alien.
Aliens are allocated in ReadView.
store-: Stores.Alien store # NIL
The alien store which has been generated by a Stores.Reader during internalization of the view.
TYPE Message
ABSTRACT
Base type of all view messages. Such messages are sent when a view's state has changed, in order to render the display consistent again. There may be several frames displaying the same view, such that every one of them needs to be updated.
Messages are sent by views when their states have changed and if they cannot use BlackBox's delayed update mechanism. This is true mainly when drawing marks, e.g., selection marks.
Messages are extended to indicate what kind of update should be performed on a frame.
view-: View
The view which has changed. If view = NIL, all frames with the same domain are notified of the view change.
TYPE NotifyMsg (Message)
EXTENSIBLE
This message notifies all visible views about a change in an interactor's state (-> Dialog).
NotifyMsg is sent by the interactor procedures Update and UpdateList in module Dialog.
NotifyMsg is never extended.
NotifyMsg is sent only internally.
id0, id1: INTEGER
Identification of the interactor or of one of its fields.
opts: SET
Determines whether controls (not described here) should check their guards, for example.
TYPE Frame (Ports.Frame)
ABSTRACT
All input and output operations of a view pass through a frame. A frame manages the whole layout of views on a port, including clipping. Model and view messages are broadcast along frame trees. A frame tree's internal structure is hidden. Frames are volatile objects, they are allocated and released by BlackBox whenever necessary, e.g., when the frame's window is resized. Thus they cannot be used to carry application-specific state, except for caches.
Frames are allocated by a view's GetNewFrame procedure.
Frames are managed internally, and passed as parameters to view procedures whenever necessary.
Standard frames are sufficient for most purposes, and thus rarely extended.
l-, t-, r-, b-: INTEGER 0 <= l <= r & 0 <= t <= b
The visible area of the view in this frame. The values are in universal coordinates, relative to the frame's view's top-left corner.
For example, f.l + f.gx is the distance of the left frame border from the left port (display, printer) border in universal coordinates; (f.l + f.gx) DIV f.unit is the same distance in pixels.
view-: View view # NIL
The frame's view.
front-: BOOLEAN
Flag which tells whether the frame is part of the front window
mark-: BOOLEAN
Flag which tells whether the frame is on its window's focus path, i.e., whether marks (caret, selection) should be drawn. Typically, marking procedures work the following way:
IF f.mark THEN
IF f.front THEN DrawMark(f) ELSE DrawBackgroundMark(f) END
END
PROCEDURE (f: Frame) Close
NEW, EMPTY
Perform finalization before the frame is removed.
After a call to Close, f.view and f.rider are set to NIL and f.ConnectTo(NIL) is called.
Close is called internally.
TYPE RootFrame
This type is used internally.
flags-: SET
Window-specific flags. Reserved for future use.
TYPE PropMessage
ABSTRACT
Use its alias Properties.Message instead (properties are not described here).
TYPE CtrlMessage
ABSTRACT
Base type of all controller messages. Use its alias Controllers.Message instead.
TYPE CtrlMsgHandler
Used internally.
TYPE Title
Type for view titles, e.g., in windows.
TYPE UpdateCachesMsg (Message)
EXTENSIBLE
Used internally.
TYPE ScrollClassMsg (Message)
EXTENSIBLE
Used internally.
PROCEDURE Broadcast (v: View; VAR msg: Message)
Broadcast msg for view. Before broadcasting, parameter v is assigned to the message's view-Field. The actual broadcast only takes place if v.domain # NIL.
Broadcast is called by a view whenever its state has changed and the delayed restore mechanism is not sufficient, e.g., to update frame-specific marks. v will receive msg once for every visible frame on itself.
The handler of a view message may not recursively broadcast another view message, since this could cause the messages to be received in another order than they have been sent, which would result in errors very hard to find.
Pre
v # NIL 20
no recursion 21
Post
msg.view = v
PROCEDURE Domaincast (domain: Stores.Domain; VAR msg: Message)
Broadcasts msg inside domain. For visual objects, the domain corresponds to the object's document. Domaincast is only necessary in exceptional cases; usually a view message is sent in places where the corresponding view, and not only its domain, is known. In these cases, Broadcast is the appropriate (and faster) procedure.
PROCEDURE Omnicast (VAR msg: ANYREC)
Broadcast msg to all open views, independent of their domain (i.e., of their document). All views will receive this message with msg.view = NIL. Omnicast is slower than Broadcast, and only necessary in exceptional cases, e.g., for clock views which should be updated every second through a message omnicast.
PROCEDURE HandlePropMsg (v: View; VAR msg: PropMessage)
Use this procedure to send a property message to a view. It is equivalent to
v.HandlePropMsg(msg)
except that a much better error handling is performed.
PROCEDURE Era (v: View): INTEGER
For views with models, returns the era in which the view was last synchronized with the model.
Pre
v # NIL 20
Post
v.ThisModel() # NIL
in-synch(v) iff Era(v) = Models.Era(v.ThisModel())
PROCEDURE BeginModification (type: INTEGER; v: View)
PROCEDURE EndModification (type: INTEGER; v: View)
PROCEDURE BeginScript (v: View; name: Stores.OpName; OUT script: Stores.Operation)
PROCEDURE EndScript (v: View; script: Stores.Operation)
PROCEDURE Do (v: View; name: Stores.OpName; op: Stores.Operation)
PROCEDURE LastOp (v: View): Stores.Operation
PROCEDURE Bunch (v: View)
PROCEDURE StopBunching (v: View)
These procedures handle modifications of a view. They are used in the same way as their model counterparts in module Models (-> Models). Note that these view procedures are provided for convenience, they are mostly identical to the Models. The only noticeable difference is that a view operation only affects this view, and doesn't affect other views even if they show the same model. For example, a script that modifies a view's model should use the Models procedure, so that all views are updated correctly. A script that modifies only a view's private state should use the procedures above.
PROCEDURE ForwardCtrlMsg (f: Frame; VAR msg: CtrlMessage)
This procedure should be used to send a controller message along the focus path. Usually, it is called within an implementation of HandleCtrlMsg. This is only necessary if it is not sufficient to just set the focus parameter of HandleCtrlMsg to the embedded view to which forwarding should occur. This in turn is only necessary if HandleCtrlMsg needs to do some postprocessing after forwarding has occurred. In this case, it calls ForwardCtrlMsg and then makes sure that focus = NIL.
Pre
f # NIL 20
PROCEDURE Update (v: View; rebuild: BOOLEAN)
Causes view v to be restored, in all frames displaying v. The update occurs delayed, after the currently executing command has terminated. rebuild should be set to keepFrames for non-containers or for operations which didn't modify the layout of a container (i.e., the places and sizes of embedded views). Otherwise, rebuildFrames should be passed.
Pre
v # NIL 20
PROCEDURE UpdateIn (v: View; l, t, r, b: INTEGER; rebuild: BOOLEAN)
Causes rectangle (l, t, r, b) of view v to be restored, in all frames displaying v. The update occurs delayed, after the currently executing command has terminated. rebuild should be set to keepFrames for non-containers or for operations which didn't modify the layout of a container (i.e., the places and sizes of embedded views). Otherwise, rebuildFrames should be passed.
Pre
v # NIL 20
PROCEDURE ReadView (VAR rd: Stores.Reader; OUT v: View)
Reads view v, using reader rd. If internalization is not possible, an alien view is returned.
PROCEDURE WriteView (VAR wr: Stores.Writer; v: View)
Writes view v, using writer wr. Alien views are handled correctly.
PROCEDURE CopyOf (v: View; shallow: BOOLEAN): View
Returns a shallow or deep copy of v.
Pre
v # NIL 20
Post
result # NIL
PROCEDURE CopyWithNewModel (v: View; m: Models.Model): View
Copies a view and assigns a new model to the copy.
Pre
v # NIL 20
v.ThisModel() # NIL 21
m # NIL 22
TYP(m) = TYP(v.ThisModel()) 23
PROCEDURE ReadFont (VAR rd: Stores.Reader; OUT f: Fonts.Font)
Reads a font from a reader.
Post
f # NIL
PROCEDURE WriteFont (VAR wr: Stores.Writer; f: Fonts.Font)
Writes a font to a writer.
Pre
f # NIL 20
PROCEDURE IsPrinterFrame (f: Frame): BOOLEAN
This function can be used to determine whether f's view is currently being restored on a printer or preview port.
Pre
f # NIL 20
PROCEDURE InstallFrame (host: Frame; view: View; x, y, level: INTEGER; focus: BOOLEAN)
If view has no corresponding embedded frame in host, Install allocates and installs a new one for it, otherwise the existing frame is kept. Parameters x and y give the position of the view's top-left corner relative to the container view's (i.e., host.view) top-left corner. The frame ordering can be influenced by passing a view level at which view lies logically. Levels need not be unique (pass 0 if you don't care, e.g., if you never have overlapping frames). A frame always lies "above" other frames with smaller levels. Parameter focus tells whether the frame is part of the focus path.
Pre
host # NIL 20
host is opened in window 21
view # NIL 22
view.context # NIL 23
view.Domain() # NIL 24
PROCEDURE ThisFrame (host: Frame; view: View): Frame
Searches the embedded frame of host which contains view view.
Pre
host # NIL 20
Post
result = NIL
view = NIL OR not found
result # NIL
view # NIL & found
result.view = view
PROCEDURE FrameAt (host: Frame; x, y: INTEGER): Frame
Searches the embedded frame of host which contains point (x, y).
Pre
host # NIL 20
Post
result = NIL
no embedded frame at (x, y)
result # NIL
result contains (x, y)
PROCEDURE Old (ask: BOOLEAN; VAR loc: Files.Locator; VAR name: Files.Name;
VAR conv: Converters.Converter): View
This procedure looks up a file, reads in the document in this file, and then returns the root view of this document. If the file is already opened in a window, the root view of this window's document is returned instead of reading the file. Parameter ask determines whether or not the user is asked interactively for the triple (loc, name, conv), via a standard file dialog. With this dialog, the user can navigate in the host file system's directory structure.
loc, name, conv are treated as in-out parameters. On input, their values are used as defaults. If ask then the user may cause them to change.
loc, name determine the file from which the document was read.
conv determines the converter which is used for reading the document. conv = NIL means that no conversion is necessary, i.e., the file format already has the standard BlackBox format.
Pre
ask OR loc # NIL 20
ask OR name # "" 21
Post
result = NIL
loc.res # 0
result # NIL
loc.res = 0
result.context # NIL
~ask
loc = loc' & name = name' & conv = conv'
PROCEDURE OldView (loc: Files.Locator; name: Files.Name): View
OldView is an abbreviation of Old(dontAsk, loc, name, NIL).
PROCEDURE Register (view: View; ask: BOOLEAN; VAR loc: Files.Locator;
VAR name: Files.Name; VAR conv: Converters.Converter;
OUT res: INTEGER)
Saves view's document in a file. Parameter ask determines whether or not the user is asked interactively for the triple (loc, name, conv), via a standard file dialog. With this dialog, the user can navigate in the host file system's directory structure.
loc, name, conv are treated as in-out parameters. On input, their values are used as defaults. If ask then the user may cause them to change.
loc, name determine the file to which the document is written.
conv determines the converter which is used for writing the document. conv = NIL means that no conversion is necessary, i.e., the file format gets the standard BlackBox format.
Pre
view # NIL 20
ask OR loc # NIL 22
ask OR name # "" 23
Post
operation was successful
res = 0
operation was not successful
res # 0
PROCEDURE RegisterView (view: View; loc: Files.Locator; name: Files.Name)
RegisterView is an abbreviation of Register(view, dontAsk, loc, name, nil, res).
PROCEDURE Open (view: View; loc: Files.Locator; name: Files.Name;
conv: Converters.Converter)
Open view in a new window. (loc, name) determines the file associated with view, if there is any. conv is the converter which will be used when the user saves the document. conv = NIL is passed when saving in the standard BlackBox file format is desired.
Pre
view # NIL 20
(loc = NIL) = (name = "") 21
PROCEDURE OpenView (view: View)
OpenView is an abbreviation of Open(view, NIL, "", NIL).
PROCEDURE OpenAux (view: View; title: Title)
Opens view in an auxiliary window with title title.
Pre
view # NIL 20
title # "" 21
PROCEDURE Deposit (view: View)
Deposit a view for later use, typically for opening it in a window, or for pasting it to the focus.
Deposit is used only by allocation commands, i.e., commands which allocate and then deposit a concrete view type.
Pre
view # NIL 20
PROCEDURE RestoreDomain (domain: Stores.Domain)
This procedure forces a restoration of all update regions on views of domain.
Normally, the display is updated in a delayed fashion, i.e., an update region is built for all invalid view areas (using Update and UpdateIn), and the display update according to this region is performed when the framework is idle, i.e., between commands. However, sometimes it is necessary to enforce a display update during a command, for which this procedure can be used. The need for enforced update comes from scrolling: if a view should be scrolled, the effect of scrolling should become immediately visible.
PROCEDURE Scroll (v: View; dx, dy: INTEGER)
Scroll the contents of each frame on v by (dx, dy).
Pre
v # NIL 20
PROCEDURE SetDir (d: Directory)
Assigns directory.
Pre
d # NIL 20
Post
stdDir' = NIL
stdDir = d
stdDir' # NIL
stdDir = stdDir'
dir = d
The following procedures are used internally:
PROCEDURE MarkBorders (root: RootFrame)
PROCEDURE MarkBorder (host: Frame; view: View; l, t, r, b: INTEGER)
PROCEDURE Fetch (OUT view: View)
PROCEDURE Available (): INTEGER
PROCEDURE ClearQueue
PROCEDURE RemoveFrame (host, f: Frame)
PROCEDURE RemoveFrames (host: Frame; l, t, r, b: INTEGER)
PROCEDURE BroadcastModelMsg (f: Frame; VAR msg: Models.Message)
PROCEDURE BroadcastViewMsg (f: Frame; VAR msg: Message)
PROCEDURE HandleCtrlMsg (op: INTEGER; f, g: Frame; VAR msg: CtrlMessage;
VAR target, front, req: BOOLEAN)
PROCEDURE SetRoot (root: RootFrame; view: View; front: BOOLEAN; flags: SET)
PROCEDURE AdaptRoot (root: RootFrame)
PROCEDURE RootOf (f: Frame): RootFrame
PROCEDURE HostOf (f: Frame): Frame
PROCEDURE UpdateRoot (root: RootFrame; l, t, r, b: INTEGER; rebuild: BOOLEAN)
PROCEDURE RestoreRoot (root: RootFrame; l, t, r, b: INTEGER)
PROCEDURE ValidateRoot (root: RootFrame)
PROCEDURE InitCtrl (p: CtrlMsgHandler)
PROCEDURE IsInvalid (v: View): BOOLEAN
PROCEDURE RevalidateView (v: View)
| System/Docu/Views.odc |
Windows
DEFINITION Windows;
IMPORT Sequencers, Files, Ports, Views, Models, Documents, Converters;
CONST
allowDuplicates = 5;
eager = FALSE;
isAux = 1;
isTool = 0;
lazy = TRUE;
neverDirty = 6;
noHScroll = 2;
noResize = 4;
noVScroll = 3;
TYPE
Directory = POINTER TO ABSTRACT RECORD
l, t, r, b: INTEGER;
minimized, maximized: BOOLEAN;
(d: Directory) Close (w: Window), NEW, ABSTRACT;
(d: Directory) First (): Window, NEW, ABSTRACT;
(d: Directory) Focus (target: BOOLEAN): Window, NEW, ABSTRACT;
(d: Directory) GetBounds (OUT w, h: INTEGER), NEW, ABSTRACT;
(d: Directory) GetThisWindow (p: Ports.Port; px, py: INTEGER;
OUT x, y: INTEGER; OUT w: Window), NEW, ABSTRACT;
(d: Directory) New (): Window, NEW, ABSTRACT;
(d: Directory) NewSequencer (): Sequencers.Sequencer, NEW;
(d: Directory) Next (w: Window): Window, NEW, ABSTRACT;
(d: Directory) Open (w: Window; doc: Documents.Document; flags: SET;
name: Views.Title; loc: Files.Locator; fname: Files.Name;
conv: Converters.Converter), NEW, EXTENSIBLE;
(d: Directory) OpenSubWindow (w: Window; doc: Documents.Document;
flags: SET; name: Views.Title), NEW, EXTENSIBLE;
(d: Directory) Select (w: Window; lazy: BOOLEAN), NEW, ABSTRACT;
(d: Directory) Update (w: Window), NEW
END;
Window = POINTER TO ABSTRACT RECORD
port: Ports.Port;
frame-: Views.RootFrame;
doc-: Documents.Document;
seq-: Sequencers.Sequencer;
link-: Window;
sub-: BOOLEAN;
flags-: SET;
loc-: Files.Locator;
name-: Files.Name;
conv-: Converters.Converter;
(w: Window) BroadcastModelMsg (VAR msg: Models.Message), NEW, EXTENSIBLE;
(w: Window) BroadcastViewMsg (VAR msg: Views.Message), NEW, EXTENSIBLE;
(w: Window) Close, NEW, EXTENSIBLE;
(w: Window) ForwardCtrlMsg (VAR msg: Views.CtrlMessage), NEW, EXTENSIBLE;
(w: Window) GetSize (OUT width, height: INTEGER), NEW, EXTENSIBLE;
(w: Window) GetTitle (OUT title: Views.Title), NEW, ABSTRACT;
(w: Window) Init (port: Ports.Port), NEW, EXTENSIBLE;
(w: Window) KeyDown (ch: CHAR; modifiers: SET), NEW, EXTENSIBLE;
(w: Window) MouseDown (x, y, time: INTEGER; modifiers: SET), NEW, ABSTRACT;
(w: Window) RefreshTitle, NEW, ABSTRACT;
(w: Window) Restore (l, t, r, b: INTEGER), NEW;
(w: Window) SetSize (width, height: INTEGER), NEW, EXTENSIBLE;
(w: Window) SetSpec (loc: Files.Locator; name: Files.Name;
conv: Converters.Converter), NEW, EXTENSIBLE;
(w: Window) SetTitle (title: Views.Title), NEW, ABSTRACT;
(w: Window) Update, NEW
END;
VAR
dir-: Directory;
PROCEDURE Init;
PROCEDURE GetBySpec (loc: Files.Locator; name: Files.Name;
conv: Converters.Converter; flags: SET): Window;
PROCEDURE SelectBySpec (loc: Files.Locator; name: Files.Name;
conv: Converters.Converter; flags: SET; VAR done: BOOLEAN);
PROCEDURE SelectByTitle (v: Views.View; flags: SET; title: Views.Title; VAR done: BOOLEAN);
PROCEDURE SetupWindow (w: Window; frame: Views.RootFrame;
doc: Documents.Document; seq: Sequencers.Sequencer; flags: SET);
END Windows.
CONST
lazy = TRUE
window will be validated normally (at the end of current command)
eager = FALSE
window is validated immediately (which causes frame tree to be built). Now Select does not have lazy argument; rather, for the frame tree to be built immediately, call Validate explicitly.
TYPE Directory
ABSTRACT
Directory for the lookup in and manipulation with windows
l, t, r, b: INTEGER;
The bounding box for the next window to be opened; a request, not a guarantee
| System/Docu/Windows.odc |
MODULE Console;
(**
A. V. Shiryaev, 2012.10
Interface based on OpenBUGS Console
**)
TYPE
Console* = POINTER TO ABSTRACT RECORD END;
VAR
cons: Console;
(* Console *)
PROCEDURE (c: Console) WriteStr- (IN s: ARRAY OF CHAR), NEW, ABSTRACT;
PROCEDURE (c: Console) WriteChar- (ch: CHAR), NEW, ABSTRACT;
PROCEDURE (c: Console) WriteLn-, NEW, ABSTRACT;
(*
post:
s = "": end of input or input error
s # "": line with end of line postfix
*)
PROCEDURE (c: Console) ReadLn- (OUT s: ARRAY OF CHAR), NEW, ABSTRACT;
PROCEDURE WriteStr* (IN text: ARRAY OF CHAR);
BEGIN
cons.WriteStr(text)
END WriteStr;
PROCEDURE WriteChar* (c: CHAR);
BEGIN
cons.WriteChar(c)
END WriteChar;
PROCEDURE WriteLn*;
BEGIN
cons.WriteLn
END WriteLn;
PROCEDURE ReadLn* (OUT text: ARRAY OF CHAR);
BEGIN
cons.ReadLn(text)
END ReadLn;
PROCEDURE SetConsole* (c: Console);
BEGIN
cons := c
END SetConsole;
END Console.
| System/Mod/Console.odc |
MODULE Containers;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20160719, center #117, fixes for non-local drop behavior
- 20170905, center #173, adding new modifiers to Controllers
- 20210425, ad, replaced soft links to HostMenus with soft links to StdMenuTool
"
issues = "
- ...
"
**)
IMPORT Kernel, Services, Ports, Dialog, Stores, Models, Views, Controllers, Properties, Mechanisms;
CONST
(** Controller.opts **)
noSelection* = 0; noFocus* = 1; noCaret* = 2;
mask* = {noSelection, noCaret}; layout* = {noFocus};
modeOpts = {noSelection, noFocus, noCaret};
(** Controller.SelectAll select **)
deselect* = FALSE; select* = TRUE;
(** Controller.PollNativeProp/etc. selection **)
any* = FALSE; selection* = TRUE;
(** Mark/MarkCaret/MarkSelection/MarkSingleton show **)
hide* = FALSE; show* = TRUE;
indirect = FALSE; direct = TRUE;
TAB = 9X; LTAB = 0AX; ENTER = 0DX; ESC = 01BX;
PL = 10X; PR = 11X; PU = 12X; PD = 13X;
DL = 14X; DR = 15; DU = 16X; DD = 17X;
AL = 1CX; AR = 1DX; AU = 1EX; AD = 1FX;
minVersion = 0; maxModelVersion = 0; maxViewVersion = 0; maxCtrlVersion = 0;
TYPE
Model* = POINTER TO ABSTRACT RECORD (Models.Model) END;
View* = POINTER TO ABSTRACT RECORD (Views.View)
model: Model;
controller: Controller;
alienCtrl: Stores.Store (* alienCtrl = NIL OR controller = NIL *)
END;
Controller* = POINTER TO ABSTRACT RECORD (Controllers.Controller)
opts-: SET;
model: Model; (* connected iff model # NIL *)
view: View;
focus, singleton: Views.View;
bVis: BOOLEAN (* control visibility of focus/singleton border *)
END;
Directory* = POINTER TO ABSTRACT RECORD END;
PollFocusMsg = RECORD (Controllers.PollFocusMsg)
all: BOOLEAN;
ctrl: Controller
END;
ViewOp = POINTER TO RECORD (Stores.Operation)
v: View;
controller: Controller; (* may be NIL *)
alienCtrl: Stores.Store
END;
ControllerOp = POINTER TO RECORD (Stores.Operation)
c: Controller;
opts: SET
END;
ViewMessage = ABSTRACT RECORD (Views.Message) END;
FocusMsg = RECORD (ViewMessage)
set: BOOLEAN
END;
SingletonMsg = RECORD (ViewMessage)
set: BOOLEAN
END;
FadeMsg = RECORD (ViewMessage)
show: BOOLEAN
END;
DropPref* = RECORD (Properties.Preference)
mode-: SET;
okToDrop*: BOOLEAN
END;
GetOpts* = RECORD (Views.PropMessage)
valid*, opts*: SET
END;
SetOpts* = RECORD (Views.PropMessage)
valid*, opts*: SET
END;
PROCEDURE ^ (v: View) SetController* (c: Controller), NEW;
PROCEDURE ^ (v: View) InitModel* (m: Model), NEW;
PROCEDURE ^ Focus* (): Controller;
PROCEDURE ^ ClaimFocus (v: Views.View): BOOLEAN;
PROCEDURE ^ MarkFocus (c: Controller; f: Views.Frame; show: BOOLEAN);
PROCEDURE ^ MarkSingleton* (c: Controller; f: Views.Frame; show: BOOLEAN);
PROCEDURE ^ FadeMarks* (c: Controller; show: BOOLEAN);
PROCEDURE ^ CopyView (source: Controller; VAR view: Views.View; VAR w, h: INTEGER);
PROCEDURE ^ ThisProp (c: Controller; direct: BOOLEAN): Properties.Property;
PROCEDURE ^ SetProp (c: Controller; old, p: Properties.Property; direct: BOOLEAN);
PROCEDURE ^ (c: Controller) InitView* (v: Views.View), NEW;
PROCEDURE (c: Controller) InitView2* (v: Views.View), NEW, EMPTY;
PROCEDURE ^ (c: Controller) ThisView* (): View, NEW, EXTENSIBLE;
PROCEDURE ^ (c: Controller) ThisFocus* (): Views.View, NEW, EXTENSIBLE;
PROCEDURE ^ (c: Controller) ConsiderFocusRequestBy* (view: Views.View), NEW;
PROCEDURE ^ (c: Controller) RestoreMarks* (f: Views.Frame; l, t, r, b: INTEGER), NEW;
PROCEDURE ^ (c: Controller) Neutralize*, NEW;
(** called by view's Neutralize **)
PROCEDURE ^ (c: Controller) HandleModelMsg* (VAR msg: Models.Message), NEW, EXTENSIBLE;
(** called by view's HandleModelMsg after handling msg **)
PROCEDURE ^ (c: Controller) HandleViewMsg* (f: Views.Frame; VAR msg: Views.Message), NEW, EXTENSIBLE;
(** called by view's HandleViewMsg after handling msg **)
PROCEDURE ^ (c: Controller) HandleCtrlMsg* (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View), NEW, EXTENSIBLE;
(** called by view's HandleCtrlMsg *before* handling msg; focus is respected/used by view **)
PROCEDURE ^ (c: Controller) HandlePropMsg* (VAR msg: Views.PropMessage), NEW, EXTENSIBLE;
(** called by view's HandlePropMsg after handling msg; controller can override view **)
(** Model **)
PROCEDURE (m: Model) Internalize- (VAR rd: Stores.Reader), EXTENSIBLE;
VAR thisVersion: INTEGER;
BEGIN
m.Internalize^(rd);
IF rd.cancelled THEN RETURN END;
rd.ReadVersion(minVersion, maxModelVersion, thisVersion)
END Internalize;
PROCEDURE (m: Model) Externalize- (VAR wr: Stores.Writer), EXTENSIBLE;
BEGIN
m.Externalize^(wr);
wr.WriteVersion(maxModelVersion)
END Externalize;
PROCEDURE (m: Model) GetEmbeddingLimits* (OUT minW, maxW, minH, maxH: INTEGER), NEW, ABSTRACT;
PROCEDURE (m: Model) ReplaceView* (old, new: Views.View), NEW, ABSTRACT;
PROCEDURE (m: Model) InitFrom- (source: Model), NEW, EMPTY;
(** View **)
PROCEDURE (v: View) AcceptableModel- (m: Model): BOOLEAN, NEW, ABSTRACT;
PROCEDURE (v: View) InitModel2- (m: Model), NEW, EMPTY;
PROCEDURE (v: View) InitModel* (m: Model), NEW;
BEGIN
ASSERT((v.model = NIL) OR (v.model = m), 20);
ASSERT(m # NIL, 21);
ASSERT(v.AcceptableModel(m), 22);
v.model := m;
Stores.Join(v, m);
v.InitModel2(m)
END InitModel;
PROCEDURE (v: View) Externalize2- (VAR rd: Stores.Writer), NEW, EMPTY;
PROCEDURE(v: View) Internalize2- (VAR rd: Stores.Reader), NEW, EMPTY;
PROCEDURE (v: View) Internalize- (VAR rd: Stores.Reader);
VAR st: Stores.Store; c: Controller; m: Model; thisVersion: INTEGER;
BEGIN
v.Internalize^(rd);
IF rd.cancelled THEN RETURN END;
rd.ReadVersion(minVersion, maxViewVersion, thisVersion);
IF rd.cancelled THEN RETURN END;
rd.ReadStore(st); ASSERT(st # NIL, 100);
IF ~(st IS Model) THEN
rd.TurnIntoAlien(Stores.alienComponent);
Stores.Report("#System:AlienModel", "", "", "");
RETURN
END;
m := st(Model);
rd.ReadStore(st);
IF st = NIL THEN c := NIL; v.alienCtrl := NIL
ELSIF st IS Stores.Alien THEN
c := NIL; v.alienCtrl := st; Stores.Join(v, v.alienCtrl);
Stores.Report("#System:AlienControllerWarning", "", "", "")
ELSE c := st(Controller); v.alienCtrl := NIL
END;
v.InitModel(m);
IF c # NIL THEN v.SetController(c) ELSE v.controller := NIL END;
v.Internalize2(rd)
END Internalize;
PROCEDURE (v: View) Externalize- (VAR wr: Stores.Writer);
BEGIN
ASSERT(v.model # NIL, 20);
v.Externalize^(wr);
wr.WriteVersion(maxViewVersion);
wr.WriteStore(v.model);
IF v.controller # NIL THEN wr.WriteStore(v.controller)
ELSE wr.WriteStore(v.alienCtrl)
END;
v.Externalize2(wr)
END Externalize;
PROCEDURE (v: View) CopyFromModelView2- (source: Views.View; model: Models.Model), NEW, EMPTY;
PROCEDURE (v: View) CopyFromModelView- (source: Views.View; model: Models.Model);
VAR c: Controller;
BEGIN
WITH source: View DO
v.InitModel(model(Model));
IF source.controller # NIL THEN
c := Stores.CopyOf(source.controller)(Controller)
ELSE
c := NIL
END;
IF source.alienCtrl # NIL THEN v.alienCtrl := Stores.CopyOf(source.alienCtrl)(Stores.Alien) END;
IF c # NIL THEN v.SetController(c) ELSE v.controller := NIL END
END;
v.CopyFromModelView2(source, model)
END CopyFromModelView;
PROCEDURE (v: View) ThisModel* (): Model, EXTENSIBLE;
BEGIN
RETURN v.model
END ThisModel;
PROCEDURE (v: View) SetController* (c: Controller), NEW;
VAR op: ViewOp;
BEGIN
ASSERT(v.model # NIL, 20);
IF v.controller # c THEN
Stores.Join(v, c);
NEW(op); op.v := v; op.controller := c; op.alienCtrl := NIL;
Views.Do(v, "#System:ViewSetting", op)
END
END SetController;
PROCEDURE (v: View) ThisController* (): Controller, NEW, EXTENSIBLE;
BEGIN
RETURN v.controller
END ThisController;
PROCEDURE (v: View) GetRect* (f: Views.Frame; view: Views.View; OUT l, t, r, b: INTEGER), NEW, ABSTRACT;
PROCEDURE (v: View) RestoreMarks* (f: Views.Frame; l, t, r, b: INTEGER);
BEGIN
IF v.controller # NIL THEN v.controller.RestoreMarks(f, l, t, r, b) END
END RestoreMarks;
PROCEDURE (v: View) Neutralize*;
BEGIN
IF v.controller # NIL THEN v.controller.Neutralize END
END Neutralize;
PROCEDURE (v: View) ConsiderFocusRequestBy- (view: Views.View);
BEGIN
IF v.controller # NIL THEN v.controller.ConsiderFocusRequestBy(view) END
END ConsiderFocusRequestBy;
PROCEDURE (v: View) HandleModelMsg2- (VAR msg: Models.Message), NEW, EMPTY;
PROCEDURE (v: View) HandleViewMsg2- (f: Views.Frame; VAR msg: Views.Message), NEW, EMPTY;
PROCEDURE (v: View) HandlePropMsg2- (VAR p: Properties.Message), NEW, EMPTY;
PROCEDURE (v: View) HandleCtrlMsg2- (f: Views.Frame; VAR msg: Controllers.Message;
VAR focus: Views.View), NEW, EMPTY;
PROCEDURE (v: View) HandleModelMsg- (VAR msg: Models.Message);
BEGIN
v.HandleModelMsg2(msg);
IF v.controller # NIL THEN v.controller.HandleModelMsg(msg) END
END HandleModelMsg;
PROCEDURE (v: View) HandleViewMsg- (f: Views.Frame; VAR msg: Views.Message);
BEGIN
v.HandleViewMsg2(f, msg);
IF v.controller # NIL THEN v.controller.HandleViewMsg(f, msg) END
END HandleViewMsg;
PROCEDURE (v: View) HandleCtrlMsg* (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View);
BEGIN
IF v.controller # NIL THEN v.controller.HandleCtrlMsg(f, msg, focus) END;
v.HandleCtrlMsg2(f, msg, focus);
WITH msg: Controllers.PollSectionMsg DO
IF ~msg.focus THEN focus := NIL END
| msg: Controllers.ScrollMsg DO
IF ~msg.focus THEN focus := NIL END
ELSE
END
END HandleCtrlMsg;
PROCEDURE (v: View) HandlePropMsg- (VAR p: Properties.Message);
BEGIN
v.HandlePropMsg2(p);
IF v.controller # NIL THEN v.controller.HandlePropMsg(p) END
END HandlePropMsg ;
(** Controller **)
PROCEDURE (c: Controller) Externalize2- (VAR rd: Stores.Writer), NEW, EMPTY;
PROCEDURE(c: Controller) Internalize2- (VAR rd: Stores.Reader), NEW, EMPTY;
PROCEDURE (c: Controller) Internalize- (VAR rd: Stores.Reader);
VAR v: INTEGER;
BEGIN
c.Internalize^(rd);
IF rd.cancelled THEN RETURN END;
rd.ReadVersion(minVersion, maxCtrlVersion, v);
IF rd.cancelled THEN RETURN END;
rd.ReadSet(c.opts);
c.Internalize2(rd)
END Internalize;
PROCEDURE (c: Controller) Externalize- (VAR wr: Stores.Writer);
BEGIN
c.Externalize^(wr);
wr.WriteVersion(maxCtrlVersion);
wr.WriteSet(c.opts);
c.Externalize2(wr)
END Externalize;
PROCEDURE (c: Controller) CopyFrom- (source: Stores.Store), EXTENSIBLE;
BEGIN
WITH source: Controller DO
c.opts := source.opts;
c.focus := NIL; c.singleton := NIL;
c.bVis := FALSE
END
END CopyFrom;
PROCEDURE (c: Controller) InitView* (v: Views.View), NEW;
VAR view: View; model: Model;
BEGIN
ASSERT((v = NIL) # (c.view = NIL) OR (v = c.view), 21);
IF c.view = NIL THEN
ASSERT(v IS View, 22); (* subclass may assert narrower type *)
view := v(View);
model := view.ThisModel(); ASSERT(model # NIL, 24);
c.view := view; c.model := model;
Stores.Join(c, c.view)
ELSE
c.view.Neutralize; c.view := NIL; c.model := NIL
END;
c.focus := NIL; c.singleton := NIL; c.bVis := FALSE;
c.InitView2(v)
END InitView;
PROCEDURE (c: Controller) ThisView* (): View, NEW, EXTENSIBLE;
BEGIN
RETURN c.view
END ThisView;
(** options **)
PROCEDURE (c: Controller) SetOpts* (opts: SET), NEW, EXTENSIBLE;
VAR op: ControllerOp;
BEGIN
IF c.view # NIL THEN
NEW(op); op.c := c; op.opts := opts;
Views.Do(c.view, "#System:ChangeOptions", op)
ELSE
c.opts := opts
END
END SetOpts;
(** subclass hooks **)
PROCEDURE (c: Controller) GetContextType* (OUT type: Stores.TypeName), NEW, ABSTRACT;
PROCEDURE (c: Controller) GetValidOps* (OUT valid: SET), NEW, ABSTRACT;
PROCEDURE (c: Controller) NativeModel* (m: Models.Model): BOOLEAN, NEW, ABSTRACT;
PROCEDURE (c: Controller) NativeView* (v: Views.View): BOOLEAN, NEW, ABSTRACT;
PROCEDURE (c: Controller) NativeCursorAt* (f: Views.Frame; x, y: INTEGER): INTEGER, NEW, ABSTRACT;
PROCEDURE (c: Controller) PickNativeProp* (f: Views.Frame; x, y: INTEGER; VAR p: Properties.Property), NEW, EMPTY;
PROCEDURE (c: Controller) PollNativeProp* (selection: BOOLEAN; VAR p: Properties.Property; VAR truncated: BOOLEAN), NEW, EMPTY;
PROCEDURE (c: Controller) SetNativeProp* (selection: BOOLEAN; old, p: Properties.Property), NEW, EMPTY;
PROCEDURE (c: Controller) MakeViewVisible* (v: Views.View), NEW, EMPTY;
PROCEDURE (c: Controller) GetFirstView* (selection: BOOLEAN; OUT v: Views.View), NEW, ABSTRACT;
PROCEDURE (c: Controller) GetNextView* (selection: BOOLEAN; VAR v: Views.View), NEW, ABSTRACT;
PROCEDURE (c: Controller) GetPrevView* (selection: BOOLEAN; VAR v: Views.View), NEW, EXTENSIBLE;
VAR p, q: Views.View;
BEGIN
ASSERT(v # NIL, 20);
c.GetFirstView(selection, p);
IF p # v THEN
WHILE (p # NIL) & (p # v) DO q := p; c.GetNextView(selection, p) END;
ASSERT(p # NIL, 21);
v := q
ELSE
v := NIL
END
END GetPrevView;
PROCEDURE (c: Controller) CanDrop* (f: Views.Frame; x, y: INTEGER): BOOLEAN, NEW, EXTENSIBLE;
BEGIN
RETURN TRUE
END CanDrop;
PROCEDURE (c: Controller) GetSelectionBounds* (f: Views.Frame; OUT x, y, w, h: INTEGER), NEW, EXTENSIBLE;
VAR g: Views.Frame; v: Views.View;
BEGIN
x := 0; y := 0; w := 0; h := 0;
v := c.singleton;
IF v # NIL THEN
g := Views.ThisFrame(f, v);
IF g # NIL THEN
x := g.gx - f.gx; y := g.gy - f.gy;
v.context.GetSize(w, h)
END
END
END GetSelectionBounds;
PROCEDURE (c: Controller) MarkDropTarget* (src, dst: Views.Frame;
sx, sy, dx, dy, w, h, rx, ry: INTEGER;
type: Stores.TypeName;
isSingle, show: BOOLEAN), NEW, EMPTY;
PROCEDURE (c: Controller) Drop* (src, dst: Views.Frame; sx, sy, dx, dy, w, h, rx, ry: INTEGER;
view: Views.View; isSingle: BOOLEAN), NEW, ABSTRACT;
PROCEDURE (c: Controller) MarkPickTarget* (src, dst: Views.Frame;
sx, sy, dx, dy: INTEGER; show: BOOLEAN), NEW, EMPTY;
PROCEDURE (c: Controller) TrackMarks* (f: Views.Frame; x, y: INTEGER; units, extend, add: BOOLEAN), NEW, ABSTRACT;
PROCEDURE (c: Controller) Resize* (view: Views.View; l, t, r, b: INTEGER), NEW, ABSTRACT;
PROCEDURE (c: Controller) DeleteSelection*, NEW, ABSTRACT;
PROCEDURE (c: Controller) MoveLocalSelection* (src, dst: Views.Frame; sx, sy, dx, dy: INTEGER), NEW, ABSTRACT;
PROCEDURE (c: Controller) CopyLocalSelection* (src, dst: Views.Frame; sx, sy, dx, dy: INTEGER), NEW, ABSTRACT;
PROCEDURE (c: Controller) SelectionCopy* (): Model, NEW, ABSTRACT;
PROCEDURE (c: Controller) NativePaste* (m: Models.Model; f: Views.Frame), NEW, ABSTRACT;
PROCEDURE (c: Controller) ArrowChar* (f: Views.Frame; ch: CHAR; units, select: BOOLEAN), NEW, ABSTRACT;
PROCEDURE (c: Controller) ControlChar* (f: Views.Frame; ch: CHAR), NEW, ABSTRACT;
PROCEDURE (c: Controller) PasteChar* (ch: CHAR), NEW, ABSTRACT;
PROCEDURE (c: Controller) PasteView* (f: Views.Frame; v: Views.View; w, h: INTEGER), NEW, ABSTRACT;
(** selection **)
PROCEDURE (c: Controller) HasSelection* (): BOOLEAN, NEW, EXTENSIBLE;
(** extended by subclass to include intrinsic selections **)
BEGIN
ASSERT(c.model # NIL, 20);
RETURN c.singleton # NIL
END HasSelection;
PROCEDURE (c: Controller) Selectable* (): BOOLEAN, NEW, ABSTRACT;
PROCEDURE (c: Controller) Singleton* (): Views.View, NEW; (* LEAF *)
BEGIN
IF c = NIL THEN RETURN NIL
ELSE RETURN c.singleton
END
END Singleton;
PROCEDURE (c: Controller) SetSingleton* (s: Views.View), NEW, EXTENSIBLE;
(** extended by subclass to adjust intrinsic selections **)
VAR con: Models.Context; msg: SingletonMsg;
BEGIN
ASSERT(c.model # NIL, 20);
ASSERT(~(noSelection IN c.opts), 21);
IF c.singleton # s THEN
IF s # NIL THEN
con := s.context;
ASSERT(con # NIL, 22); ASSERT(con.ThisModel() = c.model, 23);
c.view.Neutralize
ELSIF c.singleton # NIL THEN
c.bVis := FALSE; msg.set := FALSE; Views.Broadcast(c.view, msg)
END;
c.singleton := s;
IF s # NIL THEN
c.bVis := TRUE; msg.set := TRUE; Views.Broadcast(c.view, msg)
END
END
END SetSingleton;
PROCEDURE (c: Controller) SelectAll* (select: BOOLEAN), NEW, ABSTRACT;
(** replaced by subclass to include intrinsic selections **)
PROCEDURE (c: Controller) InSelection* (f: Views.Frame; x, y: INTEGER): BOOLEAN, NEW, ABSTRACT;
(** replaced by subclass to include intrinsic selections **)
PROCEDURE (c: Controller) MarkSelection* (f: Views.Frame; show: BOOLEAN), NEW, EXTENSIBLE;
(** replaced by subclass to include intrinsic selections **)
BEGIN
MarkSingleton(c, f, show)
END MarkSelection;
(** focus **)
PROCEDURE (c: Controller) ThisFocus* (): Views.View, NEW, EXTENSIBLE;
BEGIN
ASSERT(c.model # NIL, 20);
RETURN c.focus
END ThisFocus;
PROCEDURE (c: Controller) SetFocus* (focus: Views.View), NEW; (* LEAF *)
VAR focus0: Views.View; con: Models.Context; msg: FocusMsg;
BEGIN
ASSERT(c.model # NIL, 20);
focus0 := c.focus;
IF focus # focus0 THEN
IF focus # NIL THEN
con := focus.context;
ASSERT(con # NIL, 21); ASSERT(con.ThisModel() = c.model, 22);
IF focus0 = NIL THEN c.view.Neutralize END
END;
IF focus0 # NIL THEN
IF ~Views.IsInvalid(focus0) THEN focus0.Neutralize END;
c.bVis := FALSE; msg.set := FALSE; Views.Broadcast(c.view, msg)
END;
c.focus := focus;
IF focus # NIL THEN
c.MakeViewVisible(focus);
c.bVis := TRUE; msg.set := TRUE; Views.Broadcast(c.view, msg)
END
END
END SetFocus;
PROCEDURE (c: Controller) ConsiderFocusRequestBy* (view: Views.View), NEW;
VAR con: Models.Context;
BEGIN
ASSERT(c.model # NIL, 20);
ASSERT(view # NIL, 21); con := view.context;
ASSERT(con # NIL, 22); ASSERT(con.ThisModel() = c.model, 23);
IF c.focus = NIL THEN c.SetFocus(view) END
END ConsiderFocusRequestBy;
(** caret **)
PROCEDURE (c: Controller) HasCaret* (): BOOLEAN, NEW, ABSTRACT;
PROCEDURE (c: Controller) MarkCaret* (f: Views.Frame; show: BOOLEAN), NEW, ABSTRACT;
(** general marking protocol **)
PROCEDURE CheckMaskFocus (c: Controller; f: Views.Frame; VAR focus: Views.View);
VAR v: Views.View;
BEGIN
IF f.mark & (c.opts * modeOpts = mask) & (c.model # NIL) & ((focus = NIL) OR ~ClaimFocus(focus)) THEN
c.GetFirstView(any, v);
WHILE (v # NIL) & ~ClaimFocus(v) DO c.GetNextView(any, v) END;
IF v # NIL THEN
c.SetFocus(v);
focus := v
ELSE c.SetFocus(NIL); focus := NIL
END
END
END CheckMaskFocus;
PROCEDURE (c: Controller) Mark* (f: Views.Frame; l, t, r, b: INTEGER; show: BOOLEAN), NEW, EXTENSIBLE;
BEGIN
MarkFocus(c, f, show); c.MarkSelection(f, show); c.MarkCaret(f, show)
END Mark;
PROCEDURE (c: Controller) RestoreMarks2- (f: Views.Frame; l, t, r, b: INTEGER), NEW, EMPTY;
PROCEDURE (c: Controller) RestoreMarks* (f: Views.Frame; l, t, r, b: INTEGER), NEW;
BEGIN
IF f.mark THEN
c.Mark(f, l, t, r, b, show);
c.RestoreMarks2(f, l, t, r, b)
END
END RestoreMarks;
PROCEDURE (c: Controller) Neutralize2-, NEW, EMPTY;
(** caret needs to be removed by this method **)
PROCEDURE (c: Controller) Neutralize*, NEW;
BEGIN
c.SetFocus(NIL); c.SelectAll(deselect);
c.Neutralize2
END Neutralize;
(** message handlers **)
PROCEDURE (c: Controller) HandleModelMsg* (VAR msg: Models.Message), NEW, EXTENSIBLE;
BEGIN
ASSERT(c.model # NIL, 20)
END HandleModelMsg;
PROCEDURE (c: Controller) HandleViewMsg* (f: Views.Frame; VAR msg: Views.Message), NEW, EXTENSIBLE;
VAR g: Views.Frame; mark: Controllers.MarkMsg;
BEGIN
ASSERT(c.model # NIL, 20);
IF msg.view = c.view THEN
WITH msg: ViewMessage DO
WITH msg: FocusMsg DO
g := Views.ThisFrame(f, c.focus);
IF g # NIL THEN
IF msg.set THEN
MarkFocus(c, f, show);
mark.show := TRUE; mark.focus := TRUE;
Views.ForwardCtrlMsg(g, mark)
ELSE
mark.show := FALSE; mark.focus := TRUE;
Views.ForwardCtrlMsg(g, mark);
MarkFocus(c, f, hide)
END
END
| msg: SingletonMsg DO
MarkSingleton(c, f, msg.set)
| msg: FadeMsg DO
MarkFocus(c, f, msg.show);
MarkSingleton(c, f, msg.show)
END
ELSE
END
END
END HandleViewMsg;
PROCEDURE CollectControlPref (c: Controller; focus: Views.View; ch: CHAR; cyclic: BOOLEAN;
VAR v: Views.View; VAR getFocus, accepts: BOOLEAN);
VAR first, w: Views.View; p: Properties.ControlPref; back: BOOLEAN;
BEGIN
back := (ch = LTAB) OR (ch = AL) OR (ch = AU); first := c.focus;
IF first = NIL THEN
c.GetFirstView(any, first);
IF back THEN w := first;
WHILE w # NIL DO first := w; c.GetNextView(any, w) END
END
END;
v := first;
WHILE v # NIL DO
p.char := ch; p.focus := focus;
p.getFocus := (v # focus) & ((ch = TAB) OR (ch = LTAB)) & ClaimFocus(v);
p.accepts := (v = focus) & (ch # TAB) & (ch # LTAB);
Views.HandlePropMsg(v, p);
IF p.accepts OR (v # focus) & p.getFocus THEN
getFocus := p.getFocus; accepts := p.accepts;
RETURN
END;
IF back THEN c.GetPrevView(any, v) ELSE c.GetNextView(any, v) END;
IF cyclic & (v = NIL) THEN
c.GetFirstView(any, v);
IF back THEN w := v;
WHILE w # NIL DO v := w; c.GetNextView(any, w) END
END
END;
IF v = first THEN v := NIL END
END;
getFocus := FALSE; accepts := FALSE
END CollectControlPref;
PROCEDURE (c: Controller) HandlePropMsg* (VAR msg: Properties.Message), NEW, EXTENSIBLE;
VAR v: Views.View;
BEGIN
ASSERT(c.model # NIL, 20);
WITH msg: Properties.PollMsg DO
msg.prop := ThisProp(c, indirect)
| msg: Properties.SetMsg DO
SetProp(c, msg.old, msg.prop, indirect)
| msg: Properties.FocusPref DO
IF {noSelection, noFocus, noCaret} - c.opts # {} THEN msg.setFocus := TRUE END
| msg: GetOpts DO
msg.valid := modeOpts; msg.opts := c.opts
| msg: SetOpts DO
c.SetOpts(c.opts - msg.valid + (msg.opts * msg.valid))
| msg: Properties.ControlPref DO
IF c.opts * modeOpts = mask THEN
v := msg.focus;
IF v = c.view THEN v := c.focus END;
CollectControlPref(c, v, msg.char, FALSE, v, msg.getFocus, msg.accepts);
IF msg.getFocus THEN msg.accepts := TRUE END
END
ELSE
END
END HandlePropMsg;
(** Directory **)
PROCEDURE (d: Directory) NewController* (opts: SET): Controller, NEW, ABSTRACT;
PROCEDURE (d: Directory) New* (): Controller, NEW, EXTENSIBLE;
BEGIN
RETURN d.NewController({})
END New;
(* ViewOp *)
PROCEDURE (op: ViewOp) Do;
VAR v: View; c0, c1: Controller; a0, a1: Stores.Store;
BEGIN
v := op.v; c0 := v.controller; a0 := v.alienCtrl; c1 := op.controller; a1 := op.alienCtrl;
IF c0 # NIL THEN c0.InitView(NIL) END;
v.controller := c1; v.alienCtrl := a1;
op.controller := c0; op.alienCtrl := a0;
IF c1 # NIL THEN c1.InitView(v) END;
Views.Update(v, Views.keepFrames)
END Do;
(* ControllerOp *)
PROCEDURE (op: ControllerOp) Do;
VAR c: Controller; opts: SET;
BEGIN
c := op.c;
opts := c.opts; c.opts := op.opts; op.opts := opts;
Views.Update(c.view, Views.keepFrames)
END Do;
(* Controller implementation support *)
PROCEDURE BorderVisible (c: Controller; f: Views.Frame): BOOLEAN;
BEGIN
IF 31 IN c.opts THEN RETURN TRUE END;
IF f IS Views.RootFrame THEN RETURN FALSE END;
IF Services.Is(c.focus, "OleClient.View") THEN RETURN FALSE END;
RETURN TRUE
END BorderVisible;
PROCEDURE MarkFocus (c: Controller; f: Views.Frame; show: BOOLEAN);
VAR focus: Views.View; f1: Views.Frame; l, t, r, b: INTEGER;
BEGIN
focus := c.focus;
IF f.front & (focus # NIL) & (~show OR c.bVis) & BorderVisible(c, f) & ~(noSelection IN c.opts) THEN
f1 := Views.ThisFrame(f, focus);
IF f1 # NIL THEN
c.bVis := show;
c.view.GetRect(f, focus, l, t, r, b);
IF (l # MAX(INTEGER)) & (t # MAX(INTEGER)) THEN
Mechanisms.MarkFocusBorder(f, focus, l, t, r, b, show)
END
END
END
END MarkFocus;
PROCEDURE MarkSingleton* (c: Controller; f: Views.Frame; show: BOOLEAN);
VAR l, t, r, b: INTEGER;
BEGIN
IF (*(f.front OR f.target) &*) (~show OR c.bVis) & (c.singleton # NIL) THEN
c.bVis := show;
c.view.GetRect(f, c.singleton, l, t, r, b);
IF (l # MAX(INTEGER)) & (t # MAX(INTEGER)) THEN
Mechanisms.MarkSingletonBorder(f, c.singleton, l, t, r, b, show)
END
END
END MarkSingleton;
PROCEDURE FadeMarks* (c: Controller; show: BOOLEAN);
VAR msg: FadeMsg; v: Views.View; fc: Controller;
BEGIN
IF (c.focus # NIL) OR (c.singleton # NIL) THEN
IF c.bVis # show THEN
IF ~show THEN
v := c.focus;
WHILE (v # NIL) & (v IS View) DO
fc := v(View).ThisController();
fc.bVis := FALSE; v := fc.focus
END
END;
c.bVis := show; msg.show := show; Views.Broadcast(c.view, msg)
END
END
END FadeMarks;
(* handle controller messages in editor mode *)
PROCEDURE ClaimFocus (v: Views.View): BOOLEAN;
VAR p: Properties.FocusPref;
BEGIN
p.atLocation := FALSE;
p.hotFocus := FALSE; p.setFocus := FALSE;
Views.HandlePropMsg(v, p);
RETURN p.setFocus
END ClaimFocus;
PROCEDURE ClaimFocusAt (v: Views.View; f, g: Views.Frame; x, y: INTEGER; mask: BOOLEAN): BOOLEAN;
VAR p: Properties.FocusPref;
BEGIN
p.atLocation := TRUE; p.x := x + f.gx - g.gx; p.y := y + f.gy - g.gy;
p.hotFocus := FALSE; p.setFocus := FALSE;
Views.HandlePropMsg(v, p);
RETURN p.setFocus & (mask OR ~p.hotFocus)
END ClaimFocusAt;
PROCEDURE NeedFocusAt (v: Views.View; f, g: Views.Frame; x, y: INTEGER): BOOLEAN;
VAR p: Properties.FocusPref;
BEGIN
p.atLocation := TRUE; p.x := x + f.gx - g.gx; p.y := y + f.gy - g.gy;
p.hotFocus := FALSE; p.setFocus := FALSE;
Views.HandlePropMsg(v, p);
RETURN p.hotFocus OR p.setFocus
END NeedFocusAt;
PROCEDURE TrackToResize (c: Controller; f: Views.Frame; v: Views.View; x, y: INTEGER; buttons: SET);
VAR minW, maxW, minH, maxH, l, t, r, b, w0, h0, w, h: INTEGER; op: INTEGER; sg, fc: Views.View;
BEGIN
c.model.GetEmbeddingLimits(minW, maxW, minH, maxH);
c.view.GetRect(f, v, l, t, r, b);
w0 := r - l; h0 := b - t; w := w0; h := h0;
Mechanisms.TrackToResize(f, v, minW, maxW, minH, maxH, l, t, r, b, op, x, y, buttons);
IF op = Mechanisms.resize THEN
sg := c.singleton; fc := c.focus;
c.Resize(v, l, t, r, b);
IF c.singleton # sg THEN c.SetSingleton(sg) END;
IF c.focus # fc THEN c.focus := fc; c.bVis := FALSE END (* delayed c.SetFocus(fc) *)
END
END TrackToResize;
PROCEDURE TrackToDrop (c: Controller; f: Views.Frame; VAR x, y: INTEGER; buttons: SET;
VAR pass: BOOLEAN);
VAR dest: Views.Frame; m: Models.Model; v: Views.View;
x0, y0, x1, y1, w, h, rx, ry, destX, destY: INTEGER; op: INTEGER; isDown, isSingle: BOOLEAN; mo: SET;
script: Stores.Operation;
BEGIN (* drag and drop c's selection: mouse is in selection *)
x0 := x; y0 := y;
REPEAT
f.Input(x1, y1, mo, isDown)
UNTIL ~isDown OR (ABS(x1 - x) > 3 * Ports.point) OR (ABS(y1 - y) > 3 * Ports.point);
pass := ~isDown;
IF ~pass THEN
v := c.Singleton();
IF v = NIL THEN v := c.view; isSingle := FALSE
ELSE isSingle := TRUE
END;
c.GetSelectionBounds(f, rx, ry, w, h);
rx := x0 - rx; ry := y0 - ry;
IF rx < 0 THEN rx := 0 ELSIF rx > w THEN rx := w END;
IF ry < 0 THEN ry := 0 ELSIF ry > h THEN ry := h END;
IF noCaret IN c.opts THEN op := Mechanisms.copy ELSE op := 0 END;
Mechanisms.TrackToDrop(f, v, isSingle, w, h, rx, ry, dest, destX, destY, op, x, y, buttons);
IF (op IN {Mechanisms.copy, Mechanisms.move}) THEN (* copy or move selection *)
IF dest # NIL THEN
m := dest.view.ThisModel();
IF (dest.view = c.view) OR (m # NIL) & (m = c.view.ThisModel()) THEN (* local drop *)
IF op = Mechanisms.copy THEN (* local copy *)
c.CopyLocalSelection(f, dest, x0, y0, destX, destY)
ELSIF op = Mechanisms.move THEN (* local move *)
c.MoveLocalSelection(f, dest, x0, y0, destX, destY)
END
ELSE (* non-local drop *)
CopyView(c, v, w, h); (* create copy of selection *)
IF (op = Mechanisms.copy) OR (noCaret IN c.opts) THEN (* drop copy *)
Controllers.Drop(x, y, f, x0, y0, v, isSingle, w, h, rx, ry)
ELSIF op = Mechanisms.move THEN (* drop copy and delete original *)
IF (c.view.Domain() # NIL) & (c.view.Domain() = dest.view.Domain()) THEN
Views.BeginScript(c.view, "#System:Moving", script)
ELSE script := NIL
END;
c.DeleteSelection; (* delete first because Controllers.Drop can remove the selection *)
Controllers.Drop(x, y, f, x0, y0, v, isSingle, w, h, rx, ry);
IF script # NIL THEN Views.EndScript(c.view, script) END
END
END
ELSIF (op = Mechanisms.move) & ~(noCaret IN c.opts) THEN
c.DeleteSelection
END
END
END
END TrackToDrop;
PROCEDURE TrackToPick (c: Controller; f: Views.Frame; x, y: INTEGER; buttons: SET;
VAR pass: BOOLEAN);
VAR p: Properties.Property; dest: Views.Frame; x0, y0, x1, y1, destX, destY: INTEGER;
op: INTEGER; isDown: BOOLEAN; m: SET;
BEGIN
x0 := x; y0 := y;
REPEAT
f.Input(x1, y1, m, isDown)
UNTIL ~isDown OR (ABS(x1 - x) > 3 * Ports.point) OR (ABS(y1 - y) > 3 * Ports.point);
pass := ~isDown;
IF ~pass THEN
Mechanisms.TrackToPick(f, dest, destX, destY, op, x, y, buttons);
IF op IN {Mechanisms.pick, Mechanisms.pickForeign} THEN
Properties.Pick(x, y, f, x0, y0, p);
IF p # NIL THEN SetProp(c, NIL, p, direct) END
END
END
END TrackToPick;
PROCEDURE MarkViews (f: Views.Frame);
VAR x, y: INTEGER; isDown: BOOLEAN; root: Views.RootFrame; m: SET;
BEGIN
root := Views.RootOf(f);
Views.MarkBorders(root);
REPEAT f.Input(x, y, m, isDown) UNTIL ~isDown;
Views.MarkBorders(root)
END MarkViews;
PROCEDURE Track (c: Controller; f: Views.Frame; VAR msg: Controllers.TrackMsg; VAR focus: Views.View);
VAR res, l, t, r, b: INTEGER; cursor: INTEGER; sel: Views.View; obj: Views.Frame;
inSel, pass, extend, add, double, popup, pick: BOOLEAN;
BEGIN
cursor := Mechanisms.outside; sel := c.Singleton();
IF focus # NIL THEN
c.view.GetRect(f, focus, l, t, r, b);
IF (BorderVisible(c, f) OR (f IS Views.RootFrame)) & ~(noSelection IN c.opts) THEN
cursor := Mechanisms.FocusBorderCursor(f, focus, l, t, r, b, msg.x, msg.y)
ELSIF (msg.x >= l) & (msg.x <= r) & (msg.y >= t) & (msg.y <= b) THEN
cursor := Mechanisms.inside
END
ELSIF sel # NIL THEN
c.view.GetRect(f, sel, l, t, r, b);
cursor := Mechanisms.SelBorderCursor(f, sel, l, t, r, b, msg.x, msg.y)
END;
IF cursor >= 0 THEN
IF focus # NIL THEN
(* resize focus *)
TrackToResize(c, f, focus, msg.x, msg.y, msg.modifiers);
focus := NIL
ELSE
(* resize singleton *)
TrackToResize(c, f, sel, msg.x, msg.y, msg.modifiers)
END
ELSIF (focus # NIL) & (cursor = Mechanisms.inside) THEN
(* forward to focus *)
ELSE
IF (focus # NIL) & (c.opts * modeOpts # mask) THEN c.SetFocus(NIL) END;
focus := NIL;
inSel := c.InSelection(f, msg.x, msg.y);
extend := Controllers.extend IN msg.modifiers;
add := Controllers.modify IN msg.modifiers;
double := Controllers.doubleClick IN msg.modifiers;
popup := Controllers.popup IN msg.modifiers;
pick := Controllers.pick IN msg.modifiers;
obj := Views.FrameAt(f, msg.x, msg.y);
IF ~inSel & (~extend OR (noSelection IN c.opts)) THEN
IF obj # NIL THEN
IF ~(noFocus IN c.opts) & NeedFocusAt(obj.view, f, obj, msg.x, msg.y)
& (~pick OR (noSelection IN c.opts)) THEN
(* set hot focus *)
focus := obj.view;
IF ClaimFocusAt(focus, f, obj, msg.x, msg.y, c.opts * modeOpts = mask) THEN
(* set permanent focus *)
c.SelectAll(deselect);
c.SetFocus(focus)
END
END;
IF (focus = NIL) & ~add & ~(noSelection IN c.opts) THEN
(* select object *)
c.SelectAll(deselect);
c.SetSingleton(obj.view); inSel := TRUE
END
ELSIF ~add THEN c.SelectAll(deselect)
END
END;
IF focus = NIL THEN
IF inSel & double & (popup OR pick) THEN (* properties *)
Dialog.Call("StdCmds.ShowProp", "", res)
ELSIF inSel & double & (obj # NIL) THEN (* primary verb *)
Dialog.Call("StdMenuTool.PrimaryVerb", "", res)
ELSIF ~inSel & pick & extend THEN
MarkViews(f)
ELSE
IF inSel & ~extend THEN (* drag *)
IF pick THEN
IF ~(noCaret IN c.opts) THEN
TrackToPick(c, f, msg.x, msg.y, msg.modifiers, pass)
END
ELSE
TrackToDrop(c, f, msg.x, msg.y, msg.modifiers, pass)
END;
IF ~pass THEN RETURN END
END;
IF ~(noSelection IN c.opts) & (~inSel OR extend OR add OR (obj = NIL) & ~popup) THEN (* select *)
c.TrackMarks(f, msg.x, msg.y, double, extend, add)
END;
IF popup THEN Dialog.Call("StdMenuTool.PopupMenu", "", res) END
END
END
END
END Track;
PROCEDURE CopyView (source: Controller; VAR view: Views.View; VAR w, h: INTEGER);
VAR s: Views.View; m: Model; v: View; p: Properties.BoundsPref;
BEGIN
s := source.Singleton();
IF s # NIL THEN (* create a copy of singular selection *)
view := Views.CopyOf(s, Views.deep); s.context.GetSize(w, h)
ELSE (* create a copy of view with a copy of whole selection as contents *)
m := source.SelectionCopy();
v := Views.CopyWithNewModel(source.view, m)(View);
p.w := Views.undefined; p.h := Views.undefined; Views.HandlePropMsg(v, p);
view := v; w := p.w; h := p.h
END
END CopyView;
PROCEDURE Paste (c: Controller; f: Views.Frame; v: Views.View; w, h: INTEGER);
VAR m: Models.Model;
BEGIN
m := v.ThisModel();
IF (m # NIL) & c.NativeModel(m) THEN
(* paste whole contents of source view *)
c.NativePaste(m, f)
ELSE
(* paste whole view *)
c.PasteView(f, v (* Views.CopyOf(v, Views.deep) *), w, h)
END
END Paste;
PROCEDURE GetValidOps (c: Controller; VAR valid: SET);
BEGIN
valid := {}; c.GetValidOps(valid);
IF noCaret IN c.opts THEN
valid := valid
- {Controllers.pasteChar, Controllers.pasteChar,
Controllers.paste, Controllers.cut}
END
END GetValidOps;
PROCEDURE Transfer (c: Controller; f: Views.Frame;
VAR msg: Controllers.TransferMessage; VAR focus: Views.View);
VAR g: Views.Frame; inSelection: BOOLEAN; dMsg: DropPref;
BEGIN
focus := NIL;
g := Views.FrameAt(f, msg.x, msg.y);
WITH msg: Controllers.PollDropMsg DO
inSelection := c.InSelection(f, msg.x, msg.y);
dMsg.mode := c.opts; dMsg.okToDrop := FALSE;
IF g # NIL THEN Views.HandlePropMsg(g.view, dMsg) END;
IF (g # NIL) & ~inSelection & (dMsg.okToDrop OR ~(noFocus IN c.opts))THEN
focus := g.view
ELSIF ~(noCaret IN c.opts) & c.CanDrop(f, msg.x, msg.y) THEN
msg.dest := f;
IF msg.mark THEN
c.MarkDropTarget(msg.source, f, msg.sourceX, msg.sourceY, msg.x, msg.y, msg.w, msg.h, msg.rx, msg.ry,
msg.type, msg.isSingle, msg.show)
END
END
| msg: Controllers.DropMsg DO
inSelection := c.InSelection(f, msg.x, msg.y);
dMsg.mode := c.opts; dMsg.okToDrop := FALSE;
IF g # NIL THEN Views.HandlePropMsg(g.view, dMsg) END;
IF (g # NIL) & ~inSelection & (dMsg.okToDrop OR ~(noFocus IN c.opts))THEN
c.SetFocus(g.view);
focus := g.view
ELSIF ~(noCaret IN c.opts) & c.CanDrop(f, msg.x, msg.y) THEN
c.Drop(msg.source, f, msg.sourceX, msg.sourceY, msg.x, msg.y, msg.w, msg.h,
msg.rx, msg.ry, msg.view, msg.isSingle)
END
| msg: Properties.PollPickMsg DO
IF g # NIL THEN
focus := g.view
ELSE
msg.dest := f;
IF msg.mark THEN
c.MarkPickTarget(msg.source, f, msg.sourceX, msg.sourceY, msg.x, msg.y, msg.show)
END
END
| msg: Properties.PickMsg DO
IF g # NIL THEN
focus := g.view
ELSE
c.PickNativeProp(f, msg.x, msg.y, msg.prop)
END
ELSE
IF g # NIL THEN focus := g.view END
END
END Transfer;
PROCEDURE FocusHasSel (): BOOLEAN;
VAR msg: Controllers.PollOpsMsg;
BEGIN
Controllers.PollOps(msg);
RETURN msg.selectable & (Controllers.copy IN msg.valid)
END FocusHasSel;
PROCEDURE FocusEditor (): Controller;
VAR msg: PollFocusMsg;
BEGIN
msg.focus := NIL; msg.ctrl := NIL; msg.all := FALSE;
Controllers.Forward(msg);
RETURN msg.ctrl
END FocusEditor;
PROCEDURE Edit (c: Controller; f: Views.Frame;
VAR msg: Controllers.EditMsg; VAR focus: Views.View);
VAR g: Views.Frame; v: Views.View; res: INTEGER;
valid: SET; select, units, getFocus, accepts: BOOLEAN;
sel: Controllers.SelectMsg;
BEGIN
IF (c.opts * modeOpts # mask) & (focus = NIL) THEN
IF (msg.op = Controllers.pasteChar) & (msg.char = ESC) THEN
c.SelectAll(FALSE)
ELSIF (c.Singleton() # NIL) & (msg.op = Controllers.pasteChar) &
(msg.char = ENTER) THEN
Dialog.Call("StdMenuTool.PrimaryVerb", "", res)
ELSE
GetValidOps(c, valid);
IF msg.op IN valid THEN
CASE msg.op OF
| Controllers.pasteChar:
IF msg.char >= " " THEN
c.PasteChar(msg.char)
ELSIF (AL <= msg.char) & (msg.char <= AD) OR
(PL <= msg.char) & (msg.char <= DD) THEN
select := Controllers.extend IN msg.modifiers;
units := Controllers.modify IN msg.modifiers;
c.ArrowChar(f, msg.char, units, select)
ELSE c.ControlChar(f, msg.char)
END
| Controllers.cut, Controllers.copy:
CopyView(c, msg.view, msg.w, msg.h);
msg.isSingle := c.Singleton() # NIL;
IF msg.op = Controllers.cut THEN c.DeleteSelection END
| Controllers.paste:
IF msg.isSingle THEN
c.PasteView(f, msg.view (* Views.CopyOf(msg.view, Views.deep) *), msg.w, msg.h)
ELSE
Paste(c, f, msg.view, msg.w, msg.h)
END
ELSE
END
END
END
ELSIF (c.opts * modeOpts # mask)
& (msg.op = Controllers.pasteChar) & (msg.char = ESC)
& (~(f IS Views.RootFrame) OR (31 IN c.opts))
& (c = FocusEditor())
& ((Controllers.extend IN msg.modifiers) OR ~FocusHasSel()) THEN
IF 31 IN c.opts THEN INCL(msg.modifiers, 31)
ELSE c.SetSingleton(focus)
END;
focus := NIL
ELSIF (c.opts * modeOpts # mask) & (c = Focus()) THEN
(* do some generic processing for non-container views *)
IF (msg.op = Controllers.pasteChar) & (msg.char = ESC) THEN
g := Views.ThisFrame(f, focus);
IF g # NIL THEN sel.set := FALSE; Views.ForwardCtrlMsg(g, sel) END
END
ELSIF (c.opts * modeOpts = mask) & (msg.op = Controllers.pasteChar) THEN
IF Controllers.pick IN msg.modifiers THEN
CollectControlPref (c, NIL, msg.char, TRUE, v, getFocus, accepts)
ELSE
CollectControlPref (c, focus, msg.char, TRUE, v, getFocus, accepts)
END;
IF v = NIL THEN
CheckMaskFocus(c, f, focus);
CollectControlPref(c, focus, msg.char, TRUE, v, getFocus, accepts)
END;
IF v # NIL THEN
IF getFocus & (v # focus) THEN
c.SetFocus(v)
END;
IF accepts THEN
g := Views.ThisFrame(f, v);
IF g # NIL THEN Views.ForwardCtrlMsg(g, msg) END
END;
focus := NIL
END
END
END Edit;
PROCEDURE PollCursor (c: Controller; f: Views.Frame; VAR msg: Controllers.PollCursorMsg; VAR focus: Views.View);
VAR l, t, r, b: INTEGER; cursor: INTEGER; sel: Views.View; obj: Views.Frame; inSel: BOOLEAN;
BEGIN
cursor := Mechanisms.outside; sel := c.Singleton();
IF focus # NIL THEN
c.view.GetRect(f, focus, l, t, r, b);
IF (BorderVisible(c, f) OR (f IS Views.RootFrame)) & ~(noSelection IN c.opts) THEN
cursor := Mechanisms.FocusBorderCursor(f, focus, l, t, r, b, msg.x, msg.y)
ELSIF (msg.x >= l) & (msg.x <= r) & (msg.y >= t) & (msg.y <= b) THEN
cursor := Mechanisms.inside
END
ELSIF sel # NIL THEN
c.view.GetRect(f, sel, l, t, r, b);
cursor := Mechanisms.SelBorderCursor(f, sel, l, t, r, b, msg.x, msg.y)
END;
IF cursor >= 0 THEN
msg.cursor := cursor; focus := NIL
ELSIF (focus # NIL) & (cursor = Mechanisms.inside) THEN
msg.cursor := Ports.arrowCursor
ELSE
IF noCaret IN c.opts THEN msg.cursor := Ports.arrowCursor
ELSE msg.cursor := c.NativeCursorAt(f, msg.x, msg.y) (* if nothing else, use native cursor *)
END;
focus := NIL; inSel := FALSE;
IF ~(noSelection IN c.opts) THEN inSel := c.InSelection(f, msg.x, msg.y) END;
IF ~inSel THEN
obj := Views.FrameAt(f, msg.x, msg.y);
IF obj # NIL THEN
IF ~(noFocus IN c.opts) & NeedFocusAt(obj.view, f, obj, msg.x, msg.y) THEN
focus := obj.view;
msg.cursor := Ports.arrowCursor
ELSIF ~(noSelection IN c.opts) THEN
inSel := TRUE
END
END
END;
IF focus = NIL THEN
IF inSel THEN
msg.cursor := Ports.arrowCursor
END
END
END
END PollCursor;
PROCEDURE PollOps (c: Controller; f: Views.Frame;
VAR msg: Controllers.PollOpsMsg; VAR focus: Views.View);
BEGIN
IF focus = NIL THEN
msg.type := "";
IF ~(noSelection IN c.opts) THEN c.GetContextType(msg.type) END;
msg.selectable := ~(noSelection IN c.opts) & c.Selectable();
GetValidOps(c, msg.valid);
msg.singleton := c.Singleton()
END
END PollOps;
PROCEDURE ReplaceView (c: Controller; old, new: Views.View);
BEGIN
ASSERT(old.context # NIL, 20);
ASSERT((new.context = NIL) OR (new.context = old.context), 22);
IF old.context.ThisModel() = c.model THEN
c.model.ReplaceView(old, new)
END;
IF c.singleton = old THEN c.singleton := new END;
IF c.focus = old THEN c.focus := new END
END ReplaceView;
PROCEDURE ViewProp (v: Views.View): Properties.Property;
VAR poll: Properties.PollMsg;
BEGIN
poll.prop := NIL; Views.HandlePropMsg(v, poll); RETURN poll.prop
END ViewProp;
PROCEDURE SetViewProp (v: Views.View; old, p: Properties.Property);
VAR set: Properties.SetMsg;
BEGIN
set.old := old; set.prop := p; Views.HandlePropMsg(v, set)
END SetViewProp;
PROCEDURE SizeProp (v: Views.View): Properties.Property;
VAR sp: Properties.SizeProp;
BEGIN
NEW(sp); sp.known := {Properties.width, Properties.height}; sp.valid := sp.known;
v.context.GetSize(sp.width, sp.height);
RETURN sp
END SizeProp;
PROCEDURE SetSizeProp (v: Views.View; p: Properties.SizeProp);
VAR w, h: INTEGER;
BEGIN
IF p.valid # {Properties.width, Properties.height} THEN
v.context.GetSize(w, h)
END;
IF Properties.width IN p.valid THEN w := p.width END;
IF Properties.height IN p.valid THEN h := p.height END;
v.context.SetSize(w, h)
END SetSizeProp;
PROCEDURE ThisProp (c: Controller; direct: BOOLEAN): Properties.Property;
CONST scanCutoff = MAX(INTEGER) (* 50 *); (* bound number of polled embedded views *)
VAR v: Views.View; np, vp, p: Properties.Property; k: INTEGER; trunc, equal: BOOLEAN;
BEGIN
trunc := FALSE; k := 1;
np := NIL; c.PollNativeProp(direct, np, trunc);
v := NIL; c.GetFirstView(direct, v);
IF v # NIL THEN
Properties.Insert(np, SizeProp(v));
vp := ViewProp(v);
k := scanCutoff; c.GetNextView(direct, v);
WHILE (v # NIL) & (k > 0) DO
DEC(k);
Properties.Insert(np, SizeProp(v));
Properties.Intersect(vp, ViewProp(v), equal);
c.GetNextView(direct, v)
END;
IF c.singleton # NIL THEN Properties.Merge(np, vp); vp := np
ELSE Properties.Merge(vp, np)
END
ELSE vp := np
END;
IF trunc OR (k = 0) THEN
p := vp; WHILE p # NIL DO p.valid := {}; p := p.next END
END;
IF noCaret IN c.opts THEN
p := vp; WHILE p # NIL DO p.readOnly := p.valid; p := p.next END
END;
RETURN vp
END ThisProp;
PROCEDURE SetProp (c: Controller; old, p: Properties.Property; direct: BOOLEAN);
TYPE
ViewList = POINTER TO RECORD next: ViewList; view: Views.View END;
VAR v: Views.View; q, sp: Properties.Property; equal: BOOLEAN; s: Stores.Operation;
list, last: ViewList;
BEGIN
IF noCaret IN c.opts THEN RETURN END;
Views.BeginScript(c.view, "#System:SetProp", s);
q := p; WHILE (q # NIL) & ~(q IS Properties.SizeProp) DO q := q.next END;
list := NIL; v := NIL; c.GetFirstView(direct, v);
WHILE v # NIL DO
IF list = NIL THEN NEW(list); last := list
ELSE NEW(last.next); last := last.next
END;
last.view := v;
c.GetNextView(direct, v)
END;
c.SetNativeProp(direct, old, p);
WHILE list # NIL DO
v := list.view; list := list.next;
SetViewProp(v, old, p);
IF direct & (q # NIL) THEN
(* q IS Properties.SizeProp *)
IF old # NIL THEN
sp := SizeProp(v);
Properties.Intersect(sp, old, equal);
Properties.Intersect(sp, old, equal)
END;
IF (old = NIL) OR equal THEN
SetSizeProp(v, q(Properties.SizeProp))
END
END
END;
Views.EndScript(c.view, s)
END SetProp;
PROCEDURE Wheel (c: Controller; f: Views.Frame;
VAR msg: Controllers.WheelMsg; VAR focus: Views.View);
VAR g: Views.Frame; dx, dy: INTEGER;
BEGIN
g := Views.FrameAt(f, msg.x, msg.y);
IF g # NIL THEN focus := g.view; ASSERT(focus.context.ThisModel() = c.model, 20) END
END Wheel;
PROCEDURE (c: Controller) HandleCtrlMsg* (f: Views.Frame;
VAR msg: Controllers.Message; VAR focus: Views.View), NEW, EXTENSIBLE;
BEGIN
focus := c.focus;
WITH msg: Controllers.PollCursorMsg DO
PollCursor(c, f, msg, focus)
| msg: Controllers.PollOpsMsg DO
PollOps(c, f, msg, focus)
| msg: PollFocusMsg DO
IF msg.all OR (c.opts * modeOpts # mask) & (c.focus # NIL) THEN msg.ctrl := c END
| msg: Controllers.TrackMsg DO
Track(c, f, msg, focus)
| msg: Controllers.EditMsg DO
Edit(c, f, msg, focus)
| msg: Controllers.TransferMessage DO
Transfer(c, f, msg, focus)
| msg: Controllers.SelectMsg DO
IF focus = NIL THEN c.SelectAll(msg.set) END
| msg: Controllers.TickMsg DO
FadeMarks(c, show);
CheckMaskFocus(c, f, focus)
| msg: Controllers.MarkMsg DO
c.bVis := msg.show;
c.Mark(f, f.l, f.t, f.r, f.b, msg.show)
| msg: Controllers.ReplaceViewMsg DO
ReplaceView(c, msg.old, msg.new)
| msg: Properties.CollectMsg DO
IF focus = NIL THEN
msg.poll.prop := ThisProp(c, direct)
END
| msg: Properties.EmitMsg DO
IF focus = NIL THEN
SetProp(c, msg.set.old, msg.set.prop, direct)
END
| msg: Controllers.WheelMsg DO Wheel(c, f, msg, focus)
ELSE
END
END HandleCtrlMsg;
(** miscellaneous **)
PROCEDURE Focus* (): Controller;
VAR msg: PollFocusMsg;
BEGIN
msg.focus := NIL; msg.ctrl := NIL; msg.all := TRUE;
Controllers.Forward(msg);
RETURN msg.ctrl
END Focus;
PROCEDURE FocusSingleton* (): Views.View;
VAR c: Controller; v: Views.View;
BEGIN
c := Focus();
IF c # NIL THEN v := c.Singleton() ELSE v := NIL END;
RETURN v
END FocusSingleton;
PROCEDURE CloneOf* (m: Model): Model;
VAR h: Model;
BEGIN
ASSERT(m # NIL, 20);
Kernel.NewObj(h, Kernel.TypeOf(m));
h.InitFrom(m);
RETURN h
END CloneOf;
END Containers.
| System/Mod/Containers.odc |
MODULE Controllers;
(** project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20141213, center #21, Fixing Controllers.TickMsg.tick overflow bug.
- 20170905, center #173, adding new modifiers to Controllers
"
issues = "
- ...
"
**)
IMPORT Kernel, Services, Ports, Stores, Models, Views;
CONST
(** Forward target **)
targetPath* = TRUE; frontPath* = FALSE;
(** ScrollMsg.op **)
decLine* = 0; incLine* = 1; decPage* = 2; incPage* = 3; gotoPos* = 4;
(** PageMsg.op **)
nextPageX* = 0; nextPageY* = 1; gotoPageX* = 2; gotoPageY* = 3;
(** PollOpsMsg.valid, EditMsg.op **)
cut* = 0; copy* = 1;
pasteChar* = 2; (* pasteLChar* = 3; *) paste* = 4; (* pasteView* = 5; *)
(** TrackMsg.modifiers, EditMsg.modifiers **)
doubleClick* = 0; (** clicking history **)
extend* = 1; modify* = 2; (** modifier keys **)
popup* = 3; (** show popup menu **)
pick* = 4; (** pick attributes **)
(** PollDropMsg.mark, PollDrop mark **)
noMark* = FALSE; mark* = TRUE;
(** PollDropMsg.show, PollDrop show **)
hide* = FALSE; show* = TRUE;
minVersion = 0; maxVersion = 0;
tickInterval = 100;
TYPE
(** messages **)
Message* = Views.CtrlMessage;
PollFocusMsg* = EXTENSIBLE RECORD (Message)
focus*: Views.Frame (** OUT, preset to NIL **)
END;
PollSectionMsg* = RECORD (Message)
focus*, vertical*: BOOLEAN; (** IN **)
wholeSize*: INTEGER; (** OUT, preset to 1 **)
partSize*: INTEGER; (** OUT, preset to 1 **)
partPos*: INTEGER; (** OUT, preset to 0 **)
valid*, done*: BOOLEAN (** OUT, preset to (FALSE, FALSE) **)
END;
PollOpsMsg* = RECORD (Message)
type*: Stores.TypeName; (** OUT, preset to "" **)
pasteType*: Stores.TypeName; (** OUT, preset to "" **)
singleton*: Views.View; (** OUT, preset to NIL **)
selectable*: BOOLEAN; (** OUT, preset to FALSE **)
valid*: SET (** OUT, preset to {} **)
END;
ScrollMsg* = RECORD (Message)
focus*, vertical*: BOOLEAN; (** IN **)
op*: INTEGER; (** IN **)
pos*: INTEGER; (** IN **)
done*: BOOLEAN (** OUT, preset to FALSE **)
END;
PageMsg* = RECORD (Message)
op*: INTEGER; (** IN **)
pageX*, pageY*: INTEGER; (** IN **)
done*, eox*, eoy*: BOOLEAN (** OUT, preset to (FALSE, FALSE, FALSE) **)
END;
TickMsg* = RECORD (Message)
tick*: LONGINT (** IN **)
END;
MarkMsg* = RECORD (Message)
show*: BOOLEAN; (** IN **)
focus*: BOOLEAN (** IN **)
END;
SelectMsg* = RECORD (Message)
set*: BOOLEAN (** IN **)
END;
RequestMessage* = ABSTRACT RECORD (Message)
requestFocus*: BOOLEAN (** OUT, preset (by framework) to FALSE **)
END;
EditMsg* = RECORD (RequestMessage)
op*: INTEGER; (** IN **)
modifiers*: SET; (** IN, valid if op IN {pasteChar, pasteLchar} **)
char*: CHAR; (** IN, valid if op = pasteChar **)
view*: Views.View; w*, h*: INTEGER; (** IN, valid if op = paste **)
(** OUT, valid if op IN {cut, copy} **)
isSingle*: BOOLEAN; (** dito **)
clipboard*: BOOLEAN (** IN, valid if op IN {cut, copy, paste} **)
END;
ReplaceViewMsg* = RECORD (RequestMessage)
old*, new*: Views.View (** IN **)
END;
CursorMessage* = ABSTRACT RECORD (RequestMessage)
x*, y*: INTEGER (** IN, needs translation when passed on **)
END;
PollCursorMsg* = RECORD (CursorMessage)
cursor*: INTEGER; (** OUT, preset to Ports.arrowCursor **)
modifiers*: SET (** IN **)
END;
TrackMsg* = RECORD (CursorMessage)
modifiers*: SET (** IN **)
END;
WheelMsg* = RECORD (CursorMessage)
done*: BOOLEAN; (** must be set if the message is handled **)
op*, nofLines*: INTEGER;
modifiers*: SET (** IN **)
END;
TransferMessage* = ABSTRACT RECORD (CursorMessage)
source*: Views.Frame; (** IN, home frame of transfer originator, may be NIL if unknown **)
sourceX*, sourceY*: INTEGER (** IN, reference point in source frame, defined if source # NIL **)
END;
PollDropMsg* = RECORD (TransferMessage)
mark*: BOOLEAN; (** IN, request to mark drop target **)
show*: BOOLEAN; (** IN, if mark then show/hide target mark **)
type*: Stores.TypeName; (** IN, type of view to drop **)
isSingle*: BOOLEAN; (** IN, view to drop is singleton **)
w*, h*: INTEGER; (** IN, size of view to drop, may be 0, 0 **)
rx*, ry*: INTEGER; (** IN, reference point in view **)
dest*: Views.Frame (** OUT, preset to NIL, set if DropMsg is acceptable **)
END;
DropMsg* = RECORD (TransferMessage)
view*: Views.View; (** IN, drop this *)
isSingle*: BOOLEAN; (** IN, view to drop is singleton **)
w*, h*: INTEGER; (** IN, proposed size *)
rx*, ry*: INTEGER (** IN, reference point in view **)
END;
(** controllers **)
Controller* = POINTER TO ABSTRACT RECORD (Stores.Store) END;
(** forwarders **)
Forwarder* = POINTER TO ABSTRACT RECORD
next: Forwarder
END;
TrapCleaner = POINTER TO RECORD (Kernel.TrapCleaner) END;
PathInfo = POINTER TO RECORD
path: BOOLEAN; prev: PathInfo
END;
BalanceCheckAction = POINTER TO RECORD (Services.Action)
wait: WaitAction
END;
WaitAction = POINTER TO RECORD (Services.Action)
check: BalanceCheckAction
END;
Ticker = POINTER TO RECORD (Services.Action) END;
VAR
path-: BOOLEAN;
list: Forwarder;
cleaner: TrapCleaner;
prevPath, cache: PathInfo;
(** BalanceCheckAction **)
PROCEDURE (a: BalanceCheckAction) Do;
BEGIN
Services.DoLater(a.wait, Services.resolution);
ASSERT(prevPath = NIL, 100);
END Do;
PROCEDURE (a: WaitAction) Do;
BEGIN
Services.DoLater(a.check, Services.immediately)
END Do;
(** Cleaner **)
PROCEDURE (c: TrapCleaner) Cleanup;
BEGIN
path := frontPath;
prevPath := NIL
END Cleanup;
PROCEDURE NewPathInfo(): PathInfo;
VAR c: PathInfo;
BEGIN
IF cache = NIL THEN NEW(c)
ELSE c := cache; cache := cache.prev
END;
RETURN c
END NewPathInfo;
PROCEDURE DisposePathInfo(c: PathInfo);
BEGIN
c.prev := cache; cache := c
END DisposePathInfo;
(** Controller **)
PROCEDURE (c: Controller) Internalize- (VAR rd: Stores.Reader), EXTENSIBLE;
(** pre: ~c.init **)
(** post: c.init **)
VAR thisVersion: INTEGER;
BEGIN
c.Internalize^(rd);
rd.ReadVersion(minVersion, maxVersion, thisVersion)
END Internalize;
PROCEDURE (c: Controller) Externalize- (VAR wr: Stores.Writer), EXTENSIBLE;
(** pre: c.init **)
BEGIN
c.Externalize^(wr);
wr.WriteVersion(maxVersion)
END Externalize;
(** Forwarder **)
PROCEDURE (f: Forwarder) Forward* (target: BOOLEAN; VAR msg: Message), NEW, ABSTRACT;
PROCEDURE (f: Forwarder) Transfer* (VAR msg: TransferMessage), NEW, ABSTRACT;
PROCEDURE Register* (f: Forwarder);
VAR t: Forwarder;
BEGIN
ASSERT(f # NIL, 20);
t := list; WHILE (t # NIL) & (t # f) DO t := t.next END;
IF t = NIL THEN f.next := list; list := f END
END Register;
PROCEDURE Delete* (f: Forwarder);
VAR t: Forwarder;
BEGIN
ASSERT(f # NIL, 20);
IF f = list THEN
list := list.next
ELSE
t := list; WHILE (t # NIL) & (t.next # f) DO t := t.next END;
IF t # NIL THEN t.next := f.next END
END;
f.next := NIL
END Delete;
PROCEDURE ForwardVia* (target: BOOLEAN; VAR msg: Message);
VAR t: Forwarder;
BEGIN
t := list; WHILE t # NIL DO t.Forward(target, msg); t := t.next END
END ForwardVia;
PROCEDURE SetCurrentPath* (target: BOOLEAN);
VAR p: PathInfo;
BEGIN
IF prevPath = NIL THEN Kernel.PushTrapCleaner(cleaner) END;
p := NewPathInfo(); p.prev := prevPath; prevPath := p; p.path := path;
path := target
END SetCurrentPath;
PROCEDURE ResetCurrentPath*;
VAR p: PathInfo;
BEGIN
IF prevPath # NIL THEN (* otherwise trap cleaner may have already removed prefPath objects *)
p := prevPath; prevPath := p.prev; path := p.path;
IF prevPath = NIL THEN Kernel.PopTrapCleaner(cleaner) END;
DisposePathInfo(p)
END
END ResetCurrentPath;
PROCEDURE Forward* (VAR msg: Message);
BEGIN
ForwardVia(path, msg)
END Forward;
PROCEDURE PollOps* (VAR msg: PollOpsMsg);
BEGIN
msg.type := "";
msg.pasteType := "";
msg.singleton := NIL;
msg.selectable := FALSE;
msg.valid := {};
Forward(msg)
END PollOps;
PROCEDURE PollCursor* (x, y: INTEGER; modifiers: SET; OUT cursor: INTEGER);
VAR msg: PollCursorMsg;
BEGIN
msg.x := x; msg.y := y; msg.cursor := Ports.arrowCursor; msg.modifiers := modifiers;
Forward(msg);
cursor := msg.cursor
END PollCursor;
PROCEDURE Transfer* (x, y: INTEGER; source: Views.Frame; sourceX, sourceY: INTEGER; VAR msg: TransferMessage);
VAR t: Forwarder;
BEGIN
ASSERT(source # NIL, 20);
msg.x := x; msg.y := y;
msg.source := source; msg.sourceX := sourceX; msg.sourceY := sourceY;
t := list; WHILE t # NIL DO t.Transfer(msg); t := t.next END
END Transfer;
PROCEDURE PollDrop* (x, y: INTEGER;
source: Views.Frame; sourceX, sourceY: INTEGER;
mark, show: BOOLEAN;
type: Stores.TypeName;
isSingle: BOOLEAN;
w, h, rx, ry: INTEGER;
OUT dest: Views.Frame; OUT destX, destY: INTEGER);
VAR msg: PollDropMsg;
BEGIN
ASSERT(source # NIL, 20);
msg.mark := mark; msg.show := show; msg.type := type; msg.isSingle := isSingle;
msg.w := w; msg.h := h; msg.rx := rx; msg.ry := ry; msg.dest := NIL;
Transfer(x, y, source, sourceX, sourceY, msg);
dest := msg.dest; destX := msg.x; destY := msg.y
END PollDrop;
PROCEDURE Drop* (x, y: INTEGER; source: Views.Frame; sourceX, sourceY: INTEGER;
view: Views.View; isSingle: BOOLEAN; w, h, rx, ry: INTEGER);
VAR msg: DropMsg;
BEGIN
ASSERT(source # NIL, 20); ASSERT(view # NIL, 21);
msg.view := view; msg.isSingle := isSingle;
msg.w := w; msg.h := h; msg.rx := rx; msg.ry := ry;
Transfer(x, y, source, sourceX, sourceY, msg)
END Drop;
PROCEDURE PasteView* (view: Views.View; w, h: INTEGER; clipboard: BOOLEAN);
VAR msg: EditMsg;
BEGIN
ASSERT(view # NIL, 20);
msg.op := paste; msg.isSingle := TRUE;
msg.clipboard := clipboard;
msg.view := view; msg.w := w; msg.h := h;
Forward(msg)
END PasteView;
PROCEDURE FocusFrame* (): Views.Frame;
VAR msg: PollFocusMsg;
BEGIN
msg.focus := NIL; Forward(msg); RETURN msg.focus
END FocusFrame;
PROCEDURE FocusView* (): Views.View;
VAR focus: Views.Frame;
BEGIN
focus := FocusFrame();
IF focus # NIL THEN RETURN focus.view ELSE RETURN NIL END
END FocusView;
PROCEDURE FocusModel* (): Models.Model;
VAR focus: Views.Frame;
BEGIN
focus := FocusFrame();
IF focus # NIL THEN RETURN focus.view.ThisModel() ELSE RETURN NIL END
END FocusModel;
PROCEDURE HandleCtrlMsgs (op: INTEGER; f, g: Views.Frame; VAR msg: Message; VAR mark, front, req: BOOLEAN);
(* g = f.up OR g = NIL *)
CONST pre = 0; translate = 1; backoff = 2; final = 3;
BEGIN
CASE op OF
pre:
WITH msg: MarkMsg DO
IF msg.show & (g # NIL) THEN mark := TRUE; front := g.front END
| msg: RequestMessage DO
msg.requestFocus := FALSE
ELSE
END
| translate:
WITH msg: CursorMessage DO
msg.x := msg.x + f.gx - g.gx;
msg.y := msg.y + f.gy - g.gy
ELSE
END
| backoff:
WITH msg: MarkMsg DO
IF ~msg.show THEN mark := FALSE; front := FALSE END
| msg: RequestMessage DO
req := msg.requestFocus
ELSE
END
| final:
WITH msg: PollFocusMsg DO
IF msg.focus = NIL THEN msg.focus := f END
| msg: MarkMsg DO
IF ~msg.show THEN mark := FALSE; front := FALSE END
| msg: RequestMessage DO
req := msg.requestFocus
ELSE
END
END
END HandleCtrlMsgs;
(** Ticker *)
PROCEDURE (a: Ticker) Do;
VAR tick: TickMsg;
BEGIN
tick.tick := Services.Ticks();
Services.DoLater(a, Services.Ticks() + tickInterval);
ForwardVia(frontPath, tick);
END Do;
PROCEDURE Init;
VAR action: BalanceCheckAction; w: WaitAction; ticker: Ticker;
BEGIN
Views.InitCtrl(HandleCtrlMsgs);
NEW(cleaner);
NEW(action); NEW(w); action.wait := w; w.check := action; Services.DoLater(action, Services.immediately);
NEW(ticker); Services.DoLater(ticker, Services.immediately);
END Init;
BEGIN
Init
END Controllers.
| System/Mod/Controllers.odc |
Subsets and Splits