texts
stringlengths 0
1.24M
| names
stringlengths 13
33
|
---|---|
MODULE ObxTabViews;
(**
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 StdTabViews, Views, Strings, Dialog, StdLog,
ObxCalc, ObxCubes;
VAR
st: StdTabViews.View;
calc: Views.View;
PROCEDURE New* (): StdTabViews.View;
VAR v: Views.View;
BEGIN
st := StdTabViews.dir.New();
calc := ObxCalc.New(); v := ObxCubes.New();
st.SetItem(0, 'Cube', v);
st.SetItem(1, 'Calc 1', calc);
st.SetItem(2, 'Calc 2', calc);
st.SetNotifier("ObxTabViews.Notify");
RETURN st
END New;
PROCEDURE Deposit*;
BEGIN
Views.Deposit(New())
END Deposit;
PROCEDURE AddNewCalc*;
VAR s: ARRAY 4 OF CHAR;
BEGIN
Strings.IntToString(st.NofTabs(), s);
st.SetItem(st.NofTabs(), 'Calc ' + s, calc)
END AddNewCalc;
PROCEDURE DeleteTab*;
VAR i: INTEGER; s: Dialog.String; v: Views.View;
BEGIN
IF st.NofTabs() > 0 THEN
FOR i := st.Index() TO st.NofTabs() - 2 DO
st.GetItem(i + 1, s, v); st.SetItem(i, s, v)
END;
st.SetNofTabs(st.NofTabs() - 1)
END
END DeleteTab;
PROCEDURE Notify* (v: StdTabViews.View; from, to: INTEGER);
BEGIN
StdLog.String("Notify: "); StdLog.Int(from); StdLog.Int(to); StdLog.Ln
END Notify;
END ObxTabViews.
| Obx/Mod/TabViews.odc |
MODULE ObxTickers;
(**
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 Views, Ports, Properties, Services, Stores, Models;
CONST minVersion = 0; maxVersion = 0;
TYPE
Ticks = POINTER TO ARRAY OF INTEGER;
View = POINTER TO RECORD (Views.View)
ticks: Ticks;
last: INTEGER;
offset: INTEGER
END;
Action = POINTER TO RECORD (Services.Action) END;
Msg = RECORD (Models.Message)
consumed: BOOLEAN
END;
VAR
action: Action;
actionIsActive: BOOLEAN;
seed: INTEGER;
PROCEDURE UniRand (): REAL;
CONST a = 16807; m = 2147483647; q = m DIV a; r = m MOD a;
BEGIN
seed := a * (seed MOD q) - r * (seed DIV q);
IF seed <= 0 THEN seed := seed + m END;
RETURN seed * (1.0 / m)
END UniRand;
PROCEDURE (a: Action) Do;
VAR msg: Msg;
BEGIN
msg.consumed := FALSE;
Views.Omnicast(msg);
IF msg.consumed THEN
Services.DoLater(action, Services.Ticks() + Services.resolution DIV 5)
ELSE
actionIsActive := FALSE
END
END Do;
(* view *)
PROCEDURE (v: View) Externalize (VAR wr: Stores.Writer);
VAR i, len: INTEGER;
BEGIN
wr.WriteVersion(maxVersion);
wr.WriteInt(v.offset);
wr.WriteInt(v.last);
len := LEN(v.ticks); wr.WriteInt(len);
FOR i := 0 TO len - 1 DO wr.WriteInt(v.ticks[i]) END
END Externalize;
PROCEDURE (v: View) Internalize (VAR rd: Stores.Reader);
VAR version, i, len: INTEGER;
BEGIN
rd.ReadVersion(minVersion, maxVersion, version);
IF ~rd.cancelled THEN
rd.ReadInt(v.offset);
rd.ReadInt(v.last);
rd.ReadInt(len); NEW(v.ticks, len);
FOR i := 0 TO len - 1 DO rd.ReadInt(v.ticks[i]) END
END
END Internalize;
PROCEDURE (v: View) CopyFromSimpleView (source: Views.View);
VAR i, len: INTEGER;
BEGIN
WITH source: View DO
v.offset := source.offset;
v.last := source.last;
len := LEN(source.ticks);
NEW(v.ticks, len);
FOR i := 0 TO len - 1 DO v.ticks[i] := source.ticks[i] END
END
END CopyFromSimpleView;
PROCEDURE (v: View) HandlePropMsg (VAR msg: Properties.Message);
BEGIN
WITH msg: Properties.SizePref DO
IF (msg.w = Views.undefined) OR (msg.h = Views.undefined) THEN
msg.w := 50 * Ports.mm; msg.h := 10 * Ports.mm
END
ELSE
END
END HandlePropMsg;
PROCEDURE (v: View) HandleModelMsg (VAR msg: Models.Message);
VAR len, m: INTEGER;
BEGIN
WITH msg: Msg DO
len := LEN(v.ticks);
m := v.ticks[v.last];
IF UniRand() > 0.5 THEN INC(m) ELSE DEC(m) END;
v.last := (v.last + 1) MOD len;
v.ticks[v.last] := m;
msg.consumed := TRUE;
Views.Update(v, Views.keepFrames)
ELSE
END
END HandleModelMsg;
PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER);
VAR w, h, x, y0, ylast, p, p1, len, len2, i, j: INTEGER; ticks: Ticks;
BEGIN
IF ~actionIsActive THEN
Services.DoLater(action, Services.now);
actionIsActive := TRUE
END;
v.context.GetSize(w, h);
len := LEN(v.ticks); len2 := 1 + w DIV f.dot;
IF len2 > len THEN (* allocate new array and copy data *)
NEW(ticks, len2);
i := 0; WHILE i <= v.last DO ticks[i] := v.ticks[i]; INC(i) END;
j := i + len2 - len; WHILE i < len DO ticks[j] := v.ticks[i]; INC(i); INC(j) END;
v.ticks := ticks; len := len2
END;
(* adjust offset so that the last point is visible *)
ylast := (v.ticks[v.last] + v.offset) * f.dot;
IF ylast > h DIV 2 THEN DEC(v.offset)
ELSIF ylast < -h DIV 2 THEN INC(v.offset)
END;
p := (v.last - (len2 - 1)) MOD len; (* index of first entry *)
x := 0; y0 := h DIV 2 + v.offset * f.dot;
WHILE p # v.last DO
p1 := (p + 1) MOD len;
f.DrawLine(x, y0 + v.ticks[p] * f.dot, x + f.dot, y0 + v.ticks[p1] * f.dot, 0, Ports.red);
x := x + f.dot; p := p1
END;
f.DrawLine(l, y0, r, y0, 0, Ports.black)
END Restore;
(* commands *)
PROCEDURE Deposit*;
VAR v: View;
BEGIN
NEW(v); NEW(v.ticks, 142);
v.last := 0; v.offset := 0;
Views.Deposit(v)
END Deposit;
BEGIN
NEW(action); actionIsActive := FALSE; seed := SHORT(Services.Ticks())
END ObxTickers.
| Obx/Mod/Tickers.odc |
MODULE ObxTrap;
(**
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 Dialog, Views, Controllers;
VAR global: INTEGER;
PROCEDURE Do*;
VAR i: INTEGER; str: Dialog.String; v: Views.View;
BEGIN
str := "String";
global := 13;
v := Controllers.FocusView();
i := 777;
str[i] := "*" (* index out of range, since the Dialog.String array only contains 256 elements *)
END Do;
PROCEDURE Hang*;
BEGIN
LOOP END
END Hang;
END ObxTrap. | Obx/Mod/Trap.odc |
MODULE ObxTwins;
(**
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 Ports, Services, Stores, Models, Views, Controllers, Properties, TextViews;
CONST
minVersion = 3; maxVersion = 3; (* old versions 0 .. 2 of ObxTwin views cannot be read anymore *)
border = Ports.mm;
TYPE
Identity = POINTER TO RECORD (Models.Model) END; (* dummy model *)
Context = POINTER TO RECORD (Models.Context)
base: View; (* container view *)
view: Views.View; (* contained view *)
l, t, r, b: INTEGER (* cached bounding box of contained view *)
END;
View = POINTER TO RECORD (Views.View)
top, bottom: Context;
ident: Identity; (* temporary dummy model *)
focus: Context (* current focus; either top or bottom *)
END;
(* Context *)
PROCEDURE (c: Context) ThisModel (): Models.Model;
BEGIN
RETURN NIL (* don't give the embedded views information about the dummy twin model *)
END ThisModel;
PROCEDURE (c: Context) GetSize (OUT w, h: INTEGER);
BEGIN
w := c.r - c.l;
h := c.b - c.t
END GetSize;
PROCEDURE (c: Context) MakeVisible (l, t, r, b: INTEGER);
VAR w, h, sep: INTEGER;
BEGIN
IF c.base.top = c THEN (* top view *)
c.base.context.MakeVisible(l + border, t + border, r + border, b + border)
ELSE (* bottom view *)
c.base.context.GetSize(w, h); sep := h DIV 3;
c.base.context.MakeVisible(l + border, t + sep + border, r + border, b + sep + border)
END
END MakeVisible;
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: View): Context;
VAR c: Context;
BEGIN
NEW(c);
c.view := v; c.base := base;
v.InitContext(c); Stores.Join(v, base);
RETURN c
END NewContext;
PROCEDURE CopyOf (source: Context; shallow: BOOLEAN; base: View): Context;
VAR v: Views.View;
BEGIN
v := Views.CopyOf(source.view, shallow );
RETURN NewContext(v, base)
END CopyOf;
(* View *)
PROCEDURE RecalcLayout (v: View);
VAR w, h, sep: INTEGER; c: Context;
BEGIN
v.context.GetSize(w, h);
sep := h DIV 3; (* separate the two views at 1/3 of the container's height *)
c := v.top; c.l := border; c.t := border; c.r := w - border; c.b := sep - border;
c := v.bottom; c.l := border; c.t := sep + border; c.r := w - border; c.b := h - border
END RecalcLayout;
PROCEDURE SetFocus (v: Views.View; x, y: INTEGER): BOOLEAN;
VAR p: Properties.FocusPref;
BEGIN (* determine whether v should be focused when the mouse is clicked at (x, y) in v *)
p.hotFocus := FALSE;
p.atLocation := TRUE; p.x := x; p.y := y;
p.setFocus := FALSE;
Views.HandlePropMsg(v, p);
RETURN p.setFocus
END SetFocus;
PROCEDURE (v: View) CopyFromModelView (source: Views.View; model: Models.Model);
VAR shallow: BOOLEAN;
BEGIN
WITH source: View DO
shallow := model = source.ident; (* shallow copy if both views share the same model *)
Stores.Join(v, model);
v.top := CopyOf(source.top, shallow, v);
v.bottom := CopyOf(source.bottom, shallow, v);
v.ident := model(Identity);
v.focus := v.bottom
END
END CopyFromModelView;
PROCEDURE (v: View) Internalize (VAR rd: Stores.Reader);
VAR version: INTEGER; h: Views.View;
BEGIN
rd.ReadVersion(minVersion, maxVersion, version);
IF ~rd.cancelled THEN
Views.ReadView(rd, h); v.top := NewContext(h, v);
Views.ReadView(rd, h); v.bottom := NewContext(h, v);
NEW(v.ident); Stores.Join(v, v.ident);
v.focus := v.bottom
END
END Internalize;
PROCEDURE (v: View) Externalize (VAR wr: Stores.Writer);
BEGIN
wr.WriteVersion(maxVersion);
Views.WriteView(wr, v.top.view);
Views.WriteView(wr, v.bottom.view)
END Externalize;
PROCEDURE (v: View) Neutralize;
BEGIN
v.focus.view.Neutralize
END Neutralize;
PROCEDURE (v: View) ThisModel (): Models.Model;
BEGIN
RETURN v.ident
END ThisModel;
PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER);
VAR d: INTEGER; c: Context;
BEGIN
RecalcLayout(v);
(* install the subframes for the subviews *)
c := v.top; Views.InstallFrame(f, c.view, c.l, c.t, 0, v.focus = c);
c := v.bottom; Views.InstallFrame(f, c.view, c.l, c.t, 1, v.focus = c);
(* draw frame around the subviews *)
d := 2 * f.dot;
c := v.top;
IF (c.t - d < c.b + d) & (c.l - d < c.r + d) THEN f.DrawRect(c.l - d, c.t - d, c.r + d, c.b + d, f.dot, Ports.black) END;
c := v.bottom;
IF (c.t - d < c.b + d) & (c.l - d < c.r + d) THEN f.DrawRect(c.l - d, c.t - d, c.r + d, c.b + d, f.dot, Ports.black) END
END Restore;
PROCEDURE (v: View) HandleCtrlMsg (f: Views.Frame; VAR msg: Views.CtrlMessage;
VAR focus: Views.View);
VAR g: Views.Frame; newFocus: Context; mMsg: Controllers.MarkMsg;
w, h, sep: INTEGER;
BEGIN
WITH msg: Controllers.CursorMessage DO
v.context.GetSize(w, h);
sep := h DIV 3;
IF msg.y >= sep THEN newFocus := v.bottom ELSE newFocus := v.top END;
focus := newFocus.view;
IF (newFocus # v.focus) & ((msg IS Controllers.TrackMsg) OR (msg IS Controllers.DropMsg)) &
SetFocus(focus, msg.x, msg.y) THEN
(* remove marks in old focus *)
mMsg.show := FALSE; mMsg.focus := TRUE;
g := Views.ThisFrame(f, v.focus.view); IF g # NIL THEN Views.ForwardCtrlMsg(g, mMsg) END;
v.focus := newFocus; (* set new focus *)
(* set marks in new focus *)
mMsg.show := TRUE; mMsg.focus := TRUE;
g := Views.ThisFrame(f, v.focus.view); IF g # NIL THEN Views.ForwardCtrlMsg(g, mMsg) END
END
(* the following scrolling-oriented messages are always sent to bottom view, independent of focus *)
| msg: Controllers.PollSectionMsg DO
g := Views.ThisFrame(f, v.bottom.view); IF g # NIL THEN Views.ForwardCtrlMsg(g, msg) END;
IF msg.vertical & ~msg.done THEN
msg.valid := FALSE; msg.done := TRUE (* disable default-scrolling *)
END
| msg: Controllers.ScrollMsg DO
g := Views.ThisFrame(f, v.bottom.view); IF g # NIL THEN Views.ForwardCtrlMsg(g, msg) END;
IF msg.vertical THEN msg.done := TRUE END
| msg: Controllers.PageMsg DO
focus := v.bottom.view
ELSE (* all other messages are sent to the focus, however *)
focus := v.focus.view
END
(* the assignment to focus signals that the view v wants to forward the message to the
corresponding embedded view *)
END HandleCtrlMsg;
PROCEDURE (v: View) HandlePropMsg (VAR msg: Views.PropMessage);
CONST defW = 80 * Ports.mm; defH = 60 * Ports.mm;
BEGIN
WITH msg: Properties.SizePref DO
IF msg.w = Views.undefined THEN msg.w := defW END;
IF msg.h = Views.undefined THEN msg.h := defH END
| msg: Properties.ResizePref DO
msg.verFitToWin := TRUE (* make view always as high as window *)
ELSE
Views.HandlePropMsg(v.bottom.view, msg)
END
END HandlePropMsg;
PROCEDURE (v: View) ConsiderFocusRequestBy (view: Views.View);
BEGIN
IF view = v.top.view THEN
v.focus := v.top
ELSIF view = v.bottom.view THEN
v.focus := v.bottom
ELSE
HALT(20)
END
END ConsiderFocusRequestBy;
PROCEDURE NewTwin* (top, bottom: Views.View): Views.View;
VAR v: View;
BEGIN
NEW(v);
v.top := NewContext(top, v); v.bottom := NewContext(bottom, v);
NEW(v.ident); Stores.Join(v, v.ident); v.focus := v.bottom;
RETURN v
END NewTwin;
(* example twin view with two embedded text views *)
PROCEDURE New* (): Views.View;
BEGIN
RETURN NewTwin(TextViews.dir.New(NIL), TextViews.dir.New(NIL))
END New;
PROCEDURE Deposit*;
BEGIN
Views.Deposit(New())
END Deposit;
END ObxTwins.
| Obx/Mod/Twins.odc |
MODULE ObxUnitConv;
(**
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 Ports, Dialog;
VAR
par*: RECORD metric*, inch*, point*: REAL; metricUnit*: Dialog.List END;
metricUnits: ARRAY 4 OF INTEGER;
PROCEDURE NotifyMetric* (op, from, to: INTEGER);
VAR units: REAL;
BEGIN
units := par.metric * metricUnits[par.metricUnit.index] * Ports.mm;
par.inch := units / Ports.inch; par.point := units / Ports.point;
Dialog.Update(par)
END NotifyMetric;
PROCEDURE NotifyInch* (op, from, to: INTEGER);
VAR units: REAL;
BEGIN
units := par.inch * Ports.inch;
par.metric := units / metricUnits[par.metricUnit.index] / Ports.mm; par.point := units / Ports.point;
Dialog.Update(par)
END NotifyInch;
PROCEDURE NotifyPoint* (op, from, to: INTEGER);
VAR units: REAL;
BEGIN
units := par.point * Ports.point;
par.metric := units / metricUnits[par.metricUnit.index] / Ports.mm; par.inch := units / Ports.inch;
Dialog.Update(par)
END NotifyPoint;
BEGIN
par.metricUnit.SetLen(4);
par.metricUnit.SetItem(0, "mm"); metricUnits[0] := 1;
par.metricUnit.SetItem(1, "cm"); metricUnits[1] := 10;
par.metricUnit.SetItem(2, "m"); metricUnits[2] := 1000;
par.metricUnit.SetItem(3, "km"); metricUnits[3] := 1000000
END ObxUnitConv.
| Obx/Mod/UnitConv.odc |
MODULE ObxViews0;
(**
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 Views, Ports;
TYPE View = POINTER TO RECORD (Views.View) END;
PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER);
BEGIN
f.DrawRect(l, t, r, b, Ports.fill, Ports.red)
END Restore;
PROCEDURE Deposit*;
VAR v: View;
BEGIN
NEW(v); Views.Deposit(v)
END Deposit;
END ObxViews0.
| Obx/Mod/Views0.odc |
MODULE ObxViews1;
(**
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 Views, Ports, Properties;
TYPE View = POINTER TO RECORD (Views.View) END;
PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER);
BEGIN
f.DrawRect(l, t, r, b, Ports.fill, Ports.red)
END Restore;
PROCEDURE (v: View) HandlePropMsg (VAR msg: Properties.Message);
BEGIN
WITH msg: Properties.SizePref DO
IF (msg.w = Views.undefined) OR (msg.h = Views.undefined) THEN
msg.w := 20 * Ports.mm; msg.h := 10 * Ports.mm
END
ELSE (* ignore other messages *)
END
END HandlePropMsg;
PROCEDURE Deposit*;
VAR v: View;
BEGIN
NEW(v); Views.Deposit(v)
END Deposit;
END ObxViews1.
| Obx/Mod/Views1.odc |
MODULE ObxViews10;
(**
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 Fonts, Ports, Views, Controllers, Properties;
CONST d = 20 * Ports.point;
TYPE
View = POINTER TO RECORD (Views.View)
i: INTEGER; (* position of next free slot in string *)
s: ARRAY 256 OF CHAR (* string *)
END;
PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER);
BEGIN
f.DrawString(d, d, Ports.black, v.s, Fonts.dir.Default())
END Restore;
PROCEDURE (v: View) HandleCtrlMsg (f: Views.Frame;
VAR msg: Controllers.Message;
VAR focus: Views.View);
BEGIN
WITH msg: Controllers.EditMsg DO
IF msg.op = Controllers.pasteChar THEN (* accept typing *)
v.s[v.i] := msg.char; INC(v.i); v.s[v.i] := 0X; (* append character to string *)
Views.Update(v, Views.keepFrames) (* restore v in any frame that displays it *)
END
ELSE (* ignore other messages *)
END
END HandleCtrlMsg;
PROCEDURE (v:View) HandlePropMsg (VAR msg: Properties.Message);
BEGIN
WITH msg: Properties.SizePref DO
IF (msg.w = Views.undefined) OR (msg.h = Views.undefined) THEN
msg.w := 10 * d; msg.h := 2 * d
END
| msg: Properties.FocusPref DO
msg.setFocus := TRUE
ELSE
END
END HandlePropMsg;
PROCEDURE Deposit*;
VAR v: View;
BEGIN
NEW(v); v.s := ""; v.i := 0;
Views.Deposit(v)
END Deposit;
END ObxViews10.
| Obx/Mod/Views10.odc |
MODULE ObxViews11;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
purpose = "Same as ObxViews10, but the view's string can be stored and copied"
changes = "
- YYYYMMDD, nn, ...
"
issues = "
- ...
"
**)
IMPORT Fonts, Ports, Stores, Views, Controllers, Properties;
CONST d = 20 * Ports.point;
TYPE
View = POINTER TO RECORD (Views.View)
i: INTEGER; (* position of next free slot in string *)
s: ARRAY 256 OF CHAR (* string *)
END;
PROCEDURE (v: View) Internalize (VAR rd: Stores.Reader);
VAR version: INTEGER;
BEGIN
rd.ReadVersion(0, 0, version);
IF ~rd.cancelled THEN
rd.ReadInt(v.i); rd.ReadString(v.s)
END
END Internalize;
PROCEDURE (v: View) Externalize (VAR wr: Stores.Writer);
BEGIN
wr.WriteVersion(0);
wr.WriteInt(v.i); wr.WriteString(v.s)
END Externalize;
PROCEDURE (v: View) CopyFromSimpleView (source: Views.View);
BEGIN
WITH source: View DO
v.i := source.i; v.s := source.s
END
END CopyFromSimpleView;
PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER);
BEGIN
f.DrawString(d, d, Ports.black, v.s, Fonts.dir.Default())
END Restore;
PROCEDURE (v: View) HandleCtrlMsg (f: Views.Frame;
VAR msg: Controllers.Message;
VAR focus: Views.View);
BEGIN
WITH msg: Controllers.EditMsg DO
IF msg.op = Controllers.pasteChar THEN (* accept typing *)
v.s[v.i] := msg.char; INC(v.i); v.s[v.i] := 0X; (* append character to string *)
Views.SetDirty(v); (* mark view's document as dirty *)
Views.Update(v, Views.keepFrames) (* restore v in any frame that displays it *)
END
ELSE (* ignore other messages *)
END
END HandleCtrlMsg;
PROCEDURE (v:View) HandlePropMsg (VAR msg: Properties.Message);
BEGIN
WITH msg: Properties.SizePref DO
IF (msg.w = Views.undefined) OR (msg.h = Views.undefined) THEN
msg.w := 10 * d; msg.h := 2 * d
END
| msg: Properties.FocusPref DO
msg.setFocus := TRUE
ELSE
END
END HandlePropMsg;
PROCEDURE Deposit*;
VAR v: View;
BEGIN
NEW(v); v.s := ""; v.i := 0;
Views.Deposit(v)
END Deposit;
END ObxViews11.
| Obx/Mod/Views11.odc |
MODULE ObxViews12;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
purpose = "Same as ObxViews11, but uses a separate model for the string"
changes = "
- YYYYMMDD, nn, ...
"
issues = "
- ...
"
**)
IMPORT Fonts, Ports, Stores, Models, Views, Controllers, Properties;
CONST d = 20 * Ports.point;
TYPE
Model = POINTER TO RECORD (Models.Model)
i: INTEGER; (* position of next free slot in string *)
s: ARRAY 256 OF CHAR (* string *)
END;
View = POINTER TO RECORD (Views.View)
model: Model
END;
(* Model *)
PROCEDURE (m: Model) Internalize (VAR rd: Stores.Reader);
VAR version: INTEGER;
BEGIN
rd.ReadVersion(0, 0, version);
IF ~rd.cancelled THEN
rd.ReadInt(m.i); rd.ReadString(m.s)
END
END Internalize;
PROCEDURE (m: Model) Externalize (VAR wr: Stores.Writer);
BEGIN
wr.WriteVersion(0);
wr.WriteInt(m.i); wr.WriteString(m.s)
END Externalize;
PROCEDURE (m: Model) CopyFrom (source: Stores.Store);
BEGIN
WITH source: Model DO
m.i := source.i; m.s := source.s
END
END CopyFrom;
(* View *)
PROCEDURE (v: View) Internalize (VAR rd: Stores.Reader);
VAR version: INTEGER; st: Stores.Store;
BEGIN
rd.ReadVersion(0, 0, version);
IF ~rd.cancelled THEN
rd.ReadStore(st);
v.model := st(Model)
END
END Internalize;
PROCEDURE (v: View) Externalize (VAR wr: Stores.Writer);
BEGIN
wr.WriteVersion(0);
wr.WriteStore(v.model)
END Externalize;
PROCEDURE (v: View) CopyFromModelView (source: Views.View; model: Models.Model);
BEGIN
v.model := model(Model)
END CopyFromModelView;
PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER);
BEGIN
f.DrawString(d, d, Ports.black, v.model.s, Fonts.dir.Default())
END Restore;
PROCEDURE (v: View) ThisModel (): Models.Model;
BEGIN
RETURN v.model
END ThisModel;
PROCEDURE (v: View) HandleModelMsg (VAR msg: Models.Message);
BEGIN
Views.Update(v, Views.keepFrames) (* restore v in any frame that displays it *)
END HandleModelMsg;
PROCEDURE (v: View) HandleCtrlMsg (f: Views.Frame;
VAR msg: Controllers.Message;
VAR focus: Views.View);
VAR m: Model; umsg: Models.UpdateMsg;
BEGIN
WITH msg: Controllers.EditMsg DO
IF msg.op = Controllers.pasteChar THEN
m := v.model;
m.s[m.i] := msg.char; INC(m.i);
m.s[m.i] := 0X; (* append character to string *)
Views.SetDirty(v); (* mark view's document as dirty *)
Models.Broadcast(m, umsg) (* update all views on this model *)
END
ELSE (* ignore other messages *)
END
END HandleCtrlMsg;
PROCEDURE (v:View) HandlePropMsg (VAR msg: Properties.Message);
BEGIN
WITH msg: Properties.SizePref DO
IF (msg.w = Views.undefined) OR (msg.h = Views.undefined) THEN
msg.w := 10 * d; msg.h := 2 * d
END
| msg: Properties.FocusPref DO
msg.setFocus := TRUE
ELSE
END
END HandlePropMsg;
PROCEDURE Deposit*;
VAR v: View; m: Model;
BEGIN
NEW(m); m.i := 0; m.s := "";
NEW(v); v.model := m; Stores.Join(v, m);
Views.Deposit(v)
END Deposit;
END ObxViews12.
| Obx/Mod/Views12.odc |
MODULE ObxViews13;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
purpose = "Same as ObxViews12, but generate undoable operations for character insertion"
changes = "
- YYYYMMDD, nn, ...
"
issues = "
- ...
"
**)
IMPORT Fonts, Ports, Stores, Models, Views, Controllers, Properties;
CONST d = 20 * Ports.point;
TYPE
Model = POINTER TO RECORD (Models.Model)
i: INTEGER; (* position of next free slot in string *)
s: ARRAY 256 OF CHAR (* string *)
END;
View = POINTER TO RECORD (Views.View)
model: Model
END;
PasteCharOp = POINTER TO RECORD (Stores.Operation)
model: Model;
char: CHAR;
do: BOOLEAN
END;
(* PasteCharOp *)
PROCEDURE (op: PasteCharOp) Do;
VAR m: Model; msg: Models.UpdateMsg;
BEGIN
m := op.model;
IF op.do THEN (* do operation's transformation *)
m.s[m.i] := op.char; INC(m.i) (* insert character into string *)
ELSE (* undo operation's transformation *)
DEC(m.i) (* remove character from string *)
END;
m.s[m.i] := 0X;
op.do := ~op.do; (* toggle between "do" and "undo" *)
Models.Broadcast(m, msg) (* update all views on this model *)
END Do;
PROCEDURE NewPasteCharOp (m: Model; char: CHAR): PasteCharOp;
VAR op: PasteCharOp;
BEGIN
NEW(op); op.model := m; op.char := char; op.do := TRUE;
RETURN op
END NewPasteCharOp;
(* Model *)
PROCEDURE (m: Model) Internalize (VAR rd: Stores.Reader);
VAR version: INTEGER;
BEGIN
rd.ReadVersion(0, 0, version);
IF ~rd.cancelled THEN
rd.ReadInt(m.i); rd.ReadString(m.s)
END
END Internalize;
PROCEDURE (m: Model) Externalize (VAR wr: Stores.Writer);
BEGIN
wr.WriteVersion(0);
wr.WriteInt(m.i); wr.WriteString(m.s)
END Externalize;
PROCEDURE (m: Model) CopyFrom (source: Stores.Store);
BEGIN
WITH source: Model DO
m.i := source.i; m.s := source.s
END
END CopyFrom;
(* View *)
PROCEDURE (v: View) Internalize (VAR rd: Stores.Reader);
VAR version: INTEGER; st: Stores.Store;
BEGIN
rd.ReadVersion(0, 0, version);
IF ~rd.cancelled THEN
rd.ReadStore(st);
v.model := st(Model)
END
END Internalize;
PROCEDURE (v: View) Externalize (VAR wr: Stores.Writer);
BEGIN
wr.WriteVersion(0);
wr.WriteStore(v.model)
END Externalize;
PROCEDURE (v: View) CopyFromModelView (source: Views.View; model: Models.Model);
BEGIN
v.model := model(Model)
END CopyFromModelView;
PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER);
BEGIN
f.DrawString(d, d, Ports.black, v.model.s, Fonts.dir.Default())
END Restore;
PROCEDURE (v: View) ThisModel (): Models.Model;
BEGIN
RETURN v.model
END ThisModel;
PROCEDURE (v: View) HandleModelMsg (VAR msg: Models.Message);
BEGIN
Views.Update(v, Views.keepFrames) (* restore v in any frame that displays it *)
END HandleModelMsg;
PROCEDURE (v: View) HandleCtrlMsg (f: Views.Frame;
VAR msg: Controllers.Message;
VAR focus: Views.View);
VAR op: Stores.Operation;
BEGIN
WITH msg: Controllers.EditMsg DO
IF msg.op = Controllers.pasteChar THEN
op := NewPasteCharOp(v.model, msg.char); (* generate operation *)
Models.Do(v.model, "Typing", op) (* execute operation *)
END
ELSE (* ignore other messages *)
END
END HandleCtrlMsg;
PROCEDURE (v:View) HandlePropMsg (VAR msg: Properties.Message);
BEGIN
WITH msg: Properties.SizePref DO
IF (msg.w = Views.undefined) OR (msg.h = Views.undefined) THEN
msg.w := 10 * d; msg.h := 2 * d
END
| msg: Properties.FocusPref DO
msg.setFocus := TRUE
ELSE
END
END HandlePropMsg;
PROCEDURE Deposit*;
VAR v: View; m: Model;
BEGIN
NEW(m); m.i := 0; m.s := "";
NEW(v); v.model := m; Stores.Join(v, m);
Views.Deposit(v)
END Deposit;
END ObxViews13.
| Obx/Mod/Views13.odc |
MODULE ObxViews14;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
purpose = "Same as ObxViews13, but interfaces and implementations separated,
and operation directly in Insert procedure"
changes = "
- YYYYMMDD, nn, ...
"
issues = "
- ...
"
**)
IMPORT Fonts, Ports, Stores, Models, Views, Controllers, Properties;
CONST d = 20 * Ports.point;
TYPE
Model* = POINTER TO ABSTRACT RECORD (Models.Model) END;
ModelDirectory* = POINTER TO ABSTRACT RECORD END;
View* = POINTER TO ABSTRACT RECORD (Views.View) END;
Directory* = POINTER TO ABSTRACT RECORD END;
StdModel = POINTER TO RECORD (Model)
i: INTEGER; (* position of next free slot in string *)
s: ARRAY 256 OF CHAR (* string *)
END;
StdModelDirectory = POINTER TO RECORD (ModelDirectory) END;
StdView = POINTER TO RECORD (View)
model: Model
END;
StdDirectory = POINTER TO RECORD (Directory) END;
PasteCharOp = POINTER TO RECORD (Stores.Operation)
model: StdModel;
char: CHAR;
do: BOOLEAN
END;
VAR
mdir-: ModelDirectory;
dir-: Directory;
(* Model *)
PROCEDURE (m: Model) Insert* (char: CHAR), NEW, ABSTRACT;
PROCEDURE (m: Model) Remove*, NEW, ABSTRACT;
PROCEDURE (m: Model) GetString* (OUT s: ARRAY OF CHAR), NEW, ABSTRACT;
(* ModelDirectory *)
PROCEDURE (d: ModelDirectory) New* (): Model, NEW, ABSTRACT;
(* PasteCharOp *)
PROCEDURE (op: PasteCharOp) Do;
VAR m: StdModel; msg: Models.UpdateMsg;
BEGIN
m := op.model;
IF op.do THEN (* do operation's transformation *)
m.s[m.i] := op.char; INC(m.i);
ELSE (* undo operation's transformation *)
DEC(m.i) (* remove character from string *)
END;
m.s[m.i] := 0X;
op.do := ~op.do; (* toggle between "do" and "undo" *)
Models.Broadcast(m, msg) (* update all views on this model *)
END Do;
(* StdModel *)
PROCEDURE (m: StdModel) Internalize (VAR rd: Stores.Reader);
VAR version: INTEGER;
BEGIN
rd.ReadVersion(0, 0, version);
IF ~rd.cancelled THEN
rd.ReadInt(m.i); rd.ReadString(m.s)
END
END Internalize;
PROCEDURE (m: StdModel) Externalize (VAR wr: Stores.Writer);
BEGIN
wr.WriteVersion(0);
wr.WriteInt(m.i); wr.WriteString(m.s)
END Externalize;
PROCEDURE (m: StdModel) CopyFrom (source: Stores.Store);
BEGIN
WITH source: StdModel DO
m.i := source.i; m.s := source.s
END
END CopyFrom;
PROCEDURE (m: StdModel) Insert (char: CHAR);
VAR op: PasteCharOp;
BEGIN
NEW(op); op.model := m; op.char := char; op.do := TRUE;
Models.Do(m, "insertion", op)
END Insert;
PROCEDURE (m: StdModel) Remove;
VAR msg: Models.UpdateMsg;
BEGIN
DEC(m.i); m.s[m.i] := 0X;
Models.Broadcast(m, msg) (* update all views on this model *)
END Remove;
PROCEDURE (m: StdModel) GetString (OUT s: ARRAY OF CHAR);
BEGIN
s := m.s$
END GetString;
(* StdModelDirectory *)
PROCEDURE (d: StdModelDirectory) New (): Model;
VAR m: StdModel;
BEGIN
NEW(m); m.s := ""; m.i := 0; RETURN m
END New;
(* Directory *)
PROCEDURE (d: Directory) New* (m: Model): View, NEW, ABSTRACT;
(* StdView *)
PROCEDURE (v: StdView) Internalize (VAR rd: Stores.Reader);
VAR version: INTEGER; st: Stores.Store;
BEGIN
rd.ReadVersion(0, 0, version);
IF ~rd.cancelled THEN
rd.ReadStore(st);
IF st IS Model THEN
v.model := st(Model)
ELSE
(* concrete model implementation couldn't be loaded->
an alien store was created *)
rd.TurnIntoAlien(Stores.alienComponent)
(* internalization of v is cancelled *)
END
END
END Internalize;
PROCEDURE (v: StdView) Externalize (VAR wr: Stores.Writer);
BEGIN
wr.WriteVersion(0);
wr.WriteStore(v.model)
END Externalize;
PROCEDURE (v: StdView) CopyFromModelView (source: Views.View; model: Models.Model);
BEGIN
WITH source: StdView DO
v.model := model(Model)
END
END CopyFromModelView;
PROCEDURE (v: StdView) Restore (f: Views.Frame; l, t, r, b: INTEGER);
VAR s: ARRAY 256 OF CHAR;
BEGIN
v.model.GetString(s);
f.DrawString(d, d, Ports.black, s, Fonts.dir.Default())
END Restore;
PROCEDURE (v: StdView) ThisModel (): Models.Model;
BEGIN
RETURN v.model
END ThisModel;
PROCEDURE (v: StdView) HandleModelMsg (VAR msg: Models.Message);
BEGIN
Views.Update(v, Views.keepFrames) (* restore v in any frame that displays it *)
END HandleModelMsg;
PROCEDURE (v: StdView) HandleCtrlMsg (f: Views.Frame;
VAR msg: Controllers.Message;
VAR focus: Views.View);
BEGIN
WITH msg: Controllers.EditMsg DO
IF msg.op = Controllers.pasteChar THEN
v.model.Insert(msg.char)
END
ELSE (* ignore other messages *)
END
END HandleCtrlMsg;
PROCEDURE (v:StdView) HandlePropMsg (VAR msg: Properties.Message);
BEGIN
WITH msg: Properties.SizePref DO
IF (msg.w = Views.undefined) OR (msg.h = Views.undefined) THEN
msg.w := 10 * d; msg.h := 2 *d
END
| msg: Properties.FocusPref DO
msg.setFocus := TRUE
ELSE
END
END HandlePropMsg;
(* StdDirectory *)
PROCEDURE (d: StdDirectory) New* (m: Model): View;
VAR v: StdView;
BEGIN
ASSERT(m # NIL, 20);
NEW(v); v.model := m; Stores.Join(v, m);
RETURN v
END New;
PROCEDURE Deposit*;
VAR v: View;
BEGIN
v := dir.New(mdir.New());
Views.Deposit(v)
END Deposit;
PROCEDURE SetModelDir* (d: ModelDirectory);
BEGIN
ASSERT(d # NIL, 20);
mdir := d
END SetModelDir;
PROCEDURE SetDir* (d: Directory);
BEGIN
ASSERT(d # NIL, 20);
dir := d
END SetDir;
PROCEDURE Init;
VAR md: StdModelDirectory; d: StdDirectory;
BEGIN
NEW(md); mdir := md;
NEW(d); dir := d
END Init;
BEGIN
Init
END ObxViews14.
| Obx/Mod/Views14.odc |
MODULE ObxViews2;
(**
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 Views, Ports, Properties;
TYPE View = POINTER TO RECORD (Views.View) END;
PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER);
BEGIN
f.DrawRect(l, t, r, b, Ports.fill, Ports.red)
END Restore;
PROCEDURE (v: View) HandlePropMsg (VAR msg: Properties.Message);
CONST min = 5 * Ports.mm; max = 50 * Ports.mm;
BEGIN
WITH msg: Properties.SizePref DO
IF (msg.w = Views.undefined) OR (msg.h = Views.undefined) THEN
msg.w := 20 * Ports.mm; msg.h := 10 * Ports.mm
ELSE
Properties.ProportionalConstraint(2, 1, msg.fixedW, msg.fixedH,
msg.w, msg.h);
IF msg.h < min THEN
msg.h := min; msg.w := 2 * min
ELSIF msg.h > max THEN
msg.h := max; msg.w := 2 * max
END
END
ELSE (* ignore other messages *)
END
END HandlePropMsg;
PROCEDURE Deposit*;
VAR v: View;
BEGIN
NEW(v); Views.Deposit(v)
END Deposit;
END ObxViews2.
| Obx/Mod/Views2.odc |
MODULE ObxViews3;
(**
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 Views, Ports, Properties;
TYPE View = POINTER TO RECORD (Views.View) END;
PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER);
BEGIN
f.DrawRect(l, t, r, b, Ports.fill, Ports.red)
END Restore;
PROCEDURE (v: View) HandlePropMsg (VAR msg: Properties.Message);
CONST min = 5 * Ports.mm; max = 50 * Ports.mm;
BEGIN
WITH msg: Properties.SizePref DO
IF (msg.w = Views.undefined) OR (msg.h = Views.undefined) THEN
msg.w := 20 * Ports.mm; msg.h := 10 * Ports.mm
ELSE
Properties.ProportionalConstraint(2, 1, msg.fixedW, msg.fixedH,
msg.w, msg.h);
IF msg.h < min THEN
msg.h := min; msg.w := 2 * min
ELSIF msg.h > max THEN
msg.h := max; msg.w := 2 * max
END
END
| msg: Properties.ResizePref DO
msg.horFitToWin := TRUE; msg.verFitToWin := TRUE
ELSE (* ignore other messages *)
END
END HandlePropMsg;
PROCEDURE Deposit*;
VAR v: View;
BEGIN
NEW(v); Views.Deposit(v)
END Deposit;
END ObxViews3.
| Obx/Mod/Views3.odc |
MODULE ObxViews4;
(**
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 Views, Ports, Properties, Controllers;
TYPE View = POINTER TO RECORD (Views.View) END;
PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER);
BEGIN
f.DrawRect(l, t, r, b, Ports.fill, Ports.red)
END Restore;
PROCEDURE (v: View) HandlePropMsg (VAR msg: Properties.Message);
CONST min = 5 * Ports.mm; max = 50 * Ports.mm;
BEGIN
WITH msg: Properties.SizePref DO
IF (msg.w = Views.undefined) OR (msg.h = Views.undefined) THEN
msg.w := 20 * Ports.mm; msg.h := 10 * Ports.mm
ELSE
Properties.ProportionalConstraint(2, 1, msg.fixedW, msg.fixedH,
msg.w, msg.h);
IF msg.h < min THEN
msg.h := min; msg.w := 2 * min
ELSIF msg.h > max THEN
msg.h := max; msg.w := 2 * max
END
END
| msg: Properties.ResizePref DO
msg.horFitToWin := TRUE; msg.verFitToWin := TRUE
| msg: Properties.FocusPref DO
msg.setFocus := TRUE
ELSE (* ignore other messages *)
END
END HandlePropMsg;
PROCEDURE (v: View) HandleCtrlMsg (f: Views.Frame;
VAR msg: Controllers.Message; VAR focus: Views.View);
BEGIN
WITH msg: Controllers.PollOpsMsg DO
msg.valid := {Controllers.paste}; msg.selectable := TRUE;
msg.type := "Obx.Tutorial"
ELSE (* ignore other messages *)
END
END HandleCtrlMsg;
PROCEDURE Deposit*;
VAR v: View;
BEGIN
NEW(v); Views.Deposit(v)
END Deposit;
END ObxViews4.
| Obx/Mod/Views4.odc |
MODULE ObxViews5;
(**
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 Views, Ports, Properties, Controllers;
TYPE
View = POINTER TO RECORD (Views.View)
x, y: INTEGER
END;
PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER);
BEGIN
f.DrawRect(l, t, r, b, Ports.fill, Ports.red);
f.DrawLine(v.x, t, v.x, b, 0, Ports.white); f.DrawLine(l, v.y, r, v.y, 0, Ports.white)
END Restore;
PROCEDURE (v: View) HandlePropMsg (VAR msg: Properties.Message);
CONST min = 5 * Ports.mm; max = 50 * Ports.mm;
BEGIN
WITH msg: Properties.SizePref DO
IF (msg.w = Views.undefined) OR (msg.h = Views.undefined) THEN
msg.w := 20 * Ports.mm; msg.h := 10 * Ports.mm
ELSE
Properties.ProportionalConstraint(2, 1, msg.fixedW, msg.fixedH,
msg.w, msg.h);
IF msg.h < min THEN msg.h := min; msg.w := 2 * min
ELSIF msg.h > max THEN msg.h := max; msg.w := 2 * max
END
END
| msg: Properties.ResizePref DO
msg.horFitToWin := TRUE; msg.verFitToWin := TRUE
| msg: Properties.FocusPref DO
msg.setFocus := TRUE
ELSE (* ignore other messages *)
END
END HandlePropMsg;
PROCEDURE (v: View) HandleCtrlMsg (f: Views.Frame;
VAR msg: Controllers.Message;
VAR focus: Views.View);
VAR x, y, w, h: INTEGER; m: SET; isDown: BOOLEAN;
BEGIN
WITH msg: Controllers.PollOpsMsg DO
msg.valid := {Controllers.paste}; msg.selectable := TRUE;
msg.type := "Obx.Tutorial"
| msg: Controllers.EditMsg DO
IF msg.op = Controllers.pasteChar THEN (* cursor keys *)
IF msg.char = 1DX THEN INC(v.x, Ports.mm)
ELSIF msg.char = 1CX THEN DEC(v.x, Ports.mm)
ELSIF msg.char = 1EX THEN DEC(v.y, Ports.mm)
ELSIF msg.char = 1FX THEN INC(v.y, Ports.mm)
END;
Views.Update(v, Views.keepFrames)
END
| msg: Controllers.TrackMsg DO
v.x := msg.x; v.y := msg.y;
v.context.GetSize(w, h); v.Restore(f, 0, 0, w, h);
REPEAT
f.Input(x, y, m, isDown);
IF (x # v.x) OR (y # v.y) THEN
v.x := x; v.y := y; v.Restore(f, 0, 0, w, h)
END
UNTIL ~isDown;
Views.Update(v, Views.keepFrames)
| msg: Controllers.PollCursorMsg DO
msg.cursor := Ports.graphicsCursor
ELSE (* ignore other messages *)
END
END HandleCtrlMsg;
PROCEDURE Deposit*;
VAR v: View;
BEGIN
NEW(v); v.x := 0; v.y := 0; Views.Deposit(v)
END Deposit;
END ObxViews5.
| Obx/Mod/Views5.odc |
MODULE ObxViews6;
(**
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 Views, Ports, Properties, Controllers;
TYPE
View = POINTER TO RECORD (Views.View)
x, y: INTEGER;
c: Ports.Color
END;
PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER);
BEGIN
f.DrawRect(l, t, r, b, Ports.fill, v.c);
f.DrawLine(v.x, t, v.x, b, 0, Ports.white); f.DrawLine(l, v.y, r, v.y, 0, Ports.white)
END Restore;
PROCEDURE (v: View) HandlePropMsg (VAR msg: Properties.Message);
CONST min = 5 * Ports.mm; max = 50 * Ports.mm;
VAR stdProp: Properties.StdProp; prop: Properties.Property;
BEGIN
WITH msg: Properties.SizePref DO
IF (msg.w = Views.undefined) OR (msg.h = Views.undefined) THEN
msg.w := 20 * Ports.mm; msg.h := 10 * Ports.mm
ELSE
Properties.ProportionalConstraint(2, 1, msg.fixedW, msg.fixedH,
msg.w, msg.h);
IF msg.h < min THEN msg.h := min; msg.w := 2 * min
ELSIF msg.h > max THEN msg.h := max; msg.w := 2 * max
END
END
| msg: Properties.ResizePref DO
msg.horFitToWin := TRUE; msg.verFitToWin := TRUE
| msg: Properties.FocusPref DO
msg.setFocus := TRUE
| msg: Properties.PollMsg DO
NEW(stdProp);
stdProp.color.val := v.c;
stdProp.valid := {Properties.color};
stdProp.known := {Properties.color};
Properties.Insert(msg.prop, stdProp)
| msg: Properties.SetMsg DO
prop := msg.prop;
WHILE prop # NIL DO
WITH prop: Properties.StdProp DO
IF Properties.color IN prop.valid THEN v.c := prop.color.val END
ELSE
END;
prop := prop.next
END;
Views.Update(v, Views.keepFrames)
ELSE (* ignore other messages *)
END
END HandlePropMsg;
PROCEDURE (v: View) HandleCtrlMsg (f: Views.Frame;
VAR msg: Controllers.Message;
VAR focus: Views.View);
VAR x, y, w, h: INTEGER; m: SET; isDown: BOOLEAN;
BEGIN
WITH msg: Controllers.PollOpsMsg DO
msg.valid := {Controllers.paste}; msg.selectable := TRUE;
msg.type := "Obx.Tutorial"
| msg: Controllers.EditMsg DO
IF msg.op = Controllers.pasteChar THEN
IF msg.char = 1DX THEN INC(v.x, Ports.mm)
ELSIF msg.char = 1CX THEN DEC(v.x, Ports.mm)
ELSIF msg.char = 1EX THEN DEC(v.y, Ports.mm)
ELSIF msg.char = 1FX THEN INC(v.y, Ports.mm)
END;
Views.Update(v, Views.keepFrames)
END
| msg: Controllers.TrackMsg DO
v.x := msg.x; v.y := msg.y; v.context.GetSize(w, h); v.Restore(f, 0, 0, w, h);
REPEAT
f.Input(x, y, m, isDown);
IF (x # v.x) OR (y # v.y) THEN
v.x := x; v.y := y; v.Restore(f, 0, 0, w, h)
END
UNTIL ~isDown;
Views.Update(v, Views.keepFrames)
| msg: Controllers.PollCursorMsg DO
msg.cursor := Ports.graphicsCursor
ELSE (* ignore other messages *)
END
END HandleCtrlMsg;
PROCEDURE Deposit*;
VAR v: View;
BEGIN
NEW(v); v.x := 0; v.y := 0; v.c := Ports.black; Views.Deposit(v)
END Deposit;
END ObxViews6.
| Obx/Mod/Views6.odc |
MODULE ObxWrappers;
(**
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 Dialog, Stores, Models, Views, Controllers, Properties, StdLog;
CONST minVersion = 2; maxVersion = 2;
TYPE
View = POINTER TO RECORD (Views.View)
inner: Views.View (* v # NIL *)
END;
PROCEDURE (v: View) Internalize (VAR rd: Stores.Reader);
VAR version: INTEGER;
BEGIN
rd.ReadVersion(minVersion, maxVersion, version);
IF ~rd.cancelled THEN
Views.ReadView(rd, v.inner) (* generate Views.Alien if necessary *)
END
END Internalize;
PROCEDURE (v: View) Externalize (VAR wr: Stores.Writer);
BEGIN
wr.WriteVersion(maxVersion);
Views.WriteView(wr, v.inner) (* handle Views.Alien if necessary *)
END Externalize;
PROCEDURE (v: View) CopyFromModelView (source: Views.View; model: Models.Model);
BEGIN
WITH source: View DO
IF model = NIL THEN
v.inner := Views.CopyOf(source.inner, Views.deep)
ELSE
v.inner := Views.CopyWithNewModel(source.inner, model)
END
END
END CopyFromModelView;
PROCEDURE (v: View) ThisModel (): Models.Model;
BEGIN
RETURN v.inner.ThisModel()
END ThisModel;
PROCEDURE (v: View) InitContext (context: Models.Context);
BEGIN
v.InitContext^(context);
v.inner.InitContext(context) (* wrapper and wrapped view share the same context *)
END InitContext;
PROCEDURE (v: View) Neutralize;
BEGIN
v.inner.Neutralize
END Neutralize;
(* GetNewFrame: wrapper uses standard frame *)
(* GetBackground: wrapper has no intrinsic background color *)
PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER);
BEGIN
Views.InstallFrame(f, v.inner, 0, 0, 0, TRUE) (* create and install wrapped view's frame *)
END Restore;
(* RestoreMarks: wrapper has no intrinsic marks, wrapped view's RestoreMarks is called by framework *)
(* HandleModelMsg: framework performs message propagation *)
(* HandleViewMsg: framework performs message propagation *)
PROCEDURE (v: View) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View);
BEGIN
(* here comes the behavior which is specific to this wrapper -
it modifies the wrapped view's behavior *)
WITH msg: Controllers.EditMsg DO
(* sample special behavior: copy typing into log *)
IF msg.op = Controllers.pasteChar THEN StdLog.Char(msg.char); StdLog.Ln END
ELSE
END;
focus := v.inner (* forward all controller messages to wrapped view *)
END HandleCtrlMsg;
PROCEDURE (v: View) HandlePropMsg (VAR msg: Properties.Message);
BEGIN
Views.HandlePropMsg(v.inner, msg) (* forward all property messages to wrapped view *)
END HandlePropMsg;
PROCEDURE Wrap*;
VAR poll: Controllers.PollOpsMsg; w: View; replace: Controllers.ReplaceViewMsg;
BEGIN
Controllers.PollOps(poll);
IF (poll.singleton # NIL) & ~(poll.singleton IS View) THEN
NEW(w); w.inner := poll.singleton; Stores.Join(w, w.inner);
replace.old := poll.singleton; replace.new := w;
Controllers.Forward(replace)
ELSE Dialog.Beep
END
END Wrap;
PROCEDURE Unwrap*;
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 := poll.singleton(View).inner;
Controllers.Forward(replace)
ELSE Dialog.Beep
END
END Unwrap;
END ObxWrappers.
| Obx/Mod/Wrappers.odc |
Obx/Rsrc/Actions.odc |
|
Obx/Rsrc/BlackBox.odc |
|
Obx/Rsrc/Controls.odc |
|
Obx/Rsrc/Cubes.odc |
|
Obx/Rsrc/Dialog.odc |
|
Obx/Rsrc/FileTree.odc |
|
MENU "Obx"
"Hello0" "" "ObxHello0.Do" ""
"Hello1" "" "ObxHello1.Do" ""
"Open0..." "" "ObxOpen0.Do" ""
"Open1..." "" "ObxOpen1.Do" ""
"Capitalize Text" "" "ObxCaps.Do" "TextCmds.SelectionGuard"
"Open Mail Template" "" "StdCmds.OpenDoc('Obx/Samples/MMTmpl')" ""
"Merge..." "" "ObxMMerge.Merge" "TextCmds.FocusGuard"
"Show Directory" "" "ObxLinks.Directory('')" ""
SEPARATOR
"Orders..." "" "StdCmds.OpenAuxDialog('Obx/Rsrc/Orders', 'Order Processing')" ""
"Controls..." "" "StdCmds.OpenAuxDialog('Obx/Rsrc/Controls', 'ObxControls Demo')" ""
"Dialog..." "" "StdCmds.OpenAuxDialog('Obx/Rsrc/Dialog', 'ObxDialog Demo')" ""
"File Tree..." "" "StdCmds.OpenAuxDialog('Obx/Rsrc/FileTree', 'ObxFileTree Demo')" ""
"Tab View..." "" "ObxTabViews.Deposit; StdCmds.Open" ""
SEPARATOR
"Trap!" "" "ObxTrap.Do" ""
"Primes..." "" "StdCmds.OpenAuxDialog('Obx/Rsrc/Actions', 'Prime Calculation')" ""
"Compute Factorial" "" "ObxFact.Compute" "TextCmds.SelectionGuard"
"Simplify" "" "ObxRatCalc.Simplify" "TextCmds.SelectionGuard"
"Approximate" "" "ObxRatCalc.Approximate" "TextCmds.SelectionGuard"
SEPARATOR
"New Pattern" "" "ObxPatterns.Deposit; StdCmds.Open" ""
"New Calculator" "" "ObxCalc.Deposit; StdCmds.Open" ""
"New Omosi" "" "ObxOmosi.Deposit; StdCmds.Open" ""
"New Cube" "" "ObxCubes.Deposit; StdCmds.Open" ""
"Cube Colors..." "" "StdCmds.OpenToolDialog('Obx/Rsrc/Cubes', 'Cube Colors')" ""
"New Checkerboard" "" "ObxScroll.Deposit; StdCmds.Open" ""
SEPARATOR
"Insert Button" "" "ObxButtons.Deposit; StdCmds.PasteView" "StdCmds.PasteViewGuard"
"New Ticker" "" "ObxTickers.Deposit; StdCmds.Open" ""
SEPARATOR
"New Lines" "" "ObxLines.Deposit; StdCmds.Open" ""
"New Graph" "" "ObxGraphs.Deposit; StdCmds.Open" ""
"Black Box..." "" "StdCmds.OpenAuxDialog('Obx/Rsrc/BlackBox', 'BlackBox Dialog')" ""
SEPARATOR
"Wrap" "" "ObxWrappers.Wrap" "StdCmds.SingletonGuard"
"Unwrap" "" "ObxWrappers.Unwrap" "StdCmds.SingletonGuard"
SEPARATOR
"New Twin" "" "ObxTwins.Deposit; StdCmds.Open" ""
"Focus Magic Control" "" "ObxContIter.Do" "StdCmds.ContainerGuard"
END
MENU "Tut"
"Phone Database..." "" "StdCmds.OpenAuxDialog('Obx/Rsrc/PhoneUI', 'Phone Database')" ""
"Phone Database 1..." "" "StdCmds.OpenAuxDialog('Obx/Rsrc/PhoneUI1', 'Phone Database')" ""
"Right-Shift Selection" "" "ObxControlShifter.Shift" "FormCmds.SelectionGuard"
"List Labels" "" "ObxLabelLister.List" "FormCmds.FocusGuard"
"Generate Report 0" "" "ObxPDBRep0.GenReport" ""
"Generate Report 1" "" "ObxPDBRep1.GenReport" ""
"Generate Report 2" "" "ObxPDBRep2.GenReport" ""
"Generate Report 3" "" "ObxPDBRep3.GenReport" ""
"Generate Report 4" "" "ObxPDBRep4.GenReport" ""
"Count Atoms" "" "ObxCount0.Do" "TextCmds.SelectionGuard"
"Count Symbols" "" "ObxCount1.Do" "TextCmds.SelectionGuard"
"Lookup 0" "" "ObxLookup0.Do" "TextCmds.SelectionGuard"
"Lookup 1" "" "ObxLookup1.Do" "TextCmds.SelectionGuard"
SEPARATOR
"New View 0" "" "ObxViews0.Deposit; StdCmds.Open" ""
"New View 1" "" "ObxViews1.Deposit; StdCmds.Open" ""
"New View 2" "" "ObxViews2.Deposit; StdCmds.Open" ""
"New View 3" "" "ObxViews3.Deposit; StdCmds.Open" ""
"New View 4" "" "ObxViews4.Deposit; StdCmds.Open" ""
"New View 5" "" "ObxViews5.Deposit; StdCmds.Open" ""
"New View 6" "" "ObxViews6.Deposit; StdCmds.Open" ""
SEPARATOR
"New View 10" "" "ObxViews10.Deposit; StdCmds.Open" ""
"New View 11" "" "ObxViews11.Deposit; StdCmds.Open" ""
"New View 12" "" "ObxViews12.Deposit; StdCmds.Open" ""
"New View 13" "" "ObxViews13.Deposit; StdCmds.Open" ""
"New View 14" "" "ObxViews14.Deposit; StdCmds.Open" ""
END
MENU "New" ("Obx.Tutorial")
"Beep" "" "Dialog.Beep" ""
END
MENU "BlackBox" ("ObxBlackBox.View")
"Show Solution" "" "ObxBlackBox.ShowSolution" "ObxBlackBox.ShowSolutionGuard"
SEPARATOR
"New Atoms" "" "ObxBlackBox.New" ""
"Set New Atoms" "" "ObxBlackBox.Set" ""
SEPARATOR
"Rules" "" "StdCmds.OpenBrowser('Obx/Docu/BB-Rules', 'BlackBox Rules')" ""
END
| Obx/Rsrc/Menus.odc |
Obx/Rsrc/Orders.odc |
|
Obx/Rsrc/Orders1.odc |
|
Obx/Rsrc/PhoneUI.odc |
|
Obx/Rsrc/PhoneUI1.odc |
|
STRINGS
Lookup Lookup
ObxConv.ImportTEXT Obx Text File
Off Switch Off
On Switch On
list[0] Daffy Duck
list[1] Wile E. Coyote
list[2] Scrooge Mc Duck
list[3] Huey Lewis
list[4] Thomas Dewey
CtrlCol.Prop ObxCtrlCol.InitDialog; StdCmds.OpenToolDialog('Obx/Rsrc/CtrlCol', 'Properties')
| Obx/Rsrc/Strings.odc |
Name Address0 Address1 State Country
Mr. A. Hill 39 Sunstreet Moon City Alabama USA
Mr. G. Ernst Feldweg 28 Hochdorf Bayern Deutschland
Ms. P. Thompson 12 Oak Ave. Littletown N.Carolina USA
Mr. W. Trou 81, rue Paris Mantes IledeParis France | Obx/Samples/MMData.odc |
Obx/Samples/MMTmpl.odc |
|
Obx/Samples/Omosi1.odc |
|
Obx/Samples/Omosi2.odc |
|
Obx/Samples/Omosi3.odc |
|
Obx/Samples/Omosi4.odc |
|
Obx/Samples/Omosi5.odc |
|
Obx/Samples/Omosi6.odc |
|
OleClient
This module has a private interface, it is only used internally.
| Ole/Docu/Client.odc |
OleData
This module has a private interface, it is only used internally.
| Ole/Docu/Data.odc |
OleServer
This module has a private interface, it is only used internally.
| Ole/Docu/Server.odc |
OleStorage
This module has a private interface, it is only used internally.
| Ole/Docu/Storage.odc |
Map to the Ole Subsystem
Views OLE wrapper views
| Ole/Docu/Sys-Map.odc |
OleViews
DEFINITION OleViews;
IMPORT CtlT, Views;
PROCEDURE NewObjectView (name: ARRAY OF CHAR): Views.View;
PROCEDURE NewObjectViewFromClipboard (): Views.View;
PROCEDURE Deposit (name: ARRAY OF CHAR);
PROCEDURE IsObjectView (v: Views.View): BOOLEAN;
PROCEDURE IsAutoView (v: Views.View): BOOLEAN;
PROCEDURE OleObject (v: Views.View): CtlT.Interface;
PROCEDURE AutoObject (v: Views.View): CtlT.Object;
PROCEDURE Connect (sink: CtlT.OutObject; source: Views.View);
END OleViews.
OleViews provides a programming interface for OLE objects used as views in BlackBox.
PROCEDURE NewObjectView (name: ARRAY OF CHAR): Views.View
Instantiates an OLE object of a given type. name can either be a valid OLE class name (e.g., "Excel.Sheet") or a GUID (global unique identifier) in string form, provided it is a valid class identifier (e.g., "{00020820-0000-0000-C000-000000000046}"). If instatiantion failed, the return value is NIL.
PROCEDURE NewObjectViewFromClipboard (): Views.View
Instantiates the OLE object currently contained in the clipboard. Returns NIL if there is no OLE object on the clipboard.
PROCEDURE Deposit (name: ARRAY OF CHAR)
Deposit command for new OLE objects of a given type. name can either be a valid OLE class name (e.g., "Excel.Sheet") or a GUID (global unique identifier) in string form, provided it is a valid class identifier (e.g., "{00020820-0000-0000-C000-000000000046}").
PROCEDURE IsObjectView (v: Views.View): BOOLEAN
Return TRUE if the given View is an OLE object, FALSE otherwise.
PROCEDURE IsAutoView (v: Views.View): BOOLEAN
Return TRUE if the given View is an OLE Automation object (an object which supports the IDispatch interface), FALSE otherwise.
PROCEDURE OleObject (v: Views.View): CtlT.Interface
Returns the IUnknown interface of the object contained in v as an automation controller object. Only useful in conjunction with the Direct-To-COM compiler (DTC). For information about automation controller objects see the CtlDocu. NIL is returned if v is not an OLE object.
PROCEDURE AutoObject (v: Views.View): CtlT.Object
Returns the automation controller object associated with v. For information about automation controller objects see the CtlDocu. NIL is returned if v is not an OLE Automation object.
PROCEDURE Connect (sink: CtlT.OutObject; source: Views.View)
Connects the automation controller callback object sink to an OLE object contained in the view source. For information about automation controller objects see the CtlDocu.
| Ole/Docu/Views.odc |
MODULE OleClient;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20070205, bh, Unicode support
- 20150714, center #19, 16-bit Unicode support for Component Pascal identifiers added
- 20171030, center #180, fixing resource string lookup in OleClient.PasteSpecial
"
issues = "
- ...
"
**)
IMPORT
SYSTEM, COM, WinApi, WinOle, WinOleCtl, WinOleAut, WinOleDlg, Kernel,
OleStorage, OleData, OleServer, Librarian,
Meta, Dialog, Services, Ports, Stores, Sequencers, Models, Views, Controllers,
Properties, Containers, Controls, Utf,
StdDialog, Log,
HostPorts := WinPorts,
HostWindows := WinWindows,
OleWindows,
HostMenus := MdiMenus;
CONST
debug = FALSE;
minModelVersion = 0; maxModelVersion = 1;
minViewVersion = 0; maxViewVersion = 0;
ObjectID = "{00000001-1000-11cf-adf0-444553540000}"; (* BlackBox views *)
miscStatus = WinOle.OLEMISC_RECOMPOSEONRESIZE
+ WinOle.OLEMISC_CANTLINKINSIDE
+ WinOle.OLEMISC_RENDERINGISDEVICEINDEPENDENT;
oleUnit = Ports.mm DIV 100;
TYPE
IOleClientSite = POINTER TO RECORD (WinOle.IOleClientSite)
ias: IAdviseSink;
iips: IOleInPlaceSite;
obj: Model;
frame: Views.Frame;
wnd: WinApi.HWND
END;
IAdviseSink = POINTER TO RECORD (WinOle.IAdviseSink)
site: IOleClientSite;
obj: Model
END;
IOleInPlaceSite = POINTER TO RECORD (WinOle.IOleInPlaceSite)
site: IOleClientSite;
obj: Model
END;
IOleInPlaceUIWindow = POINTER TO RECORD (WinOle.IOleInPlaceUIWindow)
wnd: WinApi.HWND;
iipao: WinOle.IOleInPlaceActiveObject
END;
WinHook = POINTER TO RECORD (HostWindows.Hook)
iipw: IOleInPlaceUIWindow
END;
IOleInPlaceFrame = POINTER TO RECORD (WinOle.IOleInPlaceFrame)
objWnd: WinApi.HWND; (* for menu handling *)
iipao: WinOle.IOleInPlaceActiveObject
END;
FrameHook = POINTER TO RECORD (HostWindows.Hook) END;
Sink = POINTER TO RECORD
next: Sink;
(*
obj: CtlT.OutObject;
*)
point: WinOle.IConnectionPoint;
cookie: INTEGER
END;
View = POINTER TO RECORD (Views.View)
model: Model;
hasNotifier: BOOLEAN
END;
Model = POINTER TO RECORD (Models.Model)
site: IOleClientSite;
advConn: INTEGER;
open: BOOLEAN;
objUnk: COM.IUnknown;
objView: WinOle.IViewObject2;
objObj: WinOle.IOleObject;
objIPObj: WinOle.IOleInPlaceObject; (* # NIL: in place open *)
stg: WinOle.IStorage;
flags: SET;
w, h: INTEGER; (* actual site size (units) *)
rw, rh: INTEGER; (* actual pos rect size (pixels) *)
guard: BOOLEAN;
focusGuard: BOOLEAN;
onServer: BOOLEAN;
view: View;
link: ARRAY 256 OF CHAR;
sinks: Sink
END;
Frame = POINTER TO RECORD (Views.Frame) END;
Notifier = POINTER TO RECORD (Sequencers.Notifier)
model: Model
END;
Deactivator = POINTER TO RECORD (Services.Action)
obj: Model
END;
UpdateMsg = RECORD (Models.UpdateMsg)
checkSize: BOOLEAN
END;
(*
ObjectValue = RECORD (Meta.Value)
obj*: CtlT.OutObject
END;
*)
ProcValue = RECORD (Meta.Value)
open*: PROCEDURE(v: Views.View)
END;
Op = POINTER TO RECORD (Stores.Operation)
model: Model;
link: ARRAY 256 OF CHAR
END;
VAR
appFrame: IOleInPlaceFrame;
winMenu: WinApi.HMENU;
hAccel: WinApi.HACCEL;
nAccel: INTEGER;
menuBar: WinApi.HMENU;
(* ----------callback linking ---------- *)
PROCEDURE Connect* (v: Views.View; iid: COM.GUID; disp: WinOleAut.IDispatch);
VAR res: COM.RESULT; cont: WinOle.IConnectionPointContainer; point: WinOle.IConnectionPoint; sink: Sink;
BEGIN
WITH v: View DO
res := v.model.objUnk.QueryInterface(COM.ID(cont), cont);
IF res >= 0 THEN
res := cont.FindConnectionPoint(iid, point);
IF res >= 0 THEN
NEW(sink); sink.point := point;
res := point.Advise(disp, sink.cookie);
IF res >= 0 THEN
sink.next := v.model.sinks; v.model.sinks := sink
END
END
END
ELSE
END
END Connect;
PROCEDURE Disconnect (model: Model);
VAR res: COM.RESULT; sink: Sink;
BEGIN
sink := model.sinks;
WHILE sink # NIL DO
res := sink.point.Unadvise(sink.cookie);
sink := sink.next
END;
model.sinks := NIL
END Disconnect;
PROCEDURE OpenLink (model: Model);
VAR item: Meta.Item; pv: ProcValue; ok: BOOLEAN;
BEGIN
IF model.link # "" THEN
Meta.LookupPath(model.link, item);
IF item.obj = Meta.procObj THEN
item.GetVal(pv, ok);
IF ok THEN pv.open(model.view)
ELSE Dialog.ShowParamMsg("#System:HasWrongType", model.link, "", "")
END
ELSE Dialog.ShowParamMsg("#System:NotFound", model.link, "", "")
END
END
END OpenLink;
(*
PROCEDURE OpenLinks (model: Model);
VAR item: Meta.Item; ov: ObjectValue; ok: BOOLEAN; iid: COM.GUID; res: COM.RESULT;
cont: WinOle.IConnectionPointContainer; disp: WinOleAut.IDispatch; point: WinOle.IConnectionPoint;
i, j: INTEGER; name: ARRAY 256 OF CHAR; sink: Sink;
BEGIN
i := 0;
WHILE model.link[i] # 0X DO
WHILE (model.link[i] # 0X) & (model.link[i] <= ",") DO INC(i) END;
j := 0;
WHILE model.link[i] > "," DO name[j] := model.link[i]; INC(j); INC(i) END;
name[j] := 0X;
IF name # "" THEN
Meta.LookupPath(name, item);
IF item.obj # Meta.undef THEN
IF (item.obj = Meta.typObj) & (item.typ = Meta.ptrTyp) THEN item.GetBaseType(item) END;
IF (item.obj = Meta.typObj) & (item.typ = Meta.recTyp) & item.Is(ov) THEN
(* item.Allocate(ov); *) ov.obj := item.New()(CtlT.OutObject);
res := model.objUnk.QueryInterface(COM.ID(cont), cont);
IF res >= 0 THEN
ov.obj.GetIID(iid);
res := cont.FindConnectionPoint(iid, point);
IF res >= 0 THEN
disp := CtlT.Disp(ov.obj); ASSERT(disp # NIL);
NEW(sink); sink.obj := ov.obj; sink.point := point;
res := point.Advise(disp, sink.cookie);
IF res >= 0 THEN
sink.next := model.sinks; model.sinks := sink;
res := model.objUnk.QueryInterface(COM.ID(disp), disp);
IF res >= 0 THEN sink.obj.source := CtlT.Obj(disp) END
END
ELSE Dialog.ShowParamMsg("#System:HasWrongType", name, "", "")
END
ELSE HALT(100)
END
ELSE Dialog.ShowParamMsg("#System:HasWrongType", name, "", "")
END
ELSE Dialog.ShowParamMsg("#System:NotFound", name, "", "")
END
END
END
END OpenLinks;
PROCEDURE CloseLinks (model: Model);
VAR res: COM.RESULT; sink: Sink; iid: COM.GUID;
BEGIN
sink := model.sinks;
WHILE sink # NIL DO
res := sink.point.Unadvise(sink.cookie);
sink.obj.source := NIL;
sink := sink.next
END;
model.sinks := NIL
END CloseLinks;
*)
PROCEDURE PollProp (model: Model; VAR list: Properties.Property);
VAR p: Controls.Prop; res: COM.RESULT; cont: WinOle.IConnectionPointContainer;
BEGIN
res := model.objUnk.QueryInterface(COM.ID(cont), cont);
IF res >= 0 THEN
NEW(p);
p.valid := {Controls.link}; p.known := p.valid;
p.link := model.link$;
Properties.Insert(list, p)
END
END PollProp;
PROCEDURE SetProp (model: Model; p: Properties.Property);
VAR res: COM.RESULT; cont: WinOle.IConnectionPointContainer; op: Op;
BEGIN
res := model.objUnk.QueryInterface(COM.ID(cont), cont);
IF res >= 0 THEN
WHILE p # NIL DO
WITH p: Controls.Prop DO
IF Controls.link IN p.valid THEN
NEW(op); op.model := model; op.link := p.link$;
Models.Do(model, "#System:SetProp", op)
END
ELSE
END;
p := p.next
END
END
END SetProp;
PROCEDURE (op: Op) Do;
VAR link: ARRAY 256 OF CHAR;
BEGIN
(*
Disconnect(op.model);
*)
link := op.model.link$; op.model.link := op.link$; op.link := link$;
OpenLink(op.model)
END Do;
(* ---------- auxiliary ---------- *)
PROCEDURE Visible (m: Model; f: Views.Frame): BOOLEAN;
VAR g: Views.Frame; ctrl: Containers.Controller;
BEGIN
IF m.flags * WinOleCtl.OLEMISC_INVISIBLEATRUNTIME = {} THEN RETURN TRUE
ELSE
g := Views.HostOf(f);
IF (g = NIL) OR ~(g.view IS Containers.View) THEN RETURN TRUE
ELSE
ctrl := g.view(Containers.View).ThisController();
RETURN Containers.mask * ctrl.opts # Containers.mask
END
END
END Visible;
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 GenStorageMedium (stg: WinOle.IStorage; unk: COM.IUnknown; VAR sm: WinOle.STGMEDIUM);
BEGIN
sm.u.hGlobal := 0;
sm.tymed := WinOle.TYMED_ISTORAGE;
sm.u.pstg := stg;
sm.pUnkForRelease := unk
END GenStorageMedium;
PROCEDURE MediumStorage (VAR sm: WinOle.STGMEDIUM): WinOle.IStorage;
BEGIN
ASSERT(sm.tymed = WinOle.TYMED_ISTORAGE, 20);
RETURN sm.u.pstg
END MediumStorage;
PROCEDURE DoVerb (obj: Model; f: Views.Frame; verb: INTEGER);
VAR res: COM.RESULT; w, h: INTEGER; rect: WinApi.RECT;
BEGIN
obj.site.frame := f;
IF f # NIL THEN
f.view.context.GetSize(w, h);
rect.left := f.gx DIV f.unit;
rect.top := f.gy DIV f.unit;
rect.right := (f.gx + w) DIV f.unit;
rect.bottom := (f.gy + h) DIV f.unit;
obj.rw := w DIV f.unit;
obj.rh := h DIV f.unit;
IF debug THEN Log.Int(rect.left); Log.Int(rect.top); Log.Int(rect.right); Log.Int(rect.bottom); Log.Ln END;
res := obj.objObj.DoVerb(verb, NIL, obj.site, 0, f.rider(HostPorts.Rider).port.wnd, rect)
ELSE
rect.left := 0; rect.top := 0; rect.right := 0; rect.bottom := 0;
res := obj.objObj.DoVerb(verb, NIL, obj.site, 0, 0, rect)
END
END DoVerb;
PROCEDURE UpdateSizes (v: View; checkSize, setRect: BOOLEAN);
VAR obj: Model; f: Views.Frame; host: Views.Frame; p: HostPorts.Port; res: COM.RESULT;
pos, clip: WinApi.RECT; size: WinApi.SIZE; w, h, ow, oh: INTEGER;
c: Containers.Controller; s: Views.View; g: BOOLEAN;
BEGIN
obj := v.model; f := obj.site.frame;
IF (f # NIL) & ((f.rider = NIL) OR (obj.objIPObj = NIL) OR (f.view # v)) THEN f := NIL END;
IF checkSize THEN
IF debug THEN Log.String("check sizes"); Log.Ln END;
res := obj.objObj.GetExtent(WinOle.DVASPECT_CONTENT, size);
IF res = WinApi.S_OK THEN
ow := size.cx * oleUnit; oh := size.cy * oleUnit;
v.context.GetSize(w, h);
IF (w # ow) OR (h # oh) THEN
IF debug THEN Log.String(" set size"); Log.Int(ow); Log.Int(oh); Log.Ln END;
Controllers.SetCurrentPath(Controllers.targetPath);
c := Containers.Focus();
Controllers.ResetCurrentPath();
s := c.Singleton();
IF f # NIL THEN host := Views.HostOf(f) END;
g := obj.focusGuard; obj.focusGuard := TRUE;
v.context.SetSize(ow, oh);
v.model.w := ow; v.model.h := oh;
IF f # NIL THEN
IF host # NIL THEN (* restore saved frame *)
IF debug THEN Log.String(" restore frame"); Log.Ln END;
Views.ValidateRoot(Views.RootOf(host));
f := Views.ThisFrame(host, v);
obj.site.frame := f
END;
c.SetFocus(v) (* restore focus *)
ELSIF (s # NIL) & (s # c.Singleton()) THEN c.SetSingleton(s) (* restore selection *)
END;
obj.focusGuard := g
END
END
END;
IF f # NIL THEN
v.context.GetSize(w, h); w := w DIV f.unit; h := h DIV f.unit;
IF w > obj.rw THEN obj.rw := w; setRect := TRUE END;
IF h > obj.rh THEN obj.rh := h; setRect := TRUE END;
IF setRect THEN
pos.left := f.gx DIV f.unit; pos.top := f.gy DIV f.unit;
pos.right := pos.left + obj.rw; pos.bottom := pos.top + obj.rh;
p := f.rider(HostPorts.Rider).port;
clip.left := 0; clip.top := 0; clip.right := p.w; clip.bottom := p.h;
IF debug THEN Log.String("set object rects"); Log.Int(obj.rw); Log.Int(obj.rh); Log.Ln END;
res := obj.objIPObj.SetObjectRects(pos, clip)
END
END
END UpdateSizes;
PROCEDURE GetAccelTable* (VAR a: WinApi.HACCEL; VAR n: INTEGER);
VAR res: INTEGER; m: HostMenus.Menu; data: ARRAY 128 OF WinApi.ACCEL; f: BYTE; i: StdDialog.Item;
BEGIN
IF menuBar # HostMenus.menuBar THEN (* update table *)
IF hAccel # 0 THEN res := WinApi.DestroyAcceleratorTable(hAccel) END;
nAccel := 0; m := HostMenus.menus;
WHILE m # NIL DO
IF m.class IN {0, 2, 4} THEN
i := m.firstItem;
WHILE (i # NIL) & (nAccel < LEN(data)) DO
WITH i: HostMenus.Item DO
IF i.code # 0 THEN
f := WinApi.FVIRTKEY;
IF i.shift THEN INC(f, WinApi.FSHIFT) END;
IF i.ctrl THEN INC(f, WinApi.FCONTROL) END;
data[nAccel].key := SHORT(i.code);
data[nAccel].cmd := SHORT(i.id);
data[nAccel].fVirt := SHORT(CHR(f));
INC(nAccel)
END
END;
i := i.next
END
END;
m := m.next
END;
hAccel := WinApi.CreateAcceleratorTableW(data[0], nAccel);
IF debug THEN Log.String("new accel table"); Log.Int(nAccel); Log.Int(hAccel); Log.Ln END;
IF hAccel = 0 THEN nAccel := 0 END;
menuBar := HostMenus.menuBar
END;
a := hAccel; n := nAccel
END GetAccelTable;
(* ---------- IOleClientSite ---------- *)
PROCEDURE (this: IOleClientSite) QueryInterface (IN iid: COM.GUID; OUT int: COM.IUnknown): COM.RESULT;
BEGIN
IF COM.QUERY(this, iid, int)
OR COM.QUERY(this.ias, iid, int)
OR COM.QUERY(this.iips, iid, int) THEN RETURN WinApi.S_OK
ELSE RETURN WinApi.E_NOINTERFACE
END
END QueryInterface;
PROCEDURE (this: IOleClientSite) SaveObject (): COM.RESULT;
VAR res: COM.RESULT; ips: WinOle.IPersistStorage;
BEGIN
IF debug THEN Log.String("do save object"); Log.Ln END;
IF (this.obj # NIL) & (this.obj.objUnk # NIL) THEN
res := this.obj.objUnk.QueryInterface(COM.ID(ips), ips);
ASSERT(res >= 0, 100);
res := WinOle.OleSave(ips, this.obj.stg, 1);
ASSERT(res >= 0, 101);
res := ips.SaveCompleted(NIL);
ASSERT(res >= 0, 102);
RETURN WinApi.S_OK
ELSE
RETURN WinApi.E_FAIL
END
END SaveObject;
PROCEDURE (this: IOleClientSite) GetMoniker (
assign, which: INTEGER; OUT mk: WinOle.IMoniker
): COM.RESULT;
BEGIN
RETURN WinApi.E_NOTIMPL
END GetMoniker;
PROCEDURE (this: IOleClientSite) GetContainer (OUT container: WinOle.IOleContainer): COM.RESULT;
BEGIN
RETURN WinApi.E_NOTIMPL
END GetContainer;
PROCEDURE (this: IOleClientSite) ShowObject (): COM.RESULT;
BEGIN
IF debug THEN Log.String("do show object"); Log.Ln END;
(* Container.MakeVisible(object) *)
RETURN WinApi.S_OK
END ShowObject;
PROCEDURE (this: IOleClientSite) OnShowWindow (show: WinApi.BOOL): COM.RESULT;
VAR msg: UpdateMsg;
BEGIN
IF debug THEN Log.String("do show window"); Log.Ln END;
this.obj.open := show # 0; msg.checkSize := FALSE;
Models.Broadcast(this.obj, msg);
RETURN WinApi.S_OK
END OnShowWindow;
PROCEDURE (this: IOleClientSite) RequestNewObjectLayout (): COM.RESULT;
BEGIN
IF debug THEN Log.String("request new layout"); Log.Ln END;
RETURN WinApi.E_NOTIMPL
END RequestNewObjectLayout;
(* ---------- IAdviseSink ---------- *)
PROCEDURE (this: IAdviseSink) OnDataChange (
IN format: WinOle.FORMATETC; IN medium: WinOle.STGMEDIUM
);
BEGIN
IF debug THEN Log.String("on data change"); Log.Ln END
END OnDataChange;
PROCEDURE (this: IAdviseSink) OnViewChange (aspect: SET; index: INTEGER);
VAR msg: UpdateMsg; ips: WinOle.IPersistStorage; res: COM.RESULT; seq: ANYPTR;
BEGIN
IF debug THEN Log.String("on view change"); Log.Ln END;
msg.checkSize := TRUE;
IF ~this.obj.guard THEN Models.Broadcast(this.obj, msg) END;
IF WinOle.OleIsRunning(this.obj.objObj) # 0 THEN (* check dirty *)
res := this.obj.objUnk.QueryInterface(COM.ID(ips), ips);
IF (res >= 0) & (ips.IsDirty() # WinApi.S_FALSE) THEN
IF debug THEN Log.String("set dirty"); Log.Int(ips.IsDirty()); Log.Ln END;
IF this.obj.Domain() # NIL THEN
seq := this.obj.Domain().GetSequencer();
IF seq # NIL THEN
seq(Sequencers.Sequencer).SetDirty(TRUE)
END
ELSIF debug THEN Log.String("nil domain !!!"); Log.Ln
END
END
END
END OnViewChange;
PROCEDURE (this: IAdviseSink) OnRename (moniker: WinOle.IMoniker);
BEGIN
IF debug THEN Log.String("on rename"); Log.Ln END
END OnRename;
PROCEDURE (this: IAdviseSink) OnSave ();
BEGIN
IF debug THEN Log.String("on save"); Log.Ln END
END OnSave;
PROCEDURE (this: IAdviseSink) OnClose ();
BEGIN
IF debug THEN Log.String("on close"); Log.Ln END;
this.obj.open := FALSE
END OnClose;
(* ---------- IOleInPlaceSite ---------- *)
PROCEDURE (this: IOleInPlaceSite) GetWindow (OUT wnd: WinApi.HWND): COM.RESULT;
BEGIN
IF debug THEN Log.String("ip site: get window"); Log.Ln END;
IF this.site.frame # NIL THEN
wnd := this.site.frame.rider(HostPorts.Rider).port.wnd;
RETURN WinApi.S_OK
ELSE RETURN WinApi.E_FAIL
END
END GetWindow;
PROCEDURE (this: IOleInPlaceSite) ContextSensitiveHelp (enter: WinApi.BOOL): COM.RESULT;
BEGIN
IF debug THEN Log.String("ip site: context help"); Log.Ln END;
RETURN WinApi.S_OK
END ContextSensitiveHelp;
PROCEDURE (this: IOleInPlaceSite) CanInPlaceActivate (): COM.RESULT;
BEGIN
IF debug THEN Log.String("ip site: can activate"); Log.Ln END;
IF this.site.frame # NIL THEN RETURN WinApi.S_OK
ELSE RETURN WinApi.S_FALSE
END
END CanInPlaceActivate;
PROCEDURE (this: IOleInPlaceSite) OnInPlaceActivate (): COM.RESULT;
VAR res: COM.RESULT; host: Views.Frame; c: Containers.Controller; style: SET;
BEGIN
IF debug THEN Log.String("ip site: on activate"); Log.Ln END;
res := this.obj.objUnk.QueryInterface(COM.ID(this.obj.objIPObj), this.obj.objIPObj);
IF this.site.frame # NIL THEN
this.site.wnd := this.site.frame.rider(HostPorts.Rider).port.wnd;
style := SYSTEM.VAL(SET, WinApi.GetWindowLongW(this.site.wnd, -16));
res := WinApi.SetWindowLongW(this.site.wnd, -16, SYSTEM.VAL(INTEGER, style + {25}));
host := Views.HostOf(this.site.frame);
IF (host # NIL) & (host.view IS Containers.View) THEN
c := host.view(Containers.View).ThisController();
c.SetFocus(this.site.frame.view)
END
END;
res := this.site.OnShowWindow(1);
RETURN WinApi.S_OK
END OnInPlaceActivate;
PROCEDURE (this: IOleInPlaceSite) OnUIActivate (): COM.RESULT;
VAR f: Views.Frame; p: HostPorts.Port; win: OleWindows.Window;
BEGIN
IF debug THEN Log.String("ip site: on ui activate"); Log.Ln END;
(* remove user interface *)
f := this.site.frame; p := f.rider(HostPorts.Rider).port;
win := SYSTEM.VAL(OleWindows.Window, WinApi.GetWindowLongW(p.wnd, 0));
OleServer.RemoveUI(win);
RETURN WinApi.S_OK
END OnUIActivate;
PROCEDURE (this: IOleInPlaceSite) GetWindowContext (OUT frame: WinOle.IOleInPlaceFrame;
OUT doc: WinOle.IOleInPlaceUIWindow;
OUT pos, clip: WinApi.RECT;
VAR info: WinOle.OLEINPLACEFRAMEINFO): COM.RESULT;
VAR pwin: IOleInPlaceUIWindow; whk: WinHook; fhk: FrameHook; p: HostPorts.Port; f: Views.Frame;
w, h: INTEGER; win: HostWindows.Window; outerSite: WinOle.IOleInPlaceSite; r1, r2: WinApi.RECT;
BEGIN
IF debug THEN Log.String("ip site: get context"); Log.Ln END;
IF this.site.frame = NIL THEN RETURN WinApi.E_FAIL END;
f := this.site.frame; p := f.rider(HostPorts.Rider).port;
pos.left := f.gx DIV f.unit; pos.top := f.gy DIV f.unit;
(*
f.view.context.GetSize(w, h);
*)
pos.right := pos.left + this.obj.rw; pos.bottom := pos.top + this.obj.rh;
clip.left := 0; clip.top := 0; clip.right := p.w; clip.bottom := p.h;
win := SYSTEM.VAL(HostWindows.Window, WinApi.GetWindowLongW(p.wnd, 0));
outerSite := OleServer.ContextOf(win);
IF outerSite # NIL THEN
RETURN outerSite.GetWindowContext(frame, doc, r1, r2, info)
ELSE
IF appFrame = NIL THEN
NEW(appFrame);
NEW(fhk); HostWindows.mainHook := fhk
END;
frame := appFrame;
NEW(pwin); doc := pwin; pwin.wnd := p.wnd;
NEW(whk); win.hook := whk; whk.iipw := pwin;
info.fMDIApp := 1;
info.hwndFrame := HostWindows.main;
GetAccelTable(info.haccel, info.cAccelEntries);
RETURN WinApi.S_OK
END
END GetWindowContext;
PROCEDURE (this: IOleInPlaceSite) Scroll (scrollExtent: WinApi.SIZE): COM.RESULT;
BEGIN
IF debug THEN Log.String("ip site: scroll"); Log.Ln END;
(* scroll document *)
RETURN WinApi.S_OK
END Scroll;
PROCEDURE (d: Deactivator) Do;
VAR res: COM.RESULT;
BEGIN
IF d.obj.objIPObj # NIL THEN
res := d.obj.objIPObj.InPlaceDeactivate()
END
END Do;
PROCEDURE (this: IOleInPlaceSite) OnUIDeactivate (undoable: WinApi.BOOL): COM.RESULT;
VAR res: COM.RESULT; win: HostWindows.Window; done: BOOLEAN; d: Deactivator;
BEGIN
IF debug THEN Log.String("ip site: ui deactivate"); Log.Ln END;
(* restore user interface *)
win := SYSTEM.VAL(HostWindows.Window, WinApi.GetWindowLongW(this.site.wnd, 0));
OleServer.ResetUI(win, done);
IF ~done & (appFrame # NIL) THEN
IF debug THEN Log.String("reset oberon/f user interface"); Log.Ln END;
res := appFrame.SetMenu(0, 0, 0);
res := appFrame.SetBorderSpace(NIL)
END;
NEW(d); d.obj := this.obj;
Services.DoLater(d, Services.now);
RETURN WinApi.S_OK
END OnUIDeactivate;
PROCEDURE (this: IOleInPlaceSite) OnInPlaceDeactivate (): COM.RESULT;
VAR host: Views.Frame; c: Containers.Controller; style: SET; res: INTEGER;
BEGIN
res := this.site.OnShowWindow(0);
IF debug THEN Log.String("ip site: deactivate"); Log.Ln END;
IF this.site.frame # NIL THEN
IF ~this.obj.guard THEN
host := Views.HostOf(this.site.frame);
IF (host # NIL) & (host.view IS Containers.View) THEN
c := host.view(Containers.View).ThisController();
IF debug THEN Log.String("remove focus"); Log.Ln END;
c.SetFocus(NIL);
c.SetSingleton(this.site.frame.view)
END
END;
style := SYSTEM.VAL(SET, WinApi.GetWindowLongW(this.site.wnd, -16));
res := WinApi.SetWindowLongW(this.site.wnd, -16, SYSTEM.VAL(INTEGER, style - {25}))
END;
(* minimal undo support *)
DoVerb(this.obj, NIL, WinOle.OLEIVERB_DISCARDUNDOSTATE);
this.obj.objIPObj := NIL;
RETURN WinApi.S_OK
END OnInPlaceDeactivate;
PROCEDURE (this: IOleInPlaceSite) DiscardUndoState (): COM.RESULT;
BEGIN
IF debug THEN Log.String("ip site: discard undo"); Log.Ln END;
(* no undo state *)
RETURN WinApi.E_NOTIMPL
END DiscardUndoState;
PROCEDURE (this: IOleInPlaceSite) DeactivateAndUndo (): COM.RESULT;
VAR res: COM.RESULT;
BEGIN
IF debug THEN Log.String("ip site: deactivate & undo"); Log.Ln END;
res := this.obj.objIPObj.InPlaceDeactivate();
RETURN WinApi.S_OK
END DeactivateAndUndo;
PROCEDURE (this: IOleInPlaceSite) OnPosRectChange (IN posRect: WinApi.RECT): COM.RESULT;
VAR pos, clip: WinApi.RECT; res: COM.RESULT; p: HostPorts.Port; f: Views.Frame; w, h: INTEGER;
host: Views.Frame; c: Containers.Controller; g: BOOLEAN; v: Views.View; size: WinApi.SIZE;
BEGIN
f := this.site.frame;
IF (f = NIL) OR (f.rider = NIL) THEN RETURN WinApi.E_FAIL END;
host := Views.HostOf(f); v := f.view;
p := f.rider(HostPorts.Rider).port;
IF debug THEN
Log.String("ip site: on pos rect change");
Log.Int((posRect.right - posRect.left) * f.unit DIV oleUnit);
Log.Int((posRect.bottom - posRect.top) * f.unit DIV oleUnit);
Log.Ln;
res := this.obj.objObj.GetExtent(WinOle.DVASPECT_CONTENT, size);
IF res = WinApi.S_OK THEN
Log.String(" get extent");
Log.Int(size.cx); Log.Int(size.cy)
ELSE
Log.String(" get extent failed")
END;
Log.Ln;
v.context.GetSize(w, h);
Log.String(" get size");
Log.Int(w DIV oleUnit); Log.Int(h DIV oleUnit);
Log.Ln
END;
this.obj.rw := posRect.right - posRect.left;
this.obj.rh := posRect.bottom - posRect.top;
UpdateSizes(this.site.frame.view(View), TRUE, TRUE);
(*
g := this.obj.focusGuard; this.obj.focusGuard := TRUE;
v.context.SetSize((posRect.right - posRect.left) * f.unit, (posRect.bottom - posRect.top) * f.unit);
IF host # NIL THEN (* update saved frame *)
Views.ValidateRoot(Views.RootOf(host));
f := Views.ThisFrame(host, v);
this.site.frame := f;
END;
IF this.obj.objIPObj # NIL THEN
pos.left := f.gx DIV f.unit; pos.top := f.gy DIV f.unit;
v.context.GetSize(w, h);
pos.right := pos.left + w DIV f.unit; pos.bottom := pos.top + h DIV f.unit;
clip.left := 0; clip.top := 0; clip.right := p.w; clip.bottom := p.h;
IF debug THEN Log.String("set object rects"); Log.Ln END;
res := this.obj.objIPObj.SetObjectRects(pos, clip);
IF (host # NIL) & (host.view IS Containers.View) THEN
c := host.view(Containers.View).ThisController();
c.SetFocus(v)
END
END;
this.obj.focusGuard := g;
*)
RETURN WinApi.S_OK
END OnPosRectChange;
(* ---------- IOleInPlaceUIWindow ---------- *)
PROCEDURE (this: IOleInPlaceUIWindow) GetWindow (OUT wnd: WinApi.HWND): COM.RESULT;
BEGIN
IF debug THEN Log.String("ip win: get window"); Log.Ln END;
wnd := this.wnd;
RETURN WinApi.S_OK
END GetWindow;
PROCEDURE (this: IOleInPlaceUIWindow) ContextSensitiveHelp (enter: WinApi.BOOL): COM.RESULT;
VAR res: COM.RESULT;
BEGIN
IF debug THEN Log.String("ip win: context help"); Log.Ln END;
IF this.iipao # NIL THEN res := this.iipao.ContextSensitiveHelp(enter) END;
RETURN WinApi.S_OK
END ContextSensitiveHelp;
PROCEDURE (this: IOleInPlaceUIWindow) GetBorder (OUT border: WinApi.RECT): COM.RESULT;
VAR res: INTEGER;
BEGIN
res := WinApi.GetClientRect(this.wnd, border);
IF debug THEN
Log.String("ip win: get border");
Log.Int(border.left); Log.Int(border.top);
Log.Int(border.right); Log.Int(border.bottom);
Log.Ln
END;
RETURN WinApi.S_OK
END GetBorder;
PROCEDURE (this: IOleInPlaceUIWindow) RequestBorderSpace (
IN width: WinOle.BORDERWIDTHS
): COM.RESULT;
BEGIN
IF debug THEN
Log.String("ip win: request space");
Log.Int(width.left); Log.Int(width.top);
Log.Int(width.right); Log.Int(width.bottom);
Log.Ln
END;
RETURN WinApi.INPLACE_E_NOTOOLSPACE
END RequestBorderSpace;
PROCEDURE (this: IOleInPlaceUIWindow) SetBorderSpace (
IN [nil] width: WinOle.BORDERWIDTHS
): COM.RESULT;
BEGIN
IF debug THEN
Log.String("ip win: set space");
IF VALID(width) THEN
Log.Int(width.left); Log.Int(width.top);
Log.Int(width.right); Log.Int(width.bottom)
ELSE Log.String(" nil")
END;
Log.Ln
END;
IF ~VALID(width) OR (width.left = 0) & (width.top = 0) & (width.right = 0) & (width.bottom = 0) THEN
RETURN WinApi.S_OK
ELSE RETURN WinApi.OLE_E_INVALIDRECT
END
END SetBorderSpace;
PROCEDURE (this: IOleInPlaceUIWindow) SetActiveObject (
obj: WinOle.IOleInPlaceActiveObject; name: WinApi.PtrWSTR
): COM.RESULT;
BEGIN
IF debug THEN Log.String("ip win: set active obj"); Log.Ln END;
this.iipao := obj;
RETURN WinApi.S_OK
END SetActiveObject;
(* ---------- WinHook ---------- *)
PROCEDURE (hk: WinHook) Activate (do: BOOLEAN);
VAR res: COM.RESULT;
BEGIN
IF (hk.iipw # NIL) & (hk.iipw.iipao # NIL) THEN
IF do THEN res := hk.iipw.iipao.OnDocWindowActivate(1)
ELSE
res := hk.iipw.iipao.OnDocWindowActivate(0);
res := WinApi.SendMessageW(HostWindows.client, 560, HostMenus.menuBar, winMenu);
res := WinApi.DrawMenuBar(HostWindows.main);
HostWindows.SetMainBorderWidth(0, 0, 0, 0);
HostMenus.isCont := FALSE
END
END
END Activate;
PROCEDURE (hk: WinHook) Focus (do: BOOLEAN);
VAR res: COM.RESULT; wnd: WinApi.HWND;
BEGIN
IF do & (hk.iipw # NIL) & (hk.iipw.iipao # NIL) THEN
res := hk.iipw.iipao.GetWindow(wnd);
res := WinApi.SetFocus(wnd)
END
END Focus;
PROCEDURE (hk: WinHook) Resize (w, h: INTEGER);
VAR res: COM.RESULT; rect: WinApi.RECT;
BEGIN
IF (hk.iipw # NIL) & (hk.iipw.iipao # NIL) THEN
res := WinApi.GetClientRect(hk.iipw.wnd, rect);
res := hk.iipw.iipao.ResizeBorder(rect, hk.iipw, 0)
END
END Resize;
(* ---------- IOleInPlaceFrame ---------- *)
PROCEDURE (this: IOleInPlaceFrame) GetWindow (OUT wnd: WinApi.HWND): COM.RESULT;
BEGIN
IF debug THEN Log.String("ip frame: get window"); Log.Ln END;
wnd := HostWindows.main;
RETURN WinApi.S_OK
END GetWindow;
PROCEDURE (this: IOleInPlaceFrame) ContextSensitiveHelp (enter: WinApi.BOOL): COM.RESULT;
VAR res: COM.RESULT;
BEGIN
IF debug THEN Log.String("ip frame: context help"); Log.Ln END;
IF this.iipao # NIL THEN res := this.iipao.ContextSensitiveHelp(enter) END;
RETURN WinApi.S_OK
END ContextSensitiveHelp;
PROCEDURE (this: IOleInPlaceFrame) GetBorder (OUT border: WinApi.RECT): COM.RESULT;
BEGIN
HostWindows.GetMainBorder(border.left, border.top, border.right, border.bottom);
IF debug THEN
Log.String("ip frame: get border");
Log.Int(border.left); Log.Int(border.top);
Log.Int(border.right); Log.Int(border.bottom);
Log.Ln
END;
RETURN WinApi.S_OK
END GetBorder;
PROCEDURE (this: IOleInPlaceFrame) RequestBorderSpace (IN width: WinOle.BORDERWIDTHS): COM.RESULT;
BEGIN
IF debug THEN
Log.String("ip frame: request space");
Log.Int(width.left); Log.Int(width.top);
Log.Int(width.right); Log.Int(width.bottom);
Log.Ln
END;
RETURN WinApi.S_OK
END RequestBorderSpace;
PROCEDURE (this: IOleInPlaceFrame) SetBorderSpace (IN [nil] width: WinOle.BORDERWIDTHS): COM.RESULT;
BEGIN
IF debug THEN
Log.String("ip frame: set space");
IF VALID(width) THEN
Log.Int(width.left); Log.Int(width.top);
Log.Int(width.right); Log.Int(width.bottom)
ELSE Log.String(" nil")
END;
Log.Ln
END;
IF VALID(width) THEN
HostWindows.SetMainBorderWidth(width.left, width.top, width.right, width.bottom)
ELSE
HostWindows.SetMainBorderWidth(0, 0, 0, 0)
END;
RETURN WinApi.S_OK
END SetBorderSpace;
PROCEDURE (this: IOleInPlaceFrame) SetActiveObject (obj: WinOle.IOleInPlaceActiveObject;
name: WinApi.PtrWSTR): COM.RESULT;
BEGIN
IF debug THEN Log.String("ip frame: set active obj"); Log.Ln END;
this.iipao := obj;
RETURN WinApi.S_OK
END SetActiveObject;
PROCEDURE (this: IOleInPlaceFrame) InsertMenus (menu: WinApi.HMENU;
VAR widths: WinOle.OLEMENUGROUPWIDTHS): COM.RESULT;
VAR res, n, p: INTEGER; m: HostMenus.Menu;
BEGIN
IF debug THEN Log.String("ip frame: insert menus"); Log.Ln END;
m := HostMenus.menus; p := 0;
WHILE p < 6 DO
WHILE (m # NIL) & (m.class < p) DO m := m.next END;
n := 0;
WHILE (m # NIL) & (m.class = p) DO
res := WinApi.AppendMenuW(menu, WinApi.MF_POPUP, m.menuH, m.menu);
m := m.next; INC(n)
END;
widths.width[p] := n;
INC(p, 2)
END;
m := HostMenus.menus;
WHILE (m # NIL) & ~m.isWinMenu DO m := m.next END;
IF m # NIL THEN winMenu := m.menuH ELSE winMenu := 0 END;
RETURN WinApi.S_OK
END InsertMenus;
PROCEDURE (this: IOleInPlaceFrame) SetMenu (menu: WinApi.HMENU; oleMenu: WinOle.HOLEMENU;
activeObj: WinApi.HWND): COM.RESULT;
VAR res: INTEGER;
BEGIN
IF debug THEN Log.String("ip frame: set menu"); Log.Int(menu); Log.Ln END;
IF menu # 0 THEN
this.objWnd := activeObj;
res := WinApi.SendMessageW(HostWindows.client, 560, menu, winMenu);
HostMenus.isCont := TRUE
ELSIF this.objWnd # 0 THEN
this.objWnd := 0;
res := WinApi.SendMessageW(HostWindows.client, 560, HostMenus.menuBar, winMenu);
HostMenus.isCont := FALSE
END;
res := WinApi.DrawMenuBar(HostWindows.main);
RETURN WinOle.OleSetMenuDescriptor(oleMenu, HostWindows.main, activeObj, this, this.iipao)
END SetMenu;
PROCEDURE (this: IOleInPlaceFrame) RemoveMenus (menu: WinApi.HMENU): COM.RESULT;
VAR m: HostMenus.Menu; i: INTEGER; sm: WinApi.HMENU; res: INTEGER;
BEGIN
IF debug THEN Log.String("ip frame: remove menus"); Log.Ln END;
i := WinApi.GetMenuItemCount(menu);
WHILE i > 0 DO
DEC(i); sm := WinApi.GetSubMenu(menu, i);
m := HostMenus.menus;
WHILE (m # NIL) & (m.menuH # sm) DO m := m.next END;
IF m # NIL THEN res := WinApi.RemoveMenu(menu, i, WinApi.MF_BYPOSITION) END
END;
RETURN WinApi.S_OK
END RemoveMenus;
PROCEDURE (this: IOleInPlaceFrame) SetStatusText (text: WinApi.PtrWSTR): COM.RESULT;
VAR res, i: INTEGER; str: ARRAY 256 OF CHAR;
BEGIN
IF debug THEN Log.String("ip frame: set status"); Log.Ln END;
IF Dialog.showsStatus THEN
IF text # NIL THEN
i := 0;
WHILE (i < LEN(str) - 1) & (text[i] # 0X) DO str[i] := text[i]; INC(i) END;
str[i] := 0X;
res := WinApi.SetWindowTextW(HostWindows.status, str);
res := WinApi.UpdateWindow(HostWindows.status)
END;
RETURN WinApi.S_OK
ELSE
RETURN WinApi.E_FAIL
END
END SetStatusText;
PROCEDURE (this: IOleInPlaceFrame) EnableModeless (enable: WinApi.BOOL): COM.RESULT;
BEGIN
IF debug THEN Log.String("ip frame: enable modeless"); Log.Ln END;
(* enable/disable modeless dialogs *)
RETURN WinApi.S_OK
END EnableModeless;
PROCEDURE (this: IOleInPlaceFrame) TranslateAccelerator (IN msg: WinApi.MSG; id: SHORTINT): COM.RESULT;
VAR res: COM.RESULT; r: INTEGER; m: WinApi.MSG;
BEGIN
IF debug THEN Log.String("ip frame: translate accelerator"); Log.Int(id); Log.Ln END;
res := WinApi.S_OK;
IF (id >= 100) & (id < HostMenus.lastId) THEN
r := WinApi.SendMessageW(HostWindows.main, 273, id + 65536, 0)
ELSE
m := msg;
r := WinApi.TranslateMDISysAccel(HostWindows.client, m);
IF r = 0 THEN res := WinApi.S_FALSE END
END;
RETURN res
END TranslateAccelerator;
(* ---------- FrameHook ---------- *)
PROCEDURE (hk: FrameHook) Activate (do: BOOLEAN);
VAR res: COM.RESULT;
BEGIN
IF (appFrame # NIL) & (appFrame.iipao # NIL) THEN
IF do THEN res := appFrame.iipao.OnFrameWindowActivate(1)
ELSE res := appFrame.iipao.OnFrameWindowActivate(0)
END
END
END Activate;
PROCEDURE (hk: FrameHook) Resize (w, h: INTEGER);
VAR res: COM.RESULT; rect: WinApi.RECT;
BEGIN
IF (appFrame # NIL) & (appFrame.iipao # NIL) THEN
HostWindows.GetMainBorder(rect.left, rect.top, rect.right, rect.bottom);
res := appFrame.iipao.ResizeBorder(rect, appFrame, 1)
END
END Resize;
PROCEDURE (hk: FrameHook) Focus (on: BOOLEAN), EMPTY;
(* ---------- View ---------- *)
PROCEDURE (v: View) GetNewFrame (VAR frame: Views.Frame);
VAR f: Frame;
BEGIN
NEW(f); frame := f
END GetNewFrame;
PROCEDURE InitModel(v: View; m: Model);
BEGIN
v.model := m; Stores.Join(v, m);
IF m.view = NIL THEN m.view := v END;
OpenLink(m)
END InitModel;
PROCEDURE (v: View) Internalize (VAR rd: Stores.Reader);
VAR thisVersion: INTEGER; s: Stores.Store;
BEGIN
v.Internalize^(rd); IF rd.cancelled THEN RETURN END;
rd.ReadVersion(minViewVersion, 1 (* maxViewVersion *), thisVersion); IF rd.cancelled THEN RETURN END;
rd.ReadStore(s); ASSERT(s # NIL, 100); ASSERT(s IS Model, 101);
InitModel(v, s(Model))
END Internalize;
PROCEDURE (v: View) Externalize (VAR wr: Stores.Writer);
BEGIN
v.Externalize^(wr);
wr.WriteVersion(maxViewVersion);
wr.WriteStore(v.model)
END Externalize;
(*
PROCEDURE (v: View) PropagateDomain;
BEGIN
Stores.InitDomain(v.model, v.Domain())
END PropagateDomain;
*)
PROCEDURE (v: View) CopyFromModelView (source: Views.View; model: Models.Model);
BEGIN
InitModel(v, model(Model))
END CopyFromModelView;
PROCEDURE (v: View) ThisModel (): Models.Model;
BEGIN
RETURN v.model
END ThisModel;
PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER);
VAR res: COM.RESULT; dc: WinApi.HDC; rect, wrect: WinApi.RECT; w, h: INTEGER;
size: WinApi.SIZE; g: BOOLEAN; p: HostPorts.Port; s: SET; fl, ft, fr, fb: INTEGER;
n: Notifier;
BEGIN
IF ~v.hasNotifier & (v.Domain() # NIL)
& (v.Domain().GetSequencer() # NIL) & (v.Domain().GetSequencer() IS Sequencers.Sequencer) THEN
NEW(n); n.model := v.model;
v.Domain().GetSequencer()(Sequencers.Sequencer).InstallNotifier(n);
v.hasNotifier := TRUE
END;
IF (v.model.objObj # NIL) & (v.model.objView # NIL) & Visible(v.model, f) THEN
v.context.GetSize(w, h);
IF (w # v.model.w) OR (h # v.model.h) THEN
size.cx := w DIV oleUnit; size.cy := h DIV oleUnit;
g := v.model.guard; v.model.guard := TRUE;
IF WinOle.OleIsRunning(v.model.objObj) # 0 THEN
IF debug THEN Log.String("set size (running)"); Log.Int(size.cx); Log.Int(size.cy); Log.Ln END;
res := v.model.objObj.SetExtent(WinOle.DVASPECT_CONTENT, size)
ELSIF v.model.flags * WinOle.OLEMISC_RECOMPOSEONRESIZE # {} THEN
res := WinOle.OleRun(v.model.objUnk);
IF debug THEN Log.String("set size (recomp)"); Log.Int(size.cx); Log.Int(size.cy); Log.Ln END;
res := v.model.objObj.SetExtent(WinOle.DVASPECT_CONTENT, size);
res := v.model.objObj.Update();
res := v.model.objObj.Close(WinOle.OLECLOSE_SAVEIFDIRTY)
END;
v.model.w := w; v.model.h := h;
v.model.guard := g
END;
p := f.rider(HostPorts.Rider).port; dc := p.dc;
rect.left := f.gx DIV f.unit;
rect.top := f.gy DIV f.unit;
rect.right := (f.gx + w) DIV f.unit;
rect.bottom := (f.gy + h) DIV f.unit;
wrect.left := 0;
wrect.top := 0;
wrect.right := p.w;
wrect.bottom := p.h;
res := WinApi.SaveDC(dc);
IF p.wnd # 0 THEN res := WinApi.SelectClipRgn(dc, 0) END;
f.rider.GetRect(fl, ft, fr, fb);
res := WinApi.IntersectClipRect(dc, fl, ft, fr, fb);
s := WinApi.SetTextAlign(dc, {});
res := v.model.objView.Draw(WinOle.DVASPECT_CONTENT, -1, 0, NIL, 0, dc, rect, wrect, NIL, 0);
h := WinApi.RestoreDC(dc, -1);
IF debug THEN
IF p.wnd # 0 THEN
Log.String("draw"); Log.Int(res);
Log.Int(SYSTEM.VAL(INTEGER, p));
Log.Int(p.wnd); Log.Int(dc);
Log.Int(rect.left); Log.Int(rect.top); Log.Int(rect.right); Log.Int(rect.bottom);
Log.Int(wrect.left); Log.Int(wrect.top); Log.Int(wrect.right); Log.Int(wrect.bottom);
Log.Ln
ELSE
Log.String("draw (p)"); Log.Int(res);
Log.Int(SYSTEM.VAL(INTEGER, p));
Log.Int(p.wnd); Log.Int(dc);
Log.Int(rect.left); Log.Int(rect.top); Log.Int(rect.right); Log.Int(rect.bottom);
Log.Int(wrect.left); Log.Int(wrect.top); Log.Int(wrect.right); Log.Int(wrect.bottom);
Log.Ln
END
END
END
END Restore;
PROCEDURE (v: View) RestoreMarks (f: Views.Frame; l, t, r, b: INTEGER);
BEGIN
IF v.model.open & ((v.model.objIPObj = NIL) OR (v.model.site.frame # f))
& ~v.model.focusGuard & ~Views.IsPrinterFrame(f) THEN
f.MarkRect(l, t, r, b, Ports.fill, HostPorts.focusPat, TRUE)
END
END RestoreMarks;
PROCEDURE (v: View) HandleModelMsg (VAR msg: Models.Message);
VAR res: COM.RESULT; size: WinApi.SIZE; ow, oh, w, h: INTEGER;
c: Containers.Controller; s: Views.View; path: BOOLEAN;
BEGIN
WITH msg: UpdateMsg DO
IF debug THEN Log.String("update"); Log.Ln END;
UpdateSizes(v, msg.checkSize, FALSE);
(*
res := v.model.objView.GetExtent(WinOle.DVASPECT_CONTENT, -1, NIL, size);
IF debug THEN Log.String("update"); Log.Int(size.cx); Log.Int(size.cy); Log.Ln END;
IF res = WinApi.S_OK THEN
ow := size.cx * oleUnit; oh := size.cy * oleUnit;
v.context.GetSize(w, h);
IF (w # ow) OR (h # oh) THEN
IF debug THEN Log.String("set size"); Log.Int(size.cx); Log.Int(size.cy); Log.Ln END;
path := Controllers.path;
Controllers.SetCurrentPath(Controllers.targetPath);
c := Containers.Focus();
Controllers.SetCurrentPath(path);
s := c.Singleton();
v.context.SetSize(ow, oh);
IF c.Singleton() # s THEN c.SetSingleton(s) END;
v.model.w := ow; v.model.h := oh
END;
END;
*)
Views.Update(v, Views.keepFrames)
ELSE
END
END HandleModelMsg;
PROCEDURE (v: View) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View);
VAR res: COM.RESULT; g: BOOLEAN;
BEGIN
WITH msg: Controllers.MarkMsg DO
IF msg.focus & ~v.model.focusGuard THEN
g := v.model.guard; v.model.guard := TRUE;
IF ~msg.show THEN (* defocus *)
IF debug THEN Log.String("defocus"); Log.Ln END;
IF v.model.objIPObj # NIL THEN
res := v.model.objIPObj.InPlaceDeactivate()
END;
(*
ELSIF msg.show & (v.model.flags * WinOle.OLEMISC_INSIDEOUT # {}) THEN
DoVerb(v.model, f, WinOle.OLEIVERB_SHOW)
*)
END;
v.model.guard := g
END
| msg: Controllers.TrackMsg DO
IF v.model.flags * WinOle.OLEMISC_INSIDEOUT # {} THEN
DoVerb(v.model, f, WinOle.OLEIVERB_SHOW)
END
ELSE
END
END HandleCtrlMsg;
PROCEDURE (v: View) HandlePropMsg (VAR msg: Properties.Message);
VAR size: WinApi.SIZE; res: COM.RESULT; i: INTEGER;
iev: WinOle.IEnumOLEVERB; ov: ARRAY 1 OF WinOle.OLEVERB; pstr: WinApi.PtrWSTR;
BEGIN
WITH msg: Properties.SizePref DO
IF (msg.w = Views.undefined) OR (msg.h = Views.undefined) THEN
res := v.model.objView.GetExtent(WinOle.DVASPECT_CONTENT, -1, NIL, size);
IF res >= 0 THEN
IF debug THEN Log.String("get size (prefs)"); Log.Int(size.cx); Log.Int(size.cy); Log.Ln END;
msg.w := size.cx * (Ports.mm DIV 100);
msg.h := size.cy * (Ports.mm DIV 100)
ELSE
IF debug THEN Log.String("get size (prefs) (no size)"); Log.Ln END;
msg.w := 60 * Ports.mm;
msg.h := 60 * Ports.mm
END
END
| msg: Properties.FocusPref DO
IF v.model.flags * WinOle.OLEMISC_INSIDEOUT # {} THEN
msg.hotFocus := TRUE
END
| msg: Properties.PollMsg DO
PollProp(v.model, msg.prop)
| msg: Properties.SetMsg DO
SetProp(v.model, msg.prop)
| msg: Properties.PollVerbMsg DO
res := v.model.objObj.EnumVerbs(iev);
IF res >= 0 THEN
REPEAT
res := iev.Next(1, ov, NIL)
UNTIL (res # WinApi.S_OK) OR (ov[0].lVerb = msg.verb);
IF res = WinApi.S_OK THEN
i := 0;
IF ov[0].lpszVerbName # NIL THEN
WHILE ov[0].lpszVerbName[i] # 0X DO msg.label[i] := ov[0].lpszVerbName[i]; INC(i) END
END;
msg.label[i] := 0X;
msg.disabled := 0 IN ov[0].fuFlags;
msg.checked := 3 IN ov[0].fuFlags
END
END
| msg: Properties.DoVerbMsg DO
DoVerb(v.model, msg.frame, msg.verb)
| msg: HostMenus.TypeMsg DO
res := v.model.objObj.GetUserType(WinOle.USERCLASSTYPE_SHORT, pstr);
IF res >= 0 THEN
i := 0;
WHILE pstr[i] # 0X DO msg.type[i] := pstr[i]; INC(i) END;
msg.type[i] := 0X;
WinOle.CoTaskMemFree(SYSTEM.VAL(WinApi.PtrVoid, pstr))
END
ELSE
END
END HandlePropMsg;
(* ---------- Frame ---------- *)
PROCEDURE (f: Frame) SetOffset (gx, gy: INTEGER);
VAR obj: Model; pos, clip: WinApi.RECT; w, h: INTEGER; p: HostPorts.Port; res: COM.RESULT;
BEGIN
f.SetOffset^(gx, gy);
obj := f.view(View).model;
IF (obj.site.frame = f) & (obj.objIPObj # NIL) THEN
IF debug THEN Log.String("set offset"); Log.Ln END;
UpdateSizes(f.view(View), FALSE, TRUE)
(*
IF debug THEN Log.String("set object rects"); Log.Ln END;
p := f.rider(HostPorts.Rider).port;
pos.left := f.gx DIV f.unit; pos.top := f.gy DIV f.unit;
f.view.context.GetSize(w, h);
pos.right := pos.left + w DIV f.unit; pos.bottom := pos.top + h DIV f.unit;
clip.left := 0; clip.top := 0; clip.right := p.w; clip.bottom := p.h;
res := obj.objIPObj.SetObjectRects(pos, clip);
*)
END
END SetOffset;
PROCEDURE (f: Frame) Close;
BEGIN
(*f.Close^;*)
IF f = f.view(View).model.site.frame THEN
f.view(View).model.site.frame := NIL
END
END Close;
(* ---------- Model ---------- *)
PROCEDURE Init (model: Model);
VAR res: COM.RESULT; ilb: WinOle.ILockBytes;
BEGIN
NEW(model.site); model.site.obj := model;
NEW(model.site.ias, model.site); model.site.ias.obj := model; model.site.ias.site := model.site;
NEW(model.site.iips, model.site); model.site.iips.obj := model; model.site.iips.site := model.site;
res := WinOle.CreateILockBytesOnHGlobal(0, 1, ilb);
ASSERT(res >= 0, 100);
res := WinOle.StgCreateDocfileOnILockBytes(ilb,
WinOle.STGM_CREATE + WinOle.STGM_READWRITE + WinOle.STGM_SHARE_EXCLUSIVE, 0, model.stg);
ASSERT(res >= 0, 101)
END Init;
PROCEDURE Setup (model: Model; object: COM.IUnknown);
VAR res: COM.RESULT; size: WinApi.SIZE; a, b: ARRAY 64 OF CHAR;
BEGIN
model.objUnk := object;
res := object.QueryInterface(COM.ID(model.objView), model.objView);
ASSERT(res >= 0, 102);
res := model.objView.SetAdvise(WinOle.DVASPECT_CONTENT, {}, model.site.ias);
ASSERT(res >= 0, 103);
res := object.QueryInterface(COM.ID(model.objObj), model.objObj);
ASSERT(res >= 0, 104);
res := model.objObj.SetClientSite(model.site);
ASSERT(res >= 0, 105);
res := model.objObj.Advise(model.site.ias, model.advConn);
IF debug THEN Log.String("setup "); Log.Int(model.advConn); Log.Ln END;
(*
res := WinOle.OleSetContainedObject(object, 1);
ASSERT(res >= 0, 107);
*)
a := "BlackBox"; b := "BlackBox Document";
res := model.objObj.SetHostNames(a, b);
IF debug & (res < 0) THEN Log.String("set host names"); Log.Int(res); Log.Ln END;
model.open := FALSE;
res := model.objObj.GetMiscStatus(WinOle.DVASPECT_CONTENT, model.flags);
res := model.objView.GetExtent(WinOle.DVASPECT_CONTENT, -1, NIL, size);
IF debug THEN Log.String("get size (setup)"); Log.Int(size.cx); Log.Int(size.cy); Log.Ln END;
model.w := size.cx * oleUnit; model.h := size.cy * oleUnit;
(*
OpenLinks(model)
*)
END Setup;
PROCEDURE (n: Notifier) Notify (VAR msg: Sequencers.Message);
VAR model: Model; res: COM.RESULT;
BEGIN
IF msg IS Sequencers.RemoveMsg THEN
model := n.model;
Disconnect(model);
IF debug THEN Log.String("release "); Log.Int(model.advConn); Log.Ln END;
IF model.objView # NIL THEN
res := model.objView.SetAdvise(WinOle.DVASPECT_CONTENT, {}, NIL);
model.objView := NIL
END;
IF model.objObj # NIL THEN
res := model.objObj.Close(WinOle.OLECLOSE_SAVEIFDIRTY);
res := model.objObj.SetClientSite(NIL);
res := model.objObj.Unadvise(model.advConn);
model.objObj := NIL
END;
model.objUnk := NIL
END
END Notify;
(*
PROCEDURE (model: Model) PropagateDomain;
VAR n: Notifier; d: Stores.Domain;
BEGIN
OpenLink(model);
NEW(n); n.model := model; d := model.Domain();
WITH d: Sequencers.Sequencer DO d.InstallNotifier(n) ELSE END
END PropagateDomain;
*)
PROCEDURE (model: Model) Internalize (VAR rd: Stores.Reader);
VAR thisVersion: INTEGER; stg: WinOle.IStorage; ilb: WinOle.ILockBytes;
res: COM.RESULT; object: COM.IUnknown; utf8: Kernel.Utf8Name;
BEGIN
model.Internalize^(rd); IF rd.cancelled THEN RETURN END;
rd.ReadVersion(minModelVersion, maxModelVersion, thisVersion); IF rd.cancelled THEN RETURN END;
Init(model);
IF thisVersion = 1 THEN rd.ReadSString(utf8); Utf.Utf8ToString(utf8, model.link, res); ASSERT(res = 0) END;
ilb := OleStorage.NewReadILockBytes(rd.rider);
ASSERT(ilb # NIL);
res := WinOle.StgOpenStorageOnILockBytes(ilb, NIL,
WinOle.STGM_DIRECT + WinOle.STGM_READWRITE + WinOle.STGM_SHARE_EXCLUSIVE, NIL, 0, stg);
ASSERT(res >= 0, 100);
res := stg.CopyTo(0, NIL, NIL, model.stg);
res := WinOle.OleLoad(model.stg, COM.ID(object), model.site, object);
ASSERT(res >= 0, 101);
res := ilb.Flush(); (* resynchronise reader *)
Setup(model, object)
END Internalize;
PROCEDURE (model: Model) Externalize (VAR wr: Stores.Writer);
VAR stg: WinOle.IStorage; res: COM.RESULT; ips: WinOle.IPersistStorage; ilb: WinOle.ILockBytes; g: BOOLEAN;
utf8: Kernel.Utf8Name;
BEGIN
g := model.guard; model.guard := TRUE;
IF debug THEN Log.String("externalize (m)"); Log.Ln END;
model.Externalize^(wr);
IF model.link # "" THEN wr.WriteVersion(1);
Utf.StringToUtf8(model.link, utf8, res); ASSERT(res = 0); wr.WriteSString(utf8)
ELSE wr.WriteVersion(0)
END;
ilb := OleStorage.NewWriteILockBytes(wr.rider);
res := WinOle.StgCreateDocfileOnILockBytes(ilb, WinOle.STGM_CREATE
+ WinOle.STGM_READWRITE + WinOle.STGM_SHARE_EXCLUSIVE, 0, stg);
ASSERT(res >= 0, 100);
IF debug THEN Log.String("externalize (1)"); Log.Ln END;
res := model.objUnk.QueryInterface(COM.ID(ips), ips);
ASSERT(res >= 0, 101);
IF debug THEN Log.String("externalize (2)"); Log.Ln END;
res := WinOle.OleSave(ips, stg, 0);
ASSERT(res >= 0, 102);
IF debug THEN Log.String("externalize (3)"); Log.Ln END;
res := ilb.Flush(); (* resynchronise writer *)
IF debug THEN Log.String("externalize (4)"); Log.Ln END;
res := ips.SaveCompleted(NIL);
ASSERT(res >= 0, 103);
model.guard := g;
IF debug THEN Log.String("externalized (m)"); Log.Ln END
END Externalize;
PROCEDURE (model: Model) CopyFrom (source: Stores.Store);
VAR res: COM.RESULT; ips: WinOle.IPersistStorage; object: COM.IUnknown;
BEGIN
WITH source: Model DO
Init(model);
res := source.objUnk.QueryInterface(COM.ID(ips), ips);
ASSERT(res >= 0, 100);
res := WinOle.OleSave(ips, model.stg, 0);
ASSERT(res >= 0, 101);
res := ips.SaveCompleted(NIL);
ASSERT(res >= 0, 102);
res := WinOle.OleLoad(model.stg, COM.ID(object), model.site, object);
model.link := source.link$;
Setup(model, object)
END
END CopyFrom;
(*
PROCEDURE (model: Model) InitFrom (source: Models.Model);
VAR res: COM.RESULT; ips: WinOle.IPersistStorage; object: COM.IUnknown;
BEGIN
WITH source: Model DO
Init(model);
res := source.objUnk.QueryInterface(COM.ID(ips), ips);
ASSERT(res >= 0, 100);
res := WinOle.OleSave(ips, model.stg, 0);
ASSERT(res >= 0, 101);
res := ips.SaveCompleted(NIL);
ASSERT(res >= 0, 102);
res := WinOle.OleLoad(model.stg, COM.ID(object), model.site, object);
model.link := source.link$;
Setup(model, object)
END
END InitFrom;
*)
(* ---------- import / export ---------- *)
PROCEDURE ImportInfo* (VAR med: WinOle.STGMEDIUM; VAR type: Stores.TypeName;
OUT w, h, rx, ry: INTEGER; OUT isSingle: BOOLEAN);
VAR hnd: WinApi.HGLOBAL; p: WinOle.PtrOBJECTDESCRIPTOR; res: INTEGER;
BEGIN
hnd := MediumGlobal(med);
p := SYSTEM.VAL(WinOle.PtrOBJECTDESCRIPTOR, WinApi.GlobalLock(hnd));
type := "OleClient.View";
w := p.sizel.cx * oleUnit;
h := p.sizel.cy * oleUnit;
rx := p.pointl.x * oleUnit;
ry := p.pointl.x * oleUnit;
isSingle := TRUE;
res := WinApi.GlobalUnlock(hnd)
END ImportInfo;
PROCEDURE Import* (
VAR med: WinOle.STGMEDIUM; OUT v: Views.View; OUT w, h: INTEGER; OUT isSingle: BOOLEAN
);
VAR cv: View; model: Model; res: COM.RESULT; object: COM.IUnknown;
BEGIN
OleServer.Import(med, v, w, h, isSingle);
IF v = NIL THEN (* no BlackBox object *)
NEW(model); Init(model);
res := WinOle.OleCreateFromData(OleData.dataObj, COM.ID(object),
WinOle.OLERENDER_DRAW, NIL, model.site, model.stg, object);
ASSERT(res >= 0, 100);
Setup(model, object);
NEW(cv); InitModel(cv, model);
v := cv; w := 0; h := 0; isSingle := TRUE
END
END Import;
PROCEDURE ExportInfo* (
v: Views.View; w, h, x, y: INTEGER; isSingle: BOOLEAN; VAR med: WinOle.STGMEDIUM
);
VAR hnd: WinApi.HGLOBAL; p: WinOle.PtrOBJECTDESCRIPTOR; id: COM.GUID; stat: SET;
res, size, nlen, slen: INTEGER; name, source: ARRAY 256 OF CHAR; sp: WinApi.PtrWSTR;
BEGIN
ASSERT(med.tymed = {}, 20);
WITH v: View DO
res := v.model.objObj.GetUserClassID(id);
res := v.model.objObj.GetMiscStatus(WinOle.DVASPECT_CONTENT, stat);
res := v.model.objObj.GetUserType(WinOle.USERCLASSTYPE_FULL, sp)
ELSE
id := ObjectID;
stat := miscStatus;
res := WinOle.OleRegGetUserType(ObjectID, WinOle.USERCLASSTYPE_FULL, sp)
END;
IF sp # NIL THEN
name := sp^$;
WinOle.CoTaskMemFree(SYSTEM.VAL(WinApi.PtrVoid, sp))
ELSE name := ""
END;
nlen := 0; slen := 0;
WHILE name[nlen] # 0X DO INC(nlen) END;
nlen := 2 * (nlen + 1);
WHILE Dialog.appName[slen] # 0X DO source[slen] := Dialog.appName[slen]; INC(slen) END;
source[slen] := 0X;
slen := 2 * (slen + 1);
size := 52 + nlen + slen;
hnd := WinApi.GlobalAlloc(WinApi.GMEM_DDESHARE + WinApi.GMEM_MOVEABLE, size);
IF hnd # 0 THEN
p := SYSTEM.VAL(WinOle.PtrOBJECTDESCRIPTOR, WinApi.GlobalLock(hnd));
p.cbSize := size;
p.clsid := id;
p.dwDrawAspect := WinOle.DVASPECT_CONTENT;
p.sizel.cx := w DIV oleUnit;
p.sizel.cy := h DIV oleUnit;
p.pointl.x := x DIV oleUnit;
p.pointl.y := y DIV oleUnit;
p.dwStatus := stat;
p.dwFullUserTypeName := 52;
p.dwSrcOfCopy := 52 + nlen;
SYSTEM.MOVE(SYSTEM.ADR(name), SYSTEM.ADR(p^) + 52, nlen);
SYSTEM.MOVE(SYSTEM.ADR(source), SYSTEM.ADR(p^) + 52 + nlen, slen);
res := WinApi.GlobalUnlock(hnd);
GenGlobalMedium(hnd, NIL, med)
END
END ExportInfo;
PROCEDURE Export* (v: Views.View; w, h, x, y: INTEGER; isSingle: BOOLEAN; VAR med: WinOle.STGMEDIUM);
VAR stg: WinOle.IStorage; res: COM.RESULT; ilb: WinOle.ILockBytes; ips: WinOle.IPersistStorage;
BEGIN
WITH v: View DO
IF med.tymed = WinOle.TYMED_ISTORAGE THEN
stg := MediumStorage(med)
ELSE
res := WinOle.CreateILockBytesOnHGlobal(0, 1, ilb);
ASSERT(res >= 0, 110);
res := WinOle.StgCreateDocfileOnILockBytes(ilb, WinOle.STGM_CREATE
+ WinOle.STGM_READWRITE + WinOle.STGM_SHARE_EXCLUSIVE, 0, stg);
ASSERT(res >= 0, 111);
GenStorageMedium(stg, NIL, med)
END;
res := v.model.objUnk.QueryInterface(COM.ID(ips), ips);
ASSERT(res >= 0, 112);
res := WinOle.OleSave(ips, stg, 0);
ASSERT(res >= 0, 113);
res := ips.SaveCompleted(NIL);
ASSERT(res >= 0, 114)
END
END Export;
(* ---------- commands ---------- *)
PROCEDURE InsertObject*;
VAR v: View; model: Model; res: COM.RESULT; pmfp: WinApi.PtrMETAFILEPICT;
p: WinOleDlg.OLEUIINSERTOBJECTW; w: HostWindows.Window;
fname: ARRAY 260 OF CHAR; guids: ARRAY 1 OF COM.GUID; object: COM.IUnknown;
c: Containers.Controller; f: Views.Frame; v1: Views.View;
BEGIN
NEW(model); Init(model);
w := HostWindows.dir.First();
guids[0] := ObjectID;
p.cbStruct := SIZE(WinOleDlg.OLEUIINSERTOBJECTW);
p.dwFlags := WinOleDlg.IOF_DISABLELINK + WinOleDlg.IOF_SELECTCREATENEW
+ WinOleDlg.IOF_CREATENEWOBJECT + WinOleDlg.IOF_CREATEFILEOBJECT
+ WinOleDlg.IOF_DISABLEDISPLAYASICON;
(*
+ WinOleDlg.IOF_SHOWINSERTCONTROL;
*)
p.hWndOwner := w.wnd;
p.lpszCaption := NIL;
p.lpfnHook := NIL;
p.lCustData := 0;
p.hInstance := 0;
p.lpszTemplate := NIL;
p.hResource := 0;
p.lpszFile := fname;
p.cchFile := LEN(fname);
p.cClsidExclude := LEN(guids);
p.lpClsidExclude := guids;
p.iid := COM.ID(object);
p.oleRender := WinOle.OLERENDER_DRAW;
p.lpFormatEtc := NIL;
p.lpIOleClientSite := model.site;
p.lpIStorage := model.stg;
p.ppvObj := SYSTEM.ADR(object);
p.sc := WinApi.S_OK;
p.hMetaPict := 0;
res := WinOleDlg.OleUIInsertObjectW(p);
IF res = WinOleDlg.OLEUI_OK THEN
IF p.hMetaPict # 0 THEN
pmfp := SYSTEM.VAL(WinApi.PtrMETAFILEPICT, WinApi.GlobalLock(p.hMetaPict));
res := WinApi.DeleteMetaFile(pmfp.hMF);
res := WinApi.GlobalUnlock(p.hMetaPict);
res := WinApi.GlobalFree(p.hMetaPict)
END;
Setup(model, object);
NEW(v); InitModel(v, model);
Controllers.PasteView(v, Views.undefined, Views.undefined, FALSE);
(*
Windows.dir.Update(w);
*)
c := Containers.Focus();
c.GetFirstView(FALSE, v1);
WHILE (v1 # NIL) & (~(v1 IS View) OR (v1(View).model # model)) DO c.GetNextView(FALSE, v1) END;
IF v1 # NIL THEN
v := v1(View);
c.SetSingleton(v);
f := Controllers.FocusFrame();
Views.ValidateRoot(Views.RootOf(f));
f := Views.ThisFrame(f, v);
IF debug THEN Log.String("Object created ("); Log.Int(SYSTEM.VAL(INTEGER, f)); Log.Char(")"); Log.Ln
END;
DoVerb(model, f, WinOle.OLEIVERB_SHOW)
END
ELSIF res # WinOleDlg.OLEUI_CANCEL THEN
IF debug THEN
Log.String("Object creation failed ("); Log.Int(res); Log.Char(")");
IF res = WinOleDlg.OLEUI_IOERR_SCODEHASERROR THEN Log.String(" ("); Log.Int(p.sc); Log.Char(")")
END;
Log.Ln
END
END
END InsertObject;
PROCEDURE MapOleConv(IN key: ARRAY OF CHAR; OUT val: ARRAY OF CHAR);
VAR subs, k: Dialog.String;
BEGIN
Dialog.MapString("#Std:" + key, val);
IF val = key THEN
Librarian.lib.SplitName(key, subs, k);
IF (subs # "Win") & (subs # "Ole") THEN
Dialog.MapString("#" + subs + ":" + key, val)
END
END
END MapOleConv;
PROCEDURE PasteSpecial*;
VAR res: INTEGER; p: WinOleDlg.OLEUIPASTESPECIALW; win: HostWindows.Window;
guids: ARRAY 1 OF COM.GUID; pmfp: WinApi.PtrMETAFILEPICT;
entries: ARRAY 16 OF WinOleDlg.OLEUIPASTEENTRYW;
conv: ARRAY 16 OF OleData.Converter; str: ARRAY 16, 2, 64 OF CHAR;
c: OleData.Converter; n: INTEGER; msg: Controllers.EditMsg;
BEGIN
win := HostWindows.dir.First();
guids[0] := ObjectID;
n := 0; c := OleData.convList;
WHILE (c # NIL) & (n < LEN(entries)) DO
IF (c.imp # "") & ~(OleData.info IN c.opts) THEN
entries[n].fmtetc := c.format;
IF c.type # "" THEN
MapOleConv(c.imp, str[n, 0]);
MapOleConv(c.type, str[n, 1]);
entries[n].lpstrFormatName := str[n, 0];
entries[n].lpstrResultText := str[n, 1]
ELSE
entries[n].lpstrFormatName := "%s";
entries[n].lpstrResultText := "%s"
END;
entries[n].dwFlags := WinOleDlg.OLEUIPASTE_PASTEONLY;
conv[n] := c; INC(n)
END;
c := c.next
END;
p.cbStruct := SIZE(WinOleDlg.OLEUIPASTESPECIALW);
p.dwFlags := WinOleDlg.PSF_DISABLEDISPLAYASICON;
p.hWndOwner := win.wnd;
p.lpszCaption := NIL;
p.lpfnHook := NIL;
p.lCustData := 0;
p.hInstance := 0;
p.lpszTemplate := NIL;
p.hResource := 0;
p.lpSrcDataObj := NIL;
p.arrPasteEntries := SYSTEM.ADR(entries[0]);
p.cPasteEntries := n;
p.arrLinkTypes := NIL;
p.cLinkTypes := 0;
p.cClsidExclude := LEN(guids);
p.lpClsidExclude := guids;
p.hMetaPict := 0;
res := WinOleDlg.OleUIPasteSpecialW(p);
IF res # WinOleDlg.OLEUI_CANCEL THEN
ASSERT(res = WinOleDlg.OLEUI_OK, 100);
ASSERT((p.nSelectedIndex >= 0) & (p.nSelectedIndex < n), 101);
OleData.GetDataViewUsing(
p.lpSrcDataObj, conv[p.nSelectedIndex], msg.view, msg.w, msg.h, msg.isSingle);
IF (msg.view = NIL) & (p.nSelectedIndex + 1 < n)
& (conv[p.nSelectedIndex].imp = conv[p.nSelectedIndex + 1].imp)
THEN
OleData.GetDataViewUsing(
p.lpSrcDataObj, conv[p.nSelectedIndex + 1], msg.view, msg.w, msg.h, msg.isSingle)
END;
IF msg.view # NIL THEN
msg.op := Controllers.paste; msg.clipboard := TRUE;
Controllers.Forward(msg)
END;
IF p.hMetaPict # 0 THEN
pmfp := SYSTEM.VAL(WinApi.PtrMETAFILEPICT, WinApi.GlobalLock(p.hMetaPict));
res := WinApi.DeleteMetaFile(pmfp.hMF);
res := WinApi.GlobalUnlock(p.hMetaPict);
res := WinApi.GlobalFree(p.hMetaPict)
END
END
END PasteSpecial;
PROCEDURE NewView* (clsid: COM.GUID): Views.View;
VAR unk: COM.IUnknown; res: COM.RESULT; m: Model; v: View;
BEGIN
NEW(m); Init(m);
res := WinOle.OleCreate(clsid, COM.ID(unk), WinOle.OLERENDER_DRAW, NIL, m.site, m.stg, unk);
IF res = WinApi.S_OK THEN
Setup(m, unk);
NEW(v); InitModel(v, m); RETURN v
ELSIF debug THEN Log.String("NewView: "); Log.Int(res); Log.Ln
END;
RETURN NIL
END NewView;
(*
PROCEDURE NewViewFrom* (unk: COM.IUnknown): Views.View;
VAR res: COM.RESULT; ips: WinOle.IPersistStorage; new: COM.IUnknown; m: Model; v: View;
BEGIN
res := unk.QueryInterface(COM.ID(ips), ips);
IF res = WinApi.S_OK THEN
NEW(m); Init(m);
res := WinOle.OleSave(ips, m.stg, 0);
ASSERT(res >= 0, 100);
res := ips.SaveCompleted(NIL);
ASSERT(res >= 0, 101);
res := WinOle.OleLoad(m.stg, COM.ID(new), m.site, new);
Setup(m, new);
NEW(v); InitModel(v, m); RETURN v
END;
RETURN NIL
END NewViewFrom;
*)
PROCEDURE NewViewFrom* (unk: COM.IUnknown): Views.View;
VAR res: COM.RESULT; dobj: WinOle.IDataObject; new: COM.IUnknown; m: Model; v: View;
BEGIN
res := unk.QueryInterface(COM.ID(dobj), dobj);
IF res = WinApi.S_OK THEN
NEW(m); Init(m);
res := WinOle.OleCreateFromData(
dobj, COM.ID(new), WinOle.OLERENDER_DRAW, NIL, m.site, m.stg, new);
IF res >= 0 THEN
Setup(m, new);
NEW(v); InitModel(v, m); RETURN v
END
END;
RETURN NIL
END NewViewFrom;
PROCEDURE NewViewFromCB* (): Views.View;
VAR res: COM.RESULT; dobj: WinOle.IDataObject; new: COM.IUnknown; m: Model; v: View;
BEGIN
res := WinOle.OleGetClipboard(dobj);
IF res >= 0 THEN
NEW(m); Init(m);
res := WinOle.OleCreateFromData(
dobj, COM.ID(new), WinOle.OLERENDER_DRAW, NIL, m.site, m.stg, new);
IF res >= 0 THEN
Setup(m, new);
NEW(v); InitModel(v, m); RETURN v
END
END;
RETURN NIL
END NewViewFromCB;
PROCEDURE IUnknown* (v: Views.View): COM.IUnknown;
BEGIN
IF v IS View THEN RETURN v(View).model.objUnk
ELSE RETURN NIL
END
END IUnknown;
PROCEDURE TranslateOleKeys (VAR msg: WinApi.MSG; VAR done: BOOLEAN);
VAR res: COM.RESULT;
BEGIN
IF (appFrame # NIL) & (appFrame.iipao # NIL) THEN
res := appFrame.iipao.TranslateAccelerator(msg);
IF res = WinApi.S_OK THEN done := TRUE END
END
END TranslateOleKeys;
BEGIN
HostMenus.TranslateOleKeys1 := TranslateOleKeys
END OleClient.
| Ole/Mod/Client.odc |
MODULE OleData;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems, Alexander Iljin"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20061012, ai, Updated procedures MemFile.NewReader and MemFile.NewWriter to reuse existing riders
- 20070130, bh, Unicode support
- 20141226, center #22, HostFiles.NewWriter violating the specification
- 20210116, bbcb, #045, restore Files interface to 1.6
"
issues = "
- ...
"
**)
IMPORT
SYSTEM, COM, WinOle, WinApi, Log,
Files, Strings, Meta, Dialog, Services, Ports, Stores, Models,
Views, Properties, Containers,
HostPorts := WinPorts;
CONST
debug = FALSE;
(* opts *)
stream* = 0;
storage* = 1;
file* = 2;
info* = 16;
single* = 17;
select* = 18;
obfTag = 6F4F4443H;
TYPE
Exporter* = PROCEDURE (
v: Views.View; w, h, rx, ry: INTEGER; isSingle: BOOLEAN; VAR med: WinOle.STGMEDIUM);
Importer* = PROCEDURE (
VAR med: WinOle.STGMEDIUM; OUT v: Views.View; OUT w, h: INTEGER; OUT isSingle: BOOLEAN);
InfoImporter* = PROCEDURE (
VAR med: WinOle.STGMEDIUM; VAR type: Stores.TypeName;
OUT w, h, rx, ry: INTEGER; OUT isSingle: BOOLEAN);
IDataObject* = POINTER TO RECORD (WinOle.IDataObject)
view-: Views.View;
w-, h-, rx, ry: INTEGER;
isSingle, useSel: BOOLEAN;
type: Stores.TypeName
END;
Converter* = POINTER TO RECORD
next-: Converter;
imp-, exp-: Dialog.String;
type-: Stores.TypeName;
format-: WinOle.FORMATETC;
opts-: SET
END;
ExpVal = RECORD (Meta.Value) p: Exporter END;
ImpVal = RECORD (Meta.Value) p: Importer END;
InfoVal = RECORD (Meta.Value) p: InfoImporter END;
MetaFileContext = POINTER TO RECORD (Models.Context)
(*domain: Stores.Domain;*)
w, h: INTEGER
END;
MetaFileView = POINTER TO RECORD (Views.View)
view: Views.View;
END;
IEnumFORMATETC = POINTER TO RECORD (WinOle.IEnumFORMATETC)
cur: INTEGER;
num: INTEGER;
data: POINTER TO ARRAY OF RECORD c: WinOle.FORMATETC END;
END;
Info = POINTER TO InfoDesc;
InfoDesc = RECORD [untagged]
type: Stores.TypeName;
w, h, rx, ry: INTEGER;
isSingle: BOOLEAN;
END;
MemFile = POINTER TO RECORD (Files.File)
mem: WinApi.HGLOBAL;
len: INTEGER;
owner: BOOLEAN
END;
MemReader = POINTER TO RECORD (Files.Reader)
base: MemFile;
pos: INTEGER
END;
MemWriter = POINTER TO RECORD (Files.Writer)
base: MemFile;
pos: INTEGER;
END;
MemPtr = POINTER TO ARRAY [untagged] OF BYTE;
VAR
dataObj-: WinOle.IDataObject; (* for importers *)
convList-: Converter;
unit: INTEGER; (* screen resolution *)
(* Auxiliary procedures *)
PROCEDURE GenFormatEtc (format: SHORTINT; aspect: SET; tymed: SET; VAR f: WinOle.FORMATETC);
BEGIN
f.cfFormat := format;
f.ptd := NIL;
f.dwAspect := aspect;
f.lindex := -1;
f.tymed := tymed
END GenFormatEtc;
PROCEDURE GenMetafileMedium (
mf: WinApi.HMETAFILEPICT; unk: COM.IUnknown; VAR sm: WinOle.STGMEDIUM
);
BEGIN
sm.tymed := WinOle.TYMED_MFPICT;
sm.u.hMetaFilePict := mf;
sm.pUnkForRelease := unk
END GenMetafileMedium;
PROCEDURE GenStreamMedium (stm: WinOle.IStream; unk: COM.IUnknown; VAR sm: WinOle.STGMEDIUM);
BEGIN
sm.tymed := WinOle.TYMED_ISTREAM;
sm.u.pstm := stm;
sm.pUnkForRelease := unk
END GenStreamMedium;
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 MediumStream (VAR sm: WinOle.STGMEDIUM): WinOle.IStream;
BEGIN
IF sm.tymed = WinOle.TYMED_ISTREAM THEN RETURN sm.u.pstm
ELSE RETURN NIL
END
END MediumStream;
PROCEDURE MediumGlobal (VAR sm: WinOle.STGMEDIUM): WinApi.HGLOBAL;
BEGIN
IF sm.tymed = WinOle.TYMED_HGLOBAL THEN RETURN sm.u.hGlobal
ELSE RETURN 0
END
END MediumGlobal;
PROCEDURE GetCommand (name: Dialog.String; VAR val: Meta.Value; VAR ok: BOOLEAN);
VAR i: Meta.Item;
BEGIN
Meta.LookupPath(name, i);
IF (i.obj = Meta.procObj) OR (i.obj = Meta.varObj) & (i.typ = Meta.procTyp) THEN
i.GetVal(val, ok)
ELSE ok := FALSE
END
END GetCommand;
PROCEDURE Eql (IN f, g: WinOle.FORMATETC): BOOLEAN;
BEGIN
RETURN (f.cfFormat = g.cfFormat) & (f.ptd = g.ptd) & (f.dwAspect = g.dwAspect)
& (f.lindex = g.lindex) & (f.tymed * g.tymed # {})
END Eql;
PROCEDURE Equiv (IN f, g: WinOle.FORMATETC): BOOLEAN;
BEGIN
RETURN (f.cfFormat = g.cfFormat) & (f.ptd = g.ptd) & (f.dwAspect = g.dwAspect)
& (f.lindex = g.lindex)
END Equiv;
PROCEDURE Compatible (c: Converter; VAR view: Views.View; isSingle: BOOLEAN): BOOLEAN;
BEGIN
RETURN ((c.type = "") OR Services.Is(view, c.type))
& (~(single IN c.opts) OR isSingle)
& (~(select IN c.opts) OR ~isSingle)
END Compatible;
PROCEDURE Setup (data: IDataObject);
VAR v: Views.View; c: Containers.Controller; m: Containers.Model;
p: Properties.BoundsPref; dx, dy: INTEGER;
BEGIN
c := data.view(Containers.View).ThisController();
m := c.SelectionCopy();
(*
v := Services.Clone(data.view)(Views.View);
v.InitModel(m); v.CopyFrom(data.view);
*)
v := Views.CopyWithNewModel(data.view, m);
p.w := Views.undefined; p.h := Views.undefined; Views.HandlePropMsg(v, p);
data.view := v; data.w := p.w; data.h := p.h; data.useSel := FALSE
END Setup;
(* IEnumFORMATETC *)
PROCEDURE CreateIEnumFORMATETC (num: INTEGER; VAR data: ARRAY OF WinOle.FORMATETC;
VAR enum: WinOle.IEnumFORMATETC);
VAR i, n: INTEGER; new: IEnumFORMATETC;
BEGIN
NEW(new);
IF new # NIL THEN
new.cur := 0;
new.num := num;
NEW(new.data, num);
i := 0;
WHILE i < num DO new.data[i].c := data[i]; INC(i) END;
enum := new
END
END CreateIEnumFORMATETC;
PROCEDURE (this: IEnumFORMATETC) Next (num: INTEGER;
OUT elem: ARRAY [untagged] OF WinOle.FORMATETC; OUT [nil] fetched: INTEGER
): COM.RESULT;
VAR n: INTEGER;
BEGIN
n := 0;
IF VALID(fetched) THEN fetched := 0
ELSIF num # 1 THEN RETURN WinApi.E_POINTER
END;
IF this.cur < this.num THEN
WHILE (this.cur < this.num) & (num > 0) DO
elem[n] := this.data[this.cur].c;
INC(this.cur); INC(n); DEC(num)
END;
IF VALID(fetched) THEN fetched := n END;
RETURN WinApi.S_OK
END;
RETURN WinApi.S_FALSE
END Next;
PROCEDURE (this: IEnumFORMATETC) Skip (num: INTEGER): COM.RESULT;
BEGIN
IF this.cur + num < this.num THEN
INC(this.cur, num); RETURN WinApi.S_OK
ELSE RETURN WinApi.S_FALSE
END
END Skip;
PROCEDURE (this: IEnumFORMATETC) Reset (): COM.RESULT;
BEGIN
this.cur := 0; RETURN WinApi.S_OK
END Reset;
PROCEDURE (this: IEnumFORMATETC) Clone (OUT enum: WinOle.IEnumFORMATETC): COM.RESULT;
VAR new: IEnumFORMATETC;
BEGIN
NEW(new);
IF new # NIL THEN
new.num := this.num;
new.cur := this.cur;
new.data := this.data;
enum := new;
RETURN WinApi.S_OK
ELSE RETURN WinApi.E_OUTOFMEMORY
END
END Clone;
(* Metafile Pictures *)
(*
PROCEDURE (c: MetaFileContext) ThisDomain (): Stores.Domain;
BEGIN
RETURN c.domain
END ThisDomain;
*)
PROCEDURE (c: MetaFileContext) ThisModel (): Models.Model;
BEGIN
RETURN NIL
END ThisModel;
PROCEDURE (c: MetaFileContext) GetSize (OUT w, h: INTEGER);
BEGIN
w := c.w; h := c.h
END GetSize;
PROCEDURE (c: MetaFileContext) SetSize (w, h: INTEGER);
END SetSize;
PROCEDURE (c: MetaFileContext) Normalize (): BOOLEAN;
BEGIN
RETURN TRUE
END Normalize;
PROCEDURE (d: MetaFileView) Restore (f: Views.Frame; l, t, r, b: INTEGER);
BEGIN
Views.InstallFrame(f, d.view, 0, 0, 0, FALSE)
END Restore;
PROCEDURE (d: MetaFileView) GetNewFrame (VAR frame: Views.Frame);
VAR f: Views.RootFrame;
BEGIN
NEW(f); frame := f
END GetNewFrame;
PROCEDURE (d: MetaFileView) GetBackground (VAR color: Ports.Color);
BEGIN
color := Ports.background
END GetBackground;
(*
PROCEDURE (d: MetaFileView) PropagateDomain;
BEGIN
Stores.InitDomain(d.view, d.domain)
END PropagateDomain;
*)
PROCEDURE Paint (dc: WinApi.HDC; v: Views.View; w, h, unit: INTEGER);
VAR d: MetaFileView; c: MetaFileContext; p: HostPorts.Port; f: Views.RootFrame; g: Views.Frame;
(* m: Models.Model; *)
BEGIN
NEW(p);
p.Init(unit, Ports.screen);
p.SetSize(w, h);
p.SetDC(dc, 0);
NEW(c);
(*
m := v.ThisModel();
IF (m # NIL) & (m.domain # NIL) THEN
c.domain := m.domain
ELSE
c.domain := Models.NewDomain()
END;
*)
(*
IF v.domain # NIL THEN
c.domain := v.domain
ELSE
c.domain := Models.NewDomain()
END;
*)
c.w := w * p.unit;
c.h := h * p.unit;
NEW(d);
d.view := Views.CopyOf(v, Views.shallow);
Stores.Join(d, d.view);
d.InitContext(c);
d.view.InitContext(c);
(* Stores.InitDomain(d, c.domain); *)
(* Stores.InitDomain(d.view, c.domain); *)
Stores.InitDomain(d);
d.GetNewFrame(g); f := g(Views.RootFrame); f.ConnectTo(p);
Views.SetRoot(f, d, FALSE, {});
Views.AdaptRoot(f);
Views.RestoreRoot(f, 0, 0, c.w, c.h);
END Paint;
(* ---------- MemFiles ---------- *)
PROCEDURE (r: MemReader) Base (): Files.File;
BEGIN
RETURN r.base
END Base;
PROCEDURE (r: MemReader) Pos (): INTEGER;
BEGIN
RETURN r.pos
END Pos;
PROCEDURE (r: MemReader) SetPos (pos: INTEGER);
BEGIN
ASSERT(pos >= 0, 22); ASSERT(pos <= r.base.len, 21);
r.pos := pos; r.eof := FALSE
END SetPos;
PROCEDURE (r: MemReader) ReadByte (OUT x: BYTE);
VAR res: INTEGER; p: MemPtr;
BEGIN
ASSERT(r.base.mem # 0, 20);
IF r.pos < r.base.len THEN
p := SYSTEM.VAL(MemPtr, WinApi.GlobalLock(r.base.mem));
x := p[r.pos]; INC(r.pos);
res := WinApi.GlobalUnlock(r.base.mem)
ELSE
x := 0; r.eof := TRUE
END
END ReadByte;
PROCEDURE (r: MemReader) ReadBytes (VAR x: ARRAY OF BYTE; beg, len: INTEGER);
VAR res: INTEGER; p: MemPtr;
BEGIN
ASSERT(r.base.mem # 0, 20);
ASSERT(beg >= 0, 21);
IF len > 0 THEN
ASSERT(beg + len <= LEN(x), 23);
IF r.pos + len <= r.base.len THEN
p := SYSTEM.VAL(MemPtr, WinApi.GlobalLock(r.base.mem));
SYSTEM.MOVE(SYSTEM.ADR(p[r.pos]), SYSTEM.ADR(x[beg]), len);
INC(r.pos, len);
res := WinApi.GlobalUnlock(r.base.mem)
ELSE
r.eof := TRUE
END
ELSE ASSERT(len = 0, 22)
END
END ReadBytes;
PROCEDURE (w: MemWriter) Base (): Files.File;
BEGIN
RETURN w.base
END Base;
PROCEDURE (w: MemWriter) Pos (): INTEGER;
BEGIN
RETURN w.pos
END Pos;
PROCEDURE (w: MemWriter) SetPos (pos: INTEGER);
BEGIN
ASSERT(pos >= 0, 22); ASSERT(pos <= w.base.len, 21);
w.pos := pos
END SetPos;
PROCEDURE (w: MemWriter) WriteByte (x: BYTE);
VAR res, size: INTEGER; p: MemPtr;
BEGIN
ASSERT(w.base.mem # 0, 20);
IF w.pos >= w.base.len THEN
w.base.len := w.pos + 1;
size := WinApi.GlobalSize(w.base.mem);
IF size < w.base.len THEN
w.base.mem := WinApi.GlobalReAlloc(w.base.mem, w.base.len + 1024,
WinApi.GMEM_DDESHARE + WinApi.GMEM_MOVEABLE)
END
END;
p := SYSTEM.VAL(MemPtr, WinApi.GlobalLock(w.base.mem));
p[w.pos] := x; INC(w.pos);
res := WinApi.GlobalUnlock(w.base.mem)
END WriteByte;
PROCEDURE (w: MemWriter) WriteBytes (IN x: ARRAY OF BYTE; beg, len: INTEGER);
VAR res, size: INTEGER; p: MemPtr;
BEGIN
ASSERT(w.base.mem # 0, 20);
ASSERT(beg >= 0, 21);
IF len > 0 THEN
ASSERT(beg + len <= LEN(x), 23);
IF w.pos + len > w.base.len THEN
w.base.len := w.pos + len;
size := WinApi.GlobalSize(w.base.mem);
IF size < w.base.len THEN
w.base.mem := WinApi.GlobalReAlloc(w.base.mem, w.base.len + 1024,
WinApi.GMEM_DDESHARE + WinApi.GMEM_MOVEABLE)
END
END;
p := SYSTEM.VAL(MemPtr, WinApi.GlobalLock(w.base.mem));
SYSTEM.MOVE(SYSTEM.ADR(x[beg]), SYSTEM.ADR(p[w.pos]), len);
INC(w.pos, len);
res := WinApi.GlobalUnlock(w.base.mem)
ELSE ASSERT(len = 0, 22)
END
END WriteBytes;
PROCEDURE (f: MemFile) Length (): INTEGER;
BEGIN
RETURN f.len
END Length;
PROCEDURE (f: MemFile) NewReader (old: Files.Reader): Files.Reader;
VAR r: MemReader;
BEGIN
ASSERT(f.mem # 0, 20);
IF (old = NIL) OR ~(old IS MemReader) THEN NEW(r)
ELSE r := old(MemReader)
END;
r.base := f;
r.pos := 0; r.eof := FALSE;
RETURN r
END NewReader;
PROCEDURE (f: MemFile) NewWriter (old: Files.Writer): Files.Writer;
VAR w: MemWriter;
BEGIN
ASSERT(f.mem # 0, 20);
IF (old = NIL) OR ~(old IS MemWriter) THEN NEW(w)
ELSE w := old(MemWriter)
END;
w.base := f;
w.pos := f.len;
RETURN w
END NewWriter;
PROCEDURE (f: MemFile) Register (name: Files.Name; type: Files.Type; ask: BOOLEAN; OUT res: INTEGER);
BEGIN
res := -1
END Register;
PROCEDURE (f: MemFile) Close;
END Close;
PROCEDURE (f: MemFile) Flush;
END Flush;
PROCEDURE (f: MemFile) FINALIZE;
BEGIN
IF f.owner THEN f.mem := WinApi.GlobalFree(f.mem) END
END FINALIZE;
PROCEDURE NewMemFile (mem: WinApi.HGLOBAL; owner: BOOLEAN): Files.File;
VAR f: MemFile;
BEGIN
NEW(f);
f.mem := mem;
f.len := WinApi.GlobalSize(mem);
f.owner := owner;
RETURN f
END NewMemFile;
(* standard exporters *)
PROCEDURE ExportNative* (
v: Views.View; w, h, x, y: INTEGER; isSingle: BOOLEAN; VAR med: WinOle.STGMEDIUM
);
VAR hnd: WinApi.HGLOBAL; f: Files.File; wr: Stores.Writer; res: COM.RESULT;
BEGIN
ASSERT(med.tymed = {}, 20);
hnd := WinApi.GlobalAlloc(WinApi.GMEM_DDESHARE + WinApi.GMEM_MOVEABLE, 1024);
f := NewMemFile(hnd, FALSE);
wr.ConnectTo(f);
wr.SetPos(0);
wr.WriteInt(obfTag);
wr.WriteInt(0);
wr.WriteInt(w);
wr.WriteInt(h);
IF isSingle THEN wr.WriteSChar(1X) ELSE wr.WriteSChar(0X) END;
wr.WriteStore(v);
GenGlobalMedium(hnd, NIL, med)
END ExportNative;
PROCEDURE ExportInfo* (
v: Views.View; w, h, x, y: INTEGER; isSingle: BOOLEAN; VAR med: WinOle.STGMEDIUM
);
VAR hnd: WinApi.HGLOBAL; p: Info; res: INTEGER;
BEGIN
ASSERT(med.tymed = {}, 20);
hnd := WinApi.GlobalAlloc(WinApi.GMEM_DDESHARE + WinApi.GMEM_MOVEABLE, SIZE(InfoDesc));
IF hnd # 0 THEN
p := SYSTEM.VAL(Info, WinApi.GlobalLock(hnd));
Services.GetTypeName(v, p.type);
p.w := w; p.h := h; p.rx := x; p.ry := y;
p.isSingle := isSingle;
res := WinApi.GlobalUnlock(hnd);
GenGlobalMedium(hnd, NIL, med)
END
END ExportInfo;
PROCEDURE ExportPicture* (
v: Views.View; w, h, x, y: INTEGER; isSingle: BOOLEAN; VAR med: WinOle.STGMEDIUM
);
VAR dc: WinApi.HDC; mf: WinApi.HMETAFILE; mp: WinApi.PtrMETAFILEPICT;
rc: WinApi.RECT; res: INTEGER; hm: WinApi.HMETAFILEPICT;
bp: Properties.BoundsPref; sp: Properties.SizePref;
BEGIN
ASSERT(med.tymed = {}, 20);
IF (w = Views.undefined) OR (h = Views.undefined) THEN
bp.w := Views.undefined; bp.h := Views.undefined;
Views.HandlePropMsg(v, bp);
w := bp.w; h := bp.h
END;
IF (w = Views.undefined) OR (h = Views.undefined) THEN
sp.w := Views.undefined; sp.h := Views.undefined;
sp.fixedW := FALSE; sp.fixedH := FALSE;
Views.HandlePropMsg(v, sp);
w := sp.w; h := sp.h
END;
(*
w := w DIV (Ports.mm DIV 100); h := h DIV (Ports.mm DIV 100); (* w, h in mm/100 *)
*)
dc := WinApi.CreateMetaFileW(NIL);
IF dc # 0 THEN
res := WinApi.SetMapMode(dc, WinApi.MM_ANISOTROPIC);
res := WinApi.SetWindowOrgEx(dc, 0, 0, NIL);
res := WinApi.SetWindowExtEx(dc, w DIV unit, h DIV unit, NIL);
IF v # NIL THEN Paint(dc, v, w DIV unit, h DIV unit, unit) END;
mf := WinApi.CloseMetaFile(dc);
IF mf # 0 THEN
hm := WinApi.GlobalAlloc(
WinApi.GMEM_DDESHARE + WinApi.GMEM_MOVEABLE, SIZE(WinApi.METAFILEPICT));
IF hm # 0 THEN
mp := SYSTEM.VAL(WinApi.PtrMETAFILEPICT, WinApi.GlobalLock(hm));
mp.hMF := mf;
mp.mm := WinApi.MM_ANISOTROPIC;
mp.xExt := w DIV (Ports.mm DIV 100); (* himetric units *)
mp.yExt := h DIV (Ports.mm DIV 100);
res := WinApi.GlobalUnlock(hm);
GenMetafileMedium(hm, NIL, med)
ELSE res := WinApi.DeleteMetaFile(mf)
END
END
END
END ExportPicture;
(* standard importers *)
PROCEDURE ImportNative* (VAR med: WinOle.STGMEDIUM; OUT v: Views.View;
OUT w, h: INTEGER; OUT isSingle: BOOLEAN);
VAR hnd: WinApi.HGLOBAL; f: Files.File; r: Stores.Reader; s: Stores.Store;
tag, version, res: COM.RESULT; ch: SHORTCHAR;
BEGIN
v := NIL;
hnd := MediumGlobal(med);
med.u.hGlobal := 0;
f := NewMemFile(hnd, TRUE);
r.ConnectTo(f); r.SetPos(0);
r.ReadInt(tag);
IF tag = obfTag THEN
r.ReadInt(version);
r.ReadInt(w);
r.ReadInt(h);
r.ReadSChar(ch); isSingle := ch # 0X;
r.ReadStore(s);
v := s(Views.View)
END
END ImportNative;
PROCEDURE ImportInfo* (VAR med: WinOle.STGMEDIUM; VAR type: Stores.TypeName;
OUT w, h, rx, ry: INTEGER; OUT isSingle: BOOLEAN);
VAR s: Stores.Store; hnd: WinApi.HANDLE; p: Info; res: INTEGER;
BEGIN
hnd := MediumGlobal(med);
IF hnd # 0 THEN
p := SYSTEM.VAL(Info, WinApi.GlobalLock(hnd));
type := p.type;
w := p.w; h := p.h; rx := p.rx; ry := p.ry;
isSingle := p.isSingle;
res := WinApi.GlobalUnlock(hnd)
END
END ImportInfo;
(* IDataObject *)
PROCEDURE (this: IDataObject) GetData* (IN format: WinOle.FORMATETC;
OUT medium: WinOle.STGMEDIUM): COM.RESULT;
VAR c: Converter; val: ExpVal; ok: BOOLEAN;
BEGIN
c := convList;
WHILE (c # NIL) & ((c.exp = "")
OR ~Compatible(c, this.view, this.isSingle)
OR ~Eql(c.format, format)) DO c := c.next END;
IF c # NIL THEN
GetCommand(c.exp, val, ok);
medium.tymed := {};
IF ok THEN
IF this.useSel & ~(info IN c.opts) THEN Setup(this) END;
val.p(this.view, this.w, this.h, this.rx, this.ry, this.isSingle, medium);
RETURN WinApi.S_OK
ELSE
IF debug THEN Log.String(c.exp); Log.String(" failed"); Log.Ln END;
RETURN WinApi.E_UNEXPECTED
END
ELSE RETURN WinApi.DV_E_FORMATETC
END
END GetData;
PROCEDURE (this: IDataObject) GetDataHere* (IN format: WinOle.FORMATETC;
VAR medium: WinOle.STGMEDIUM): COM.RESULT;
VAR c: Converter; val: ExpVal; ok: BOOLEAN;
BEGIN
IF format.tymed * (WinOle.TYMED_ISTORAGE + WinOle.TYMED_ISTREAM) # {} THEN
c := convList;
WHILE (c # NIL) & ((c.exp = "")
OR ~Compatible(c, this.view, this.isSingle)
OR ~Eql(c.format, format)) DO c := c.next END;
IF (c # NIL) & (medium.tymed = c.format.tymed) THEN
GetCommand(c.exp, val, ok);
IF ok THEN
IF this.useSel & ~(info IN c.opts) THEN Setup(this) END;
val.p(this.view, this.w, this.h, this.rx, this.ry, this.isSingle, medium);
RETURN WinApi.S_OK
ELSE
IF debug THEN Log.String(c.exp); Log.String(" failed"); Log.Ln END;
RETURN WinApi.E_UNEXPECTED
END
ELSE RETURN WinApi.DV_E_FORMATETC
END
ELSE RETURN WinApi.DV_E_FORMATETC
END
END GetDataHere;
PROCEDURE (this: IDataObject) QueryGetData* (IN format: WinOle.FORMATETC): COM.RESULT;
VAR c: Converter;
BEGIN
c := convList;
WHILE (c # NIL) & ((c.exp = "")
OR ~Compatible(c, this.view, this.isSingle)
OR ~Eql(c.format, format)) DO c := c.next END;
IF c # NIL THEN RETURN WinApi.S_OK
ELSE RETURN WinApi.DV_E_FORMATETC
END
END QueryGetData;
PROCEDURE (this: IDataObject) GetCanonicalFormatEtc* (IN formatIn: WinOle.FORMATETC;
OUT formatOut: WinOle.FORMATETC): COM.RESULT;
BEGIN
RETURN WinApi.DATA_S_SAMEFORMATETC
END GetCanonicalFormatEtc;
PROCEDURE (this: IDataObject) SetData* (IN format: WinOle.FORMATETC;
IN medium: WinOle.STGMEDIUM; release: WinApi.BOOL): COM.RESULT;
BEGIN
RETURN WinApi.DV_E_FORMATETC
END SetData;
PROCEDURE (this: IDataObject) EnumFormatEtc* (direction: SET;
OUT enum: WinOle.IEnumFORMATETC): COM.RESULT;
VAR format: ARRAY 32 OF WinOle.FORMATETC; p: WinOle.IEnumFORMATETC;
n, i: INTEGER; c: Converter;
BEGIN
IF direction = WinOle.DATADIR_GET THEN
n := 0; c := convList;
WHILE (n < LEN(format)) & (c # NIL) DO
IF (c.exp # "") & Compatible(c, this.view, this.isSingle) THEN
format[n] := c.format; i := 0;
WHILE ~Equiv(format[i], c.format) DO INC(i) END;
IF i = n THEN INC(n)
ELSE format[i].tymed := format[i].tymed + c.format.tymed
END
END;
c := c.next
END;
IF n > 0 THEN
CreateIEnumFORMATETC(n, format, p);
IF p # NIL THEN enum := p; RETURN WinApi.S_OK
ELSE RETURN WinApi.E_OUTOFMEMORY
END
ELSE RETURN WinApi.E_FAIL
END
ELSE
RETURN WinApi.E_NOTIMPL
END
END EnumFormatEtc;
PROCEDURE (this: IDataObject) DAdvise* (IN format: WinOle.FORMATETC; flags: SET;
advSink: WinOle.IAdviseSink; OUT connection: INTEGER): COM.RESULT;
BEGIN
RETURN WinApi.E_FAIL
END DAdvise;
PROCEDURE (this: IDataObject) DUnadvise* (connection: INTEGER): COM.RESULT;
BEGIN
RETURN WinApi.E_FAIL
END DUnadvise;
PROCEDURE (this: IDataObject) EnumDAdvise* (OUT enum: WinOle.IEnumSTATDATA): COM.RESULT;
BEGIN
RETURN WinApi.E_FAIL
END EnumDAdvise;
(* import/export *)
PROCEDURE DataConvTo* (data: WinOle.IDataObject; type: Stores.TypeName): BOOLEAN;
VAR t: Stores.TypeName; c: Converter; v: Views.View; res: COM.RESULT; ok, s: BOOLEAN;
med: WinOle.STGMEDIUM; ival: InfoVal; w, h, x, y: INTEGER;
BEGIN
v := NIL; c := convList;
WHILE c # NIL DO
IF c.imp # "" THEN
IF (type = "") OR (c.type # "") & Services.Extends(c.type, type) THEN
IF data.QueryGetData(c.format) = WinApi.S_OK THEN RETURN TRUE END
ELSIF info IN c.opts THEN
res := data.GetData(c.format, med);
IF res >= 0 THEN
GetCommand(c.imp, ival, ok); t := "";
IF ok THEN ival.p(med, t, w, h, x, y, s)
ELSIF debug THEN Log.String(c.imp); Log.String(" failed (c)"); Log.Ln
END;
WinOle.ReleaseStgMedium(med);
IF t = type THEN RETURN TRUE END
END
END
END;
c := c.next
END;
RETURN FALSE
END DataConvTo;
PROCEDURE GetDataView* (data: WinOle.IDataObject; type: Stores.TypeName; OUT v: Views.View;
OUT w, h: INTEGER; OUT isSingle: BOOLEAN);
VAR t: Stores.TypeName; c: Converter; val: ImpVal; ival: InfoVal; ok, s: BOOLEAN;
res: COM.RESULT; med: WinOle.STGMEDIUM; x, y: INTEGER;
BEGIN
v := NIL; t := ""; c := convList;
WHILE (c # NIL) & (v = NIL) DO
IF c.imp # "" THEN
IF info IN c.opts THEN
IF type # "" THEN
res := data.GetData(c.format, med); t := "";
IF debug THEN Log.String("Get Data "); Log.String(c.imp); Log.String(c.exp); Log.Int(res); Log.Ln
END;
IF res >= 0 THEN
GetCommand(c.imp, ival, ok);
IF ok THEN ival.p(med, t, w, h, x, y, s)
ELSIF debug THEN Log.String(c.imp); Log.String(" failed (i)"); Log.Ln
END;
WinOle.ReleaseStgMedium(med)
END
END
ELSIF (type = "") OR (c.type # "") & Services.Extends(c.type, type)
OR (c.type = "") & (t # "") & Services.Extends(t, type) THEN
IF debug THEN Log.String("query"); Log.Int(data.QueryGetData(c.format)); Log.Ln END;
res := data.GetData(c.format, med);
IF debug THEN Log.String("Get Data "); Log.String(c.imp); Log.String(c.exp); Log.Int(res); Log.Ln END;
IF res >= 0 THEN
GetCommand(c.imp, val, ok);
IF ok THEN
dataObj := data; val.p(med, v, w, h, isSingle); dataObj := NIL
ELSIF debug THEN Log.String(c.imp); Log.String(" failed (g)"); Log.Ln
END;
WinOle.ReleaseStgMedium(med)
END
END
END;
c := c.next
END
END GetDataView;
PROCEDURE GetDataViewUsing* (data: WinOle.IDataObject; c: Converter; OUT v: Views.View;
OUT w, h: INTEGER; OUT isSingle: BOOLEAN);
VAR val: ImpVal; ok: BOOLEAN; res: COM.RESULT; med: WinOle.STGMEDIUM;
BEGIN
ASSERT(c # NIL, 20);
ASSERT(c.imp # "", 21);
ASSERT(~(info IN c.opts), 22);
v := NIL;
res := data.GetData(c.format, med);
IF debug THEN Log.String("Get Data "); Log.String(c.imp); Log.String(c.exp); Log.Int(res); Log.Ln END;
IF res >= 0 THEN
GetCommand(c.imp, val, ok);
IF ok THEN
dataObj := data; val.p(med, v, w, h, isSingle); dataObj := NIL
ELSIF debug THEN Log.String(c.imp); Log.String(" failed (g)"); Log.Ln
END;
WinOle.ReleaseStgMedium(med)
END
END GetDataViewUsing;
PROCEDURE GetTextDataView* (data: WinOle.IDataObject; OUT v: Views.View;
OUT w, h: INTEGER; OUT isSingle: BOOLEAN);
VAR c: Converter;
BEGIN
v := NIL; c := convList;
WHILE (c # NIL) & (c.imp # "OleData.ImportNative") DO c := c.next END;
IF c # NIL THEN GetDataViewUsing(data, c, v, w, h, isSingle) END;
IF v = NIL THEN
c := convList;
WHILE (c # NIL) & (c.imp # "WinTextConv.ImportDRichText") DO c := c.next END;
IF c # NIL THEN GetDataViewUsing(data, c, v, w, h, isSingle) END;
END;
IF v = NIL THEN
GetDataView(data, "", v, w, h, isSingle)
END
END GetTextDataView;
PROCEDURE GetDataType* (data: WinOle.IDataObject; OUT type: Stores.TypeName;
OUT w, h, x, y: INTEGER; OUT isSingle: BOOLEAN);
VAR t: Stores.TypeName; c: Converter; res: COM.RESULT; med: WinOle.STGMEDIUM;
ival: InfoVal; ok: BOOLEAN;
BEGIN
type := ""; c := convList;
WHILE (c # NIL) & (type = "") DO
IF c.imp # "" THEN
IF info IN c.opts THEN
res := data.GetData(c.format, med);
IF res >= 0 THEN
GetCommand(c.imp, ival, ok);
IF ok THEN ival.p(med, type, w, h, x, y, isSingle)
ELSIF debug THEN Log.String(c.imp); Log.String(" failed (t)"); Log.Ln
END;
WinOle.ReleaseStgMedium(med)
END
ELSIF c.type # "" THEN
IF data.QueryGetData(c.format) = WinApi.S_OK THEN
type := c.type; isSingle := FALSE;
w := 0; h := 0; x := 0; y := 0
END
END
END;
c := c.next
END
END GetDataType;
(* creation *)
PROCEDURE ViewData* (v: Views.View; w, h: INTEGER; isSingle: BOOLEAN): IDataObject;
VAR new: IDataObject;
BEGIN
NEW(new); new.view := v; new.w := w; new.h := h; new.rx := 0; new.ry := 0;
new.isSingle := isSingle; new.useSel := FALSE;
IF v # NIL THEN Services.GetTypeName(v, new.type) ELSE new.type := "*" END;
RETURN new
END ViewData;
PROCEDURE ViewDropData* (v: Views.View; w, h, rx, ry: INTEGER; isSingle, useSel: BOOLEAN): IDataObject;
VAR new: IDataObject;
BEGIN
IF useSel THEN
ASSERT(~isSingle, 20);
ASSERT(v IS Containers.View, 21);
ASSERT(v(Containers.View).ThisController() # NIL, 22)
END;
NEW(new); new.view := v; new.w := w; new.h := h; new.rx := rx; new.ry := ry;
new.isSingle := isSingle; new.useSel := useSel;
IF v # NIL THEN Services.GetTypeName(v, new.type) ELSE new.type := "*" END;
RETURN new
END ViewDropData;
PROCEDURE SetView* (data: IDataObject; v: Views.View; w, h: INTEGER);
BEGIN
data.view := v; data.w := w; data.h := h;
IF v # NIL THEN Services.GetTypeName(v, data.type) ELSE data.type := "*" END;
END SetView;
(* registration *)
PROCEDURE Register* (imp, exp, format: Dialog.String; type: Stores.TypeName; opts: SET);
VAR c, f: Converter; tymed: SET; cbf: SHORTINT;
BEGIN
tymed := WinOle.TYMED_HGLOBAL;
IF format = "TEXT" THEN cbf := WinApi.CF_TEXT
ELSIF format = "BITMAP" THEN cbf := WinApi.CF_BITMAP; tymed := WinOle.TYMED_GDI
ELSIF format = "METAFILEPICT" THEN cbf := WinApi.CF_METAFILEPICT; tymed := WinOle.TYMED_MFPICT
ELSIF format = "SYLK" THEN cbf := WinApi.CF_SYLK
ELSIF format = "DIF" THEN cbf := WinApi.CF_DIF
ELSIF format = "TIFF" THEN cbf := WinApi.CF_TIFF
ELSIF format = "OEMTEXT" THEN cbf := WinApi.CF_OEMTEXT
ELSIF format = "DIB" THEN cbf := WinApi.CF_DIB; tymed := WinOle.TYMED_GDI
ELSIF format = "PALETTE" THEN cbf := WinApi.CF_PALETTE
ELSIF format = "PENDATA" THEN cbf := WinApi.CF_PENDATA
ELSIF format = "RIFF" THEN cbf := WinApi.CF_RIFF
ELSIF format = "WAVE" THEN cbf := WinApi.CF_WAVE
ELSIF format = "UNICODETEXT" THEN cbf := WinApi.CF_UNICODETEXT
ELSIF format = "ENHMETAFILE" THEN cbf := WinApi.CF_ENHMETAFILE; tymed := WinOle.TYMED_ENHMF
ELSIF format = "HDROP" THEN cbf := WinApi.CF_HDROP
ELSIF format = "LOCALE" THEN cbf := WinApi.CF_LOCALE
ELSE cbf := SHORT(WinApi.RegisterClipboardFormatW(format))
END;
IF stream IN opts THEN tymed := WinOle.TYMED_ISTREAM
ELSIF storage IN opts THEN tymed := WinOle.TYMED_ISTORAGE
ELSIF file IN opts THEN tymed := WinOle.TYMED_FILE
END;
NEW(c); c.imp := imp; c.exp := exp; c.type := type; c.opts := opts;
GenFormatEtc(cbf, WinOle.DVASPECT_CONTENT, tymed, c.format);
IF convList = NIL THEN convList := c
ELSE f := convList;
WHILE f.next # NIL DO f := f.next END;
f.next := c
END
END Register;
(* debug *)
PROCEDURE DumpData* (data: WinOle.IDataObject);
VAR type: Stores.TypeName; c: Converter; val: ImpVal; ival: InfoVal; ok, s: BOOLEAN;
res: COM.RESULT; med: WinOle.STGMEDIUM; w, h, x, y: INTEGER; v: Views.View;
BEGIN
c := convList;
WHILE c # NIL DO
IF c.imp # "" THEN
res := data.QueryGetData(c.format);
IF res >= 0 THEN
Log.String(c.imp); Log.Char(" ");
res := data.GetData(c.format, med);
IF res >= 0 THEN
Log.String(" read ");
IF info IN c.opts THEN
Log.String("(i) ");
GetCommand(c.imp, ival, ok);
IF ok THEN
type := "";
ival.p(med, type, w, h, x, y, s);
Log.String(type);
Log.Int(w); Log.Int(h); Log.Int(x); Log.Int(y);
IF s THEN Log.String(" singleton") END
ELSE
Log.String("failed");
END
ELSE
GetCommand(c.imp, val, ok);
IF ok THEN
v := NIL;
dataObj := data; val.p(med, v, w, h, s); dataObj := NIL;
IF v # NIL THEN
Services.GetTypeName(v, type);
Log.String(type);
Log.Int(w); Log.Int(h);
IF s THEN Log.String(" singleton") END
ELSE
Log.String("NIL")
END
ELSE
Log.String("failed");
END
END;
WinOle.ReleaseStgMedium(med);
Log.Ln
END
END
END;
c := c.next
END
END DumpData;
PROCEDURE Init;
VAR res: INTEGER; dc: WinApi.HDC;
BEGIN
dc := WinApi.GetDC(0);
unit := 914400 DIV WinApi.GetDeviceCaps(dc, 90);
res := WinApi.ReleaseDC(0, dc)
END Init;
BEGIN
Init
END OleData.
| Ole/Mod/Data.odc |
MODULE OleServer;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20070205, bh, Unicode support
"
issues = "
- ...
"
**)
IMPORT
SYSTEM, COM, WinOle, WinApi,
OleStorage, OleData, StdDialog,
Kernel, Files, Services, Ports, Dialog, Stores, Sequencers, Views,
Controllers, Properties, Converters, Containers, Documents, Windows,
TextViews, Log,
HostPorts := WinPorts,
HostDialog := WinDialog,
(*HostWindows := WinWindows,*)
OleWindows,
WinGui,
HostMenus := MdiMenus;
CONST
debug = FALSE;
ObjectID = "{00000001-1000-11cf-adf0-444553540000}";
streamStr = "CONTENTS";
cbFormat = 200H;
obfTag = 6F4F4443H;
miscStatus = WinOle.OLEMISC_RECOMPOSEONRESIZE
+ WinOle.OLEMISC_CANTLINKINSIDE
+ WinOle.OLEMISC_RENDERINGISDEVICEINDEPENDENT;
oleUnit = Ports.mm DIV 100;
borderW = 5 * Ports.point;
fixed = 31; (* controller option *)
TYPE
IClassFactory = POINTER TO RECORD (WinOle.IClassFactory) END;
Object = POINTER TO RECORD (COM.IUnknown)
ioo: IOleObject;
ido: IDataObject;
ips: IPersistStorage;
iipo: IOleInPlaceObject;
iipao: IOleInPlaceActiveObject;
ics: WinOle.IOleClientSite;
iips: WinOle.IOleInPlaceSite; (* # NIL => in place open *)
iipf: WinOle.IOleInPlaceFrame;
iipw: WinOle.IOleInPlaceUIWindow;
fInfo: WinOle.OLEINPLACEFRAMEINFO;
idah: WinOle.IDataAdviseHolder;
ioah: WinOle.IOleAdviseHolder;
isg: WinOle.IStorage;
ism: WinOle.IStream;
rsm: WinOle.IStream;
menu: WinApi.HMENU;
oleMenu: WinOle.HOLEMENU;
menuType: Stores.TypeName;
w, h: INTEGER;
view: Views.View;
seq: Sequencers.Sequencer;
win: OleWindows.Window; (* # NIL => open *)
embedded: BOOLEAN;
update: BOOLEAN;
uiActive: BOOLEAN;
useMenu: BOOLEAN;
unit: INTEGER (* scaling when in place open *)
END;
IOleObject = POINTER TO RECORD (WinOle.IOleObject)
obj: Object
END;
IDataObject = POINTER TO RECORD (WinOle.IDataObject)
obj: Object;
data: OleData.IDataObject
END;
IPersistStorage = POINTER TO EXTENSIBLE RECORD (WinOle.IPersistStorage)
obj: Object
END;
IOleInPlaceObject = POINTER TO RECORD (WinOle.IOleInPlaceObject);
obj: Object
END;
IOleInPlaceActiveObject = POINTER TO RECORD (WinOle.IOleInPlaceActiveObject)
obj: Object
END;
Window = POINTER TO RECORD (OleWindows.Window)
obj: Object
END;
WinDir = POINTER TO RECORD (OleWindows.Directory)
obj: Object;
host: WinApi.HWND;
pos, clip: WinApi.RECT;
END;
Action = POINTER TO RECORD (Services.Action)
w: Window
END;
Verb = POINTER TO RECORD
verb: INTEGER;
name: ARRAY 64 OF CHAR;
disabled, checked: BOOLEAN;
next: Verb
END;
IEnumOLEVERB = POINTER TO RECORD (WinOle.IEnumOLEVERB)
first, cur: Verb
END;
VAR
factory: IClassFactory;
token: INTEGER;
winDir: WinDir;
(* ---------- auxiliary ---------- *)
PROCEDURE Max (x, y: INTEGER): INTEGER;
BEGIN
IF x > y THEN RETURN x ELSE RETURN y END
END Max;
PROCEDURE Min (x, y: INTEGER): INTEGER;
BEGIN
IF x < y THEN RETURN x ELSE RETURN y END
END Min;
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 GenStorageMedium (stg: WinOle.IStorage; unk: COM.IUnknown; VAR sm: WinOle.STGMEDIUM);
TYPE PS = POINTER TO RECORD t: SET; s: WinOle.IStorage; u: COM.IUnknown END;
VAR ps: PS;
BEGIN
sm.u.hGlobal := 0;
sm.tymed := WinOle.TYMED_ISTORAGE;
sm.u.pstg := stg;
sm.pUnkForRelease := unk
END GenStorageMedium;
PROCEDURE MediumStorage (VAR sm: WinOle.STGMEDIUM): WinOle.IStorage;
BEGIN
ASSERT(sm.tymed = WinOle.TYMED_ISTORAGE, 20);
RETURN sm.u.pstg
END MediumStorage;
PROCEDURE NewString (VAR str: ARRAY OF CHAR): WinApi.PtrWSTR;
VAR n: INTEGER; p: WinApi.PtrWSTR;
BEGIN
n := 0; WHILE str[n] # 0X DO INC(n) END;
p := SYSTEM.VAL(WinApi.PtrWSTR, WinOle.CoTaskMemAlloc(SIZE(CHAR) * (n + 1)));
p^ := str$;
RETURN p
END NewString;
PROCEDURE CheckVerb (v: Views.View; n: INTEGER; VAR pvm: Properties.PollVerbMsg);
BEGIN
pvm.verb := n;
pvm.label := "";
pvm.disabled := FALSE; pvm.checked := FALSE;
IF v # NIL THEN Views.HandlePropMsg(v, pvm) END
END CheckVerb;
(* ---------- IClassFactory ---------- *)
PROCEDURE (this: IClassFactory) CreateInstance (outer: COM.IUnknown; IN [iid] iid: COM.GUID;
OUT [new] int: COM.IUnknown): COM.RESULT;
VAR res: COM.RESULT; new: Object;
BEGIN
IF debug THEN Log.String("create instance"); Log.Ln END;
IF outer = NIL THEN
NEW(new);
IF new # NIL THEN
NEW(new.ioo, new); NEW(new.ido, new); NEW(new.ips, new); NEW(new.iipo, new);
NEW(new.iipao); (* separate component *)
IF (new.ioo # NIL) & (new.ido # NIL) & (new.ips # NIL) & (new.iipo # NIL) & (new.iipao # NIL) THEN
new.ioo.obj := new;
new.ido.obj := new;
new.ido.data := OleData.ViewData(NIL, 0, 0, TRUE);
new.ips.obj := new;
new.iipo.obj := new;
new.iipao.obj := new;
new.embedded := FALSE;
res := new.QueryInterface(iid, int);
IF res >= 0 THEN HostMenus.Lock END;
IF debug THEN Log.String("c lock "); Log.Int(HostMenus.locks); Log.Ln END;
ELSE res := WinApi.E_OUTOFMEMORY
END
ELSE res := WinApi.E_OUTOFMEMORY
END
ELSE res := WinApi.CLASS_E_NOAGGREGATION
END;
RETURN res
END CreateInstance;
PROCEDURE (this: IClassFactory) LockServer (lock: WinApi.BOOL): COM.RESULT;
BEGIN
IF lock # 0 THEN HostMenus.Lock ELSE HostMenus.Unlock END;
IF debug THEN Log.String("lock server "); Log.Int(lock); Log.Int(HostMenus.locks); Log.Ln END;
RETURN WinApi.S_OK
END LockServer;
(* IEnumOLEVERB *)
PROCEDURE (this: IEnumOLEVERB) Next (num: INTEGER; OUT elem: ARRAY [untagged] OF WinOle.OLEVERB;
OUT [nil] fetched: INTEGER): COM.RESULT;
VAR n: INTEGER; flags: SET;
BEGIN
n := 0;
IF VALID(fetched) THEN fetched := 0
ELSIF num # 1 THEN RETURN WinApi.E_POINTER
END;
IF this.cur # NIL THEN
WHILE (this.cur # NIL) & (num > 0) DO
elem[n].lVerb := this.cur.verb;
elem[n].lpszVerbName := NewString(this.cur.name);
flags := {};
IF this.cur.disabled THEN INCL(flags, 0) END;
IF this.cur.checked THEN INCL(flags, 3) END;
elem[n].fuFlags := flags;
IF this.cur.verb >= 0 THEN
elem[n].grfAttribs := WinOle.OLEVERBATTRIB_ONCONTAINERMENU
ELSE
elem[n].grfAttribs := {}
END;
this.cur := this.cur.next; INC(n); DEC(num)
END;
IF VALID(fetched) THEN fetched := n END;
RETURN WinApi.S_OK
END;
RETURN WinApi.S_FALSE
END Next;
PROCEDURE (this: IEnumOLEVERB) Skip (num: INTEGER): COM.RESULT;
BEGIN
WHILE (num > 0) & (this.cur # NIL) DO this.cur := this.cur.next; DEC(num) END;
IF this.cur # NIL THEN RETURN WinApi.S_OK
ELSE RETURN WinApi.S_FALSE
END
END Skip;
PROCEDURE (this: IEnumOLEVERB) Reset (): COM.RESULT;
BEGIN
this.cur := this.first;
RETURN WinApi.S_OK
END Reset;
PROCEDURE (this: IEnumOLEVERB) Clone (OUT enum: WinOle.IEnumOLEVERB): COM.RESULT;
VAR new: IEnumOLEVERB;
BEGIN
NEW(new);
IF new # NIL THEN
new.first := this.first;
new.cur := this.cur;
enum := new;
RETURN WinApi.S_OK
ELSE RETURN WinApi.E_OUTOFMEMORY
END
END Clone;
(*
(* ---------- Object Release Patch ---------- *) (* VERY BIG HACK !!!!!!!!! *)
PROCEDURE^ (this: Object) InPlaceDeactivate ();
PROCEDURE ObjectRelease (this: Object): LONGINT;
VAR n: LONGINT; msg: Sequencers.RemoveMsg;
BEGIN
n := Kernel.Release(SYSTEM.VAL(LONGINT, this));
IF debug THEN Log.String("release "); Log.Int(n); Log.Ln END;
IF n = 0 THEN
IF this.iips # NIL THEN this.InPlaceDeactivate END;
this.ics := NIL; this.idah := NIL; this.ioah := NIL;
IF this.seq # NIL THEN this.seq.Notify(msg) END;
HostMenus.Unlock;
IF debug THEN Log.String("r unlock "); Log.Int(HostMenus.locks); Log.Ln END;
Kernel.Cleanup
END;
RETURN n
END ObjectRelease;
PROCEDURE PatchObjectRelease;
CONST releaseMethOff = -4;
BEGIN
SYSTEM.PUT(SYSTEM.ADR(Object) + releaseMethOff, SYSTEM.ADR(ObjectRelease))
END PatchObjectRelease;
*)
(* ---------- Object ---------- *)
PROCEDURE^ (this: Object) InPlaceDeactivate (), NEW;
PROCEDURE (this: Object) RELEASE;
VAR msg: Sequencers.RemoveMsg;
BEGIN
IF this.iips # NIL THEN this.InPlaceDeactivate END;
this.ics := NIL; this.idah := NIL; this.ioah := NIL;
IF this.seq # NIL THEN this.seq.Notify(msg) END;
HostMenus.Unlock;
IF debug THEN Log.String("r unlock "); Log.Int(HostMenus.locks); Log.Ln END;
Kernel.Cleanup
END RELEASE;
PROCEDURE (this: Object) QueryInterface (IN iid: COM.GUID; OUT int: COM.IUnknown): COM.RESULT;
BEGIN
IF debug THEN Log.String("query interface"); Log.Ln END;
IF COM.QUERY(this, iid, int)
OR COM.QUERY(this.ioo, iid, int)
OR COM.QUERY(this.ido, iid, int)
OR COM.QUERY(this.ips, iid, int)
OR COM.QUERY(this.iipo, iid, int) THEN RETURN WinApi.S_OK
ELSE RETURN WinApi.E_NOINTERFACE
END
END QueryInterface;
PROCEDURE (this: Object) GetMenuType (VAR changed: BOOLEAN), NEW;
VAR ops: Controllers.PollOpsMsg;
BEGIN
ops.type := ""; this.win.ForwardCtrlMsg(ops);
IF ops.type # this.menuType THEN
changed := TRUE;
this.menuType := ops.type$
ELSE
changed := FALSE
END
END GetMenuType;
PROCEDURE (this: Object) InPlaceMenuCreate (), NEW;
VAR menu: WinApi.HMENU; res, i, p, n: INTEGER; widths: WinOle.OLEMENUGROUPWIDTHS;
m: HostMenus.Menu;
BEGIN
IF debug THEN Log.String("create menu"); Log.Ln END;
i := 0; WHILE i < 6 DO widths.width[i] := 0; INC(i) END;
menu := WinApi.CreateMenu();
res := this.iipf.InsertMenus(menu, widths);
m := HostMenus.menus; p := 0; i := 0;
WHILE p < 6 DO
WHILE (m # NIL) & (m.class <= p) DO m := m.next END;
INC(i, widths.width[p]); INC(p); n := 0;
WHILE (m # NIL) & (m.class = p) DO
IF (m.type = "") OR (m.type = this.menuType) THEN
res := WinApi.InsertMenuW(menu, i, WinApi.MF_POPUP + WinApi.MF_BYPOSITION,
m.menuH, m.menu);
INC(n); INC(i)
END;
m := m.next;
END;
widths.width[p] := n; INC(p)
END;
this.menu := menu;
this.oleMenu := WinOle.OleCreateMenuDescriptor(menu, widths);
IF debug THEN Log.String("menu created"); Log.Ln END;
END InPlaceMenuCreate;
PROCEDURE (this: Object) InPlaceMenuDestroy (), NEW;
VAR res: COM.RESULT; i: INTEGER; m: HostMenus.Menu; sm: WinApi.HMENU;
BEGIN
IF debug THEN Log.String("destroy menu"); Log.Ln END;
res := WinOle.OleDestroyMenuDescriptor(this.oleMenu);
this.oleMenu := 0;
i := WinApi.GetMenuItemCount(this.menu);
WHILE i > 0 DO
DEC(i); sm := WinApi.GetSubMenu(this.menu, i);
m := HostMenus.menus;
WHILE (m # NIL) & (m.menuH # sm) DO m := m.next END;
IF m # NIL THEN res := WinApi.RemoveMenu(this.menu, i, WinApi.MF_BYPOSITION) END
END;
IF this.iipf # NIL THEN res := this.iipf.RemoveMenus(this.menu) END;
res := WinApi.DestroyMenu(this.menu);
this.menu := 0;
IF debug THEN Log.String("menu destroyed"); Log.Ln END;
END InPlaceMenuDestroy;
PROCEDURE (this: Object) UIActivate (): COM.RESULT, NEW;
VAR res: COM.RESULT; dumy: BOOLEAN; rect: WinApi.RECT;
BEGIN
IF debug THEN Log.String("ui activate"); Log.Ln END;
IF this.iips # NIL THEN res := this.iips.OnUIActivate() END;
res := WinApi.SetFocus(this.win.wnd);
OleWindows.ActivateWindow(this.win, TRUE);
IF this.iipf # NIL THEN res := this.iipf.SetActiveObject(this.iipao, "") END;
IF this.iipw # NIL THEN res := this.iipw.SetActiveObject(this.iipao, "") END;
this.GetMenuType(dumy);
this.InPlaceMenuCreate;
res := this.iipf.SetMenu(this.menu, this.oleMenu, WinGui.mainWnd);
this.useMenu := TRUE;
HostMenus.isObj := TRUE;
rect.left := 0; rect.top := 0; rect.right := 0; rect.bottom := 0;
IF this.iipf # NIL THEN res := this.iipf.SetBorderSpace(rect) END;
IF this.iipw # NIL THEN res := this.iipw.SetBorderSpace(rect) END;
this.uiActive := TRUE;
IF debug THEN Log.String("ui active"); Log.Ln END;
RETURN WinApi.S_OK
END UIActivate;
PROCEDURE (this: Object) UIDeactivate (), NEW;
VAR res: COM.RESULT;
BEGIN
IF debug THEN Log.String("ui deactivate"); Log.Ln END;
IF this.iipf # NIL THEN res := this.iipf.SetMenu(0, 0, 0) END;
this.useMenu := FALSE;
this.InPlaceMenuDestroy;
IF this.win # NIL THEN OleWindows.ActivateWindow(this.win, FALSE) END;
IF this.iipf # NIL THEN res := this.iipf.SetActiveObject(NIL, NIL) END;
IF this.iipw # NIL THEN res := this.iipw.SetActiveObject(NIL, NIL) END;
IF this.iips # NIL THEN res := this.iips.OnUIDeactivate(0) END;
HostMenus.isObj := FALSE;
this.uiActive := FALSE;
IF debug THEN Log.String("ui deactive"); Log.Ln END;
END UIDeactivate;
PROCEDURE (this: Object) InPlaceActivate (site: WinOle.IOleClientSite; ui: BOOLEAN): COM.RESULT, NEW;
VAR res: COM.RESULT; host: WinApi.HWND;
d: Documents.Document; c: Containers.Controller; w: Windows.Window;
BEGIN
IF site # NIL THEN
IF this.iips = NIL THEN
IF debug THEN Log.String("try in place"); Log.Ln END;
res := site.QueryInterface(COM.ID(this.iips), this.iips);
IF res < 0 THEN RETURN res END;
res := this.iips.CanInPlaceActivate();
IF res = WinApi.S_OK THEN
IF debug THEN Log.String("in place activate"); Log.Ln END;
res := this.iips.OnInPlaceActivate();
(* undodeactivates := TRUE *)
res := this.iips.GetWindow(host);
this.fInfo.cb := SIZE(WinOle.OLEINPLACEFRAMEINFO);
res := this.iips.GetWindowContext(this.iipf, this.iipw, winDir.pos, winDir.clip, this.fInfo);
(* open window *)
this.view := Views.CopyOf(this.view, Views.shallow);
winDir.obj := this; winDir.host := host;(*!*)
OleWindows.Open(this.view, this.win, TRUE);
(*Windows.SetDir(winDir);
d := Documents.dir.New(this.view, this.w, this.h);
c := d.ThisController();
c.SetOpts(c.opts - {Documents.pageWidth..Documents.winHeight} + {31});
StdDialog.Open(d, "", NIL, "", NIL, TRUE, FALSE, FALSE, FALSE, TRUE);
w := Windows.dir.First();
this.win := w(Window);*)
this.seq := w.seq;
OleData.SetView(this.ido.data, this.view, this.w, this.h);
Windows.SetDir(Windows.stdDir);
IF this.ics # NIL THEN res := this.ics.ShowObject() END;
IF debug THEN Log.String("in place active"); Log.Ln END;
ELSE
this.iips := NIL;
RETURN WinApi.E_FAIL
END
END;
IF ui THEN res := this.UIActivate() END;
IF this.iips # NIL THEN (* minimal undo support *)
res := this.iips.DiscardUndoState()
END
ELSE RETURN WinApi.E_INVALIDARG
END;
RETURN WinApi.S_OK
END InPlaceActivate;
PROCEDURE (this: Object) CheckViewUpdate (), NEW;
VAR res: COM.RESULT; w, h: INTEGER; v: Views.View; changed: BOOLEAN;
BEGIN
IF (this.win # NIL) & (this.win.doc # NIL) THEN
v := this.win.doc.ThisView();
v.context.GetSize(w, h);
IF (v # this.view) OR (w # this.w) OR (h # this.h) THEN
this.view := v; this.w := w; this.h := h;
OleData.SetView(this.ido.data, v, w, h);
this.update := TRUE
END
END;
IF this.update & (this.idah # NIL) & (this.iips = NIL) THEN
IF debug THEN Log.String("on data change"); Log.Ln END;
res := this.idah.SendOnDataChange(this.ido, 0, {});
this.update := FALSE
END;
(* check menus *)
IF (this.win # NIL) & (this.iipf # NIL) & (this.menu # 0) & (Windows.dir.Focus(Controllers.targetPath) = this.win.win)
THEN
this.GetMenuType(changed);
IF changed THEN
this.InPlaceMenuDestroy(); this.InPlaceMenuCreate;
IF this.useMenu THEN
res := this.iipf.SetMenu(this.menu, this.oleMenu, WinGui.mainWnd)
END
END
END
END CheckViewUpdate;
PROCEDURE (this: Object) InPlaceDeactivate (), NEW;
VAR res: COM.RESULT;
BEGIN
IF debug THEN Log.String("in place deactivate"); Log.Ln END;
this.UIDeactivate;
IF this.win # NIL THEN OleWindows.Close(this.win); this.win := NIL END;
IF this.iips # NIL THEN res := this.iips.OnInPlaceDeactivate() END;
this.iips := NIL; this.iipf := NIL; this.iipw := NIL;
this.CheckViewUpdate;
Kernel.Cleanup;
IF debug THEN Log.String("in place deactive"); Log.Ln END;
END InPlaceDeactivate;
PROCEDURE (this: Object) Open (), NEW;
VAR res: COM.RESULT; v: Views.View; d: Documents.Document; c: Containers.Controller; w: Windows.Window;
BEGIN
IF this.win = NIL THEN
IF this.view = NIL THEN
IF debug THEN Log.String("show new"); Log.Ln END;
v := TextViews.dir.New(NIL)
ELSE
IF debug THEN Log.String("show old"); Log.Ln END;
v := Views.CopyOf(this.view, Views.shallow);
END;
winDir.obj := this;
OleWindows.Open(v, this.win, FALSE);
(*Windows.SetDir(winDir);
d := Documents.dir.New(v, this.w, this.h);
c := d.ThisController();
c.SetOpts(c.opts - {Documents.pageWidth..Documents.winHeight});
Views.OpenAux(d, "BlackBox Object");
w := Windows.dir.First();
this.view := v;
this.win := w(Window);*)
this.seq := w.seq;
OleData.SetView(this.ido.data, this.view, this.w, this.h);
Windows.SetDir(Windows.stdDir)
END;
Windows.dir.Select(this.win.win, Windows.lazy);
IF this.ics # NIL THEN res := this.ics.ShowObject() END;
IF this.ics # NIL THEN res := this.ics.OnShowWindow(1) END;
END Open;
PROCEDURE (this: Object) CustomVerb (
verb: INTEGER; IN msg: WinApi.MSG; activeSite: WinOle.IOleClientSite;
index: INTEGER; parent: WinApi.HWND; IN posRect: WinApi.RECT
): COM.RESULT, NEW;
VAR res: COM.RESULT; pvm: Properties.PollVerbMsg; dvm: Properties.DoVerbMsg;
BEGIN
CheckVerb(this.view, 0, pvm);
IF pvm.label = "" THEN
IF verb = 0 THEN
RETURN this.ioo.DoVerb(WinOle.OLEIVERB_SHOW, msg, activeSite, index, parent, posRect)
ELSIF verb = 1 THEN
RETURN this.ioo.DoVerb(WinOle.OLEIVERB_OPEN, msg, activeSite, index, parent, posRect)
ELSE
DEC(verb)
END
END;
CheckVerb(this.view, verb, pvm);
IF pvm.label = "" THEN
res := this.ioo.DoVerb(0, msg, activeSite, index, parent, posRect);
RETURN WinApi.OLEOBJ_S_INVALIDVERB
END;
dvm.frame := NIL;
dvm.verb := verb;
Views.HandlePropMsg(this.view, dvm);
RETURN WinApi.S_OK
END CustomVerb;
(* ---------- IOleObject ---------- *)
PROCEDURE (this: IOleObject) SetClientSite (site: WinOle.IOleClientSite): COM.RESULT;
BEGIN
this.obj.ics := site;
IF site = NIL THEN Kernel.Cleanup END;
RETURN WinApi.S_OK
END SetClientSite;
PROCEDURE (this: IOleObject) GetClientSite (OUT site: WinOle.IOleClientSite): COM.RESULT;
BEGIN
site := this.obj.ics;
RETURN WinApi.S_OK
END GetClientSite;
PROCEDURE (this: IOleObject) SetHostNames (app, obj: WinApi.PtrWSTR): COM.RESULT;
BEGIN
this.obj.embedded := TRUE;
RETURN WinApi.S_OK
END SetHostNames;
PROCEDURE (this: IOleObject) Close (saveOption: INTEGER): COM.RESULT;
VAR res: COM.RESULT; dirty: BOOLEAN; r: INTEGER; q: BOOLEAN;
BEGIN
IF (this.obj.view = NIL) OR (this.obj.seq # NIL) & this.obj.seq.Dirty() THEN
IF saveOption = WinOle.OLECLOSE_SAVEIFDIRTY THEN
IF this.obj.ics # NIL THEN res := this.obj.ics.SaveObject() END;
IF this.obj.ioah # NIL THEN res := this.obj.ioah.SendOnSave() END
ELSIF saveOption = WinOle.OLECLOSE_PROMPTSAVE THEN
IF this.obj.win # NIL THEN HostDialog.CloseDialog(this.obj.win.win, q, r) (* This may result in a halt: HostDialog might expect a HostWindows.Window unconditionally *)
ELSE r := HostDialog.save
END;
IF r = HostDialog.save THEN
IF this.obj.ics # NIL THEN res := this.obj.ics.SaveObject() END;
IF this.obj.ioah # NIL THEN res := this.obj.ioah.SendOnSave() END
ELSIF r = HostDialog.cancel THEN
RETURN WinApi.OLE_E_PROMPTSAVECANCELLED
ENDHALT(126)
END
END;
IF this.obj.win # NIL THEN Windows.dir.Close(this.obj.win.win) END;
Kernel.Cleanup;
RETURN WinApi.S_OK
END Close;
PROCEDURE (this: IOleObject) SetMoniker (which: INTEGER; mk: WinOle.IMoniker): COM.RESULT;
BEGIN
RETURN WinApi.E_NOTIMPL
END SetMoniker;
PROCEDURE (this: IOleObject) GetMoniker (assign, which: INTEGER; OUT mk: WinOle.IMoniker): COM.RESULT;
BEGIN
RETURN WinApi.E_NOTIMPL
END GetMoniker;
PROCEDURE (this: IOleObject) InitFromData (obj: WinOle.IDataObject; creation: WinApi.BOOL;
reserved: INTEGER): COM.RESULT;
BEGIN
RETURN WinApi.E_NOTIMPL
END InitFromData;
PROCEDURE (this: IOleObject) GetClipboardData (reserved: INTEGER; OUT obj: WinOle.IDataObject
): COM.RESULT;
BEGIN
RETURN WinApi.E_NOTIMPL
END GetClipboardData;
PROCEDURE (this: IOleObject) DoVerb (
verb: INTEGER; IN msg: WinApi.MSG; activeSite: WinOle.IOleClientSite;
index: INTEGER; parent: WinApi.HWND; IN posRect: WinApi.RECT
): COM.RESULT;
VAR res: COM.RESULT; v: Views.View; d: Documents.Document; pvm: Properties.PollVerbMsg;
c: Containers.Controller; w: Windows.Window; vw, vh: INTEGER; dvm: Properties.DoVerbMsg;
BEGIN
CASE verb OF
| WinOle.OLEIVERB_HIDE:
IF this.obj.iips # NIL THEN
this.obj.InPlaceDeactivate()
ELSE
IF this.obj.win # NIL THEN Windows.dir.Close(this.obj.win.win) END;
IF this.obj.ics # NIL THEN res := this.obj.ics.OnShowWindow(0) END;
Kernel.Cleanup
END
| WinOle.OLEIVERB_PRIMARY, WinOle.OLEIVERB_SHOW:
IF this.obj.win = NIL THEN
res := this.obj.InPlaceActivate(activeSite, TRUE);
IF res # WinApi.S_OK THEN this.obj.Open END
END
| WinOle.OLEIVERB_OPEN:
IF this.obj.iips # NIL THEN this.obj.InPlaceDeactivate END;
this.obj.Open
| WinOle.OLEIVERB_INPLACEACTIVATE:
RETURN this.obj.InPlaceActivate(activeSite, FALSE)
| WinOle.OLEIVERB_UIACTIVATE:
RETURN this.obj.InPlaceActivate(activeSite, TRUE)
| WinOle.OLEIVERB_DISCARDUNDOSTATE:
(* discard undo *)
ELSE
IF verb >= 0 THEN RETURN this.obj.CustomVerb(verb, msg, activeSite, index, parent, posRect)
ELSE RETURN WinApi.E_NOTIMPL
END
END;
RETURN WinApi.S_OK
END DoVerb;
PROCEDURE (this: IOleObject) EnumVerbs (OUT enum: WinOle.IEnumOLEVERB): COM.RESULT;
VAR e: IEnumOLEVERB; v, last: Verb; pvm: Properties.PollVerbMsg; i, j: INTEGER;
BEGIN
NEW(e);
IF e # NIL THEN
NEW(v); v.verb := -3; v.name := "Hide"; e.first := v; last := v;
NEW(v); v.verb := -2; v.name := "Open"; last.next := v; last := v;
NEW(v); v.verb := -1; v.name := "Show"; last.next := v; last := v;
i := 0; j := 0;
CheckVerb(this.obj.view, 0, pvm);
IF pvm.label = "" THEN
NEW(v); v.verb := i; INC(i); last.next := v; last := v;
Dialog.MapString("#System:Edit", v.name);
NEW(v); v.verb := i; INC(i); last.next := v; last := v;
Dialog.MapString("#System:Open", v.name);
INC(j);
CheckVerb(this.obj.view, j, pvm)
END;
WHILE pvm.label # "" DO
NEW(v); v.verb := i; INC(i); last.next := v; last := v;
Dialog.MapString(pvm.label, v.name);
v.disabled := pvm.disabled;
v.checked := pvm.checked;
INC(j);
CheckVerb(this.obj.view, j, pvm)
END;
e.cur := e.first; enum := e;
RETURN WinApi.S_OK
ELSE RETURN WinApi.E_OUTOFMEMORY
END
END EnumVerbs;
PROCEDURE (this: IOleObject) Update (): COM.RESULT;
BEGIN
RETURN WinApi.S_OK
END Update;
PROCEDURE (this: IOleObject) IsUpToDate (): COM.RESULT;
BEGIN
RETURN WinApi.S_OK
END IsUpToDate;
PROCEDURE (this: IOleObject) GetUserClassID (OUT id: COM.GUID): COM.RESULT;
BEGIN
id := ObjectID;
RETURN WinApi.S_OK
END GetUserClassID;
PROCEDURE (this: IOleObject) GetUserType (form: INTEGER; OUT type: WinApi.PtrWSTR): COM.RESULT;
BEGIN
RETURN WinApi.OLE_S_USEREG
END GetUserType;
PROCEDURE (this: IOleObject) SetExtent (aspect: SET; IN size: WinApi.SIZE): COM.RESULT;
VAR res: COM.RESULT;
BEGIN
IF aspect * WinOle.DVASPECT_CONTENT # {} THEN
IF debug THEN Log.String("set extent"); Log.Int(size.cx); Log.Int(size.cy); Log.Ln END;
this.obj.w := size.cx * oleUnit; this.obj.h := size.cy * oleUnit;
OleData.SetView(this.obj.ido.data, this.obj.view, this.obj.w, this.obj.h);
IF this.obj.win # NIL THEN
this.obj.view.context.SetSize(this.obj.w, this.obj.h)
END;
IF debug THEN Log.String("on data change (se)"); Log.Ln END;
IF this.obj.idah # NIL THEN res := this.obj.idah.SendOnDataChange(this.obj.ido, 0, {}) END;
RETURN WinApi.S_OK
ELSE RETURN WinApi.E_FAIL
END
END SetExtent;
PROCEDURE (this: IOleObject) GetExtent (aspect: SET; OUT size: WinApi.SIZE): COM.RESULT;
BEGIN
IF aspect * WinOle.DVASPECT_CONTENT # {} THEN
this.obj.CheckViewUpdate;
IF (this.obj.w # 0) & (this.obj.h # 0) THEN
size.cx := this.obj.w DIV oleUnit; size.cy := this.obj.h DIV oleUnit;
IF debug THEN Log.String("get extent"); Log.Int(size.cx); Log.Int(size.cy); Log.Ln END;
RETURN WinApi.S_OK
END
END;
RETURN WinApi.E_FAIL
END GetExtent;
PROCEDURE (this: IOleObject) Advise (sink: WinOle.IAdviseSink; OUT connection: INTEGER): COM.RESULT;
VAR res: COM.RESULT;
BEGIN
IF this.obj.ioah = NIL THEN
res := WinOle.CreateOleAdviseHolder(this.obj.ioah);
IF res < 0 THEN RETURN res END
END;
RETURN this.obj.ioah.Advise(sink, connection)
END Advise;
PROCEDURE (this: IOleObject) Unadvise (connection: INTEGER): COM.RESULT;
BEGIN
IF this.obj.ioah # NIL THEN
RETURN this.obj.ioah.Unadvise(connection)
ELSE RETURN WinApi.E_FAIL
END
END Unadvise;
PROCEDURE (this: IOleObject) EnumAdvise (OUT enum: WinOle.IEnumSTATDATA): COM.RESULT;
BEGIN
IF this.obj.ioah # NIL THEN
RETURN this.obj.ioah.EnumAdvise(enum)
ELSE RETURN WinApi.E_FAIL
END
END EnumAdvise;
PROCEDURE (this: IOleObject) GetMiscStatus (aspect: SET; OUT status: SET): COM.RESULT;
BEGIN
status := miscStatus;
RETURN WinApi.S_OK
END GetMiscStatus;
PROCEDURE (this: IOleObject) SetColorScheme (IN pal: WinApi.LOGPALETTE): COM.RESULT;
BEGIN
RETURN WinApi.E_NOTIMPL
END SetColorScheme;
(* ---------- IDataObject ---------- *)
PROCEDURE (this: IDataObject) GetData (IN format: WinOle.FORMATETC;
OUT medium: WinOle.STGMEDIUM): COM.RESULT;
BEGIN
IF debug THEN Log.String("get data"); Log.Ln END;
RETURN this.data.GetData(format, medium)
END GetData;
PROCEDURE (this: IDataObject) GetDataHere (IN format: WinOle.FORMATETC;
VAR medium: WinOle.STGMEDIUM): COM.RESULT;
BEGIN
IF debug THEN Log.String("get data here"); Log.Ln END;
RETURN this.data.GetDataHere(format, medium)
END GetDataHere;
PROCEDURE (this: IDataObject) QueryGetData (IN format: WinOle.FORMATETC): COM.RESULT;
BEGIN
IF debug THEN Log.String("query get data"); Log.Ln END;
RETURN this.data.QueryGetData(format)
END QueryGetData;
PROCEDURE (this: IDataObject) GetCanonicalFormatEtc (IN formatIn: WinOle.FORMATETC;
OUT formatOut: WinOle.FORMATETC): COM.RESULT;
BEGIN
RETURN WinApi.DATA_S_SAMEFORMATETC
END GetCanonicalFormatEtc;
PROCEDURE (this: IDataObject) SetData (IN format: WinOle.FORMATETC;
IN medium: WinOle.STGMEDIUM; release: WinApi.BOOL): COM.RESULT;
BEGIN
RETURN WinApi.DV_E_FORMATETC
END SetData;
PROCEDURE (this: IDataObject) EnumFormatEtc (
direction: SET; OUT enum: WinOle.IEnumFORMATETC
): COM.RESULT;
BEGIN
RETURN this.data.EnumFormatEtc(direction, enum)
END EnumFormatEtc;
PROCEDURE (this: IDataObject) DAdvise (
IN format: WinOle.FORMATETC; flags: SET; advSink: WinOle.IAdviseSink; OUT connection: INTEGER
): COM.RESULT;
VAR res: COM.RESULT;
BEGIN
IF this.obj.idah = NIL THEN
res := WinOle.CreateDataAdviseHolder(this.obj.idah);
IF res < 0 THEN RETURN res END
END;
RETURN this.obj.idah.Advise(this, format, flags, advSink, connection)
END DAdvise;
PROCEDURE (this: IDataObject) DUnadvise (connection: INTEGER): COM.RESULT;
BEGIN
IF this.obj.idah # NIL THEN
RETURN this.obj.idah.Unadvise(connection)
ELSE RETURN WinApi.E_FAIL
END
END DUnadvise;
PROCEDURE (this: IDataObject) EnumDAdvise (OUT enum: WinOle.IEnumSTATDATA): COM.RESULT;
BEGIN
IF this.obj.idah # NIL THEN
RETURN this.obj.idah.EnumAdvise(enum)
ELSE RETURN WinApi.E_FAIL
END
END EnumDAdvise;
(* ---------- IPersistStorage ---------- *)
PROCEDURE (this: IPersistStorage) GetClassID* (OUT id: COM.GUID): COM.RESULT, EXTENSIBLE;
BEGIN
id := ObjectID;
RETURN WinApi.S_OK
END GetClassID;
PROCEDURE (this: IPersistStorage) IsDirty (): COM.RESULT;
BEGIN
IF (this.obj.view = NIL) OR (this.obj.seq # NIL) & this.obj.seq.Dirty() THEN RETURN WinApi.S_OK
ELSE RETURN WinApi.S_FALSE
END
END IsDirty;
PROCEDURE (this: IPersistStorage) InitNew (stg: WinOle.IStorage): COM.RESULT;
VAR res: COM.RESULT; ps: WinApi.PtrWSTR;
BEGIN
IF debug THEN Log.String("init new"); Log.Ln END;
IF stg # NIL THEN
res := stg.CreateStream(streamStr,
WinOle.STGM_DIRECT + WinOle.STGM_CREATE
+ WinOle.STGM_READWRITE + WinOle.STGM_SHARE_EXCLUSIVE,
0, 0, this.obj.ism);
IF res >= 0 THEN
res := WinOle.OleRegGetUserType(ObjectID, WinOle.USERCLASSTYPE_SHORT, ps);
res := WinOle.WriteFmtUserTypeStg(stg, cbFormat, ps);
WinOle.CoTaskMemFree(SYSTEM.VAL(WinApi.PtrVoid, ps));
this.obj.isg := stg;
this.obj.w := 60 * Ports.mm;
this.obj.h := 60 * Ports.mm;
this.obj.rsm := NIL;
this.obj.view := TextViews.dir.New(NIL);
this.obj.seq := NIL;
this.obj.win := NIL;
OleData.SetView(this.obj.ido.data, this.obj.view, this.obj.w, this.obj.h);
RETURN WinApi.S_OK
ELSE RETURN res
END
ELSE RETURN WinApi.E_POINTER
END
END InitNew;
PROCEDURE (this: IPersistStorage) Load (stg: WinOle.IStorage): COM.RESULT;
VAR res: COM.RESULT; tag, version: INTEGER; is: BOOLEAN;
BEGIN
IF debug THEN Log.String("load"); Log.Ln END;
IF stg # NIL THEN
res := stg.OpenStream(streamStr, 0,
WinOle.STGM_DIRECT + WinOle.STGM_READWRITE + WinOle.STGM_SHARE_EXCLUSIVE,
0, this.obj.ism);
IF res >= 0 THEN
res := WinOle.CreateStreamOnHGlobal(0, 1, this.obj.rsm);
res := this.obj.ism.CopyTo(this.obj.rsm, MAX(LONGINT), NIL, NIL);
OleStorage.ImportFromStream(this.obj.rsm, this.obj.view, this.obj.w, this.obj.h, is);
IF this.obj.view # NIL THEN
this.obj.seq := NIL;
this.obj.win := NIL;
this.obj.isg := stg;
OleData.SetView(this.obj.ido.data, this.obj.view, this.obj.w, this.obj.h);
RETURN WinApi.S_OK
END
END;
RETURN WinApi.STG_E_READFAULT
ELSE RETURN WinApi.E_POINTER
END
END Load;
PROCEDURE (this: IPersistStorage) Save (stg: WinOle.IStorage; sameAsLoad: WinApi.BOOL): COM.RESULT;
VAR stm: WinOle.IStream; res: COM.RESULT; ps: WinApi.PtrWSTR;
BEGIN
IF sameAsLoad # 0 THEN
IF debug THEN Log.String("save same"); Log.Ln END;
stm := this.obj.ism;
ELSIF stg # NIL THEN
IF debug THEN Log.String("save"); Log.Ln END;
res := stg.CreateStream(streamStr,
WinOle.STGM_DIRECT + WinOle.STGM_CREATE
+ WinOle.STGM_READWRITE + WinOle.STGM_SHARE_EXCLUSIVE,
0, 0, stm);
IF res < 0 THEN RETURN res END;
res := WinOle.OleRegGetUserType(ObjectID, WinOle.USERCLASSTYPE_SHORT, ps);
res := WinOle.WriteFmtUserTypeStg(stg, cbFormat, ps);
WinOle.CoTaskMemFree(SYSTEM.VAL(WinApi.PtrVoid, ps));
ELSE RETURN WinApi.E_POINTER
END;
this.obj.CheckViewUpdate;
OleStorage.ExportToStream(stm, this.obj.view, this.obj.w, this.obj.h, TRUE);
IF this.obj.seq # NIL THEN
this.obj.seq.BeginModification(Sequencers.notUndoable, NIL);
this.obj.seq.EndModification(Sequencers.notUndoable, NIL); (* clear sequencer *)
this.obj.seq.SetDirty(FALSE)
END;
RETURN WinApi.S_OK
END Save;
PROCEDURE (this: IPersistStorage) SaveCompleted (new: WinOle.IStorage): COM.RESULT;
VAR res: COM.RESULT;
BEGIN
IF debug THEN Log.String("save completed"); Log.Ln END;
IF new # NIL THEN
res := new.OpenStream(streamStr, 0,
WinOle.STGM_DIRECT + WinOle.STGM_READWRITE + WinOle.STGM_SHARE_EXCLUSIVE,
0, this.obj.ism);
IF res >= 0 THEN
this.obj.isg := new;
ELSE RETURN res
END
END;
IF this.obj.ioah # NIL THEN res := this.obj.ioah.SendOnSave() END;
RETURN WinApi.S_OK
END SaveCompleted;
PROCEDURE (this: IPersistStorage) HandsOffStorage (): COM.RESULT;
VAR n: INTEGER;
BEGIN
this.obj.ism := NIL; this.obj.isg := NIL;
RETURN WinApi.S_OK
END HandsOffStorage;
(* ---------- IOleInPlaceObject ---------- *)
PROCEDURE (this: IOleInPlaceObject) GetWindow (OUT wnd: WinApi.HWND): COM.RESULT;
BEGIN
IF debug THEN Log.String("iipo: get window"); Log.Ln END;
wnd := this.obj.win.wnd;
ASSERT(wnd # 0, 100);
RETURN WinApi.S_OK
END GetWindow;
PROCEDURE (this: IOleInPlaceObject) ContextSensitiveHelp (enter: WinApi.BOOL): COM.RESULT;
BEGIN
IF debug THEN Log.String("iipo: context help"); Log.Ln END;
RETURN WinApi.S_OK
END ContextSensitiveHelp;
PROCEDURE (this: IOleInPlaceObject) InPlaceDeactivate (): COM.RESULT;
BEGIN
IF debug THEN Log.String("iipo: ip deactivate"); Log.Ln END;
this.obj.InPlaceDeactivate;
RETURN WinApi.S_OK
END InPlaceDeactivate;
PROCEDURE (this: IOleInPlaceObject) UIDeactivate (): COM.RESULT;
BEGIN
IF debug THEN Log.String("iipo: ui deactivate"); Log.Ln END;
this.obj.UIDeactivate;
RETURN WinApi.S_OK
END UIDeactivate;
PROCEDURE (this: IOleInPlaceObject) SetObjectRects (IN pos, clip: WinApi.RECT): COM.RESULT;
VAR l, t, r, b, bw, u, res: INTEGER;
BEGIN
IF debug THEN Log.String("iipo: set rect"); Log.Ln END;
u := this.obj.unit;
bw := borderW DIV OleWindows.Unit();
l := Max(pos.left - bw, clip.left);
t := Max(pos.top - bw, clip.top);
r := Min(pos.right + bw, clip.right);
b := Min(pos.bottom + bw, clip.bottom);
res := WinApi.SetWindowPos(this.obj.win.wnd, 0, l, t, r - l, b - t, WinApi.SWP_NOZORDER);
this.obj.win.win.SetSize(r - l, b - t);
l := Min(bw, pos.left - clip.left) * u;
t := Min(bw, pos.top - clip.top) * u;
(*
r := l + (pos.right - pos.left) * u;
b := t + (pos.bottom - pos.top) * u;
*)
r := l + this.obj.w;
b := t + this.obj.h;
this.obj.win.doc.SetRect(l, t, r, b);
RETURN WinApi.S_OK
END SetObjectRects;
PROCEDURE (this: IOleInPlaceObject) ReactivateAndUndo (): COM.RESULT;
BEGIN
IF debug THEN Log.String("iipo: reactivate & undo"); Log.Ln END;
RETURN WinApi.S_OK
END ReactivateAndUndo;
(* ---------- IOleInPlaceActiveObject ---------- *)
PROCEDURE (this: IOleInPlaceActiveObject) GetWindow (OUT wnd: WinApi.HWND): COM.RESULT;
BEGIN
IF debug THEN Log.String("iipao: get window"); Log.Ln END;
wnd := this.obj.win.wnd;
RETURN WinApi.S_OK
END GetWindow;
PROCEDURE (this: IOleInPlaceActiveObject) ContextSensitiveHelp (enter: WinApi.BOOL): COM.RESULT;
BEGIN
IF debug THEN Log.String("iipao: context help"); Log.Ln END;
RETURN WinApi.S_OK
END ContextSensitiveHelp;
PROCEDURE (this: IOleInPlaceActiveObject) TranslateAccelerator (IN msg: WinApi.MSG): COM.RESULT;
BEGIN
IF debug THEN Log.String("iipao: translate acc"); Log.Ln END;
RETURN WinApi.S_FALSE
END TranslateAccelerator;
PROCEDURE (this: IOleInPlaceActiveObject) OnFrameWindowActivate (activate: WinApi.BOOL): COM.RESULT;
VAR res: COM.RESULT;
BEGIN
IF debug THEN Log.String("iipao: on frame active "); Log.Int(activate); Log.Ln END;
IF (this.obj.iipf # NIL) & (this.obj.iipw = NIL) THEN
IF activate # 0 THEN
OleWindows.ActivateWindow(this.obj.win, TRUE);
HostMenus.isObj := TRUE
ELSE
OleWindows.ActivateWindow(this.obj.win, FALSE);
HostMenus.isObj := FALSE
END
END;
RETURN WinApi.S_OK
END OnFrameWindowActivate;
PROCEDURE (this: IOleInPlaceActiveObject) OnDocWindowActivate (activate: WinApi.BOOL): COM.RESULT;
VAR res: COM.RESULT;
BEGIN
IF debug THEN Log.String("iipao: on win active"); Log.Int(activate); Log.Ln END;
IF this.obj.iipf # NIL THEN
IF activate # 0 THEN
IF this.obj.uiActive THEN res := this.obj.iipf.SetActiveObject(this, "") END;
OleWindows.ActivateWindow(this.obj.win, TRUE);
HostMenus.isObj := TRUE;
IF this.obj.menu # 0 THEN
res := this.obj.iipf.SetMenu(this.obj.menu, this.obj.oleMenu, WinGui.mainWnd);
this.obj.useMenu := TRUE
END
ELSE
IF this.obj.menu # 0 THEN
res := this.obj.iipf.SetMenu(0, 0, 0);
this.obj.useMenu := FALSE
END;
OleWindows.ActivateWindow(this.obj.win, FALSE);
HostMenus.isObj := FALSE;
IF this.obj.uiActive THEN res := this.obj.iipf.SetActiveObject(NIL, NIL) END
END
END;
RETURN WinApi.S_OK
END OnDocWindowActivate;
PROCEDURE (this: IOleInPlaceActiveObject) ResizeBorder (IN border: WinApi.RECT;
win: WinOle.IOleInPlaceUIWindow; frameWin: WinApi.BOOL): COM.RESULT;
BEGIN
IF debug THEN Log.String("iipao: resize border"); Log.Ln END;
RETURN WinApi.S_OK
END ResizeBorder;
PROCEDURE (this: IOleInPlaceActiveObject) EnableModeless (enable: WinApi.BOOL): COM.RESULT;
BEGIN
IF debug THEN Log.String("iipao: enable modeless"); Log.Ln END;
RETURN WinApi.S_OK
END EnableModeless;
(* ---------- Window ---------- *)
PROCEDURE (w: Window) BroadcastViewMsg (VAR msg: Views.Message);
VAR res: COM.RESULT;
BEGIN
(*w.BroadcastViewMsg^(msg);*)
IF msg.view = w.obj.view THEN w.obj.update := TRUE END
END BroadcastViewMsg;
PROCEDURE (w: Window) ForwardCtrlMsg (VAR msg: Views.CtrlMessage);
VAR c, dc: Containers.Controller;
BEGIN
(*w.ForwardCtrlMsg^(msg);*)
WITH msg: Controllers.EditMsg DO
IF (msg.op = Controllers.pasteChar) & (msg.char = 1BX) & (31 IN msg.modifiers) & w.obj.uiActive THEN
w.obj.InPlaceDeactivate()
END
ELSE
END
END ForwardCtrlMsg;
PROCEDURE (w: Window) DoClose (do: PROCEDURE (w: OleWindows.Window));
VAR res: COM.RESULT;
BEGIN
IF w.obj.uiActive THEN
IF debug THEN Log.String("close -> deactivate"); Log.Ln END;
w.obj.InPlaceDeactivate()
ELSE
IF debug THEN Log.String("close window"); Log.Ln END;
w.obj.CheckViewUpdate;
(*SYSTEM.PUT(SYSTEM.ADR(w.sub), TRUE); (* don't send remove msg *) (* crazy hack!!! *)*)
do(w);
(*w.Close^;*)
IF (w.obj.ics # NIL) & (w.obj.iips = NIL) THEN res := w.obj.ics.OnShowWindow(0) END;
IF debug THEN Log.String("close window c"); Log.Ln END;
w.obj.win := NIL
END
END DoClose;
(* ---------- Action ---------- *)
PROCEDURE (a: Action) Do;
VAR res: COM.RESULT; w, h: INTEGER;
BEGIN
IF a.w.win.frame # NIL THEN
a.w.obj.CheckViewUpdate;
Services.DoLater(a, Services.Ticks() + Services.resolution)
END
END Do;
(* ---------- WinDir ---------- *)
(*PROCEDURE (d: WinDir) New (): HostWindows.Window;
VAR w: Windows.Window; sw: Window; a: Action;
BEGIN
IF d.obj # NIL THEN
NEW(sw); sw.obj := d.obj;
NEW(a); a.w := sw; Services.DoLater(a, Services.now);
RETURN sw
ELSE
w := Windows.stdDir.New(); RETURN w(HostWindows.Window)
END
END New;
PROCEDURE (d: WinDir) Open (w: Windows.Window; doc: Documents.Document; flags: SET; name: Views.Title;
loc: Files.Locator; fname: Files.Name; conv: Converters.Converter);
VAR l, t, r, b, bw, u, u1, res: INTEGER; style: SET; wnd: WinApi.HWND; c: Containers.Controller; dc: WinApi.HDC;
BEGIN
IF (d.obj # NIL) & (d.obj.iips # NIL) THEN (* open in place *)
WITH w: Window DO
IF debug THEN Log.String("open window in place"); Log.Ln END;
flags := flags + {Windows.noHScroll, Windows.noVScroll, Windows.noResize, HostWindows.inPlace};
u := d.obj.w DIV (d.pos.right - d.pos.left);
u1 := d.obj.h DIV (d.pos.bottom - d.pos.top);
IF u1 > u THEN u := u1 END;
d.unit := u;
d.Open^(w, doc, flags, name, loc, fname, conv);
(*
u := HostWindows.unit;
*)
bw := borderW DIV HostWindows.unit;
l := Max(d.pos.left - bw, d.clip.left);
t := Max(d.pos.top - bw, d.clip.top);
r := Min(d.pos.right + bw, d.clip.right);
b := Min(d.pos.bottom + bw, d.clip.bottom);
style := {30}; (* child *)
wnd := WinApi.CreateWindowExW({}, "Oberon Dlg", "", style, l, t, r - l, b - t,
d.host, 0, WinApi.GetModuleHandleW(NIL), SYSTEM.VAL(INTEGER, w));
ASSERT(wnd # 0, 100);
dc := WinApi.GetDC(wnd);
w.port(HostPorts.Port).SetDC(dc, wnd);
w.SetSize(r - l, b - t);
l := Min(bw, d.pos.left - d.clip.left) * u;
t := Min(bw, d.pos.top - d.clip.top) * u;
(*
r := l + (d.pos.right - d.pos.left) * u;
b := t + (d.pos.bottom - d.pos.top) * u;
*)
IF debug THEN Log.Int(d.obj.w); Log.Int(d.obj.h); Log.Ln END;
r := l + d.obj.w;
b := t + d.obj.h;
w.doc.SetRect(l, t, r, b);
res := WinApi.ShowWindow(wnd, 1);
d.obj.unit := u;
IF debug THEN
style := SYSTEM.VAL(SET, WinApi.GetWindowLongW(wnd, -16));
Log.Set(style);
Log.Ln
END;
c := w.doc.ThisController();
c.SetFocus(w.doc.ThisView())
END
ELSE
d.Open^(w, doc, flags, name, loc, fname, conv)
END;
d.obj := NIL
END Open;*)
(* ---------- import / export ---------- *)
PROCEDURE Export* (v: Views.View; w, h, x, y: INTEGER; isSingle: BOOLEAN; VAR med: WinOle.STGMEDIUM);
VAR stg: WinOle.IStorage; stm: WinOle.IStream; res: COM.RESULT; ilb: WinOle.ILockBytes; ps: WinApi.PtrWSTR;
BEGIN
IF debug THEN Log.String("export"); Log.Ln END;
IF med.tymed = WinOle.TYMED_ISTORAGE THEN
stg := MediumStorage(med)
ELSE
res := WinOle.CreateILockBytesOnHGlobal(0, 1, ilb);
ASSERT(res >= 0, 110);
res := WinOle.StgCreateDocfileOnILockBytes(ilb, WinOle.STGM_CREATE
+ WinOle.STGM_READWRITE + WinOle.STGM_SHARE_EXCLUSIVE, 0, stg);
ASSERT(res >= 0, 111);
GenStorageMedium(stg, NIL, med)
END;
res := WinOle.WriteClassStg(stg, ObjectID);
ASSERT(res >= 0, 112);
res := stg.CreateStream(streamStr, WinOle.STGM_CREATE
+ WinOle.STGM_READWRITE + WinOle.STGM_SHARE_EXCLUSIVE, 0, 0, stm);
ASSERT(res >= 0, 113);
res := WinOle.OleRegGetUserType(ObjectID, WinOle.USERCLASSTYPE_SHORT, ps);
res := WinOle.WriteFmtUserTypeStg(stg, cbFormat, ps);
WinOle.CoTaskMemFree(SYSTEM.VAL(WinApi.PtrVoid, ps));
ASSERT(res >= 0, 114);
OleStorage.ExportToStream(stm, v, w, h, isSingle);
res := stg.Commit({});
ASSERT(res >= 0, 115)
END Export;
PROCEDURE Import* (
VAR med: WinOle.STGMEDIUM; VAR v: Views.View; VAR w, h: INTEGER; VAR isSingle: BOOLEAN
);
VAR stg: WinOle.IStorage; res: COM.RESULT; id: COM.GUID; stm, stm2: WinOle.IStream;
BEGIN
IF debug THEN Log.String("import"); Log.Ln END;
stg := MediumStorage(med);
res := WinOle.ReadClassStg(stg, id);
IF (res = WinApi.S_OK) & (id = ObjectID) THEN
res := stg.OpenStream(streamStr, 0,
WinOle.STGM_DIRECT + WinOle.STGM_READWRITE + WinOle.STGM_SHARE_EXCLUSIVE,
0, stm);
ASSERT(res >= 0, 110);
res := WinOle.CreateStreamOnHGlobal(0, 1, stm2);
ASSERT(res >= 0, 111);
res := stm.CopyTo(stm2, MAX(LONGINT), NIL, NIL);
ASSERT(res >= 0, 112);
OleStorage.ImportFromStream(stm2, v, w, h, isSingle);
ELSE
v := NIL
END
END Import;
(* ---------- commands ---------- *)
(*These are only used in OleClient, so defer their refactoring*)
PROCEDURE ContextOf* (w: Windows.Window): WinOle.IOleInPlaceSite;
BEGIN
WITH w: Window DO
IF w.obj # NIL THEN RETURN w.obj.iips END
ELSE RETURN NIL
ENDHALT(126); RETURN NIL
END ContextOf;
PROCEDURE RemoveUI* (w: OleWindows.Window);
VAR res: COM.RESULT;
BEGIN
WITH w: Window DO
IF (w.obj # NIL) & (w.obj.iips # NIL) & w.obj.uiActive THEN
IF debug THEN Log.String("remove ui"); Log.Ln END;
IF w.obj.iipf # NIL THEN res := w.obj.iipf.SetActiveObject(NIL, NIL) END;
IF w.obj.iipw # NIL THEN res := w.obj.iipw.SetActiveObject(NIL, NIL) END;
IF (w.obj.iipf # NIL) & (w.obj.menu # 0) THEN
res := w.obj.iipf.SetMenu(0, 0, 0);
w.obj.useMenu := FALSE
END;
(*
HostWindows.ActivateWindow(w, FALSE);
*)
END
ELSE
ENDHALT(126)
END RemoveUI;
PROCEDURE ResetUI* (w: Windows.Window; VAR done: BOOLEAN);
VAR res: COM.RESULT; rect: WinApi.RECT;
BEGIN
done := FALSE;
WITH w: Window DO
IF (w.obj # NIL) & (w.obj.iips # NIL) & w.obj.uiActive THEN
IF debug THEN Log.String("reset ui"); Log.Ln END;
IF w.obj.iipf # NIL THEN res := w.obj.iipf.SetActiveObject(w.obj.iipao, "") END;
IF w.obj.iipw # NIL THEN res := w.obj.iipw.SetActiveObject(w.obj.iipao, "") END;
IF (w.obj.iipf # NIL) & (w.obj.menu # 0) THEN
res := w.obj.iipf.SetMenu(w.obj.menu, w.obj.oleMenu, HostWindows.main);
w.obj.useMenu := TRUE
END;
rect.left := 0; rect.top := 0; rect.right := 0; rect.bottom := 0;
IF w.obj.iipf # NIL THEN res := w.obj.iipf.SetBorderSpace(rect) END;
IF w.obj.iipw # NIL THEN res := w.obj.iipw.SetBorderSpace(rect) END;
(*
HostWindows.ActivateWindow(w, TRUE);
*)
done := TRUE
END
ELSE
ENDHALT(126)
END ResetUI;
(*PROCEDURE ShowOleStatus (w: Windows.Window; s: ARRAY OF CHAR);
VAR res: COM.RESULT;
BEGIN
WITH w: Window DO
IF w.obj.iipf # NIL THEN
res := w.obj.iipf.SetStatusText(s)
END
ELSE
END
END ShowOleStatus;
PROCEDURE UpdateOleMenus ();
VAR w: Windows.Window; res: COM.RESULT;
BEGIN
w := Windows.dir.First();
WHILE w # NIL DO
WITH w: Window DO
IF (w.obj.iipf # NIL) & (w.obj.menu # 0) THEN
w.obj.InPlaceMenuDestroy(); w.obj.InPlaceMenuCreate();
IF w.obj.useMenu THEN
res := w.obj.iipf.SetMenu(w.obj.menu, w.obj.oleMenu, HostWindows.main)
END
END
ELSE
END;
w := Windows.dir.Next(w)
END
END UpdateOleMenus;
PROCEDURE TranslateOleKeys (VAR msg: WinApi.MSG; VAR done: BOOLEAN);
VAR w: Windows.Window; res: COM.RESULT;
BEGIN
w := Windows.dir.First(); done := FALSE;
IF w # NIL THEN
WITH w: Window DO
IF w.obj.iipf # NIL THEN
res := WinOle.OleTranslateAccelerator(w.obj.iipf, w.obj.fInfo, msg);
IF res = WinApi.S_OK THEN done := TRUE END
END
ELSE
END
END
END TranslateOleKeys;*)
PROCEDURE Register;
VAR res: COM.RESULT;
BEGIN
NEW(factory);
res := WinOle.CoRegisterClassObject(ObjectID, factory,
WinOle.CLSCTX_LOCAL_SERVER, WinOle.REGCLS_MULTIPLEUSE, token);
END Register;
PROCEDURE Unregister;
VAR res: COM.RESULT; n: INTEGER; p: Object;
BEGIN
IF token # 0 THEN
res := WinOle.CoRevokeClassObject(token)
END
END Unregister;
BEGIN
NEW(winDir);
(*!*)(*these variables are OK with NIL, so make decisions later*)(*HostDialog.ShowOleStatus := ShowOleStatus;
HostMenus.UpdateOleMenus := UpdateOleMenus;
HostMenus.TranslateOleKeys2 := TranslateOleKeys;*)
Register
CLOSE
Unregister
END OleServer.
OleServer.xy OleServer.Close
DevDecoder.Decode OleServer
| Ole/Mod/Server.odc |
MODULE OleStorage;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20141226, center #22, HostFiles.NewWriter violating the specification
- 20210116, bbcb, #045, restore Files interface to 1.6
"
issues = "
- ...
"
**)
IMPORT Log,
SYSTEM, COM, WinApi, WinOle, Files, Stores, Views;
CONST
debug = FALSE;
obfTag = 6F4F4443H;
TYPE
ILockBytes = POINTER TO RECORD (WinOle.ILockBytes)
org: INTEGER;
len: INTEGER; (* org + len <= file.Length() *)
file: Files.File; (* file # NIL *)
rd: Files.Reader; (* (rd # NIL) & (rd.Base() = file) *)
wr: Files.Writer (* (wr = NIL) OR (wr.Base() = file) *)
END;
StreamFile = POINTER TO RECORD (Files.File)
stream: WinOle.IStream;
org: LONGINT;
len: INTEGER;
pos: INTEGER (* actual seek pos of stream *)
END;
StreamReader = POINTER TO RECORD (Files.Reader)
base: StreamFile;
pos: INTEGER
END;
StreamWriter = POINTER TO RECORD (Files.Writer)
base: StreamFile;
pos: INTEGER;
END;
(* ---------- ILockBytes ---------- *)
PROCEDURE (this: ILockBytes) ReadAt (offset: LONGINT; buf: WinApi.PtrVoid;
len: INTEGER; OUT [nil] read: INTEGER): COM.RESULT;
TYPE P = POINTER TO ARRAY [untagged] 2000000000 OF BYTE;
VAR p: P;
BEGIN
IF debug THEN
Log.String("read@"); Log.Int(SHORT(offset)); Log.Int(len);
END;
IF (len > 0) & (offset < this.len) THEN
this.rd.SetPos(SHORT(this.org + offset));
IF offset + len > this.len THEN len := SHORT(this.len - offset) END;
p := SYSTEM.VAL(P, buf);
this.rd.ReadBytes(p^, 0, len)
ELSE len := 0
END;
IF VALID(read) THEN read := len END;
IF debug THEN
Log.Int(len);
Log.Int(p[0]); Log.Int(p[1]); Log.Int(p[2]); Log.Int(p[3]);
Log.Ln
END;
RETURN WinApi.S_OK
END ReadAt;
PROCEDURE (this: ILockBytes) WriteAt (offset: LONGINT; buf: WinApi.PtrVoid;
len: INTEGER; OUT [nil] written: INTEGER): COM.RESULT;
TYPE P = POINTER TO ARRAY [untagged] 2000000000 OF BYTE;
VAR res: COM.RESULT; p: P;
BEGIN
p := SYSTEM.VAL(P, buf);
IF debug THEN
Log.String("write@"); Log.Int(SHORT(offset)); Log.Int(len);
Log.Int(p[0]); Log.Int(p[1]); Log.Int(p[2]); Log.Int(p[3]);
Log.Ln
END;
IF this.wr # NIL THEN
IF len > 0 THEN
IF offset > this.len THEN res := this.SetSize(offset) END;
this.wr.SetPos(SHORT(this.org + offset));
this.wr.WriteBytes(p^, 0, len);
IF offset + len > this.len THEN this.len := SHORT(offset + len) END
ELSE len := 0
END;
IF VALID(written) THEN written := len END;
IF debug THEN Log.String("written"); Log.Ln END;
RETURN WinApi.S_OK
ELSE
IF VALID(written) THEN written := 0 END;
RETURN WinApi.STG_E_ACCESSDENIED
END
END WriteAt;
PROCEDURE (this: ILockBytes) Flush (): COM.RESULT;
TYPE A4 = ARRAY 4 OF BYTE;
BEGIN
IF debug THEN Log.String("flush"); Log.Ln END;
IF this.wr # NIL THEN
this.wr.SetPos(this.org - 4);
this.wr.WriteBytes(SYSTEM.VAL(A4, this.len), 0, 4);
this.file.Flush();
this.wr.SetPos(this.org + this.len)
ELSE
this.rd.SetPos(this.org + this.len)
END;
IF debug THEN Log.String("flushed"); Log.Ln END;
RETURN WinApi.S_OK
END Flush;
PROCEDURE (this: ILockBytes) SetSize (size: LONGINT): COM.RESULT;
VAR len: INTEGER; buf: ARRAY 256 OF BYTE;
BEGIN
IF debug THEN Log.String("set size"); Log.Int(SHORT(size)); Log.Ln END;
IF this.wr # NIL THEN
IF size > this.len THEN (* enlarge file *)
this.wr.SetPos(this.org + this.len);
len := SHORT(size - this.len);
WHILE len > 256 DO this.wr.WriteBytes(buf, 0, 256); DEC(len, 256) END;
this.wr.WriteBytes(buf, 0, len);
END;
this.len := SHORT(size);
RETURN WinApi.S_OK
ELSE RETURN WinApi.STG_E_ACCESSDENIED
END
END SetSize;
PROCEDURE (this: ILockBytes) LockRegion (offset, len: LONGINT; lockType: SET): COM.RESULT;
BEGIN
RETURN WinApi.STG_E_INVALIDFUNCTION
END LockRegion;
PROCEDURE (this: ILockBytes) UnlockRegion (offset, len: LONGINT; lockType: SET): COM.RESULT;
BEGIN
RETURN WinApi.STG_E_INVALIDFUNCTION
END UnlockRegion;
PROCEDURE (this: ILockBytes) Stat (OUT statStg: WinOle.STATSTG; statflag: INTEGER): COM.RESULT;
BEGIN
IF debug THEN Log.String("stat"); Log.Ln END;
statStg.pwcsName := NIL;
statStg.type := WinOle.STGTY_LOCKBYTES;
statStg.cbSize := this.len;
statStg.mtime.dwLowDateTime := 0;
statStg.mtime.dwHighDateTime := 0;
statStg.ctime.dwLowDateTime := 0;
statStg.ctime.dwHighDateTime := 0;
statStg.atime.dwLowDateTime := 0;
statStg.atime.dwHighDateTime := 0;
statStg.grfMode := WinOle.STGM_DIRECT + WinOle.STGM_CREATE + WinOle.STGM_SHARE_EXCLUSIVE;
IF this.wr # NIL THEN statStg.grfMode := statStg.grfMode + WinOle.STGM_READWRITE
ELSE statStg.grfMode := statStg.grfMode + WinOle.STGM_READ
END;
statStg.grfLocksSupported := {};
statStg.clsid := WinOle.GUID_NULL;
statStg.grfStateBits := {};
statStg.dwStgFmt := WinOle.STGFMT_FILE;
IF debug THEN Log.String("stat end"); Log.Ln END;
RETURN WinApi.S_OK
END Stat;
(* ---------- StreamReader ---------- *)
PROCEDURE (r: StreamReader) Base (): Files.File;
BEGIN
RETURN r.base
END Base;
PROCEDURE (r: StreamReader) Pos (): INTEGER;
BEGIN
RETURN r.pos
END Pos;
PROCEDURE (r: StreamReader) SetPos (pos: INTEGER);
VAR res: COM.RESULT;
BEGIN
ASSERT(pos >= 0, 22); ASSERT(pos <= r.base.len, 21);
r.pos := pos; r.eof := FALSE
END SetPos;
PROCEDURE (r: StreamReader) ReadByte (OUT x: BYTE);
VAR res: COM.RESULT;
BEGIN
IF r.pos < r.base.len THEN
IF r.pos # r.base.pos THEN
res := r.base.stream.Seek(r.base.org + r.pos, WinOle.STREAM_SEEK_SET, NIL);
r.base.pos := r.pos
END;
res := r.base.stream.Read(SYSTEM.ADR(x), 1, NIL);
INC(r.pos); INC(r.base.pos);
ELSE
x := 0; r.eof := TRUE
END
END ReadByte;
PROCEDURE (r: StreamReader) ReadBytes (VAR x: ARRAY OF BYTE; beg, len: INTEGER);
VAR res: COM.RESULT;
BEGIN
ASSERT(beg >= 0, 21);
IF len > 0 THEN
ASSERT(beg + len <= LEN(x), 23);
IF r.pos + len <= r.base.len THEN
IF r.pos # r.base.pos THEN
res := r.base.stream.Seek(r.base.org + r.pos, WinOle.STREAM_SEEK_SET, NIL);
r.base.pos := r.pos
END;
res := r.base.stream.Read(SYSTEM.ADR(x[beg]), len, NIL);
INC(r.pos, len); INC(r.base.pos, len)
ELSE
r.eof := TRUE
END
ELSE ASSERT(len = 0, 22)
END
END ReadBytes;
(* ---------- StreamWriter ---------- *)
PROCEDURE (w: StreamWriter) Base (): Files.File;
BEGIN
RETURN w.base
END Base;
PROCEDURE (w: StreamWriter) Pos (): INTEGER;
BEGIN
RETURN w.pos
END Pos;
PROCEDURE (w: StreamWriter) SetPos (pos: INTEGER);
VAR res: COM.RESULT;
BEGIN
ASSERT(pos >= 0, 22); ASSERT(pos <= w.base.len, 21);
w.pos := pos
END SetPos;
PROCEDURE (w: StreamWriter) WriteByte (x: BYTE);
VAR res: COM.RESULT;
BEGIN
IF w.pos # w.base.pos THEN
res := w.base.stream.Seek(w.base.org + w.pos, WinOle.STREAM_SEEK_SET, NIL);
w.base.pos := w.pos
END;
res := w.base.stream.Write(SYSTEM.ADR(x), 1, NIL);
INC(w.pos); INC(w.base.pos);
IF w.pos > w.base.len THEN w.base.len := w.pos END
END WriteByte;
PROCEDURE (w: StreamWriter) WriteBytes (IN x: ARRAY OF BYTE; beg, len: INTEGER);
VAR res: COM.RESULT;
BEGIN
ASSERT(beg >= 0, 21);
IF len > 0 THEN
ASSERT(beg + len <= LEN(x), 23);
IF w.pos # w.base.pos THEN
res := w.base.stream.Seek(w.base.org + w.pos, WinOle.STREAM_SEEK_SET, NIL);
w.base.pos := w.pos
END;
res := w.base.stream.Write(SYSTEM.ADR(x[beg]), len, NIL);
INC(w.pos, len); INC(w.base.pos, len);
IF w.pos > w.base.len THEN w.base.len := w.pos END
ELSE ASSERT(len = 0, 22)
END
END WriteBytes;
(* ---------- StreamFile ---------- *)
PROCEDURE (f: StreamFile) Length (): INTEGER;
BEGIN
RETURN f.len
END Length;
PROCEDURE (f: StreamFile) NewReader (old: Files.Reader): Files.Reader;
VAR r: StreamReader;
BEGIN
ASSERT(f.stream # NIL, 20);
NEW(r); r.base := f;
r.pos := 0; r.eof := FALSE;
RETURN r
END NewReader;
PROCEDURE (f: StreamFile) NewWriter (old: Files.Writer): Files.Writer;
VAR w: StreamWriter;
BEGIN
ASSERT(f.stream # NIL, 20);
NEW(w); w.base := f;
w.pos := f.len;
RETURN w
END NewWriter;
PROCEDURE (f: StreamFile) Flush;
VAR res: COM.RESULT;
BEGIN
ASSERT(f.stream # NIL, 20);
res := f.stream.Commit(WinOle.STGC_DEFAULT)
END Flush;
PROCEDURE (f: StreamFile) Close;
BEGIN
IF f.stream # NIL THEN
f.Flush;
f.stream := NIL;
END
END Close;
PROCEDURE (f: StreamFile) Register (name: Files.Name; type: Files.Type; ask: BOOLEAN; OUT res: INTEGER);
BEGIN
res := 10
END Register;
(* ---------- file creation ---------- *)
PROCEDURE NewStreamFile* (stream: WinOle.IStream): Files.File;
VAR f: StreamFile; res: COM.RESULT; y: LONGINT;
BEGIN
NEW(f);
f.stream := stream;
res := stream.Seek(0, WinOle.STREAM_SEEK_CUR, f.org);
res := stream.Seek(0, WinOle.STREAM_SEEK_END, y);
DEC(y, f.org);
IF y > MAX(INTEGER) THEN y := MAX(INTEGER) END;
f.len := SHORT(y);
res := stream.Seek(f.org, WinOle.STREAM_SEEK_SET, NIL);
f.pos := 0;
RETURN f
END NewStreamFile;
PROCEDURE NewWriteILockBytes* (wr: Files.Writer): WinOle.ILockBytes;
VAR new: ILockBytes;
BEGIN
IF debug THEN Log.String("new write"); Log.Ln END;
NEW(new);
IF new = NIL THEN RETURN NIL END;
wr.WriteByte(0); wr.WriteByte(0); wr.WriteByte(0); wr.WriteByte(0); (* length *)
new.len := 0;
new.org := wr.Pos();
new.file := wr.Base();
new.rd := new.file.NewReader(NIL);
new.wr := wr;
RETURN new
END NewWriteILockBytes;
PROCEDURE NewReadILockBytes* (rd: Files.Reader): WinOle.ILockBytes;
TYPE A4 = ARRAY 4 OF BYTE;
VAR new: ILockBytes;
BEGIN
IF debug THEN Log.String("new read"); Log.Ln END;
NEW(new);
IF new = NIL THEN RETURN NIL END;
rd.ReadBytes(SYSTEM.VAL(A4, new.len), 0, 4);
new.org := rd.Pos();
new.file := rd.Base();
new.rd := rd;
new.wr := NIL;
RETURN new
END NewReadILockBytes;
(* stream import/export *)
PROCEDURE GenStreamMedium (stm: WinOle.IStream; unk: COM.IUnknown; VAR sm: WinOle.STGMEDIUM);
BEGIN
sm.tymed := WinOle.TYMED_ISTREAM;
sm.u.pstm := stm;
sm.pUnkForRelease := unk
END GenStreamMedium;
PROCEDURE MediumStream (VAR sm: WinOle.STGMEDIUM): WinOle.IStream;
BEGIN
ASSERT(sm.tymed = WinOle.TYMED_ISTREAM, 20);
RETURN SYSTEM.VAL(WinOle.IStream, sm.u.pstm)
END MediumStream;
PROCEDURE ExportToStream* (stream: WinOle.IStream; v: Views.View; w, h: INTEGER; isSingle: BOOLEAN);
VAR f: Files.File; wr: Stores.Writer; res: COM.RESULT;
BEGIN
res := stream.Seek(0, WinOle.STREAM_SEEK_SET, NIL);
f := NewStreamFile(stream);
wr.ConnectTo(f);
wr.SetPos(0);
wr.WriteInt(obfTag);
wr.WriteInt(0);
wr.WriteInt(w);
wr.WriteInt(h);
IF isSingle THEN wr.WriteSChar(1X) ELSE wr.WriteSChar(0X) END;
wr.WriteStore(v);
f.Close
END ExportToStream;
PROCEDURE ExportOberon* (
v: Views.View; w, h, x, y: INTEGER; isSingle: BOOLEAN; VAR med: WinOle.STGMEDIUM
);
VAR stream: WinOle.IStream; res: COM.RESULT;
BEGIN
IF med.tymed = WinOle.TYMED_ISTREAM THEN (* use old stream *)
stream := MediumStream(med)
ELSE (* create new temporary stream *)
res := WinOle.CreateStreamOnHGlobal(0, 1, stream);
GenStreamMedium(stream, NIL, med)
END;
ExportToStream(stream, v, w, h, isSingle)
END ExportOberon;
PROCEDURE ImportFromStream* (stream: WinOle.IStream; VAR v: Views.View;
VAR w, h: INTEGER; VAR isSingle: BOOLEAN);
VAR f: Files.File; r: Stores.Reader; s: Stores.Store; tag, version, res: COM.RESULT; ch: SHORTCHAR;
BEGIN
v := NIL;
res := stream.Seek(0, WinOle.STREAM_SEEK_SET, NIL);
f := NewStreamFile(stream);
r.ConnectTo(f); r.SetPos(0);
r.ReadInt(tag);
IF tag = obfTag THEN
r.ReadInt(version);
r.ReadInt(w);
r.ReadInt(h);
r.ReadSChar(ch); isSingle := ch # 0X;
r.ReadStore(s);
v := s(Views.View)
END
END ImportFromStream;
PROCEDURE ImportOberon* (VAR med: WinOle.STGMEDIUM; VAR v: Views.View;
VAR w, h: INTEGER; VAR isSingle: BOOLEAN);
VAR stream: WinOle.IStream;
BEGIN
stream := MediumStream(med);
ImportFromStream(stream, v, w, h, isSingle)
END ImportOberon;
END OleStorage.
OleStorage?
DevDecoder.Decode OleStorage
| Ole/Mod/Storage.odc |
MODULE OleViews;
(**
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 COM, WinApi, WinOle, WinOleAut, CtlT, Properties, Views, Containers, Windows, OleServer, OleClient;
(* client wrappers *)
PROCEDURE NewObjectView* (name: ARRAY OF CHAR): Views.View;
VAR clsid: COM.GUID; res: COM.RESULT;
BEGIN
IF name[0] = "{" THEN res := WinOle.CLSIDFromString(name, clsid)
ELSE res := WinOle.CLSIDFromProgID(name, clsid)
END;
IF res = WinApi.S_OK THEN RETURN OleClient.NewView(clsid)
ELSE RETURN NIL
END
END NewObjectView;
(*
PROCEDURE NewObjectViewFrom* (obj: CtlT.Object): Views.View;
VAR disp: WinOleAut.IDispatch;
BEGIN
disp := CtlT.Disp(obj);
RETURN OleClient.NewViewFrom(disp)
END NewObjectViewFrom;
*)
PROCEDURE NewObjectViewFromClipboard* (): Views.View;
BEGIN
RETURN OleClient.NewViewFromCB()
END NewObjectViewFromClipboard;
PROCEDURE IsObjectView* (v: Views.View): BOOLEAN;
VAR unk: COM.IUnknown;
BEGIN
unk := OleClient.IUnknown(v);
RETURN unk # NIL
END IsObjectView;
PROCEDURE IsAutoView* (v: Views.View): BOOLEAN;
VAR unk: COM.IUnknown; disp: WinOleAut.IDispatch; res: COM.RESULT;
BEGIN
unk := OleClient.IUnknown(v);
IF unk # NIL THEN
res := unk.QueryInterface(COM.ID(disp), disp);
RETURN res = WinApi.S_OK
ELSE RETURN FALSE
END
END IsAutoView;
PROCEDURE OleObject* (v: Views.View): CtlT.Interface;
VAR unk: COM.IUnknown;
BEGIN
unk := OleClient.IUnknown(v);
IF unk # NIL THEN RETURN CtlT.Intfce(unk)
ELSE RETURN NIL
END
END OleObject;
PROCEDURE AutoObject* (v: Views.View): CtlT.Object;
VAR unk: COM.IUnknown; disp: WinOleAut.IDispatch; res: COM.RESULT;
BEGIN
unk := OleClient.IUnknown(v);
IF unk # NIL THEN
res := unk.QueryInterface(COM.ID(disp), disp);
IF res = WinApi.S_OK THEN RETURN CtlT.Obj(disp) END
END;
RETURN NIL
END AutoObject;
PROCEDURE Deposit* (name: ARRAY OF CHAR);
VAR v: Views.View;
BEGIN
v := NewObjectView(name);
IF v # NIL THEN Views.Deposit(v) END
END Deposit;
(*
PROCEDURE Activate*;
VAR v, dv: Views.View; msg: Properties.DoVerbMsg; w: Windows.Window; f: Views.Frame;
BEGIN
v := Containers.FocusSingleton();
IF v # NIL THEN
w := Windows.dir.Focus(TRUE);
IF w # NIL THEN
dv := w.doc.ThisView();
f := Views.ThisFrame(w.frame, dv);
msg.frame := Views.ThisFrame(f, v);
msg.verb := WinOle.OLEIVERB_SHOW;
Views.HandlePropMsg(v, msg)
END
END
END Activate;
*)
PROCEDURE Connect* (sink: CtlT.OutObject; source: Views.View);
VAR iid: COM.GUID; disp: WinOleAut.IDispatch;
BEGIN
sink.GetIID(iid); disp := CtlT.Disp(sink);
OleClient.Connect(source, iid, disp)
END Connect;
(*
(* server wrappers *)
PROCEDURE NewViewObject* (v: Views.View): CtlT.Interface;
BEGIN
ASSERT(v.context = NIL, 20);
END NewViewObject;
PROCEDURE IsViewObject* (i: CtlT.Interface): BOOLEAN;
BEGIN
END IsViewObject;
PROCEDURE View* (i: CtlT.Interface): Views.View;
BEGIN
END View;
*)
END OleViews.
| Ole/Mod/Views.odc |
MODULE OleWindows;
IMPORT Views, Controllers, Windows, Documents, WinApi;
TYPE
Window* = POINTER TO ABSTRACT RECORD
wnd-: WinApi.HANDLE;
doc-: Documents.Document;
win-: Windows.Window;
back: Backend;
END;
Backend* = POINTER TO ABSTRACT RECORD END;
Hook* = POINTER TO ABSTRACT RECORD END;
Directory* = POINTER TO ABSTRACT RECORD END;
PROCEDURE ActivateWindow* (w: Window; on: BOOLEAN);
(* <= WinWindows.ActivateWindow *)
(* how is it different from Windows.Directory.Select? *)
END ActivateWindow;
PROCEDURE (w: Window) DoClose- (do: PROCEDURE (w: Window)), NEW, ABSTRACT;
(** To be extended in OleServer *)
PROCEDURE (b: Backend) DoClose-, NEW, ABSTRACT;
(** To be extended by a backend (MDI or tiled) *)
PROCEDURE DoClose (w: Window); BEGIN w.back.DoClose END DoClose;
PROCEDURE Close* (w: Window);
BEGIN ASSERT(w # NIL, 20);
w.DoClose(DoClose)
END Close;
PROCEDURE (w: Window) ForwardCtrlMsg* (VAR msg: Controllers.Message), NEW, ABSTRACT;
PROCEDURE (w: Window) BroadcastViewMsg* (VAR msg: Views.Message), NEW, ABSTRACT;
PROCEDURE Open* (v: Views.View; OUT w: Window; inPlace: BOOLEAN);
BEGIN HALT(126)
END Open;
PROCEDURE Unit* (): INTEGER; BEGIN HALT(126); RETURN 0 END Unit;
END OleWindows. | Ole/Mod/Windows.odc |
SqlBrowser
See developermanual.
| Sql/Docu/Browser.odc |
SqlControls
See developermanual.
| Sql/Docu/Controls.odc |
SqlDB
DEFINITION SqlDB;
CONST
names = -1;
converted = 1; truncated = 2; overflow = 3; incompatible = 4; noData = 5;
sync = FALSE; async = TRUE;
hideErrors = FALSE; showErrors = TRUE;
TYPE
String = POINTER TO ARRAY OF CHAR;
Row = RECORD
fields: POINTER TO ARRAY OF String
END;
Blob = RECORD
len: INTEGER;
data: POINTER TO ARRAY OF BYTE
END;
Command = PROCEDURE (par: ANYPTR);
TableCommand = PROCEDURE (t: Table; par: ANYPTR);
Database = POINTER TO ABSTRACT RECORD
res: INTEGER;
async: BOOLEAN;
showErrors: BOOLEAN;
(d: Database) Exec (statement: ARRAY OF CHAR), NEW, ABSTRACT;
(d: Database) NewTable (): Table, NEW, ABSTRACT;
(d: Database) Call (command: Command; par: ANYPTR), NEW, ABSTRACT;
(d: Database) Commit, NEW, ABSTRACT;
(d: Database) Rollback, NEW, ABSTRACT
END;
Table = POINTER TO ABSTRACT RECORD
base-: Database;
rows, columns: INTEGER;
res: INTEGER;
strictNotify: BOOLEAN;
(t: Table) InitBase (base: Database), NEW;
(t: Table) Exec (statement: ARRAY OF CHAR), NEW, ABSTRACT;
(t: Table) Available (): BOOLEAN, NEW, ABSTRACT;
(t: Table) Read (row: INTEGER; VAR data: ANYREC), NEW, ABSTRACT;
(t: Table) Clear, NEW, ABSTRACT;
(t: Table) Call (command: TableCommand; par: ANYPTR), NEW, ABSTRACT
END;
VAR debug: BOOLEAN;
PROCEDURE OpenDatabase (protocol, id, password, datasource: ARRAY OF CHAR;
async, showErr: BOOLEAN; OUT d: Database; OUT res: INTEGER);
END SqlDB.
Module SqlDB is the application programming interface for applications using relational databases supporting the SQL language.
names
The constant names can be used as the row parameter in a table's Read method. This is legal if the passed interactor is of type Row. The interactor is filled with the column names of the actual table.
converted
Possible value of a table's res field after a Read operation. Indicates that some database values had to be converted to match the type of the corresponding interactor field.
truncated
Possible value of a table's res field after a Read operation. Indicates that some string values had to be truncated to fit in the corresponding interactor field.
overflow
Possible value of a table's res field after a Read operation. Indicates that some numeric values could not be read because they where too large to fit in the corresponding interactor field.
incompatible
Possible value of a table's res field after a Read operation. Indicates that some database values could not be read because of a type incompatibility
noData
Possible value of a table's res field after a Read operation. Indicates that the row parameter pointed to a non-existing row.
sync
Possible value for the async parameter of OpenDatabase.
async
Possible value for the async parameter of OpenDatabase.
hideErrors
Possible value for the showErr parameter of OpenDatabase, and of the showErrors field of a database object.
showErrors
Possible value for the showErr parameter of OpenDatabase, and of the showErrors field of a database object.
TYPE Row
A Row variable contains a textual representation of a single row of a database. An interactor of this type can be used as parameter of the Table.Read operation when a textual representation of an unknown table is to be retrieved.
fields: POINTER TO ARRAY OF String
The actual fields of the table row. The array is allocated by the Table.Read operation. fields is allocated by SqlDB if it is NIL or the length is not correct, otherwise the existing array is reused. The same holds for the string pointers in fields, except that a string is not reallocated if the new value fits into the old string.
TYPE Blob
Used for the representation of data of any kind and size ("binary large object").
len: INTEGER len >= 0
The length of the data in bytes.
data: POINTER TO ARRAY OF BYTE len > 0 => data # NIL
The binary data stored as an array of character. There is no special termination symbol in the array.
TYPE Par
Basetype for extensible parameter lists.
TYPE Command
Procedure type with extensible parameter list, used in Database.Call.
TYPE TableCommand
Procedure type with table argument and extensible parameter list, used in Table.Call.
TYPE Database
ABSTRACT
A Database variable represents an SQL database.
res: INTEGER
Result value; valid after opening the database, and after each call to Database.Exec or Database.NewTable.
async: BOOLEAN
Set from the async parameter of OpenDatabase. async = TRUE means asynchronous operation is allowed.
showErrors: BOOLEAN
Can be set to enforce the database driver to display verbose error messages if an SQL statement is incorrect.
PROCEDURE (d: Database) Exec (statement: ARRAY OF CHAR)
NEW, ABSTRACT
Execute the SQL statement passed as parameter. It must not be a table-returning statement.
If d has been opened in async mode, the evaluation of statement is only started; it will be completed asynchronously.
The following portable error codes may be returned in res:
5 outOfTables
6 notExecutable
9 tooManyBlobs
Warning: don't use the SQL transaction statements (commit / abort), since they may interfere with SqlDB. Instead, call db.Commit or db.Abort.
Pre
statement # "" 20
statement is not table-returning 21 (* may be delayed *)
Post
res denotes error value (0 if no error occurred)
PROCEDURE (d: Database) NewTable (): Table
NEW, ABSTRACT
Allocate a new table object. A table represents the result table of the most recently executed SQL statement on it.
Post
result # NIL
d.res = 0
result.base = d
result.rows = 0
result.columns = 0
result.res = 0
result.strictNotify = FALSE
result = NIL
d.res # 0
PROCEDURE (d: Database) Call (command: Command; par: Par);
NEW, ABSTRACT
The procedure command(par) is executed. par may be NIL. Inside command no table based operations (Table.Read, Table.Exec, Table.Clear, or Table.Call) may be invoked on an existing table. Operations on tables allocated (with Database.NewTable) inside the command are legal.
This procedure is useful in asynchronously executing statements.
Pre
command # NIL 20
PROCEDURE (d: Database) Commit
NEW, ABSTRACT
Commits the currently executing transaction. Note that a transaction need not be started explicitly.
Do not use the database's SQL transaction commands directly.
PROCEDURE (d: Database) Rollback
NEW, ABSTRACT
Aborts the currently executing transaction. Note that a transaction need not be started explicitly.
Do not use the database's SQL transaction commands directly.
TYPE Table
ABSTRACT
A table represents the result of an SQL query, typically of a SELECT statement. The result table is a snapshot, i.e., retains the state which was valid when the query has been performed.
base-: Database base # NIL
The database to which the table belongs.
rows: INTEGER rows >= 0
The number of rows that the most recent query returned. If the actual database driver cannot return the number of rows in a query, rows is set to MAX(INTEGER).
columns: INTEGER columns >= 0
The number of columns that the most recent query returned.
columns = 0 means no table was returned.
res: INTEGER
The result value of the most recent query (0 if no error).
strictNotify: BOOLEAN
After one or several SQL queries have been performed on the table and BlackBox is idle again, a Dialog.Update is performed automatically by an action (-> Services). This is normally the desired behavior. If the result state after each query should be reflected in controls bound to the table's interactor, strictNotify should be set. This may be desired for long-running commands, so that the user sees progress while the command is running.
PROCEDURE (t: Table) InitBase (base: Database)
NEW
Initialize the table's base pointer.
InitBase is called internally.
Pre
base # NIL 20
t.base = NIL OR t.base = base 21
Post
t.base = base
PROCEDURE (t: Table) Exec (statement: ARRAY OF CHAR)
NEW, ABSTRACT
Execute the SQL statement passed as parameter. It must be a row-returning statement. Exec first performs t.Clear in order to flush the old result table, then executes the query.
If t.base has been opened in async mode, the evaluation of statement is only started and will be completed asynchronously.
The following portable error codes may be returned in res:
5 outOfTables
6 notExecutable
9 tooManyBlobs
Pre
statement # "" 20
t is legal table in enclosing command 21
Post
res denotes error value (0 if no error occurred).
PROCEDURE (t: Table) Available (): BOOLEAN;
NEW, ABSTRACT
Tells whether Read can execute immediately. This procedure is rarely used. It should be used before a Read is performed, if it is not guaranteed that the previous Exec has already returned a result. This may only happen if Exec is performed asynchronously. Note that Available() only guarantees that a result table has become available, but this table may well be empty (columns = 0 and rows = 0).
PROCEDURE (t: Table) Read (row: INTEGER; VAR data: ANYREC)
NEW, ABSTRACT
Reads the row'th row of the result table into the interactor data.
The generic data type Row which consists of an open array of strings can be used to read a row of data from an arbitrary table. All table values are converted to a string representation in this case. Otherwise the fields of the data record must be of one of the following types:
BYTE, SHORTINT, INTEGER, LONGINT, SHORTREAL, REAL, BOOLEAN, ARRAY n OF CHAR; POINTER TO ARRAY OF CHAR, Dialog.Currency, Dialog.List, Dialog.Combo, Dates.Date, Dates.Time, or SqlDB.Blob. Other array and record types are handled recursively. Pointers are dereferenced, and the bound structures are handled recursively. Pointers must not be NIL with the exception of POINTER TO ARRAY OF CHAR. If such a pointer is NIL or the bound array is too small to receive the corresponding string, a new array of suitable length is allocated automatically.
Four levels of complications can arise during the read:
• A value has to be converted from one data type to another. Conversions from any type to strings (ARRAY n OF CHAR or POINTER TO ARRAY OF CHAR) are always supported. Other conversions are driver-dependent.
• A string needs to be truncated because the destination array is too small.
• A numeric value is too large to be stored in the destination (overflow).
• A value cannot be assigned because its type is incompatible with the corresponding field. The field is cleared in such a situation.
After the call, t.res contains the most serious event (in the order converted, truncated, overflow, incompatible) that happened during the reading of all columns.
The column names of the table can be read into a variable of type Row, using the special value names for the row parameter.
It is permissible to read past the end of the table (row >= t.rows). The whole interactor is cleared in this case and t.res is set to noData.
Pre
t.columns > 0 20; (* may be delayed *)
row >= 0 OR row = names & data IS Row 21
data contains legal data types 22 (* may be delayed *)
data contains no NIL pointers 23 (* may be delayed *)
t.base.async => data is global variable 24
t is legal table in enclosing command 25
Post
t.res IN {0, converted, truncated, overflow, incompatible, noData}
PROCEDURE (t: Table) Clear
NEW, ABSTRACT
Releases the resources needed to represent the most recently created result table of t.
Pre
t is legal table in enclosing command 20
Post
t.rows = 0
t.columns = 0
t.res = 0
PROCEDURE (t: Table) Call (command: TableCommand; par: Par)
NEW, ABSTRACT
The procedure command(t, par) is executed. par may be NIL. Inside command no table based operations (Table.Read, Table.Exec, Table.Clear, or Table.Call) may be invoked on a preexisting table different from t. Operations on tables allocated (with Database.NewTable) inside the command are legal.
This procedure is useful for asynchronously executing commands.
Pre
command # NIL 20
t is legal table in enclosing command 21
VAR debug: BOOLEAN
Used internally. (Shows a protocol of what is happening during the execution of SqlDB commands.)
PROCEDURE OpenDatabase (protocol, id, password, datasource: ARRAY OF CHAR;
async, showErr: BOOLEAN; OUT d: Database; OUT res: INTEGER)
Open the database specified by the parameters. protocol is the name of the module which contains the database driver, e.g., "SqlOdbc" or "SqlOdbc3". Note that these names are case sensitive. id is a driver-specific string which denotes the connection information for the network in use, or similar protocol-specific information. password is the password used to log into the DBMS. It may be empty; in this case the user may be prompted for the password, depending on the driver. datasource specifies the database to be opened. It should be a unique name for the particular protocol.
If the database described by protocol and datasource is already open in the same BlackBox environment, the same database connection may be used, without considering the password again.
Consult the driver documentation for further information on the parameters to be passed.
If async is true, the returned database object is allowed to behave asynchronously.
If showErr is true, the returned database displays verbose error messages when incorrect SQL statements are detected.
The following portable error codes may be returned in res:
1 noDriverMod
2 noDriverProc
3 wrongDriverType
4 connectionsExceeded
7 cannotOpenDB
8 wrongIdentification
Pre
protocol # "" 20
Post
res = 0
database was correctly opened
d # NIL
d.async = async
d.showErrors = showErr
res # 0
database couldn't be opened
| Sql/Docu/DB.odc |
Sql Subsystem
Developer Manual
Contents
Introduction
Overview
Databases,tables,andinteractors
InterpretedembeddedSQL
TypeRow
SqlBrowser
Blobs
Asynchronousoperation
SqlDrivers
ODBCdriver
SqlDB
ClearingDatabaseandTablepointers
Displayingtables
Designrules
Example
Introduction
One of the most important applications of personal computers is as database frontends, i.e., as user interfaces to a database management system (DBMS). For small applications, the database resides on the same computer as the frontend, thus only one single user can access the database at any one time. For more demanding applications, the database is moved to a central server, to which several client PCs are connected, e.g. via a local area network. A client provides a graphical user interface and runs the application software; the server performs data storage. Typically, several clients may access the same database concurrently.
Today, the most important DBMS systems are based on a relational data model and use the SQL language (Structured Query Language) as the means to define, retrieve, and manipulate data.
The Sql subsystem for BlackBox provides a simple, portable, extensible, and integrated access mechanism to SQL databases. It is extensible, i.e., different database implementations can be interfaced through suitable driver modules. Today, there exists one driver module: a generic one that uses Microsoft's ODBC (Open Database Connectivity) standard. The ODBC driver comes standard with BlackBox (SqlOdbc and SqlOdbc3, respectively).
It is assumed that the reader knows about database design, SQL, and BlackBox; in particular the latter's Form subsystem, controls, and module Dialog.
Overview
The following goals have been pursued in the design of the Sql subsystem:
Simplicity
Existing interfaces to SQL are often very complicated to use. Sql provides an interface that is easier to learn and to use than other interfaces with a similar level of flexibility. The central programming interface (module SqlDB) only exports two major and a few minor data types. The major datatypes are the interface types SqlDB.Database and SqlDB.Table. They provide object-oriented abstractions for SQL databases and SQL result tables, respectively. Elements of a result table can be read into Component Pascal records, i.e., into objects that represent one single row of a table.
Full access to SQL
It has not been attempted to hide SQL. SQL is too powerful to be completely hidden behind "magic" database-aware controls, for example. Sql is oriented towards the professional developer, it is not attempted to provide "end-user" tools.
Integration
Often, SQL statements need to be constructed at run-time. In particular, actual parameters must be spliced into statements which contain symbolic place holders as formal parameters. In Sql, this need not be done manually by the programmer. Instead, BlackBox's built-in metaprogramming facilities are used to do it automatically. In fact, a dynamically interpreted kind of "embedded" SQL is realized, where Component Pascal variable names can be used directly in SQL statements.
Extensibility
Application programs use the SqlDB programming interface. This interface is implemented on top of a lower-level driver interface (SqlDrivers). This driver interface is defined in a component-oriented style, i.e., different driver implementations can be used without invalidating application programs. In fact, several different drivers could be used in the same application concurrently.
Figure a Simple application interface, extensible driver interface
Separation of program logic and user interface
For clarity, maintainability, and maximum platform independence, user interface and program logic (the latter including the so-called "business logic") are separated as far as possible. A graphical user interface is treated as a merely cosmetic addition to the program, and can be modified without touching the core application's source code. In fact, a command button or a text entry field need not even be "database-aware" in order to invoke database operations or to represent database contents.
A program produces and consumes database contents via so-called interactor objects, i.e., Component Pascal records. Such record variables are used as sources and destinations of command parameters or result data.
Figure b Interactors as switchboards for application program, DBMS, and user interface
Framework-friendly, user-friendly
A framework depends on the cooperation of the objects that it is composed of. An object cannot be considered cooperative if it blocks the others or the user for a long time. You shouldn't have to wait several minutes until you can continue with your work, just because a remote server machine takes so long to complete a database transaction.
For this reason, SqlDB supports a non-blocking asynchronous programming style in addition to the traditional blocking style. The programmer can decide which style is more appropriate for the given application. Non-blocking operation is especially important if an application may access a server database. Server queries sometimes take much longer than local queries. Blocking operations may be appropriate for simple local queries, or for batch processes that require no user interaction.
The non-blocking programming style is more involved than the straight-forward blocking style. It uses object-oriented programming principles to avoid an even more intricate and hard-to-debug programming style based on so-called threads (i.e., preemptive multitasking).
Even an application which uses a blocking programming style is non-modal, meaning that several data query or entry masks (windows) can be open at the same time. This is in the general spirit of BlackBox, which avoids modal dialog boxes wherever feasible. Ultimately it is the user who benefits, by not being locked into a single task at any time.
For an overview over the files of Sql, see its Map text.
Databases, tables, and interactors
From a program's perspective, a database is represented by a SqlDB.Database object. As long as a database object is available, SQL commands can be executed. Execution may be local, or remote on a server.
The following declaration describes the SqlDB.Database type:
Database = POINTER TO ABSTRACT RECORD
res: INTEGER;
async: BOOLEAN;
showErrors: BOOLEAN;
(d: Database) Exec (statement: ARRAY OF CHAR), NEW, ABSTRACT;
(d: Database) Commit, NEW, ABSTRACT;
(d: Database) Abort, NEW, ABSTRACT;
(d: Database) Call (command: Command; par: ANYPTR), NEW, ABSTRACT;
(d: Database) NewTable (): Table, NEW, ABSTRACT
END;
Procedure Exec is used to execute SQL statements which don't return result tables; e.g., DELETE or INSERT statements, such as:
database.Exec("DELETE FROM Companies WHERE id = 5" )
Transactions are started automatically when the first modifying SQL command is executed. A transaction is terminated either by calling Commit or Abort.
Warning: don't use the database's SQL transaction statements, since they may interfere with Commit and Abort.
A database object is obtained by calling SqlDB.OpenDatabase:
PROCEDURE OpenDatabase (protocol, id, password,
datasource: ARRAY OF CHAR;
async: BOOLEAN;
OUT d: SqlDB.Database;
OUT res: INTEGER);
This procedure opens the database given by the pair (protocol, datasource). If that database is already open from a previous call to OpenDatabase, the same database connection may be used, without considering the id and password information again. The exact interpretation of the latter parameters depends on the database driver, whose name is given in protocol (e.g. SqlOdbc3).
If an application needs to fetch result tables from a database, typically generated by SELECT statements, it needs to provide table objects, which represent the returned result tables. The contents of a table is static, i.e., it represents a snapshot of the database contents at the time the statement is executed. Conceptually, a table is a local and independent copy of the database contents. Several tables can be used simultaneously.
A table object is obtained by calling its database object's NewTable procedure.
An SqlDB.Table is declared as
Table = POINTER TO ABSTRACT RECORD
base-: Database;
rows, columns, res: INTEGER;
strictNotify: BOOLEAN;
(t: Table) Exec (statement: ARRAY OF CHAR), NEW, ABSTRACT;
(t: Table) Available (): BOOLEAN, NEW, ABSTRACT;
(t: Table) Read (row: INTEGER; VAR data: ANYREC), NEW, ABSTRACT;
(t: Table) Clear, NEW, ABSTRACT;
(t: Table) Call (command: TableCommand; par: ANYPTR), NEW, ABSTRACT
END;
The pair (rows, columns) denotes the number of rows and columns of the most recently computed result table. A result table is generated by calling the table's Exec procedure. It may only be used with row-returning SQL statements, i.e., statements which return a (possibly empty) table. Typically, this is a SELECT statement such as
table.Exec("SELECT * FROM Companies WHERE id = 17)
Read can be used to read a row from the result table into an interactor (i.e. an exported record variable). The interactor can then be manipulated by the program or by its graphical user interface elements. For example, the following statement
table.Read(17, company);
reads the contents of row 17 of table into the variable company, which might be declared as
VAR
company: RECORD
id: INTEGER;
name, ceo: ARRAY 32 OF CHAR;
employees: INTEGER
END;
Note that the field table.rows cannot be computed by all database drivers, some may return MAX(INTEGER) instead. To loop over all rows of a result table, it is therefore better to avoid using table.rows in the loop termination condition. Instead, looping can be done while table.res # SqlDB.noData holds.
Record fields and rows of a result table are matched in the order that they are defined in the record or in the database, respectively (SQL doesn't define an order, but every actual database product does). Record fields to be matched must be exported. If there are non-exported record fields, they are simply ignored.
The following Component Pascal types are interpreted by SqlDB:
BOOLEAN
BYTE, SHORTINT, INTEGER, LONGINT
SHORTREAL, REAL
ARRAY OF CHAR
Dates.Date
Dates.Time
Dialog.Currency
Dialog.List
Dialog.Combo
SqlDB.Blob
How these types are mapped to SQL data types depends on the actual SQL database product and the Sql driver. The following example table applies to Microsoft's Sql Server product which is accessed via ODBC:
SQL Component Pascal
{bit, tinyint, smallint, integer, bigint} {BOOLEAN(1), BYTE, SHORTINT, INTEGER,
LONGINT, Dialog.List}
{real, float(p), double precision} {SHORTREAL, REAL}
{char(n)(2), varchar(n)(3), long varchar} {ARRAY OF CHAR, Dialog.Combo}
{decimal(p, s), numeric(p, s)} Dialog.Currency
{date, timestamp(4)} Dates.Date
{time, timestamp(4)} Dates.Time
{binary(n), varbinary(n), long varbinay) SqlDB.Blob
(1) 0 = FALSE, 1 = TRUE
(2) character string of fixed string-length n
(3) variable-length character string with a maximum string length n
(4) only the date or the time part is used, not both simultaneously
Note:
Values of any SQL data type can be read in a textual form, into an ARRAY OF CHAR.
SQL datetime values can be mapped either to Dates.Date or to Dates.Time, but not to both simultaneously.
Interpreted embedded SQL
Consider the following simple SQL statement:
SELECT * FROM Companies WHERE id = 249
It is easy to provide a programming interface which can execute this query, e.g., something like
table.Exec("SELECT * FROM Companies WHERE id = 249")
However, things get messy when the SQL statement should be parameterized with program variables, e.g.,
SELECT * FROM Companies WHERE id = searchId
where searchId is a global variable. Note that it would not be correct to call
table.Exec("SELECT * FROM Companies WHERE id = searchId")
since the DBMS has no idea that the application program has a variable called searchId.
What could be done is something like the following:
ConvertIntegerToString(searchId, str);
str := "SELECT * FROM Companies WHERE id = " + str;
table.Exec(str);
Some systems provide precompilers for so-called embedded SQL, where true statements of a programming language can be mixed with SQL statements, and these SQL statements may contain formal parameters. Syntactically, such formal parameters are preceeded by colons. In embedded SQL, the above example would look like this:
SELECT * FROM Companies WHERE id = :searchId
Embedded SQL has drawbacks in that the precompiler typically produces code for one particular combination of programming language/compiler and DBMS only. Precompilers are often static in that they prevent the dynamic composition of SQL strings. They slow down compilation because of the preprocessing they have to perform.
BlackBox uses a novel approach which combines the convenience of embedded SQL with the flexibility of explicit SQL programming interfaces ("call level interfaces"). For this purpose, it uses its metaprogramming facilities (i.e., run-time type information) to access global variables, as they occur in an SQL string.
For example, if there is a global and exported integer variable searchId in module Sample, the following SQL statement can be used:
"SELECT * FROM Companies WHERE id = :Sample.searchId"
SqlDB provides a procedure to execute such a string (SqlDB.Database.Exec, SqlDB.Table.Exec). These procedures replace all placeholders starting with a colon by the appropriate run-time values.
For additional convenience, whole record variables can be used in SQL strings. Their fields will be expanded suitably. For example, if there is a global and exported interactor company in module Sample with the fields id, name, ceo, employees then SqlDB will expand the following string
INSERT INTO Companies VALUES (:Sample.company)
into
INSERT INTO Companies VALUES (5, 'Macrosoft Corp.', 'Doors', 10000)
assuming that company.id = 5, company.name = "Macrosoft Corp.", company.ceo = "Doors" and company.employees = 10000.
Note: A colon does not trigger string substitution if a Windows path name follows the colon (this is useful e.g. when using MS Access), as in "SELECT * FROM C:\directory\databaseName.tableName".
Type Row
Normally, a table's Read procedure is performed on an interactor that contains one record field per result table column. This is convenient, since it provides automatic mapping between relational data and Component Pascal objects, i.e., an object-oriented front-end for SQL databases.
However, specialized tools such as database browsers don't know about the exact definition of the tables they will be accessing, and thus cannot define the necessary interactor types in advance. For those special cases, a more general dynamic mechanism is provided.
Instead of passing a normal interactor to Read, a variable of the special type SqlDB.Row is passed for this purpose. As a result, it will contain an array of pointers to strings. Each string contains the textual representation of one table column of the row read. If SqlDB.names is passed as row parameter, the strings will contain the names of the table columns, instead of values.
String = POINTER TO ARRAY OF CHAR;
Row = RECORD
fields: POINTER TO ARRAY OF String
END
SqlBrowser
Module SqlBrowser implements a database browsing utility. The user can interactively enter the protocol, id, password, and datasource parameters in a dialog box. A further text entry field allows to enter arbitrary SQL statements. Clicking on the "Execute" button or pressing Enter executes the query. If the database is not already open, it is opened automatically and remains open until the Browser dialog box is closed. If the statement returns a result table, it is displayed in its own window. For statements not returning a result, the message "statement executed" is displayed. In case of an error, a suitable error message appears.
The source of SqlBrowser is available. It demonstrates the use of SqlDB.Row to obtain data from tables that are not known at compile time, i.e., "dynamically".
Blobs
Binary Large Objects, or "blobs", allow to store unstructured data as large ARRAY OF BYTE variables. For example, large image bitmaps, serialized stores, or any other data may be stored in blobs. A blob is represented as a record
Blob = RECORD
len: INTEGER;
data: POINTER TO ARRAY OF BYTE
END
The field len indicates the number of valid bytes in data. Data is a pointer to the byte array. A Blob that is used in several Read operations reuses the same data array if possible, i.e. if the new data takes at most as many bytes as the previous result's data.
Asynchronous operation
There are different ways how a database can be accessed. In particular, access may occur to a local or to a remote server database. Access to remote databases may take considerably longer than access to local databases. If an operation takes long to complete, a user should not be blocked from other work during this time. This requires asynchronous operation, i.e., a query is started, but the user can immediately continue to work while the query is being completed.
Asynchronous operation is usually associated with preemptive multitasking, so-called threads. However, threads incur considerable additional complexity, often also for programmers who don't even use this feature. Sql uses a more light-weight approach to the problem. It allows to open a database in an asynchronous mode, such that any Exec statement only starts a query. The procedure immediately returns; i.e., it doesn't block the rest of the framework, and thus the user, from further work. When the result of the query is ready, the program is notified and can continue its work, using the results of the query.
Conceptually, the procedures Exec, Clear, Read and Call for an asynchronously accessed database are not executed right away when the procedure is called. Instead, the operations are queued in SqlDB, with one queue for the database and one queue for each table on this database. These queues are processed in the background. The results can be accessed when they are ready (indicated by Table.Available). Polling a table whether a pending Exec has returned a result may be done with a Services.Action. However, SqlDB provides a more convenient means, namely a table's or a database's Call procedure. The idea is that one or several asynchronous operations are started, and then a continuation procedure is set up by calling Call(ContinuationProc, someData). When the previous operations in the queue have terminated, the continuation procedure is called. In the continuation procedure, it can be assumed that the result of the most recent operation is now available. Thus, Call allows to chain several delayed operations, without having to deal explicitly with actions or with the synchronization problems of threads. Call must be used to break up a procedure into a chain of asynchronously executed procedures whenever the procedure needs to directly manipulate the results of an asynchronous query, i.e. before the next Read is performed. (Several successive Reads on the same result table need not be broken up by Call, since once the result table has become available, it remains available unless a new query is started.)
The following example shows a chain of procedures linked by Call statements:
PROCEDURE Last (t: SqlDB.Table; p: SqlDB.Par);
VAR i: INTEGER;
BEGIN (* t.Available() can be assumed *)
i := 0;
WHILE t.res # SqlDB.noData DO
t.Read(i, interactor); (* read i-th row into interactor *)
Out.Int(interactor.amount); Out.Ln; (* use interactor somehow *)
INC(i)
END;
t.Clear (* release table resources *)
END Last;
PROCEDURE Middle (t: SqlDB.Table; p: SqlDB.Par);
BEGIN (* t.Available() can be assumed *)
t.Read(0, interactor);
interactor.amount := interactor.amount + 30; (* do something with interactor *)
t.Exec("SELECT * FROM SomeTable WHERE amount > 20"); (* start next query *)
t.Call(Last, NIL) (* later continue with Last *)
END Middle;
PROCEDURE First (t: SqlDB.Table; p: SqlDB.Par);
BEGIN
t.Exec("SELECT * FROM SomeTable WHERE someId = 42"); (* start a query *)
t.Call(Middle, NIL) (* later continue with Middle *)
END First;
Note that the three procedures are given in reverse order, to avoid forward declarations. Parameter p can be used to pass arbitrary data along the chain of procedure invocations. Here it is sufficient to pass NIL.
This asynchronous mechanism is implemented by queueing database operations, with one queue per database object. This queue handles all Exec and Call calls (indepent of whether called via database or table object) in the strict order that they have been called originally. Only table.Read and table.Clear are optimized such that they may swap their places with operations that don't affect the corresponding table. As a result of this sequencing strategy, e.g., a database.Commit after a table.Exec always works correctly.
Sometimes it can be useful to have two database objects for the same database. For example, one may be opened synchronously, and the other asynchronously, when migrating from one to the other programming model. But this requires careful consideration of a possible interference between the two, since their individual chains of continuation procedures are not synchronized and may thus execute in any order, possibly resulting in different outcomes. Wherever possible, simultaneously opening to database objects on the same database should thus be avoided.
Obviously, asynchronous programming is more involved than synchronous operation. But if the database access is interactive and the database operation may involve a remote server, it is strongly suggested to consider the non-blocking asynchronous programming style. Blocking is considered "anti-social".
Even if a particular driver does not support true asynchronous operation, the asynchronous mode can still be used and will produce the same results, although possibly blocking sometimes. (SqlOdbc works this way.) But as soon as an asynchronous driver becomes available, the benefits will become apparent. For non-interactive applications, e.g., batch processing of a large database by night, there is no benefit in using asynchronous mode.
SqlDrivers
There is a template of a new Sql driver, which empty parts can be filled out to create a new driver for a database not yet supported by Sql, or to avoid the use of ODBC.
MODULE SqlObxDriv;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20151125, center #87, adding support for LONGINT in SqlDrivers.Table
- 20160907, center #129, command for generating a compile list for a set of subsystems
"
issues = "
- ...
"
**)
IMPORT Dates, Dialog, Services, SqlDrivers;
CONST
(* general error code *)
connectionsExceeded = 4;
outOfTables = 5;
notExecutable = 6;
cannotOpenDB = 7;
wrongIdentification = 8;
(* table read error codes *)
converted = 1;
truncated = 2;
overflow = 3;
incompatible = 4;
(* states *)
connecting = 1;
connected = 2;
executing = 3;
closed = 4;
TYPE
Table = POINTER TO RECORD (SqlDrivers.Table)
rows, columns: INTEGER;
(* additional resultset related data *)
END;
Driver = POINTER TO RECORD (SqlDrivers.Driver)
(* the state variable is not strictly necessary, it is used here to show the conceptual states *)
state: INTEGER; (* connecting, connected, executing, closed *)
(* additional database related data *)
END;
(* Driver *)
PROCEDURE (d: Driver) Ready (): BOOLEAN;
BEGIN
(* check for completion if asynchronous operation in progress *)
RETURN (d.state # closed) & <asynchronous operation terminated>
END Ready;
PROCEDURE (d: Driver) EndOpen (OUT res: INTEGER);
(* Pre: database connection was initiated by Open 20
d.Ready() 21 *)
BEGIN
ASSERT(d.state = connecting, 20);
ASSERT(d.Ready(), 21);
(* deliver result of asynchronous database connection request *)
(* return res = 0 if open is synchronous *)
d.state := connected; res := 0
END EndOpen;
PROCEDURE (d: Driver) BeginExec (IN statement: ARRAY OF CHAR; data: SqlDrivers.Blob;
async, showErr: BOOLEAN; OUT res: INTEGER);
(* asynchronous execution is optional, a driver may legally execute synchronously if async is TRUE *)
(* Pre: statement # "" 20
no other execution started 21 *)
(* Post: res = 0 <=> execution has started and will be completed later with EndExec
~async => d.Ready() *)
BEGIN
ASSERT(statement # "", 20);
ASSERT(d.state = connected, 21);
WHILE data # NIL DO
(* pass blob data in database specific way *)
data := data.next
END;
IF async THEN
(* try to start asynchronous execution of statement *)
ELSE
(* try to execute statement *)
END;
IF <successful> THEN
d.state := executing; res := 0
ELSE
res := notExecutable
END
END BeginExec;
PROCEDURE (d: Driver) EndExec (VAR t: SqlDrivers.Table; OUT rows, columns, res: INTEGER);
(* Pre: execution was started successfully with BeginExec 20
d.Ready() 21 *)
(* Post: res = 0 <=> (t # NIL) OR (rows = 0) & (columns = 0) *)
VAR h: Table;
BEGIN
ASSERT(d.state = executing, 20);
ASSERT(d.Ready(), 21);
d.state := connected;
IF <successful execution returning a result set> THEN
NEW(h); h.Init(d);
(* initialize table data *)
h.columns := <number of columns in result set>; (* h.columns > 0 *)
h.rows := <number of rows in result set>; (* h.rows >= 0 *)
t := h; columns := h.columns; rows := h.rows; res := 0
ELSIF <successful execution without result set> THEN
t := NIL; columns := 0; rows := 0; res := 0
ELSE (* execution failed *)
t := NIL; columns := 0; rows := 0; res := notExecutable
END
END EndExec;
PROCEDURE (d: Driver) Commit (accept: BOOLEAN; OUT res: INTEGER);
BEGIN
IF accept THEN
(* commit actual transaction *)
res := 0
ELSE
IF <rollback possible> THEN
(* rollback actual transaction *)
res := 0
ELSE res := notExecutable
END
END
END Commit;
PROCEDURE (d: Driver) Cleanup;
BEGIN
(* cleanup database data *)
(* release database specific resources *)
d.state := closed
END Cleanup;
(* Table *)
PROCEDURE (t: Table) ReadInteger (row, column: INTEGER; OUT val: INTEGER);
BEGIN
ASSERT(row >= 0, 20); ASSERT(row < t.rows, 21);
ASSERT(column >= 0, 22); ASSERT(column < t.columns, 23);
(* try to read an integer from table *)
IF <table value is not an integer> THEN val := 0; t.res := incompatible
ELSIF <table value is out of range> THEN val := 0; t.res := overflow
ELSE val := <value>
END
END ReadInteger;
PROCEDURE (t: Table) ReadLong (row, column: INTEGER; OUT val: LONGINT);
BEGIN
ASSERT(row >= 0, 20); ASSERT(row < t.rows, 21);
ASSERT(column >= 0, 22); ASSERT(column < t.columns, 23);
(* try to read a long integer from table *)
IF <table value is not an integer> THEN val := 0; t.res := incompatible
ELSE val := <value>
END
END ReadLong;
PROCEDURE (t: Table) ReadReal (row, column: INTEGER; OUT val: LONGREAL);
BEGIN
ASSERT(row >= 0, 20); ASSERT(row < t.rows, 21);
ASSERT(column >= 0, 22); ASSERT(column < t.columns, 23);
(* try to read a real from table *)
IF <table value is not a real> THEN val := 0; t.res := incompatible
ELSIF <table value is out of range> THEN val := 0; t.res := overflow
ELSE val := <value>
END
END ReadReal;
PROCEDURE (t: Table) ReadDate (row, column: INTEGER; OUT val: Dates.Date);
BEGIN
ASSERT(row >= 0, 20); ASSERT(row < t.rows, 21);
ASSERT(column >= 0, 22); ASSERT(column < t.columns, 23);
(* try to read a date from table *)
IF <table value is not a date> THEN
val.year := 0; val.month := 0; val.day := 0; t.res := incompatible
ELSE
val.year := <value>; val.month := <value>; val.day := <value>
END
END ReadDate;
PROCEDURE (t: Table) ReadTime (row, column: INTEGER; OUT val: Dates.Time);
BEGIN
ASSERT(row >= 0, 20); ASSERT(row < t.rows, 21);
ASSERT(column >= 0, 22); ASSERT(column < t.columns, 23);
(* try to read a time from table *)
IF <table value is not a time> THEN
val.hour := 0; val.minute := 0; val.second := 0; t.res := incompatible
ELSE
val.hour := <value>; val.minute := <value>; val.second := <value>
END
END ReadTime;
PROCEDURE (t: Table) ReadCurrency (row, column: INTEGER; OUT val: Dialog.Currency);
BEGIN
ASSERT(row >= 0, 20); ASSERT(row < t.rows, 21);
ASSERT(column >= 0, 22); ASSERT(column < t.columns, 23);
(* try to read a currency from table *)
IF <table value is not a currency> THEN
val.val := 0; val.scale := 0; t.res := incompatible
ELSE
val.val := <value>; val.scale := <value>
END
END ReadCurrency;
PROCEDURE (t: Table) ReadString (row, column: INTEGER; OUT str: ARRAY OF CHAR);
(* any value should be readable as a string *)
BEGIN
ASSERT(row >= 0, 20); ASSERT(row < t.rows, 21);
ASSERT(column >= 0, 22); ASSERT(column < t.columns, 23);
(* try to read a string from table *)
IF <table value is not a string> THEN
(* convert table value to a string *)
t.res := converted
END;
IF <length of string (incl 0X)> > LEN(str) THEN
(* copy truncated string to str *)
t.res := truncated
ELSE
(* copy string to str *)
END
END ReadString;
PROCEDURE (t: Table) ReadVarString (row, column: INTEGER; OUT str: SqlDrivers.String);
(* any value should be readable as a string *)
BEGIN
ASSERT(row >= 0, 20); ASSERT(row < t.rows, 21);
ASSERT(column >= 0, 22); ASSERT(column < t.columns, 23);
(* try to read a string from table *)
IF <table value is not a string> THEN
(* convert table value to a string *)
t.res := converted
END;
IF (str = NIL) OR (<length of string (incl 0X)> > LEN(str^)) THEN
NEW(str, <length of string (incl 0X)>)
END;
(* copy string to str^ *)
END ReadVarString;
PROCEDURE (t: Table) ReadBlob (row, column: INTEGER; VAR len: INTEGER;
OUT data: POINTER TO ARRAY OF BYTE);
(* blobs are not zero terminated *)
BEGIN
ASSERT(row >= 0, 20); ASSERT(row < t.rows, 21);
ASSERT(column >= 0, 22); ASSERT(column < t.columns, 23);
(* try to read a blob from table *)
IF <table value is not a blob> THEN
len := 0; t.res := incompatible
ELSE
len := <length of blob>;
IF (data = NIL) OR (len > LEN(data^)) THEN NEW(str, len) END;
(* copy blob data to data^ *)
END
END ReadBlob;
PROCEDURE (t: Table) ReadName (column: INTEGER; OUT str: SqlDrivers.String);
BEGIN
ASSERT(column >= 0, 20); ASSERT(column < t.columns, 21);
(* get column name *)
IF (str = NIL) OR (<length of name (incl 0X)> > LEN(str^)) THEN
NEW(str, <length of name (incl 0X)>)
END;
(* copy name to str^ *)
END ReadName;
PROCEDURE (t: Table) ReadType (column: INTEGER; OUT str: SqlDrivers.String);
BEGIN
ASSERT(column >= 0, 20); ASSERT(column < t.columns, 21);
(* get column type *)
IF (str = NIL) OR (<length of type (incl 0X)> > LEN(str^)) THEN
NEW(str, <length of type (incl 0X)>)
END;
(* copy type to str^ *)
END ReadType;
PROCEDURE (t: Table) Cleanup;
BEGIN
(* cleanup resultset data *)
(* release resultset specific resources *)
END Cleanup;
PROCEDURE Open* (id, password, datasource: ARRAY OF CHAR;
async, showErr: BOOLEAN; VAR d: SqlDrivers.Driver; OUT res: INTEGER);
(* asynchronous operation is optional, a driver may legally open synchronously if async is TRUE *)
(* Post: res = 0 <=> connection has started and will be completed later with EndOpen
res = 0 <=> d # NIL
~async & (res = 0) => d.Ready() *)
VAR h: Driver;
BEGIN
(* check id & password *)
IF <valid> THEN
IF async THEN
(* try to start connect request to datasource *)
ELSE
(* try to connect to datasource *)
END;
IF <successful> THEN
NEW(h); h.Init("<blob representation in statements>");
(* Initialize driver data *)
h.state := connecting; d := h; res := 0
ELSE
d := NIL; res := cannotOpenDB
END
ELSE
d := NIL; res := wrongIdentification
END
END Open;
END SqlObxDriv.
template module (ex SqlObxDriver)
ODBC driver
Microsoft's Open Database Connectivity (ODBC) is an interface standard for accessing relational SQL databases. There are ODBC drivers for most relational products, and even for some non-relational databases.
SqlOdbc is an Sql driver which builds a bridge to the ODBC driver manager. Given a suitable 32-bit ODBC driver, this allows to use a database via ODBC and Sql.
SqlOdbc supports all features of Sql, except asynchronous operation.
To use ODBC, the ODBC driver manager from Microsoft and a suitable ODBC driver is needed. The ODBC driver is installed along with the first driver installed on a system. Consult the documentation of your database on how to install an ODBC driver for it.
During installation of BlackBox, it can be chosen whether the ODBC driver manager and one of Microsoft's "desktop drivers", the text driver, should be installed. The text driver uses plain ASCII text files as "database" files. It is very handy for testing purposes. It is not meant for productive use, and it is not permitted to distribute this Microsoft software along with applications.
In its software development kits, Microsoft also provides further desktop drivers, e.g., for Excel, Access,or dBase.
When connecting to a desktop driver, empty strings can be passed to the password and id parameters of SqlDB.OpenDatabase. The datasource parameter must be a name shown in the "User Data Sources" list in the ODBC control panel application. The protocol name must be the module name "SqlOdbc" (case sensitive!). Note that it is not possible to connect to a 16-bit driver.
protocol "SqlOdbc"
datasource data source name as presented in the ODBC control panel
id user id, if the ODBC driver supports user identification
password password, if the ODBC driver supports user identification
For productive use, Microsoft's SQL Server product is a suitable choice, not least because it directly implements ODBC, so no inefficient translation occurs in its driver, which slows down some other ODBC-connected database products.
SqlOdbc works with 32-bit ODBC drivers that support the ODBC core functions, ODBC Level 1, and the ODBC Level 2 procedure SQLExtendedFetch. It works with older ODBC managers. For ODBC 3, as it is distributed e.g. with Windows 2000, module SqlOdbc3 must be used instead.
For further information on ODBC, please consult the Microsoft literature and software development kits.
SqlDB
See the on-linedocumentation.
Clearing Database and Table pointers
An open database need and cannot be closed explicitly. BlackBox closes it automatically when there exist no more references to it. This is accomplished by the garbage collector. When the garbage collector detects that a database object isn't accessible anymore, it finalizes (i.e., closes) it.
For the programmer it is important to make sure that no global database or table pointers are left which anchor the database object, and thus would prevent garbage collection.
For mere "batch" commands, this is no problem. Such a command is started, opens a database and possibly some tables, does some processing, and then terminates. Database and table pointers are kept as local variables, and thus vanish after the command has terminated. This means that there is no need to set any pointers to NIL, since they just disappear.
Things are different for interactive database applications, where the user interacts with a database via a dialog box. There the database should be opened when the (first) dialog box for it is opened, and closed after the (last) dialog box is closed. In between, there are references which keep the database from being collected.
Opening is simple: the menu entry which opens the dialog box first invokes an initialization command before opening the dialog box window. This initialization command opens the database and stores the necessary table objects in global variables. Typically, it won't save the database pointer itself; since most of the time a database ought to be closed when there exist no more table objects. Furthermore, a table's database can be accessed via its base field.
After the initialization command, other commands can use the database and table pointers to perform SQL queries and operations, until the user closes the last dialog box of the application.
The question is how the various global table pointers can be set to NIL, such that the garbage collector can perform its duty. For this purpose, module SqlControls provides so-called anchor controls. They are controls that can be linked to global table pointer variables. They have two main purposes: determining whether the window should be closed, and cleaning up if and when the window is closed.
An anchor control can be linked to a global table pointer variable. This is the actual "anchor" as far as the garbage collector is concerned. It can be "cut" (set to NIL) by the anchor control when the control's window is closed.
Determining whether the window should be closed
When the user attempts to close a dialog box containing one or several anchors, and if at least one of the anchors is linked to a non-NIL table variable (or has an empty link name), the user is asked whether the dialog box should really be closed. This is useful e.g. when the user has entered some data into a data entry mask, but hasn't performed an operation (e.g., a database insertion) with the data.
Asking only happens if the control's optional guard sets disabled to TRUE, and thus indicates that it wants to prevent closing the dialog box for the table (e.g., because entered data has not been inserted). If there is no guard, or if it doesn't set disabled to TRUE, then the user is not given the opportunity to stop window closing. But if the user is asked, he or she has the last word; an anchor control cannot prevent the user from closing the window.
The message that is shown to the user when asking is determined by the guard setting the label field. If there is no guard or it doesn't set this field, then the control's label value is used. If this label value is empty, then a standard message (with a mapping defined in Sql/Rsrc/Strings with the key IsCloseOK) is used.
For example, a dialog box may contain two anchor views with the following properties:
link "SqlObxDB.c"
label "Do you really want to close the window without saving your input?"
link "SqlObxDB.m"
label ""
Cleaning up when the window is closed
If and when the dialog box is closed, all the anchors that it contains set their pointers to NIL. In other words: when the last anchor view vanishes, the table pointers are set to NIL. If there are no further references to the database object (directly or indirectly), then this means that it is not globally anchored anymore and can be garbage collected. Closing the window causes the garbage collector to run, so the database will be closed immediately.
If active notification about a closed database is desired, the control's notifier can be used for this purpose. This allows to perform arbitrary cleanup actions upon window closing, in addition to (or instead of) setting a table pointer to NIL.
The link may even be left empty, so that only the notifier is used and no pointer variable is needed.
Control properties
link optional link to a global pointer variable
label optional message that the user is asked before window closing
guard optional determines whether to ask, and what message to show
notifier optional notifies about window closing
Note that actually the anchor controls can be used universally for any kind of pointers, they need not be table pointers. Whenever you need to clear global pointers when no document references (i.e., anchors) to them exist anymore, you can use these anchors.
Displaying tables
Often it is necessary to display result tables in tabular fashion. For this purpose, module SqlControls provides table controls. Tables cannot be edited, but its possible to select a field in a table.
A table control needs to be linked to a global variable of type SqlDB.Table.
A table control may also denote a notifier with the following signature:
TableNotifier = PROCEDURE (t: SqlDB.Table; row, column: INTEGER; modifiers: SET)
It is called whenever the user has clicked into a field of the table, indicating the table, its row and column numbers, and the track message's modifier set (-> Controllers.TrackMsg).
A table control is used in one of two ways: either it is opened in its own window, or it is embedded in some container, typically a form view. In the first case, the window provides scrollbars if necessary. In the second case, it is usually wrapped in a scroller view (Tools->Add Scroller) which provides the scrollbars.
When a table control is generated by a program, it is not necessary to link it to a global table pointer variable. Instead, the table pointer can be directly passed as parameter in the call to SqlControls.dir.NewTableOn(table).
Design rules
This section gives some rules which should be followed when designing a database application. The reason for each rule is given after the rule.
Interactors or at least their types must be exported if they should be used as place holders in SQL statements.
(Non-exported types are not accessible through metaprogramming, and thus controls and the SQL string translation mechanism could not be used with them.)
A globally anchored database and all its table pointers must be set to NIL if the database ought to be closed.
(If a global pointer variable is not set to NIL, the garbage collector cannot reclaim the data structures anchored in it. Upon garbage collection of a database, the database is closed if there are no more pointers to it. Note that a table contains a pointer to its database object and thus anchors it.)
A database pointer should not be declared as global variable.
(Normally there are global table pointers, which contain references to their databases. A global database pointer would be one more pointer to set to NIL eventually; and anchor views can only set table pointers to NIL.)
Database.Exec may only execute non-row-returning statements, e.g. DELETE or INSERT.
(A result table must always be assigned to a table and via the table to an interactor, otherwise it cannot be accessed by the application.)
Table.Exec should only execute row-returning statements, e.g., SELECT.
The order and types (but not necessarily the names) of fields in an interactor variable must match those defined in the SQL database. The number of fields must be the same as the number of columns.
Only complete tables may be assigned to an interactor by Table.Read, no partial assignment is allowed. The correspondence of result table columns and interactor fields is given by their respective declaration order. Nested arrays, records and pointers are handled recursively.
Pointers must not be NIL except for POINTER TO ARRAY OF CHAR which are allocated automatically if the pointer is NIL or if the bound array is too small to receive the corresponding string.
Scalar result variables are treated as tables with table.rows = 1 and table.columns = 1.
After an SQL statement which may render a row inconsistent with the database, use a SELECT statement to re-establish consistency.
(For example, an interactor may still contain the value of a row which has just been deleted through a DELETE statement. Exec on the table will flush the old result table and possibly assign a new one.)
Example
This very simple example allows to insert, update, delete, and find rows in a database. A row consists of an integer id, two strings name and ceo, and an integer employees. The application consists of a core logic module (SqlObxDB) and a user interface module with guards and notifiers (SqlObxUI).
SqlObxDB SqlObxUI
Use the following menu entry to open the data entry mask (it may already be installed in the standard configuration of your software):
MENU "Sql"
"Insert Anchor" "" "SqlControls.DepositAnchor; StdCmds.PasteView" "StdCmds.PasteViewGuard"
"Insert Table" "" "SqlControls.DepositTable; StdCmds.PasteView" "StdCmds.PasteViewGuard"
SEPARATOR
"Browser..." "" "StdCmds.OpenAuxDialog('Sql/Rsrc/Browser', 'Browser')" ""
"Execute" "" "SqlBrowser.ExecuteSel" "TextCmds.SelectionGuard"
SEPARATOR
"Company..." "" "SqlObxDB.Open; StdCmds.OpenAuxDialog('Sql/Rsrc/Company', 'Company')" ""
"Ownership..." "" "SqlObxExt.Open; StdCmds.OpenAuxDialog('Sql/Rsrc/Owner', 'Ownership')" ""
"Set Test Data" "" "SqlObxDB.SetTestData" ""
SEPARATOR
"Help" "" "StdCmds.OpenBrowser('Sql/Docu/Dev-Man', 'Sql Docu')" ""
END
The following form is opened when Sql->Company... is invoked:
"StdCmds.OpenDoc('Sql/Rsrc/Company')"
On-line, there are some extensions to the above example. The module SqlObxExt demonstrates an extension of SqlObxDB and SqlObxUI. It handles the ownership dialog box, i.e., it allows to enter ownerships between companies. A suitable command to open the ownership dialog box is given in the menu definition above (Sql->Ownership...).
The modules SqlObxGen, SqlObxViews, SqlObxNets implement an algorithm which generates a graphical representation out of the companies in the sample database, showing the ownership relations of the companies. It is interesting insofar as this is a graph algorithm (known as Lee algorithm or Dijkstra's algorithm) which requires the creation of an intermediate data structure; fetching the necessary data cannot be formulated as a single SQL query.
To try this example out, find an existing company in the Company dialog box, e.g. company with id = 1 of the test data generated by SqlObxDB.SetTestData. Then click on the Graph button in the dialog box. This will cause SqlObxGen.GenNet to be called. This command implements a layout algorithm, which first finds all the companies which are related to the selected company by ownership, then converts the company and ownership information into a Component Pascal data structure (module SqlObxNets), then performs a layout algorithm to place the companies graphically, and then generates a view which displays the graph.
In order to run the examples provided by the Sql subsystem, some sample tables have to be created first. This can be done with the command SqlObxInit.Setup. The following two tables are created:
CREATE TABLE Companies
(id INTEGER,
name CHAR(255)
ceo CHAR(255)
employees INTEGER)
CREATE TABLE Ownership
(owner INTEGER,
owned INTEGER,
percent INTEGER)
By default, the ODBC Text drivers are installed, for which the example database has already been created, so you don't need to perform the above CREATE TABLE statements anymore.
The modules SqlObxDB, SqlObxExt, SqlObxGen, and SqlObxInit contain ODBC-specific references (protocol, datasource, id, password) which have to be adapted before using them if another database driver is used instead of the SqlOdbc driver. It is sufficient to change the constant declarations appropriately.
The tables can be inspected and modified using the database browser SqlBrowser. Just type an SQL query in the Statement field of the browser window and press return.
| Sql/Docu/Dev-Man.odc |
SqlDrivers
See developermanual.
| Sql/Docu/Drivers.odc |
SqlObxDB
See developermanual.
| Sql/Docu/ObxDB.odc |
SqlObxExt
See developermanual.
| Sql/Docu/ObxExt.odc |
SqlObxGen
See developermanual.
| Sql/Docu/ObxGen.odc |
SqlObxInit
See developermanual.
| Sql/Docu/ObxInit.odc |
SqlObxNets
See developermanual.
| Sql/Docu/ObxNets.odc |
SqlObxTab
See developermanual.
| Sql/Docu/ObxTab.odc |
SqlObxUI
See developermanual.
| Sql/Docu/ObxUI.odc |
SqlObxViews
See developermanual.
| Sql/Docu/ObxViews.odc |
Map to the Sql Subsystem
DeveloperManual
SqlDB Sql database access
SqlDrivers Sql driver module
SqlControls special-purpose controls
SqlOdbc ODBC access (pre OLE 3.0)
SqlOdbc3 ODBC access (OLE 3.0)
Samples:
SqlBrowser simple SQL browser
SqlObxDriv template of a driver module
SqlObxTab write a table into a text
SqlObxInit create example database
SqlObxDB "business logic" module
SqlObxUI user interface module
SqlObxExt extension of above example
SqlObxNets example models
SqlObxViews example views
SqlObxGen view generator
SqlObxInit database initialization
| Sql/Docu/Sys-Map.odc |
MODULE SqlBrowser;
(**
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 Dialog, Views, TextModels, TextControllers, SqlDB, SqlControls;
VAR
dlg*: RECORD
id*,
password*,
database*,
driver*: ARRAY 32 OF CHAR;
statement*: ARRAY 1024 OF CHAR
END;
table*: SqlDB.Table; (* anchor for database *)
PROCEDURE CheckResult (tab: SqlDB.Table; par: ANYPTR);
VAR v: Views.View;
BEGIN
IF tab.res = 0 THEN
IF tab.columns > 0 THEN
v := SqlControls.dir.NewTableOn(tab);
Views.OpenAux(v, "#Sql:Result")
ELSE Dialog.ShowMsg("#Sql:StatementExecuted")
END
ELSE Dialog.ShowMsg("#Sql:ExecutionFailed")
END
END CheckResult;
PROCEDURE ExecuteThis (statement: ARRAY OF CHAR);
VAR res: INTEGER; db: SqlDB.Database; tab: SqlDB.Table;
BEGIN
IF table = NIL THEN
SqlDB.OpenDatabase(dlg.driver, dlg.id, dlg.password, dlg.database,
SqlDB.async, SqlDB.showErrors, db, res);
IF res = 0 THEN
table := db.NewTable()
ELSIF res <= 3 THEN
Dialog.ShowMsg("#Sql:CannotLoadDriver")
ELSE
Dialog.ShowMsg("#Sql:ConnectionFailed")
END
END;
IF (statement # "") & (table # NIL) THEN
(* allocate separate table to allow for multiple open tables *)
tab := table.base.NewTable();
tab.Exec(statement);
(* separate result check from execution to allow for asynchronous operation *)
tab.Call(CheckResult, NIL)
END
END ExecuteThis;
PROCEDURE Execute*;
BEGIN
ExecuteThis(dlg.statement)
END Execute;
PROCEDURE ExecuteSel*;
VAR c: TextControllers.Controller; r: TextModels.Reader; beg, end, i: INTEGER; stat: ARRAY 1024 OF CHAR;
BEGIN
c := TextControllers.Focus();
IF (c # NIL) & c.HasSelection() THEN
c.GetSelection(beg, end);
r := c.text.NewReader(NIL);
r.SetPos(beg); i := 0;
WHILE r.Pos() < end DO r.ReadChar(stat[i]); INC(i) END;
stat[i] := 0X;
ExecuteThis(stat)
END
END ExecuteSel;
PROCEDURE Commit*;
BEGIN
IF table # NIL THEN
table.base.Commit
END
END Commit;
BEGIN
dlg.id := ""; dlg.password := ""; dlg.database := "Test Database"; dlg.driver := "WinSqlOdbc"
END SqlBrowser.
| Sql/Mod/Browser.odc |
MODULE SqlControls;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20150521, center #50, unlimited number of columns in SqlControls.Control
- 20150714, center #19, 16-bit Unicode support for Component Pascal identifiers added
"
issues = "
- ...
"
**)
IMPORT SYSTEM, (* SYSTEM.ADR only *)
Stores, Sequencers, Views, Properties, Dialog, Meta,
Fonts, Ports, Controllers, Containers, Controls, SqlDB, TextModels, TextViews;
CONST
nil* = -1; (** navigator pseudo position **)
minVersion = 0; maxBaseVersion = 1;
anchVersion = 0; navVersion = 0; tabVersion = 0;
w = 24;
defColW = 30 * Ports.mm;
left = -1; right = -2; center = -3; (* adjustment modes *)
move = 1; adjust = 2; field = 3; (* cursor modes *)
update = 2; (* notify options *)
TYPE
Directory* = POINTER TO ABSTRACT RECORD END;
Control = POINTER TO ABSTRACT RECORD (Views.View)
item: Meta.Item;
prop: Controls.Prop
END;
Anchor = POINTER TO RECORD (Control)
hasNotifier: BOOLEAN
END;
Navigator = POINTER TO RECORD (Control) END;
Table = POINTER TO RECORD (Control)
(* persistent *)
sprop: Properties.StdProp; (* font attributes *)
columns: INTEGER;
width: POINTER TO ARRAY OF INTEGER;
mode: POINTER TO ARRAY OF INTEGER;
(* not persistent *)
table: SqlDB.Table;
fldFont, titFont: Fonts.Font;
rowH, baseOff: INTEGER;
orgRow, orgX: INTEGER; (* scroll state *)
selRow, selCol: INTEGER; (* selected field *)
selected: BOOLEAN
END;
StdDirectory = POINTER TO RECORD (Directory) END;
SelMsg = RECORD (Views.Message)
show: BOOLEAN
END;
Op = POINTER TO RECORD (Stores.Operation)
ctrl: Control;
prop: Controls.Prop;
sprop: Properties.StdProp
END;
FormatOp = POINTER TO RECORD (Stores.Operation)
tab: Table;
col, width, mode: INTEGER;
END;
CloseNotifier = POINTER TO RECORD (Sequencers.Notifier)
control: Anchor
END;
TableValue = RECORD (Meta.Value)
ptr: SqlDB.Table
END;
TableNotifier = PROCEDURE (t: SqlDB.Table; row, column: INTEGER; modifiers: SET);
NotifierValue = RECORD (Meta.Value)
p: TableNotifier
END;
NavProc = PROCEDURE (pos: INTEGER; VAR resPos, count: INTEGER);
GuardProcVal = RECORD (Meta.Value) p*: Dialog.GuardProc END;
NavProcVal = RECORD (Meta.Value) p*: NavProc END;
VAR dir-, stdDir-: Directory;
(* auxiliary procedures *)
PROCEDURE CallGuard (c: Control; VAR disabled: BOOLEAN; VAR string: ARRAY OF CHAR);
VAR ok: BOOLEAN; dpar: Dialog.Par; v: GuardProcVal; i: Meta.Item;
BEGIN
dpar.disabled := FALSE; dpar.undef := FALSE; dpar.readOnly := FALSE;
dpar.checked := FALSE; dpar.label := "";
Meta.LookupPath(c.prop.guard, i);
IF (i.obj = Meta.procObj) OR (i.obj = Meta.varObj) & (i.typ = Meta.procTyp) THEN
i.GetVal(v, ok);
IF ok THEN v.p(dpar) END
END;
disabled := dpar.disabled; string := dpar.label$
END CallGuard;
PROCEDURE CallLink (c: Navigator; pos: INTEGER; VAR newPos, count: INTEGER);
VAR ok: BOOLEAN; v: NavProcVal;
BEGIN
newPos := nil; count := nil; ok := FALSE;
IF (c.item.obj = Meta.procObj) OR (c.item.obj = Meta.varObj) & (c.item.typ = Meta.procTyp) THEN
c.item.GetVal(v, ok);
IF ok THEN v.p(pos, newPos, count) END
END;
IF ~ok & (pos # nil) & (c.prop.label # "") THEN
Dialog.ShowParamMsg("#Sql:HasWrongType", c.prop.link, "", "")
END
END CallLink;
PROCEDURE CallNotifier (c: Anchor);
VAR res: INTEGER;
BEGIN
IF c.prop.notifier # "" THEN
Dialog.Call(c.prop.notifier, " ", res)
END
END CallNotifier;
PROCEDURE CallTableNotifier (t: Table; row, column: INTEGER; modifiers: SET );
VAR item: Meta.Item; nv: NotifierValue; ok: BOOLEAN;
BEGIN
IF t.prop.notifier # "" THEN
Meta.LookupPath(t.prop.notifier, item);
IF item.Valid() THEN
item.GetVal(nv, ok);
IF ok THEN
nv.p(t.table, row, column, modifiers)
ELSE
Dialog.ShowParamMsg("#Sql:HasWrongType", t.prop.notifier, "", "")
END
ELSE
Dialog.ShowParamMsg("#Sql:NotFound", t.prop.notifier, "", "")
END
END
END CallTableNotifier;
PROCEDURE OpenLink (c: Control; p: Controls.Prop);
VAR mod, type: Meta.Name; tv: TableValue; ok: BOOLEAN;
BEGIN
c.prop := Properties.CopyOf(p)(Controls.Prop);
IF c.prop.link # "" THEN
Meta.LookupPath(c.prop.link, c.item);
IF c.item.Valid() & (c.item.obj = Meta.varObj) THEN
WITH c: Anchor DO
IF c.item.typ # Meta.ptrTyp THEN
Dialog.ShowParamMsg("#Sql:HasWrongType", c.prop.link, "", "")
END
| c: Table DO
c.item.GetTypeName(mod, type);
IF (mod = "SqlDB") & (type = "Table") THEN
c.item.GetVal(tv, ok); ASSERT(ok, 100);
c.table := tv.ptr
ELSE
Dialog.ShowParamMsg("#Sql:HasWrongType", c.prop.link, "", "")
END
ELSE
END
ELSE
Dialog.ShowParamMsg("#Sql:NotFound", c.prop.link, "", "")
END
END
END OpenLink;
PROCEDURE SetupTable (t: Table);
VAR 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.rowH := 3 * t.sprop.size DIV 2;
t.fldFont.GetBounds(asc, dsc, w);
t.baseOff := (t.rowH -asc - dsc) DIV 2 + asc;
END SetupTable;
(** Directory **)
PROCEDURE (d: Directory) NewAnchor* (p: Controls.Prop): Views.View, NEW, ABSTRACT;
PROCEDURE (d: Directory) NewNavigator* (p: Controls.Prop): Views.View, NEW, ABSTRACT;
PROCEDURE (d: Directory) NewTable* (p: Controls.Prop): Views.View, NEW, ABSTRACT;
PROCEDURE (d: Directory) NewTableOn* (tab: SqlDB.Table): Views.View, NEW, ABSTRACT;
(* Control *)
PROCEDURE (c: Control) Internalize (VAR rd: Stores.Reader), EXTENSIBLE;
VAR thisVersion: INTEGER; x: BOOLEAN;
BEGIN
c.Internalize^(rd);
IF rd.cancelled THEN RETURN END;
rd.ReadVersion(minVersion, maxBaseVersion, thisVersion);
IF rd.cancelled THEN RETURN END;
NEW(c.prop);
IF thisVersion >= 1 THEN
rd.ReadString(c.prop.link);
rd.ReadString(c.prop.label);
rd.ReadString(c.prop.guard);
rd.ReadString(c.prop.notifier);
ELSE (* thisVersion = 0 *)
rd.ReadXString(c.prop.link);
rd.ReadXString(c.prop.label);
rd.ReadXString(c.prop.guard);
rd.ReadXString(c.prop.notifier);
END ;
rd.ReadBool(c.prop.opt[Controls.sorted]);
rd.ReadBool(c.prop.opt[Controls.default]);
rd.ReadBool(c.prop.opt[Controls.cancel]);
rd.ReadXInt(c.prop.level);
rd.ReadBool(x);
OpenLink(c, c.prop)
END Internalize;
PROCEDURE (c: Control) Externalize (VAR wr: Stores.Writer), EXTENSIBLE;
BEGIN
c.Externalize^(wr);
wr.WriteVersion(maxBaseVersion);
wr.WriteString(c.prop.link);
wr.WriteString(c.prop.label);
wr.WriteString(c.prop.guard);
wr.WriteString(c.prop.notifier);
wr.WriteBool(c.prop.opt[Controls.sorted]);
wr.WriteBool(c.prop.opt[Controls.default]);
wr.WriteBool(c.prop.opt[Controls.cancel]);
wr.WriteXInt(c.prop.level);
wr.WriteBool(FALSE)
END Externalize;
PROCEDURE (c: Control) CopyFromSimpleView (source: Views.View), EXTENSIBLE;
BEGIN
(* c.CopyFrom^(source); *)
WITH source: Control DO
NEW(c.prop); c.prop^ := source.prop^;
c.item := source.item
END
END CopyFromSimpleView;
(* Op *)
PROCEDURE (op: Op) Do;
VAR c: Control; prop: Controls.Prop; sprop: Properties.StdProp;
BEGIN
c := op.ctrl;
IF op.prop # NIL THEN
NEW(prop);
prop^ := c.prop^; prop.valid := op.prop.valid;
IF Controls.link IN op.prop.valid THEN c.prop.link := op.prop.link END;
IF Controls.label IN op.prop.valid THEN c.prop.label := op.prop.label END;
IF Controls.guard IN op.prop.valid THEN c.prop.guard := op.prop.guard END;
IF Controls.notifier IN op.prop.valid THEN c.prop.notifier := op.prop.notifier END;
IF Controls.default IN op.prop.valid THEN c.prop.opt[Controls.default] := op.prop.opt[Controls.default] END;
IF Controls.cancel IN op.prop.valid THEN c.prop.opt[Controls.cancel] := op.prop.opt[Controls.cancel] END;
IF Controls.level IN op.prop.valid THEN c.prop.level := op.prop.level END;
IF Controls.sorted IN op.prop.valid THEN c.prop.opt[Controls.sorted] := op.prop.opt[Controls.sorted] END;
IF c.prop.link # prop.link THEN OpenLink(c, c.prop) END;
op.prop := prop
END;
WITH c: Table DO
IF op.sprop # NIL THEN
NEW(sprop);
sprop^ := c.sprop^; sprop.valid := op.sprop.valid;
IF Properties.typeface IN op.sprop.valid THEN c.sprop.typeface := op.sprop.typeface END;
IF Properties.size IN op.sprop.valid THEN c.sprop.size := op.sprop.size END;
IF Properties.style IN op.sprop.valid THEN c.sprop.style := op.sprop.style END;
IF Properties.weight IN op.sprop.valid THEN c.sprop.weight := op.sprop.weight END;
IF sprop.valid # {} THEN SetupTable(c) END;
op.sprop := sprop
END
ELSE
END;
Views.Update(c, Views.rebuildFrames);
END Do;
PROCEDURE FillArray(VAR a: ARRAY OF INTEGER; start, len, val: INTEGER);
VAR i: INTEGER;
BEGIN
FOR i := start TO start + len - 1 DO a[i] := val END
END FillArray;
PROCEDURE CopyArray(VAR from, to: ARRAY OF INTEGER);
VAR i: INTEGER;
BEGIN
FOR i := 0 TO LEN(from) - 1 DO to[i] := from[i] END
END CopyArray;
PROCEDURE Expand(t: Table; nofCols: INTEGER);
VAR len: INTEGER; width, mode: POINTER TO ARRAY OF INTEGER;
BEGIN
len := LEN(t.width);
NEW(width, nofCols); CopyArray(t.width, width); FillArray(width, len, nofCols - len, defColW);
NEW(mode, nofCols); CopyArray(t.mode, mode); FillArray(mode, len, nofCols - len, center);
t.width := width; t.mode := mode
END Expand;
(* FormatOp *)
PROCEDURE (op: FormatOp) Do;
VAR t: Table; c, w, m: INTEGER;
BEGIN
t := op.tab; c := op.col; w := op.width; m := op.mode;
IF c >= LEN(t.width) THEN Expand(t, c + 10) END;
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: Controls.Prop; sp: Properties.StdProp;
BEGIN
NEW(p); p^ := c.prop;
WITH c: Anchor DO
p.valid := {Controls.link, Controls.label, Controls.guard, Controls.notifier}
| c: Navigator DO
p.valid := {Controls.link}
| c: Table DO
p.valid := {Controls.link, Controls.notifier};
NEW(sp); sp^ := c.sprop^;
sp.valid := {Properties.typeface, Properties.size, Properties.style, Properties.weight};
sp.known := sp.valid; sp.readOnly := {Properties.weight};
Properties.Insert(list, sp)
ELSE
END;
p.known := p.valid;
Properties.Insert(list, p)
END PollProp;
PROCEDURE SetProp (c: Control; p: Properties.Property);
VAR op: Op; valid: SET;
BEGIN
op := NIL;
WHILE p # NIL DO
WITH p: Controls.Prop DO
WITH c: Anchor DO
valid := {Controls.link, Controls.label, Controls.guard, Controls.notifier}
| c: Navigator DO
valid := {Controls.link}
| c: Table DO
valid := {Controls.link, Controls.notifier}
ELSE
END;
valid := p.valid * valid;
IF valid # {} THEN
IF op = NIL THEN NEW(op); op.ctrl := c END;
NEW(op.prop); op.prop^ := p^; op.prop.valid := valid
END
| p: Properties.StdProp DO
WITH c: Table DO
valid := p.valid * {Properties.typeface, Properties.size, Properties.style};
IF valid # {} THEN
IF op = NIL THEN NEW(op); op.ctrl := c END;
NEW(op.sprop); op.sprop^ := p^; op.sprop.valid := valid
END
ELSE
END
ELSE
END;
p := p.next
END;
IF op # NIL THEN Views.Do(c, "#System:SetProp", op) END
END SetProp;
(* CloseNotifier *)
PROCEDURE (n: CloseNotifier) Notify (VAR msg: Sequencers.Message);
VAR disabled: BOOLEAN; string: Dialog.String; res: INTEGER;
BEGIN
WITH msg: Sequencers.CloseMsg DO
IF ~msg.sticky & (~n.control.item.Valid() OR (n.control.item.PtrVal() # NIL)) THEN
CallGuard(n.control, disabled, string);
IF disabled THEN
IF string = "" THEN string := n.control.prop.label$ END;
IF string = "" THEN string := "#Sql:IsCloseOk" END;
Dialog.GetOK(string, "", "", "", {Dialog.yes, Dialog.no}, res);
msg.sticky := res = Dialog.no
END
END
| msg: Sequencers.RemoveMsg DO
IF n.control.item.Valid() THEN n.control.item.PutPtrVal(NIL) END;
CallNotifier(n.control) (* Dialog.CheckGuards is called by HostWindows *)
ELSE
END
END Notify;
(* Anchor *)
PROCEDURE (a: Anchor) Internalize (VAR rd: Stores.Reader);
VAR thisVersion: INTEGER;
BEGIN
a.Internalize^(rd);
IF ~rd.cancelled THEN
rd.ReadVersion(minVersion, anchVersion, thisVersion)
END
END Internalize;
PROCEDURE (a: Anchor) Externalize (VAR wr: Stores.Writer);
BEGIN
a.Externalize^(wr);
wr.WriteVersion(anchVersion)
END Externalize;
PROCEDURE Visible (v: Views.View; f: Views.Frame): BOOLEAN;
VAR visible: BOOLEAN; g: Views.Frame; ctrl: Containers.Controller;
BEGIN
g := Views.HostOf(f);
IF (g = NIL) OR ~(g.view IS Containers.View) THEN
visible := TRUE
ELSE
ctrl := g.view(Containers.View).ThisController();
visible := Containers.mask * ctrl.opts # Containers.mask
END;
RETURN visible
END Visible;
PROCEDURE (a: Anchor) Restore (f: Views.Frame; l, t, r, b: INTEGER);
VAR u: INTEGER; col: Ports.Color; n: CloseNotifier;
BEGIN
IF ~a.hasNotifier & (a.Domain() # NIL) & (a.Domain().GetSequencer() # NIL) THEN
NEW(n); n.control := a;
a.Domain().GetSequencer()(Sequencers.Sequencer).InstallNotifier(n);
a.hasNotifier := TRUE
END;
IF Visible(a, f) THEN
u := Ports.point;
f.DrawRect(0, 0, 20 * u, 16 * u, u, Ports.defaultColor);
f.DrawLine(u, 3 * u, 19 * u, 3 * u, u, Ports.defaultColor);
IF (a.prop.link # "") OR (a.prop.label # "") OR (a.prop.guard # "") THEN
col := Ports.red ELSE col := Ports.green
END;
f.DrawLine(2 * u, 5 * u, 17 * u, 13 * u, u, col);
f.DrawLine(2 * u, 13 * u, 17 * u, 5 * u, u, col)
END
END Restore;
PROCEDURE (a: Anchor) HandlePropMsg (VAR msg: Properties.Message);
BEGIN
WITH msg: Properties.ResizePref DO
msg.fixed := TRUE
| msg: Properties.PollMsg DO
PollProp(a, msg.prop)
| msg: Properties.SetMsg DO
SetProp(a, msg.prop)
| msg: Properties.SizePref DO
IF msg.w = Views.undefined THEN msg.w := 20 * Ports.point END;
IF msg.h = Views.undefined THEN msg.h := 16 * Ports.point END
ELSE
END
END HandlePropMsg;
(* Navigator *)
PROCEDURE (n: Navigator) Internalize (VAR rd: Stores.Reader);
VAR thisVersion: INTEGER;
BEGIN
n.Internalize^(rd);
IF ~rd.cancelled THEN
rd.ReadVersion(minVersion, navVersion, thisVersion)
END
END Internalize;
PROCEDURE (n: Navigator) Externalize (VAR wr: Stores.Writer);
BEGIN
n.Externalize^(wr);
wr.WriteVersion(navVersion)
END Externalize;
PROCEDURE DrawArrow (f: Views.Frame; VAR y: INTEGER; w, u: INTEGER; bar, up, guard: BOOLEAN);
VAR d, y0, y1: INTEGER; col: Ports.Color;
BEGIN
d := w DIV 2 - 2;
IF guard THEN col := Ports.defaultColor ELSE col := Ports.grey50 END;
IF bar & up THEN f.DrawLine(2 * u, y * u, (w - 3) * u, y * u, u, col); INC(y) END;
IF up THEN y0 := (y + d - 1) * u; y1 := y * u ELSE y0 := y * u; y1 := (y + d - 1) * u END;
f.DrawLine(2 * u, y0, (w DIV 2 - 1) * u, y1, u, col); (* left diagonal *)
f.DrawLine(w DIV 2 * u, y1, (w - 3) * u, y0, u, col); (* right diagonal *)
INC(y, d);
IF bar & ~up THEN f.DrawLine(2 * u, y * u, (w - 3) * u, y * u, u, col); INC(y) END
END DrawArrow;
PROCEDURE (n: Navigator) Restore (f: Views.Frame; l, t, r, b: INTEGER);
VAR newPos, count, u, y: INTEGER; col: Ports.Color;
BEGIN
CallLink(n, nil, newPos, count);
u := f.dot; y := 2;
DrawArrow(f, y, w, u, TRUE, TRUE, newPos > 0); INC(y, 2);
DrawArrow(f, y, w, u, FALSE, TRUE, newPos > 0); INC(y, 2);
DrawArrow(f, y, w, u, FALSE, FALSE, newPos < count - 1); INC(y, 2);
DrawArrow(f, y, w, u, TRUE, FALSE, newPos < count - 1); INC(y, 2);
IF n.prop.link # "" THEN col := Ports.defaultColor ELSE col := Ports.grey50 END;
f.DrawRect(0, 0, w * u, y * u, u, col)
END Restore;
PROCEDURE HitArrow (f: Views.Frame; VAR y: INTEGER; w, u, xm, ym: INTEGER; bar, up, guard: BOOLEAN;
VAR hit: BOOLEAN);
VAR d, y0, xd, yd: INTEGER; m: SET; isDown: BOOLEAN;
BEGIN
hit := FALSE; xm := xm DIV u; ym := ym DIV u; y0 := y - 1;
IF (xm >= 0) & (xm < w) & (ym >= y) THEN
d := w DIV 2 - 2;
IF bar & up THEN INC(y) END;
INC(y, d);
IF bar & ~up THEN INC(y) END;
IF ym < y THEN
IF guard THEN
f.MarkRect(u, y0 * u, (w - 1) * u, (y + 1) * u, Ports.fill, Ports.hilite, Ports.show);
REPEAT f.Input(xd, yd, m, isDown) UNTIL ~isDown;
f.MarkRect(u, y0 * u, (w - 1) * u, (y + 1) * u, Ports.fill, Ports.hilite, Ports.hide);
hit := TRUE
ELSE Dialog.Beep
END
END
END
END HitArrow;
PROCEDURE TrackMsg (v: Navigator; f: Views.Frame; w, u, xm, ym: INTEGER);
VAR newPos, count, y: INTEGER; hit: BOOLEAN;
BEGIN
CallLink(v, nil, newPos, count);
u := f.dot; y := 2;
HitArrow(f, y, w, u, xm, ym, TRUE, TRUE, newPos > 0, hit); INC(y, 2);
IF hit THEN CallLink(v, 0, newPos, count) END;
HitArrow(f, y, w, u, xm, ym, FALSE, TRUE, newPos > 0, hit); INC(y, 2);
IF hit THEN CallLink(v, newPos - 1, newPos, count) END;
HitArrow(f, y, w, u, xm, ym, FALSE, FALSE, newPos < count - 1, hit); INC(y, 2);
IF hit THEN CallLink(v, newPos + 1, newPos, count) END;
HitArrow(f, y, w, u, xm, ym, TRUE, FALSE, newPos < count - 1, hit);
IF hit THEN CallLink(v, count - 1, newPos, count) END;
Views.Update(v, Views.keepFrames)
END TrackMsg;
PROCEDURE (n: Navigator) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message;
VAR focus: Views.View);
BEGIN
ASSERT(focus = NIL, 23);
WITH msg: Controllers.TrackMsg DO
TrackMsg(n, f, w, f.dot, msg.x, msg.y)
ELSE (* ignore other messages *)
END
END HandleCtrlMsg;
PROCEDURE (n: Navigator) HandlePropMsg (VAR msg: Properties.Message);
BEGIN
WITH msg: Properties.FocusPref DO
msg.hotFocus := TRUE
| msg: Properties.SizePref DO
IF msg.w = Views.undefined THEN msg.w := w * Ports.point END;
IF msg.h = Views.undefined THEN msg.h := (12 + 4 * (w DIV 2 - 2)) * Ports.point END
| msg: Properties.PollMsg DO
PollProp(n, msg.prop)
| msg: Properties.SetMsg DO
SetProp(n, msg.prop)
ELSE
END
END HandlePropMsg;
(* Table *)
PROCEDURE DrawField (f: Views.Frame; x, y, w, mode: INTEGER; VAR s: ARRAY OF CHAR; font: Fonts.Font);
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, Ports.defaultColor, s, font)
END
END DrawField;
PROCEDURE DrawSelection (t: Table; f: Views.Frame; show: BOOLEAN);
VAR c, x, y: INTEGER;
BEGIN
c := 0; x := 2 * f.dot - t.orgX;
WHILE c < t.selCol DO INC(x, t.width[c]); INC(c) END;
IF t.selRow >= t.orgRow THEN
y := (t.selRow + 1 - t.orgRow) * t.rowH + 3 * f.dot;
f.MarkRect(x + f.dot, y + f.dot, x + t.width[t.selCol] - 2 * f.dot, y + t.rowH - 2 * f.dot,
Ports.fill, Ports.hilite, show)
END
END DrawSelection;
PROCEDURE Select (t: Table; on: BOOLEAN);
VAR msg: SelMsg;
BEGIN
IF on # t.selected THEN
msg.show := on; Views.Broadcast(t, msg); t.selected := on
END
END Select;
PROCEDURE ViewFromSelection (t: Table): Views.View;
VAR m: TextModels.Model; w: TextModels.Writer; data: SqlDB.Row; i: INTEGER;
BEGIN
IF t.selected THEN
t.table.Read(t.selRow, data);
m := TextModels.dir.New(); w := m.NewWriter(NIL); i := 0;
WHILE data.fields[t.selCol][i] # 0X DO w.WriteChar(data.fields[t.selCol][i]); INC(i) END;
RETURN TextViews.dir.New(m)
ELSE RETURN NIL
END
END ViewFromSelection;
PROCEDURE GetTableSize (t: Table; dot: INTEGER; VAR w, h: INTEGER);
VAR c: INTEGER;
BEGIN
w := 0; h := 0;
IF (t.table # NIL) & t.table.Available() & (t.table.columns > 0) THEN
c := 0;
WHILE c < t.table.columns DO INC(w, t.width[c]); INC(c) END;
INC(w, 3 * dot);
IF t.table.rows = MAX(INTEGER) THEN h := 10000 * Ports.mm
ELSE h := (t.table.rows + 1) * t.rowH + 4 * dot
END
END
END GetTableSize;
PROCEDURE CheckPos (t: Table; x, y, dot: INTEGER; VAR col, type, p: INTEGER);
VAR c, w, h, a: INTEGER;
BEGIN
GetTableSize(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 < t.table.columns) & (x >= w + t.width[c]) DO INC(w, t.width[c]); INC(c) END;
IF (c = t.table.columns) OR (x <= w + 3 * dot) & (c > 0) THEN
col := c - 1; p := w + dot - t.orgX; type := move
ELSIF y - dot < t.rowH 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 - dot) DIV t.rowH + t.orgRow - 1; type := field;
IF p >= t.table.rows THEN type := 0 END
END
ELSE type := 0
END
END CheckPos;
PROCEDURE MoveLine (t: Table; f: Views.Frame; col, x0: INTEGER);
VAR w, h, x, y, x1, limit: INTEGER; m: SET; isDown: BOOLEAN; op: FormatOp;
BEGIN
GetTableSize(t, f.dot, 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: Table; 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 TableSections (t: Table; f: Views.Frame; vertical: BOOLEAN; VAR size, part, pos: INTEGER);
VAR c, w, max: INTEGER;
BEGIN
size := 0; part := 0; pos := 0;
IF (t.table # NIL) & t.table.Available() & (t.table.columns > 0) THEN
IF vertical THEN
size := t.table.rows;
part := (f.b - f.t) DIV t.rowH - 1;
pos := t.orgRow
ELSE
c := 0; w := 0; max := t.table.columns;
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
END TableSections;
PROCEDURE ScrollTable (t: Table; f: Views.Frame; op, pos: INTEGER; vertical: BOOLEAN);
VAR size, part, p, delta, l, t0, r, b: INTEGER;
BEGIN
IF vertical THEN
TableSections(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.gx + t.rowH + 4 * 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.rowH);
f.rider.SetRect(l, t0, r, b)
END;
t.orgRow := p
ELSE
TableSections(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 ScrollTable;
PROCEDURE HandleChar (t: Table; f: Views.Frame; ch: CHAR);
BEGIN
CASE ch OF
| 10X: ScrollTable(t, f, Controllers.decPage, 0, FALSE)
| 11X: ScrollTable(t, f, Controllers.incPage, 0, FALSE)
| 12X: ScrollTable(t, f, Controllers.decPage, 0, TRUE)
| 13X: ScrollTable(t, f, Controllers.incPage, 0, TRUE)
| 14X: ScrollTable(t, f, Controllers.gotoPos, 0, FALSE)
| 15X: ScrollTable(t, f, Controllers.gotoPos, MAX(INTEGER), FALSE)
| 16X: ScrollTable(t, f, Controllers.gotoPos, 0, TRUE)
| 17X: ScrollTable(t, f, Controllers.gotoPos, MAX(INTEGER), TRUE)
| 1CX: ScrollTable(t, f, Controllers.decLine, 0, FALSE)
| 1DX: ScrollTable(t, f, Controllers.incLine, 0, FALSE)
| 1EX: ScrollTable(t, f, Controllers.decLine, 0, TRUE)
| 1FX: ScrollTable(t, f, Controllers.incLine, 0, TRUE)
| 07X, 08X, 1BX: Select(t, FALSE)
ELSE
END
END HandleChar;
PROCEDURE (t: Table) Internalize (VAR rd: Stores.Reader);
VAR thisVersion: INTEGER; i: INTEGER;
BEGIN
t.Internalize^(rd);
IF ~rd.cancelled THEN
rd.ReadVersion(minVersion, tabVersion, thisVersion);
IF ~rd.cancelled THEN
NEW(t.sprop);
rd.ReadXString(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);
IF t.columns > 0 THEN
NEW(t.width, t.columns);
NEW(t.mode, t.columns);
FOR i := 0 TO t.columns - 1 DO
rd.ReadInt(t.width[i]);
rd.ReadInt(t.mode[i]);
END
ELSE
NEW(t.width, 10); FillArray(t.width, 0, 10, defColW);
NEW(t.mode, 10); FillArray(t.mode, 0, 10, center);
END;
SetupTable(t)
END
END
END Internalize;
PROCEDURE (t: Table) Externalize (VAR wr: Stores.Writer);
VAR i: INTEGER;
BEGIN
t.Externalize^(wr);
wr.WriteVersion(tabVersion);
wr.WriteXString(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 Externalize;
PROCEDURE (t: Table) CopyFromSimpleView (source: Views.View);
BEGIN
t.CopyFromSimpleView^(source);
WITH source: Table DO
NEW(t.sprop); t.sprop^ := source.sprop^;
t.columns := source.columns;
NEW(t.width, LEN(source.width)); CopyArray(source.width, t.width);
NEW(t.mode, LEN(source.mode)); CopyArray(source.mode, t.mode);
t.table := source.table;
SetupTable(t)
END
END CopyFromSimpleView;
PROCEDURE (t: Table) Neutralize;
BEGIN
Select(t, FALSE)
END Neutralize;
PROCEDURE (t: Table) GetBackground (VAR color: Ports.Color);
BEGIN
color := Ports.background
END GetBackground;
PROCEDURE (t: Table) Restore (f: Views.Frame; l, t1, r, b: INTEGER);
VAR row, col, x, y, w: INTEGER; data: SqlDB.Row; font: Fonts.Font;
BEGIN
IF (t.table # NIL) & t.table.Available() & (t.table.columns > 0) THEN
IF t.table.columns > LEN(t.width) THEN Expand(t, t.table.columns + 10) END;
DEC(t.rowH, t.rowH MOD f.unit);
row := SqlDB.names; y := 2 * f.dot; font := t.titFont;
WHILE (row < t.table.rows) & (y < b) DO
IF ~Views.IsPrinterFrame(f) OR (y + t.rowH < b) THEN
t.table.Read(row, data);
IF t.table.res # SqlDB.noData THEN
col := 0; x := 2 * f.dot - t.orgX;
WHILE (col < t.table.columns) & (x < r) DO
w := t.width[col];
IF x + w >= 0 THEN
f.DrawRect(x - f.dot, y, x, y + t.rowH, Ports.fill, Ports.defaultColor);
(* left vertical separation line *)
IF ~Views.IsPrinterFrame(f) OR (x + w < r) THEN
DrawField(f, x, y + t.baseOff, w - f.dot, t.mode[col], data.fields[col]^, font)
END
END;
INC(col); INC(x, w)
END;
f.DrawRect(x - f.dot, y, x, y + t.rowH, Ports.fill, Ports.defaultColor); (* right vertical separator line *)
IF Views.IsPrinterFrame(f) & (x >= r) THEN DEC(x, w) END;
IF row = SqlDB.names THEN row := t.orgRow; font := t.fldFont; INC(y, f.dot)
ELSE INC(row)
END;
INC(y, t.rowH);
f.DrawRect(f.dot - t.orgX, y - f.dot, x, y, Ports.fill, Ports.defaultColor) (* bottom line *)
ELSE y := b
END
END
END;
f.DrawRect(f.dot - t.orgX, f.dot, x, 2 * f.dot, Ports.fill, Ports.defaultColor);
f.DrawRect(f.dot - t.orgX, t.rowH + f.dot, x, t.rowH + 2 * f.dot, Ports.fill, Ports.defaultColor)
END;
END Restore;
PROCEDURE (t: Table) RestoreMarks (f: Views.Frame; l, t1, r, b: INTEGER);
BEGIN
IF (t.table # NIL) & t.table.Available() & (t.table.columns > 0) & t.selected THEN
DrawSelection(t, f, TRUE)
END
END RestoreMarks;
PROCEDURE (t: Table) HandleViewMsg (f: Views.Frame; VAR msg: Views.Message);
BEGIN
WITH msg: Views.NotifyMsg DO
IF update IN msg.opts THEN
IF (t.table # NIL) & (msg.id0 = SYSTEM.ADR(t.table^)) THEN
Views.Update(t, Views.keepFrames)
END
END
| msg: SelMsg DO
DrawSelection(t, f, msg.show)
ELSE
END
END HandleViewMsg;
PROCEDURE (t: Table) HandleCtrlMsg (f: Views.Frame;
VAR msg: Controllers.Message; VAR focus: Views.View);
VAR p, col, type: INTEGER; c, w, size, part, pos: INTEGER;
BEGIN
WITH msg: Properties.CollectMsg DO
Views.HandlePropMsg(t, msg.poll)
| msg: Properties.EmitMsg DO
Views.HandlePropMsg(t, msg.set)
| msg: Controllers.PollOpsMsg DO
IF t.selected THEN msg.valid := {Controllers.copy} END
| msg: Controllers.EditMsg DO
IF 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
| msg: Controllers.TrackMsg DO
CheckPos(t, msg.x, msg.y, f.dot, col, type, p);
IF type = move THEN MoveLine(t, f, col, p)
ELSIF type = adjust THEN ChangeAdjust(t, col, p)
ELSIF type = field THEN
CallTableNotifier(t, p, col, msg.modifiers);
Select(t, FALSE);
t.selRow := p; t.selCol := col; Select(t, TRUE)
ELSE
Select(t, FALSE)
END
| msg: Controllers.PollCursorMsg DO
CheckPos(t, msg.x, msg.y, f.dot, col, type, p);
IF type = move THEN msg.cursor := 16 (* Ports.ResizeHCursor *)
ELSIF type = adjust THEN msg.cursor := Ports.refCursor
ELSIF type = field THEN msg.cursor := Ports.tableCursor
END
| msg: Controllers.SelectMsg DO
IF ~msg.set THEN
Select(t, FALSE);
END
| msg: Controllers.PollSectionMsg DO
TableSections(t, f, msg.vertical, msg.wholeSize, msg.partSize, msg.partPos);
IF (msg.partPos > 0) & (msg.partPos > msg.wholeSize - msg.partSize) THEN
ScrollTable(t, f, Controllers.gotoPos, msg.wholeSize - msg.partSize, msg.vertical);
TableSections(t, f, msg.vertical, msg.wholeSize, msg.partSize, msg.partPos)
END;
msg.valid := msg.partSize < msg.wholeSize;
msg.done := TRUE
| msg: Controllers.ScrollMsg DO
ScrollTable(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 *)
TableSections(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 *)
TableSections(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 HandleCtrlMsg;
PROCEDURE (t: Table) HandlePropMsg (VAR msg: Properties.Message);
BEGIN
WITH msg: Properties.FocusPref DO
IF t.table # NIL THEN msg.setFocus := TRUE END
| msg: Properties.SizePref DO
IF (msg.w = Views.undefined) & (msg.h = Views.undefined) THEN
GetTableSize(t, Ports.point, msg.w, msg.h)
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: Properties.PollMsg DO
PollProp(t, msg.prop)
| msg: Properties.SetMsg DO
SetProp(t, msg.prop)
ELSE
END
END HandlePropMsg;
(* StdDirectory *)
PROCEDURE InitProp (VAR p: Controls.Prop);
BEGIN
NEW(p);
p.link := ""; p.label := ""; p.guard := ""; p.notifier := "";
p.opt[Controls.default] := FALSE; p.opt[Controls.cancel] := FALSE;
p.level := 0; p.opt[Controls.sorted] := FALSE
END InitProp;
PROCEDURE InitStdProp (VAR 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 (d: StdDirectory) NewAnchor (p: Controls.Prop): Views.View;
VAR c: Anchor;
BEGIN
NEW(c); OpenLink(c, p); RETURN c
END NewAnchor;
PROCEDURE (d: StdDirectory) NewNavigator (p: Controls.Prop): Views.View;
VAR c: Navigator;
BEGIN
NEW(c); OpenLink(c, p); RETURN c
END NewNavigator;
PROCEDURE (d: StdDirectory) NewTable (p: Controls.Prop): Views.View;
VAR c: Table;
BEGIN
NEW(c); OpenLink(c, p); InitStdProp(c.sprop);
NEW(c.width, 10); FillArray(c.width, 0, 10, defColW); (* extended on demand *)
NEW(c.mode, 10); FillArray(c.mode, 0, 10, center);
SetupTable(c); RETURN c
END NewTable;
PROCEDURE (d: StdDirectory) NewTableOn (tab: SqlDB.Table): Views.View;
VAR c: Table;
BEGIN
NEW(c); InitProp(c.prop); c.table := tab; InitStdProp(c.sprop);
c.columns := tab.columns;
NEW(c.width, tab.columns); FillArray(c.width, 0, tab.columns, defColW);
NEW(c.mode, tab.columns); FillArray(c.mode, 0, tab.columns, center);
SetupTable(c); RETURN c
END NewTableOn;
PROCEDURE SetDir* (d: Directory);
BEGIN
ASSERT(d # NIL, 20); dir := d
END SetDir;
PROCEDURE DepositAnchor*;
VAR p: Controls.Prop;
BEGIN
InitProp(p); Views.Deposit(dir.NewAnchor(p))
END DepositAnchor;
PROCEDURE DepositNavigator*;
VAR p: Controls.Prop;
BEGIN
InitProp(p); Views.Deposit(dir.NewNavigator(p))
END DepositNavigator;
PROCEDURE DepositTable*;
VAR p: Controls.Prop;
BEGIN
InitProp(p); Views.Deposit(dir.NewTable(p))
END DepositTable;
PROCEDURE Init;
VAR d: StdDirectory;
BEGIN
NEW(d); stdDir := d; dir := d
END Init;
BEGIN
Init
END SqlControls.
| Sql/Mod/Controls.odc |
MODULE SqlDB;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20070414, mf, Compile: expansion of 'native' designators corrected
- 20141027, center #19, full Unicode support for Component Pascal identifiers added
- 20151125, center #87, adding support for LONGINT in SqlDrivers.Table
"
issues = "
- ...
"
**)
IMPORT SYSTEM, Kernel, Log, Strings, Dates, Meta, Dialog, Services, SqlDrivers;
(*
The following framework-defined types are handled by this module, in
addition to the data types of the language itself:
Dialog.Currency
Dialog.List
Dialog.Combo
Dates.Date
Dates.Time
SqlDB.Blob
*)
CONST
names* = -1; types = -2;
converted* = 1; truncated* = 2; overflow* = 3; incompatible* = 4; noData* = 5;
sync* = FALSE; async* = TRUE;
showErrors* = TRUE; hideErrors* = FALSE;
readOp = -10; clearOp = -11; openOp = -12; beginOp = -13; endOp = -14;
commitOp = -15; rollbackOp = -16; callOp = -17; tcallOp = -18;
update = 2; guardCheck = 4;
varLen = 48;
maxOperations = 20;
TYPE
Database* = POINTER TO ABSTRACT RECORD
res*: INTEGER;
async*: BOOLEAN;
showErrors*: BOOLEAN
END;
Table* = POINTER TO ABSTRACT RECORD
base-: Database;
rows*, columns*: INTEGER;
res*: INTEGER;
strictNotify*: BOOLEAN (* strict notification *)
END;
String* = POINTER TO ARRAY OF CHAR;
Row* = RECORD
fields*: POINTER TO ARRAY OF String;
END;
Blob* = RECORD
len*: INTEGER;
data*: POINTER TO ARRAY OF BYTE (* not 0X terminated **)
END;
Command* = PROCEDURE (p: ANYPTR);
TableCommand* = PROCEDURE (t: Table; p: ANYPTR);
Range = POINTER TO RECORD (* list of pending update notifications *)
next: Range;
adr0, adr1: INTEGER (* address range belonging to an interactor that has been modified *)
END;
StdDatabase = POINTER TO RECORD (Database)
queue: Elem; (* list of tasks *)
tail: Elem; (* first element of low priority part in queue *)
range: Range; (* list of pending notifications *)
lastRange: Range; (* the last element in the list of ranges - allows for search optimization *)
action: Action; (* action which executes queue elements & ranges *)
id: INTEGER; (* timestamp of actually executing command *)
executing: BOOLEAN;
driver: SqlDrivers.Driver
END;
StdTable = POINTER TO RECORD (Table)
table: SqlDrivers.Table; (* current result table *)
db: StdDatabase; (* = base(StdDatabase) *)
srows: INTEGER; (* safe copy of rows *)
id: INTEGER (* table creation id *)
END;
Elem = POINTER TO RECORD (* async operations are put into queues of such elements *)
next: Elem; (* list of tasks *)
op: INTEGER;
table: StdTable;
statement: String;
item: Meta.Item;
cmd: Command;
tcmd: TableCommand;
par: ANYPTR
END;
Action = POINTER TO RECORD (Services.Action)
database: StdDatabase (* database # NIL *)
END;
Statement = RECORD (* representation of one SQL statement *)
buf: ARRAY 1024 OF CHAR; (* valid if idx < LEN(buf) *)
ext: String; (* valid if idx >= LEN(buf) *)
idx: INTEGER; (* actual length without 0X *)
blobs, last: SqlDrivers.Blob (* blob parameters *)
END;
CurrencyValue = RECORD (Meta.Value)
value: Dialog.Currency
END;
DateValue = RECORD (Meta.Value)
value: Dates.Date
END;
TimeValue = RECORD (Meta.Value)
value: Dates.Time
END;
StringValue = RECORD (Meta.Value)
value: String
END;
BlobValue = RECORD (Meta.Value)
value: Blob
END;
RowValue = RECORD (Meta.Value)
value: Row
END;
VAR
debug*: BOOLEAN;
dummy: Meta.Item; (* remains undefined *)
ptr: POINTER TO RECORD END; (* used for ptr field in contructed items *)
nullStr: ARRAY 5 OF CHAR;
(* error handling *)
PROCEDURE WriteString (s: ARRAY OF CHAR);
BEGIN
IF debug THEN Log.String(s); Log.Ln END
END WriteString;
(** Table interface **)
PROCEDURE (t: Table) InitBase* (base: Database), NEW;
BEGIN
ASSERT(base # NIL, 20); ASSERT((t.base = NIL) OR (t.base = base), 21);
t.base := base
END InitBase;
PROCEDURE (t: Table) Exec* (statement: ARRAY OF CHAR), NEW, ABSTRACT;
PROCEDURE (t: Table) Available* (): BOOLEAN, NEW, ABSTRACT;
PROCEDURE (t: Table) Read* (row: INTEGER; VAR data: ANYREC), NEW, ABSTRACT;
PROCEDURE (t: Table) Clear*, NEW, ABSTRACT;
PROCEDURE (t: Table) Call* (command: TableCommand; par: ANYPTR), NEW, ABSTRACT;
(** Database interface **)
PROCEDURE (d: Database) Exec* (statement: ARRAY OF CHAR), NEW, ABSTRACT;
PROCEDURE (d: Database) Commit*, NEW, ABSTRACT;
PROCEDURE (d: Database) Rollback*, NEW, ABSTRACT;
PROCEDURE (d: Database) Call* (command: Command; par: ANYPTR), NEW, ABSTRACT;
PROCEDURE (d: Database) NewTable* (): Table, NEW, ABSTRACT;
(* statement expansion *)
PROCEDURE ReadPath (IN s: ARRAY OF CHAR; OUT t: ARRAY OF CHAR; VAR i: INTEGER; VAR ch: CHAR);
VAR j: INTEGER;
BEGIN (* extract the designator that describes a global variable *)
j := 0;
IF Strings.IsIdentStart(ch) THEN
REPEAT
t[j] := ch; INC(j);
INC(i); ch := s[i]
UNTIL ~Strings.IsIdent(ch) & (ch # ".")
END;
t[j] := 0X
END ReadPath;
PROCEDURE AddStr (IN s: ARRAY OF CHAR; native: BOOLEAN; max: INTEGER; VAR t: Statement);
VAR i, len: INTEGER; e: String; ch: CHAR;
BEGIN (* append a string to a statement *)
IF (t.idx + max < LEN(t.buf)) & (t.ext = NIL) THEN
i := 0; ch := s[0];
WHILE (i < max) & (ch # 0X) DO
t.buf[t.idx] := ch; INC(t.idx);
IF (ch = "'") & ~native THEN t.buf[t.idx] := "'"; INC(t.idx) END;
INC(i); ch := s[i]
END
ELSE
IF t.ext = NIL THEN
len := LEN(t.buf); REPEAT len := len * 4 UNTIL t.idx + max < len;
NEW(t.ext, len); t.buf[t.idx] := 0X; t.ext^ := t.buf$
ELSIF t.idx + max >= LEN(t.ext^) THEN
len := LEN(t.ext^); REPEAT len := len * 4 UNTIL t.idx + max < len;
NEW(e, len); t.ext[t.idx] := 0X; e^ := t.ext^$; t.ext := e
END;
i := 0; ch := s[0];
WHILE (i < max) & (ch # 0X) DO
t.ext[t.idx] := ch; INC(t.idx);
IF (ch = "'") & ~native THEN t.ext[t.idx] := "'"; INC(t.idx) END;
INC(i); ch := s[i]
END
END
END AddStr;
PROCEDURE AddChar (ch: CHAR; VAR t: Statement);
VAR e: String;
BEGIN (* append a character to a statement *)
IF (t.idx < LEN(t.buf) - 1) & (t.ext = NIL) THEN
t.buf[t.idx] := ch; INC(t.idx)
ELSE
IF t.ext = NIL THEN
NEW(t.ext, 4 * LEN(t.buf)); t.buf[t.idx] := 0X; t.ext^ := t.buf$
ELSIF t.idx = LEN(t.ext^) - 1 THEN
NEW(e, 4 * LEN(t.ext^)); t.ext[t.idx] := 0X; e^ := t.ext^$; t.ext := e
END;
t.ext[t.idx] := ch; INC(t.idx)
END
END AddChar;
PROCEDURE RealToString (x: SHORTREAL; minPrec: SHORTINT; OUT s: ARRAY OF CHAR);
VAR y: REAL; res: INTEGER;
BEGIN
(* find the shortest string that can represent the number as a string *)
(* this is a hack to avoid conversion problems between binary and textual representations *)
REPEAT
Strings.RealToStringForm(x, minPrec, 0, 0, " ", s);
Strings.StringToReal(s, y, res);
INC(minPrec)
UNTIL x = SHORT(y)
END RealToString;
PROCEDURE LongToString (x: LONGINT; scale: INTEGER; OUT s: ARRAY OF CHAR);
VAR d: ARRAY 24 OF CHAR; i, j: INTEGER;
BEGIN
i := 0; j := 0;
IF x < 0 THEN s[0] := "-"; i := 1; x := -x END;
REPEAT d[j] := CHR(x MOD 10 + ORD("0")); INC(j); x := x DIV 10 UNTIL x = 0;
WHILE j <= scale DO d[j] := "0"; INC(j) END;
WHILE j > scale DO DEC(j); s[i] := d[j]; INC(i) END;
IF j > 0 THEN s[i] := "."; INC(i) END;
WHILE j > 0 DO DEC(j); s[i] := d[j]; INC(i) END;
s[i] := 0X
END LongToString;
PROCEDURE AddItem (d: StdDatabase; item: Meta.Item; native: BOOLEAN; VAR s: Statement);
TYPE Ptr = POINTER TO ARRAY [1] MAX(INTEGER) DIV 2 OF CHAR;
VAR base: Meta.Item; ok: BOOLEAN; i, len, res: INTEGER; h: ARRAY 64 OF CHAR;
mod, typ: Meta.Name; dc: CurrencyValue; dv: DateValue; dt: TimeValue; p: Ptr;
sc: Meta.Scanner; x, y: REAL; z: SHORTREAL; prec: SHORTINT;
bv: BlobValue; blob: SqlDrivers.Blob;
BEGIN (* read the value represented by an item, translate it into a string, and append this string to a statement *)
CASE item.typ OF
| Meta.byteTyp, Meta.sIntTyp, Meta.intTyp:
Strings.IntToString(item.IntVal(), h); AddStr(h, FALSE, 12, s)
| Meta.longTyp:
Strings.IntToString(item.LongVal(), h); AddStr(h, FALSE, 24, s)
| Meta.sRealTyp:
z := SHORT(item.RealVal()); prec := 7;
(* find the shortest string that can represent the number as a string *)
(* this is a hack to avoid conversion problems between binary and textual representations *)
REPEAT
Strings.RealToStringForm(z, prec, 0, 0, " ", h);
Strings.StringToReal(h, y, res);
INC(prec)
UNTIL (z = SHORT(y)) OR (prec = 10);
AddStr(h, FALSE, 20, s)
| Meta.realTyp:
x := item.RealVal(); prec := 16;
(* find the shortest string that can represent the number as a string *)
(* this is a hack to avoid conversion problems between binary and textual representations *)
REPEAT
Strings.RealToStringForm(x, prec, 0, 0, " ", h);
Strings.StringToReal(h, y, res);
INC(prec)
UNTIL (x = y) OR (prec = 19);
AddStr(h, FALSE, 28, s)
| Meta.boolTyp:
IF item.BoolVal() THEN AddChar("1", s) ELSE AddChar("0", s) END
| Meta.arrTyp:
IF item.BaseTyp() = Meta.charTyp THEN (* string *)
p := SYSTEM.VAL(Ptr, item.adr);
IF ~native THEN AddChar("'", s) END;
AddStr(p^, native, item.Len(), s);
IF ~native THEN AddChar("'", s) END
ELSE (* array of basic type *)
len := item.Len(); ASSERT(len > 0, 100);
item.Index(0, base); AddItem(d, base, native, s); i := 1;
WHILE i < len DO
AddChar(",", s); AddChar(" ", s);
item.Index(i, base); AddItem(d, base, native, s);
INC(i)
END
END
| Meta.recTyp:
item.GetTypeName(mod, typ);
IF (mod = "Dialog") & (typ = "Currency") THEN
item.GetVal(dc, ok); ASSERT(ok, 101);
LongToString(dc.value.val, dc.value.scale, h); AddStr(h, FALSE, 24, s);
ELSIF (mod = "Dialog") & (typ = "List") THEN
item.Lookup("index", base);
AddItem(d, base, native, s)
ELSIF (mod = "Dialog") & (typ = "Combo") THEN
item.Lookup("item", base);
AddItem(d, base, native, s)
ELSIF (mod = "Dates") & (typ = "Date") THEN
item.GetVal(dv, ok); ASSERT(ok, 101);
IF (dv.value.year = 0) & (dv.value.month = 0) & (dv.value.day = 0) THEN
AddStr(nullStr, FALSE, 4, s)
ELSE
IF ~native THEN AddChar("'", s) END;
Strings.IntToString(dv.value.year, h);
AddStr(h, FALSE, 8, s); AddChar("/", s);
Strings.IntToStringForm(dv.value.month, Strings.decimal, 2, "0", FALSE, h);
AddStr(h, FALSE, 4, s); AddChar("/", s);
Strings.IntToStringForm(dv.value.day, Strings.decimal, 2, "0", FALSE, h);
AddStr(h, FALSE, 4, s);
IF ~native THEN AddChar("'", s) END
END
ELSIF (mod = "Dates") & (typ = "Time") THEN
item.GetVal(dt, ok); ASSERT(ok, 101);
IF ~native THEN AddChar("'", s) END;
Strings.IntToString(dt.value.hour, h); AddStr(h, native, 8, s); AddChar(":", s);
Strings.IntToString(dt.value.minute, h); AddStr(h, native, 8, s); AddChar(":", s);
Strings.IntToString(dt.value.second, h); AddStr(h, native, 8, s);
IF ~native THEN AddChar("'", s) END
ELSIF (mod = "SqlDB") & (typ = "Blob") THEN
item.GetVal(bv, ok); ASSERT(ok, 101);
AddStr(d.driver.blobStr, FALSE, LEN(d.driver.blobStr), s);
NEW(blob); blob.len := bv.value.len; blob.data := bv.value.data;
IF s.last = NIL THEN s.blobs := blob ELSE s.last.next := blob END;
s.last := blob
ELSE
sc.ConnectTo(item);
sc.Scan; ASSERT(~sc.eos, 22);
AddItem(d, sc.this, native, s); sc.Scan;
WHILE ~sc.eos DO
AddChar(",", s); AddChar(" ", s);
AddItem(d, sc.this, native, s); sc.Scan
END
END
| Meta.ptrTyp:
item.Deref(base); AddItem(d, base, native, s)
ELSE HALT(21)
END
END AddItem;
PROCEDURE Compile (d: StdDatabase; IN s: ARRAY OF CHAR; OUT t: Statement);
VAR i: INTEGER; ch: CHAR; path: ARRAY varLen OF CHAR; quoted, native: BOOLEAN; item: Meta.Item;
BEGIN (* expand designators in an SQL statement by their current values, yielding a correct SQL statement *)
i := 0; ch := s[0]; t.idx := 0; t.ext := NIL; quoted := FALSE;
WHILE ch # 0X DO
IF (ch = ":") & ~quoted & (s[i+1] # "\") THEN
(* ":\" does not trigger Meta substitution, in order to allow for Windows path names such as in
"SELECT * FROM C:\directory\databaseName.tableName"
*)
INC(i); ch := s[i];
IF ch = "!" THEN native := TRUE; INC(i); ch := s[i] ELSE native := FALSE END;
ReadPath(s, path, i, ch); ASSERT(path # "", 20);
Meta.LookupPath(path, item); ASSERT(item.Valid(), 21); ASSERT(item.obj = Meta.varObj, 22);
AddItem(d, item, native, t)
ELSE
IF ch = "'" THEN quoted := ~quoted END;
AddChar(ch, t);
INC(i); ch := s[i]
END
END
END Compile;
PROCEDURE Execute (d: StdDatabase; VAR s: Statement);
BEGIN
IF s.ext # NIL THEN
s.ext[s.idx] := 0X; d.driver.BeginExec(s.ext^, s.blobs, d.async, d.showErrors, d.res)
ELSE
s.buf[s.idx] := 0X; d.driver.BeginExec(s.buf, s.blobs, d.async, d.showErrors, d.res)
END
END Execute;
(* item manipulation *)
PROCEDURE LookupItem (OUT i: Meta.Item; VAR r: ANYREC; async: BOOLEAN);
VAR type: Kernel.Type; mod: Kernel.Module; attr: Kernel.ItemAttr;
BEGIN (* create a meta item for a global variable passed as VAR parameter *)
attr.obj := Meta.varObj;
attr.typ := Meta.recTyp;
attr.vis := Meta.exported;
attr.adr := SYSTEM.ADR(r);
attr.mod := NIL;
attr.desc := SYSTEM.VAL(Kernel.Type, SYSTEM.TYP(r));
attr.ptr := NIL;
attr.ext := NIL;
IF async THEN (* check for global variable *)
mod := Kernel.modList;
WHILE (mod # NIL) & ((attr.adr < mod.data) OR (attr.adr >= mod.data + mod.dsize)) DO mod := mod.next END;
ASSERT(mod # NIL, 24); (* trap if variable was not found in any module *)
attr.mod := mod
ELSE
attr.mod := NIL
END;
Meta.GetThisItem(attr, i)
END LookupItem;
PROCEDURE ReadItem (item: Meta.Item; t: StdTable; row: INTEGER; VAR col: INTEGER);
VAR i, len: INTEGER; long: LONGINT; base: Meta.Item; s: Meta.Scanner; mod, typ: Meta.Name; ok: BOOLEAN;
r: REAL; date: DateValue; time: TimeValue; cy: CurrencyValue; str: StringValue;
blob: BlobValue; rw: RowValue; tab: SqlDrivers.Table;
BEGIN (* read a value from a result table, and copy it to a global variable represented by a meta item *)
tab := t.table; tab.res := 0;
CASE item.typ OF
| Meta.boolTyp:
tab.ReadInteger(row, col, i);
IF i = 0 THEN item.PutBoolVal(FALSE) ELSE item.PutBoolVal(TRUE) END;
INC(col)
| Meta.byteTyp, Meta.sIntTyp, Meta.intTyp:
tab.ReadInteger(row, col, i);
IF (item.typ = Meta.byteTyp) & ((i < MIN(BYTE)) OR (i > MAX(BYTE)))
OR (item.typ = Meta.sIntTyp) & ((i < MIN(SHORTINT)) OR (i > MAX(SHORTINT))) THEN
i := 0; tab.res := overflow
END;
item.PutIntVal(i); INC(col)
| Meta.longTyp:
tab.ReadLong(row, col, long);
item.PutLongVal(long); INC(col)
| Meta.sRealTyp, Meta.realTyp:
tab.ReadReal(row, col, r);
IF (item.typ = Meta.sRealTyp) & ((r < MIN(SHORTREAL)) OR (r > MAX(SHORTREAL))) THEN
r := 0; tab.res := overflow
END;
item.PutRealVal(r); INC(col)
| Meta.arrTyp:
IF item.BaseTyp() = Meta.charTyp THEN
tab.ReadString(row, col, SYSTEM.THISARRAY(item.adr, item.Len()));
INC(col)
ELSE
i := 0; len := item.Len();
WHILE i # len DO
item.Index(i, base); ReadItem(base, t, row, col);
INC(i)
END
END
| Meta.recTyp:
item.GetTypeName(mod, typ);
IF (mod = "Dialog") & (typ = "Currency") THEN
tab.ReadCurrency(row, col, cy.value);
item.PutVal(cy, ok); ASSERT(ok, 100);
INC(col)
ELSIF (mod = "Dialog") & (typ = "List") THEN
item.Lookup("index", base);
ReadItem(base, t, row, col)
ELSIF (mod = "Dialog") & (typ = "Combo") THEN
item.Lookup("item", base);
ReadItem(base, t, row, col)
ELSIF (mod = "Dates") & (typ = "Date") THEN
tab.ReadDate(row, col, date.value);
item.PutVal(date, ok); ASSERT(ok, 100);
INC(col)
ELSIF (mod = "Dates") & (typ = "Time") THEN
tab.ReadTime(row, col, time.value);
item.PutVal(time, ok); ASSERT(ok, 100);
INC(col)
ELSIF (mod = "SqlDB") & (typ = "Blob") THEN
tab.ReadBlob(row, col, blob.value.len, blob.value.data);
item.PutVal(blob, ok); ASSERT(ok, 100);
INC(col)
ELSE
IF (mod = "SqlDB") & (typ = "Row") THEN
item.GetVal(rw, ok); ASSERT(ok, 100);
IF (rw.value.fields = NIL) OR (LEN(rw.value.fields^) # t.columns - col) THEN
NEW(rw.value.fields, t.columns - col);
item.PutVal(rw, ok); ASSERT(ok, 100)
END
END;
s.ConnectTo(item);
s.Scan; WHILE ~s.eos DO ReadItem(s.this, t, row, col); s.Scan END
END
| Meta.ptrTyp:
item.GetBaseType(base);
IF (base.typ = Meta.arrTyp) & (base.BaseTyp() = Meta.charTyp) THEN
item.GetVal(str, ok); ASSERT(ok, 100);
IF row = types THEN tab.ReadType(col, str.value)
ELSIF row = names THEN tab.ReadName(col, str.value)
ELSE tab.ReadVarString(row, col, str.value)
END;
item.PutVal(str, ok); ASSERT(ok, 101);
INC(col)
ELSE
item.Deref(base);
ASSERT(base.obj = Meta.varObj, 23);
ReadItem(base, t, row, col)
END
| Meta.procTyp: (* skip *)
ELSE HALT(22)
END;
IF tab.res > t.res THEN t.res := tab.res END
END ReadItem;
PROCEDURE ClearItem (item: Meta.Item);
VAR s: Meta.Scanner; ok: BOOLEAN; base: Meta.Item; len, i: INTEGER;
BEGIN (* zero a global variable represented by a meta item *)
ASSERT(item.Valid(), 20);
IF item.vis = Meta.exported THEN
CASE item.typ OF
| Meta.byteTyp, Meta.sIntTyp, Meta.intTyp:
item.PutIntVal(0)
| Meta.longTyp:
item.PutLongVal(0)
| Meta.sRealTyp, Meta.realTyp:
item.PutRealVal(0)
| Meta.boolTyp:
item.PutBoolVal(FALSE)
| Meta.arrTyp:
IF item.BaseTyp() = Meta.charTyp THEN
item.PutStringVal("", ok); ASSERT(ok, 22)
ELSE
i := 0; len := item.Len();
WHILE i # len DO
item.Index(i, base); ClearItem(base);
INC(i)
END
END
| Meta.recTyp:
s.ConnectTo(item);
s.Scan; WHILE ~s.eos DO ClearItem(s.this); s.Scan END
| Meta.ptrTyp:
item.Deref(base);
IF base.obj = Meta.varObj THEN ClearItem(base) END
END
END
END ClearItem;
(* notification *)
PROCEDURE NotifyLater (d: StdDatabase; adr0, adr1: INTEGER);
VAR r: Range;
BEGIN (* register an address range for later notification via an action *)
r := d.range;
IF r = NIL THEN
Services.DoLater(d.action, Services.now)
ELSE
IF (d.lastRange # NIL) & (d.lastRange.adr1 < adr0) THEN
r := NIL
ELSE
WHILE (r # NIL) & ((r.adr1 < adr0) OR (r.adr0 > adr1)) DO r := r.next END
END
END;
IF r # NIL THEN
r.adr0 := MIN(r.adr0, adr0); r.adr1 := MAX(r.adr1, adr1)
ELSE
NEW(r); r.adr0 := adr0; r.adr1 := adr1;
r.next := d.range; d.range := r;
d.lastRange := r
END
END NotifyLater;
PROCEDURE Update (d: StdDatabase);
VAR r: Range;
BEGIN (* notify an address range immediately *)
r := d.range;
WHILE r # NIL DO
Dialog.Notify(r.adr0, r.adr1, {update});
r := r.next
END;
IF d.range # NIL THEN Dialog.Notify(0, 0, {guardCheck}) END; (* check only once, after all updates *)
d.range := NIL
END Update;
(* delayed operations *)
PROCEDURE DoRead (t: StdTable; row: INTEGER; VAR item: Meta.Item);
VAR col: INTEGER;
BEGIN
WriteString("DoRead");
ASSERT(t.columns > 0, 20);
IF row < t.rows THEN
col := 0; t.res := 0;
ReadItem(item, t, row, col);
ELSE
ClearItem(item);
t.res := noData
END;
IF t.strictNotify THEN
Dialog.Notify(item.adr, item.adr + item.Size(), {update, guardCheck});
ELSE
NotifyLater(t.db, item.adr, item.adr + item.Size())
END
END DoRead;
PROCEDURE DoClear (t: StdTable);
BEGIN
WriteString("DoClear");
IF (t.table # NIL) & (t.db.driver # NIL) THEN
t.table.Close; t.table := NIL
END;
t.res := 0; t.rows := 0; t.columns := 0; t.srows := 0
END DoClear;
PROCEDURE DoEndOpen (d: StdDatabase);
VAR res: INTEGER;
BEGIN
WriteString("DoEndOpen");
ASSERT(d.driver.Ready(), 100);
d.driver.EndOpen(res);
d.res := res
END DoEndOpen;
PROCEDURE DoBeginExec (d: StdDatabase; t: StdTable; VAR statement: ARRAY OF CHAR);
VAR res: INTEGER; s: Statement;
BEGIN
WriteString("DoBeginExec");
Compile(d, statement, s);
IF debug THEN
IF s.ext # NIL THEN
s.ext[s.idx] := 0X; WriteString(s.ext^)
ELSE
s.buf[s.idx] := 0X; WriteString(s.buf)
END
END;
IF t # NIL THEN DoClear(t) END;
Execute(d, s);
IF t # NIL THEN t.res := d.res END
END DoBeginExec;
PROCEDURE DoEndExec (d: StdDatabase; t: StdTable);
VAR dt: SqlDrivers.Table; rows, columns: INTEGER;
BEGIN
IF d.res = 0 THEN
WriteString("DoEndExec");
ASSERT(d.driver.Ready(), 100);
d.driver.EndExec(dt, rows, columns, d.res);
IF t # NIL THEN
t.rows := rows; t.srows := rows; t.columns := columns;
t.table := dt; t.res := d.res;
IF t.strictNotify THEN
Dialog.Notify(SYSTEM.ADR(t^), SYSTEM.ADR(t^) + 4, {update, guardCheck})
ELSE
NotifyLater(t.db, SYSTEM.ADR(t^), SYSTEM.ADR(t^) + 4)
END
ELSE
ASSERT(columns = 0, 21);
END
END
END DoEndExec;
PROCEDURE DoCommit (d: StdDatabase; accept: BOOLEAN);
BEGIN
WriteString("DoCommit");
d.driver.Commit(accept, d.res)
END DoCommit;
(* serialization *)
PROCEDURE Reset (d: StdDatabase);
VAR e: Elem;
BEGIN (* trap cleanup *)
e := d.queue; d.queue := NIL; d.range := NIL; d.tail := NIL;
WHILE e # NIL DO
IF e.table # NIL THEN e.table.Clear END;
IF e.item.Valid() THEN ClearItem(e.item) END;
e := e.next
END
END Reset;
PROCEDURE Process (d: StdDatabase);
VAR e: Elem; operations: INTEGER;
BEGIN (* this is the heart of the processing of asynchronous operations *)
WriteString("start processing");
operations := 0;
WHILE (d.queue # NIL) & (operations < maxOperations) & d.driver.Ready() DO
e := d.queue; d.queue := e.next; d.tail := d.queue; INC(operations);
CASE e.op OF
| openOp: DoEndOpen(d)
| beginOp: DoBeginExec(d, e.table, e.statement^)
| endOp: DoEndExec(d, e.table)
| commitOp: DoCommit(d, TRUE)
| rollbackOp: DoCommit(d, FALSE)
| clearOp: DoClear(e.table)
| callOp: INC(d.id); e.cmd(e.par)
| tcallOp: INC(d.id); e.table.id := d.id; e.tcmd(e.table, e.par)
ELSE DoRead(e.table, e.op, e.item)
END;
d.tail := NIL
END;
WriteString("stop processing")
END Process;
PROCEDURE (a: Action) Do;
VAR d: StdDatabase;
BEGIN (* async operations are advanced by an action, which belongs to the database object *)
d := a.database;
IF d.executing THEN (* trapped *)
Reset(d)
ELSIF (d.queue # NIL) OR (d.range # NIL) THEN
Services.DoLater(a, Services.now);
d.executing := TRUE;
Process(d);
Update(d)
END;
d.executing := FALSE
END Do;
PROCEDURE Put (d: StdDatabase; op: INTEGER; t: StdTable; s: ARRAY OF CHAR;
VAR i: Meta.Item; cmd: Command; tcmd: TableCommand; par: ANYPTR);
VAR e, h, k: Elem;
BEGIN (* put a SQL statement into a queue for later async processing *)
NEW(e); e.op := op; e.table := t; e.item := i; e.cmd := cmd; e.tcmd := tcmd; e.par := par;
IF s # "" THEN NEW(e.statement, LEN(s)); e.statement^ := s$ END;
h := d.queue;
IF h = NIL THEN Services.DoLater(d.action, Services.now) END; (* start process *)
IF h = d.tail THEN
e.next := h; d.queue := e
ELSIF op >= clearOp THEN (* clear, read: insert after last op on same table *)
k := NIL;
WHILE h # d.tail DO
IF h.table = t THEN k := h END;
h := h.next
END;
IF k = NIL THEN e.next := d.queue; d.queue := e
ELSE e.next := k.next; k.next := e
END
ELSE
WHILE h.next # d.tail DO h := h.next END;
e.next := h.next; h.next := e
END
END Put;
PROCEDURE Synch (d: StdDatabase; op: INTEGER; t: StdTable): BOOLEAN;
(* check whether it is necessary to enqueue this operation *)
(* TRUE if Put would insert at beginning of queue *)
VAR h: Elem;
BEGIN
h := d.queue;
IF h = d.tail THEN
RETURN TRUE
ELSIF op >= clearOp THEN
WHILE (h # d.tail) & (h.table # t) DO h := h.next END;
RETURN h = d.tail
ELSE
RETURN FALSE
END
END Synch;
(* StdTable *)
PROCEDURE (t: StdTable) Exec (statement: ARRAY OF CHAR);
BEGIN
WriteString("Table Exec");
ASSERT(t.db.driver # NIL, 100); ASSERT(statement # "", 20);
ASSERT(~t.db.executing OR (t.id >= t.db.id), 21);
IF Synch(t.db, beginOp, t) THEN DoBeginExec(t.db, t, statement)
ELSE Put(t.db, beginOp, t, statement, dummy, NIL, NIL, NIL)
END;
IF Synch(t.db, endOp, t) & t.db.driver.Ready() THEN DoEndExec(t.db, t)
ELSE Put(t.db, endOp, t, "", dummy, NIL, NIL, NIL)
END
END Exec;
PROCEDURE (t: StdTable) Available (): BOOLEAN;
BEGIN
RETURN Synch(t.db, readOp, t)
END Available;
PROCEDURE (t: StdTable) Read (row: INTEGER; VAR data: ANYREC);
VAR item: Meta.Item;
BEGIN
WriteString("Read");
ASSERT((row >= 0) OR (data IS Row) & (row >= -2), 21);
ASSERT(~t.db.executing OR (t.id >= t.db.id), 25);
IF Synch(t.db, readOp, t) THEN
LookupItem(item, data, FALSE);
DoRead(t, row, item)
ELSE
LookupItem(item, data, TRUE);
Put(t.db, row, t, "", item, NIL, NIL, NIL)
END
END Read;
PROCEDURE (t: StdTable) Clear;
BEGIN
WriteString("Clear");
ASSERT(~t.db.executing OR (t.id >= t.db.id), 20);
IF Synch(t.db, clearOp, t) THEN DoClear(t)
ELSE Put(t.db, clearOp, t, "", dummy, NIL, NIL, NIL)
END
END Clear;
PROCEDURE (t: StdTable) Call (command: TableCommand; par: ANYPTR);
BEGIN
WriteString("Table Call");
ASSERT(command # NIL, 20);
ASSERT(~t.db.executing OR (t.id >= t.db.id), 21);
IF Synch(t.db, tcallOp, t) THEN command(t, par)
ELSE Put(t.db, tcallOp, t, "", dummy, NIL, command, par)
END
END Call;
(* StdDatabase *)
PROCEDURE (d: StdDatabase) Exec (statement: ARRAY OF CHAR);
BEGIN
WriteString("Exec");
ASSERT(d.driver # NIL, 100); ASSERT(statement # "", 20);
IF Synch(d, beginOp, NIL) THEN DoBeginExec(d, NIL, statement)
ELSE Put(d, beginOp, NIL, statement, dummy, NIL, NIL, NIL)
END;
IF Synch(d, endOp, NIL) & d.driver.Ready() THEN DoEndExec(d, NIL)
ELSE Put(d, endOp, NIL, "", dummy, NIL, NIL, NIL)
END
END Exec;
PROCEDURE (d: StdDatabase) Commit;
BEGIN
WriteString("Commit");
IF Synch(d, commitOp, NIL) THEN DoCommit(d, TRUE)
ELSE Put(d, commitOp, NIL, "", dummy, NIL, NIL, NIL)
END
END Commit;
PROCEDURE (d: StdDatabase) Rollback;
BEGIN
WriteString("Rollback");
IF Synch(d, rollbackOp, NIL) THEN DoCommit(d, FALSE)
ELSE Put(d, rollbackOp, NIL, "", dummy, NIL, NIL, NIL)
END
END Rollback;
PROCEDURE (d: StdDatabase) Call (command: Command; par: ANYPTR);
BEGIN
WriteString("Call");
ASSERT(command # NIL, 20);
IF Synch(d, callOp, NIL) THEN command(par)
ELSE Put(d, callOp, NIL, "", dummy, command, NIL, par)
END
END Call;
PROCEDURE (d: StdDatabase) NewTable (): Table;
VAR t: StdTable;
BEGIN
ASSERT(d.driver # NIL, 100);
NEW(t);
t.res := 0; t.rows := 0; t.columns := 0; t.strictNotify := FALSE;
t.table := NIL; t.srows := 0; t.id := d.id;
t.InitBase(d); t.db := d;
d.res := 0;
RETURN t
END NewTable;
PROCEDURE OpenDatabase* (protocol, id, password, datasource: ARRAY OF CHAR;
async, showErrors: BOOLEAN; OUT d: Database; OUT res: INTEGER);
VAR driver: SqlDrivers.Driver; sd: StdDatabase;
BEGIN
WriteString("OpenDatabase");
ASSERT(protocol # "", 20);
SqlDrivers.Open(protocol, id, password, datasource, async, showErrors, driver, res);
IF res = 0 THEN
ASSERT(driver # NIL, 100);
NEW(sd); sd.driver := driver; sd.queue := NIL; sd.tail := NIL;
sd.async := async; sd.showErrors := showErrors;
NEW(sd.action); sd.action.database := sd;
IF driver.Ready() THEN DoEndOpen(sd)
ELSE Put(sd, openOp, NIL, "", dummy, NIL, NIL, NIL)
END;
sd.res := 0; d := sd
ELSE
d := NIL
END
END OpenDatabase;
BEGIN
NEW(ptr);
nullStr := "null"
END SqlDB.
| Sql/Mod/DB.odc |
MODULE SqlDrivers;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20151125, center #87, adding support for LONGINT in SqlDrivers.Table
"
issues = "
- ...
"
**)
IMPORT Meta, Dates, Dialog;
CONST
noDriverMod = 1;
noDriverProc = 2;
wrongDriverType = 3;
connectionsExceeded = 4;
outOfTables = 5;
notExecutable = 6;
cannotOpenDB = 7;
wrongIdentification = 8;
tooManyBlobs = 9;
converted = 1;
truncated = 2;
overflow = 3;
incompatible = 4;
noData = 5;
TYPE
Driver* = POINTER TO ABSTRACT RECORD
blobStr-: ARRAY 8 OF CHAR;
open: BOOLEAN;
tables: INTEGER; (* number of currently open tables for this driver *)
END;
Table* = POINTER TO ABSTRACT RECORD
(** an open table must anchor its driver; a closed table must not anchor it **)
res*: INTEGER; (** sticky result, replaced by higher values only **)
open: BOOLEAN;
driver: Driver (* only used to prevent too early garbage collection of driver *)
END;
String* = POINTER TO ARRAY OF CHAR;
Blob* = POINTER TO RECORD
len*: INTEGER;
data*: POINTER TO ARRAY OF BYTE; (** not 0X terminated **)
next*: Blob
END;
DriverAllocator = PROCEDURE (id, password, datasource: ARRAY OF CHAR;
async, showErr: BOOLEAN; OUT d: Driver; OUT res: INTEGER);
(* Post: res = 0 <=> connection has started and should be completed later with EndOpen
res = 0 <=> d # NIL
~async & (res = 0) => d.Ready() *)
PROCEDURE (d: Driver) Ready* (): BOOLEAN, NEW, ABSTRACT;
PROCEDURE (d: Driver) EndOpen* (OUT res: INTEGER), NEW, ABSTRACT;
(** Pre: d.Ready() 20 **)
PROCEDURE (d: Driver) BeginExec* (IN statement: ARRAY OF CHAR; data: Blob;
async, showErrors: BOOLEAN; OUT res: INTEGER), NEW, ABSTRACT;
(** asynchronous execution is optional, a driver may legally execute synchronously if async is TRUE **)
(** Pre: statement # "" 20
no other execution started 21 **)
(** Post: res = 0 <=> execution has started and should be completed later with EndExec
~async => d.Ready() **)
PROCEDURE (d: Driver) EndExec* (VAR t: Table; OUT rows, columns, res: INTEGER), NEW, ABSTRACT;
(** Pre: execution must have been started successfully with BeginExec 20
d.Ready() 21 **)
(** Post: res = 0 <=> (t # NIL) OR (rows = 0) & (columns = 0) **)
PROCEDURE (d: Driver) Commit* (accept: BOOLEAN; OUT res: INTEGER), NEW, ABSTRACT;
PROCEDURE (d: Driver) Cleanup-, NEW, EMPTY;
PROCEDURE (d: Driver) Close*, NEW;
BEGIN
IF d.open THEN
IF d.tables = 0 THEN
d.Cleanup (* release driver info *)
END;
d.open := FALSE;
END
END Close;
PROCEDURE (d: Driver) Init* (blobStr: ARRAY OF CHAR), NEW;
BEGIN
d.blobStr := blobStr$;
d.open := TRUE
END Init;
PROCEDURE (d: Driver) FINALIZE-;
BEGIN
d.Close
END FINALIZE;
PROCEDURE (t: Table) ReadInteger* (row, column: INTEGER; OUT val: INTEGER), NEW, ABSTRACT;
(** Pre: row >= 0 20
row < rows 21
column >= 0 22
column < columns 23 **)
PROCEDURE (t: Table) ReadLong* (row, column: INTEGER; OUT val: LONGINT), NEW, ABSTRACT;
(** Pre: row >= 0 20
row < rows 21
column >= 0 22
column < columns 23 **)
PROCEDURE (t: Table) ReadReal* (row, column: INTEGER; OUT val: REAL), NEW, ABSTRACT;
(** Pre: row >= 0 20
row < rows 21
column >= 0 22
column < columns 23 **)
PROCEDURE (t: Table) ReadDate* (row, column: INTEGER; OUT val: Dates.Date), NEW, ABSTRACT;
(** Pre: row >= 0 20
row < rows 21
column >= 0 22
column < columns 23 **)
PROCEDURE (t: Table) ReadTime* (row, column: INTEGER; OUT val: Dates.Time), NEW, ABSTRACT;
(** Pre: row >= 0 20
row < rows 21
column >= 0 22
column < columns 23 **)
PROCEDURE (t: Table) ReadCurrency* (row, column: INTEGER; OUT val: Dialog.Currency), NEW, ABSTRACT;
(** Pre: row >= 0 20
row < rows 21
column >= 0 22
column < columns 23 **)
PROCEDURE (t: Table) ReadString* (row, column: INTEGER; OUT str: ARRAY OF CHAR), NEW, ABSTRACT;
(** Pre: row >= 0 20
row < rows 21
column >= 0 22
column < columns 23 **)
PROCEDURE (t: Table) ReadVarString* (row, column: INTEGER; OUT str: String), NEW, ABSTRACT;
(** Pre: row >= 0 20
row < rows 21
column >= 0 22
column < columns 23 **)
PROCEDURE (t: Table) ReadBlob* (row, column: INTEGER; OUT len: INTEGER;
OUT data: POINTER TO ARRAY OF BYTE), NEW, ABSTRACT;
(** Pre: row >= 0 20
row < rows 21
column >= 0 22
column < columns 23 **)
PROCEDURE (t: Table) ReadName* (column: INTEGER; OUT str: String), NEW, ABSTRACT;
(** Pre: column >= 0 20
column < columns 21 **)
PROCEDURE (t: Table) ReadType* (column: INTEGER; OUT str: String), NEW, ABSTRACT;
(** Pre: column >= 0 20
column < columns 21 *)
PROCEDURE (t: Table) Cleanup-, NEW, EMPTY;
PROCEDURE (t: Table) Close*, NEW;
BEGIN
IF t.open THEN
t.Cleanup; (* release table info *)
DEC(t.driver.tables);
IF (t.driver.tables = 0) & ~t.driver.open THEN
t.driver.Cleanup (* release driver info *)
END;
t.driver := NIL; (* allow for garbage collection of driver *)
t.open := FALSE
END
END Close;
PROCEDURE (t: Table) Init* (d: Driver), NEW;
BEGIN
ASSERT(d.open, 20);
t.driver := d; INC(d.tables);
t.open := TRUE
END Init;
PROCEDURE (t: Table) FINALIZE-;
BEGIN
t.Close
END FINALIZE;
PROCEDURE Open* (protocol, id, password, datasource: ARRAY OF CHAR;
async, showErrors: BOOLEAN; OUT d: Driver; OUT res: INTEGER);
VAR ok: BOOLEAN; m, p: Meta.Item; mod: Meta.Name;
v: RECORD (Meta.Value)
Open: DriverAllocator
END;
BEGIN
ASSERT(protocol # "", 20);
mod := protocol$; Meta.Lookup(mod, m); d := NIL; res := 0;
IF m.obj = Meta.modObj THEN
m.Lookup("Open", p);
IF p.obj = Meta.procObj THEN
p.GetVal(v, ok);
IF ok THEN
v.Open(id, password, datasource, async, showErrors, d, res);
ELSE res := wrongDriverType
END
ELSE res := noDriverProc
END
ELSE res := noDriverMod
END
END Open;
END SqlDrivers.
| Sql/Mod/Drivers.odc |
MODULE SqlObxDB;
(**
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 Dialog, SqlDB;
CONST
protocol = "SqlOdbc";
id = ""; password = "";
datasource = "Test Database";
VAR
company*: RECORD
id*: INTEGER;
name*: ARRAY 32 OF CHAR;
ceo*: ARRAY 32 OF CHAR;
employees*: INTEGER
END;
dirty*: BOOLEAN; (* company is dirty *)
max*: RECORD
value*: INTEGER
END;
searchId*: INTEGER;
table*: SqlDB.Table;
PROCEDURE Reset;
BEGIN
company.id := 0;
company.name := "";
company.ceo := "";
company.employees := 0;
dirty := FALSE;
Dialog.Update(company)
END Reset;
PROCEDURE Open*;
VAR d: SqlDB.Database; res: INTEGER;
BEGIN
SqlDB.OpenDatabase(protocol, id, password, datasource, SqlDB.async, SqlDB.hideErrors, d, res);
IF d # NIL THEN
table := d.NewTable()
END
END Open;
PROCEDURE Closed* (): BOOLEAN;
BEGIN
RETURN table = NIL
END Closed;
PROCEDURE Insert*;
BEGIN
table.Exec("SELECT MAX(id) FROM Companies");
table.Read(0, max);
company.id := max.value + 1; (* generate a unique key *)
table.base.Exec("INSERT INTO Companies VALUES (:SqlObxDB.company)");
table.base.Commit;
(* now the contents of c is inconsistent with database *)
table.Exec("SELECT * FROM Companies WHERE id = :SqlObxDB.company.id");
table.Read(0, company); dirty := FALSE
END Insert;
PROCEDURE Update*;
BEGIN
table.base.Exec("DELETE FROM Companies WHERE id = :SqlObxDB.company.id");
table.base.Exec("INSERT INTO Companies VALUES (:SqlObxDB.company)");
table.base.Commit;
(* now the contents of table is inconsistent with database *)
table.Exec("SELECT * FROM Companies WHERE id = :SqlObxDB.company.id");
table.Read(0, company); dirty := FALSE
END Update;
PROCEDURE Delete*;
BEGIN
table.base.Exec("DELETE FROM Companies WHERE id = :SqlObxDB.company.id");
table.base.Commit;
(* now the contents of table is inconsistent with database *)
table.Clear; (* company has become stale *)
Reset (* clear interactor *)
END Delete;
PROCEDURE Revert*;
BEGIN
IF company.id > 0 THEN
table.Exec("SELECT * FROM Companies WHERE id = :SqlObxDB.company.id");
table.Read(0, company); dirty := FALSE
ELSE
table.Clear;
Reset (* clear interactor *)
END
END Revert;
PROCEDURE Find*;
BEGIN
table.Exec("SELECT * FROM Companies WHERE id = :SqlObxDB.searchId");
table.Read(0, company); dirty := FALSE
END Find;
PROCEDURE SetTestData*;
VAR d: SqlDB.Database;
BEGIN
d := table.base;
d.Exec("DELETE FROM Companies WHERE id > 0");
d.Exec("DELETE FROM Ownership WHERE owner > 0");
(* single company *)
d.Exec("INSERT INTO Companies VALUES (11, 'Test', 'Bill', 234)");
(* two companies (tree) *)
d.Exec("INSERT INTO Companies VALUES (12, 'Test', 'Bill', 234)");
d.Exec("INSERT INTO Companies VALUES (13, 'Test company AG', 'John', 45)");
d.Exec("INSERT INTO Ownership VALUES (12, 13, 100)");
(* four companies (with ring) *)
d.Exec("INSERT INTO Companies VALUES (14, 'Test', 'Bill', 234)");
d.Exec("INSERT INTO Companies VALUES (15, 'Test company AG', 'John', 45)");
d.Exec("INSERT INTO Companies VALUES (16, 'Test Services GmbH', 'Jim', 23000)");
d.Exec("INSERT INTO Companies VALUES (17, 'Test Commands & Co.', 'Mary', 523)");
d.Exec("INSERT INTO Ownership VALUES (14, 15, 50)");
d.Exec("INSERT INTO Ownership VALUES (15, 17, 100)");
d.Exec("INSERT INTO Ownership VALUES (16, 15, 50)");
d.Exec("INSERT INTO Ownership VALUES (15, 17, 100)");
(* four companies (tree) *)
d.Exec("INSERT INTO Companies VALUES (18, 'Test', 'Bill', 234)");
d.Exec("INSERT INTO Companies VALUES (19, 'Test company AG', 'John', 45)");
d.Exec("INSERT INTO Companies VALUES (20, 'Test Services GmbH', 'Jim', 23000)");
d.Exec("INSERT INTO Companies VALUES (21, 'Test Commands & Co.', 'Mary', 523)");
d.Exec("INSERT INTO Ownership VALUES (18, 19, 20)");
d.Exec("INSERT INTO Ownership VALUES (18, 20, 30)");
d.Exec("INSERT INTO Ownership VALUES (18, 21, 50)");
(* most complex example *)
d.Exec("INSERT INTO Companies VALUES (1, 'Test', 'Bill', 234)");
d.Exec("INSERT INTO Companies VALUES (2, 'Test company AG', 'John', 45)");
d.Exec("INSERT INTO Companies VALUES (3, 'Test Services GmbH', 'Jim', 23000)");
d.Exec("INSERT INTO Companies VALUES (4, 'Test Commands & Co.', 'Mary', 523)");
d.Exec("INSERT INTO Companies VALUES (5, 'Test Views KG', 'Frank', 17)");
d.Exec("INSERT INTO Companies VALUES (6, 'Test Genossenschaft', 'Hans', 2109)");
d.Exec("INSERT INTO Companies VALUES (7, 'Test Mentoring, Inc.', 'Marlis', 128)");
d.Exec("INSERT INTO Companies VALUES (8, 'Test Training Plc.', 'Paul', 4)");
d.Exec("INSERT INTO Companies VALUES (9, 'Test Trainers SA', 'Jean', 87)");
d.Exec("INSERT INTO Companies VALUES (10, 'Test Wrappers AB', 'Gordon', 912)");
d.Exec("INSERT INTO Ownership VALUES (1, 2, 100)");
d.Exec("INSERT INTO Ownership VALUES (1, 3, 100)");
d.Exec("INSERT INTO Ownership VALUES (2, 4, 100)");
d.Exec("INSERT INTO Ownership VALUES (2, 5, 100)");
d.Exec("INSERT INTO Ownership VALUES (3, 6, 100)");
d.Exec("INSERT INTO Ownership VALUES (3, 7, 100)");
d.Exec("INSERT INTO Ownership VALUES (7, 8, 100)");
d.Exec("INSERT INTO Ownership VALUES (5, 9, 49)");
d.Exec("INSERT INTO Ownership VALUES (8, 9, 51)");
d.Exec("INSERT INTO Ownership VALUES (9, 10, 100)");
d.Commit
END SetTestData;
BEGIN
searchId := 1
END SqlObxDB.
| Sql/Mod/ObxDB.odc |
MODULE SqlObxExt;
(**
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 SqlDB;
CONST
protocol = "SqlOdbc";
id = ""; password = "";
datasource = "Test Database";
VAR
company0*, company1*: RECORD
id*: INTEGER;
name*: ARRAY 32 OF CHAR
END;
ownership*: RECORD
owner*, owned*: INTEGER;
percent*: INTEGER
END;
VAR table*: SqlDB.Table;
PROCEDURE Open*;
VAR d: SqlDB.Database; res: INTEGER;
BEGIN
SqlDB.OpenDatabase(protocol, id, password, datasource, SqlDB.async, SqlDB.hideErrors, d, res);
IF d # NIL THEN
table := d.NewTable()
END
END Open;
PROCEDURE FindOwner*;
BEGIN
table.Exec("SELECT * FROM Companies WHERE id = :SqlObxExt.company0.id");
table.Read(0, company0);
table.Exec("SELECT * FROM Ownership WHERE owner = :SqlObxExt.company0.id AND owned = :SqlObxExt.company1.id");
table.Read(0, ownership)
END FindOwner;
PROCEDURE FindOwned*;
BEGIN
table.Exec("SELECT * FROM Companies WHERE id = :SqlObxExt.company1.id");
table.Read(0, company1);
table.Exec("SELECT * FROM Ownership WHERE owner = :SqlObxExt.company0.id AND owned = :SqlObxExt.company1.id");
table.Read(0, ownership)
END FindOwned;
PROCEDURE UpdatePercent*;
BEGIN
ownership.owner := company0.id; ownership.owned := company1.id;
table.base.Exec("DELETE FROM Ownership WHERE owner = :SqlObxExt.ownership.owner AND owned = :SqlObxExt.ownership.owned");
table.base.Exec("INSERT INTO Ownership VALUES (:SqlObxExt.ownership)");
table.base.Commit;
(* now the contents of table is inconsistent with database *)
table.Exec("SELECT * FROM Ownership WHERE owner = :SqlObxExt.ownership.owner AND owned = :SqlObxExt.ownership.owned");
table.Read(0, ownership)
END UpdatePercent;
END SqlObxExt.
| Sql/Mod/ObxExt.odc |
MODULE SqlObxGen;
(**
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 Views, SqlDB, SqlObxDB, SqlObxNets, SqlObxViews;
CONST
protocol = "SqlOdbc";
id = ""; password = "";
datasource = "Test Database";
TYPE
Node = POINTER TO RECORD
next: Node;
id: INTEGER
END;
VAR
company*: RECORD
id*: INTEGER;
name*: ARRAY 32 OF CHAR
END;
ownership*: RECORD
owner*, owned*: INTEGER;
percent*: INTEGER
END;
VAR
set, queue: Node;
g: SqlObxNets.Net;
PROCEDURE Marked (id: INTEGER): BOOLEAN;
VAR h: Node;
BEGIN (* test whether id is in set *)
h := set; WHILE (h # NIL) & (h.id # id) DO h := h.next END;
RETURN h # NIL
END Marked;
PROCEDURE Mark (id: INTEGER);
VAR h: Node;
BEGIN (* include id in set (not idempotent) *)
NEW(h); h.id := id; h.next := set; set := h
END Mark;
PROCEDURE Enqueue (id: INTEGER);
VAR h: Node;
BEGIN (* insert id at end of queue (idempotent) *)
IF queue = NIL THEN
NEW(queue); h := queue
ELSE
h := queue; WHILE (h.next # NIL) & (h.id # id) DO h := h.next END;
IF h.id # id THEN NEW(h.next); h := h.next END
END;
h.id := id
END Enqueue;
PROCEDURE Dequeue (VAR id: INTEGER);
BEGIN (* remove first queue element *)
IF queue # NIL THEN
id := queue.id; queue := queue.next
ELSE
id := 0
END
END Dequeue;
PROCEDURE ProcessCompany (t: SqlDB.Table; p: ANYPTR);
VAR h: SqlObxNets.Net; cp: SqlObxNets.Company;
BEGIN (* process all companies in set with id > 0 *)
ASSERT(t.rows = 1, 20);
t.Read(0, company);
SqlObxNets.AddCompany(g, company.id, company.name, "", 0);
WHILE (set # NIL) & (set.id < 0) DO set := set.next END;
IF set # NIL THEN
SqlObxDB.searchId := set.id; ASSERT(set.id > 0, 100); set := set.next;
t.Exec("SELECT id, name FROM Companies WHERE id = :SqlObxDB.searchId");
t.Call(ProcessCompany, NIL)
ELSE
cp := SqlObxNets.ThisCompany(g, company.id); h := g; g := NIL; Views.OpenView(SqlObxViews.New(h, cp))
END
END ProcessCompany;
PROCEDURE ^ConsumeCompany(t: SqlDB.Table; p: ANYPTR);
PROCEDURE ProduceCompanies (t: SqlDB.Table; p: ANYPTR);
VAR i: INTEGER;
BEGIN
i := 0;
WHILE i < t.rows DO
t.Read(i, ownership);
SqlObxNets.AddOwnership(g, ownership.owner, ownership.owned, ownership.percent);
Enqueue(ownership.owner); Enqueue(-ownership.owner);
Enqueue(ownership.owned); Enqueue(-ownership.owned);
INC(i)
END;
t.Call(ConsumeCompany, NIL)
END ProduceCompanies;
PROCEDURE ConsumeCompany (t: SqlDB.Table; p: ANYPTR);
VAR id: INTEGER;
BEGIN
Dequeue(id); WHILE (id # 0) & Marked(id) DO Dequeue(id) END;
IF id # 0 THEN (* ~Marked(id) *)
Mark(id);
IF id > 0 THEN (* select owner *)
SqlObxDB.searchId := id;
t.Exec("SELECT * FROM Ownership WHERE owned = :SqlObxDB.searchId");
ELSE (* select owned *)
SqlObxDB.searchId := -id;
t.Exec("SELECT * FROM Ownership WHERE owner = :SqlObxDB.searchId")
END;
t.Call(ProduceCompanies, NIL)
ELSE (* queue is empty *)
ASSERT(queue = NIL, 100);
WHILE (set # NIL) & (set.id < 0) DO set := set.next END; ASSERT(set # NIL, 101); ASSERT(set.id > 0, 102);
SqlObxDB.searchId := set.id; set := set.next;
t.Exec("SELECT id, name FROM Companies WHERE id = :SqlObxDB.searchId");
t.Call(ProcessCompany, NIL)
END
END ConsumeCompany;
PROCEDURE GenNet*;
VAR d: SqlDB.Database; res: INTEGER; t: SqlDB.Table;
BEGIN
ASSERT(SqlObxDB.searchId > 0, 20);
SqlDB.OpenDatabase(protocol, id, password, datasource, SqlDB.async, SqlDB.hideErrors, d, res);
ASSERT(d # NIL, 100);
t := d.NewTable();
set := NIL; queue := NIL; g := SqlObxNets.New();
company.id := SqlObxDB.searchId;
Enqueue(company.id); Enqueue(-company.id); (* produce first company *)
t.Call(ConsumeCompany, NIL);
t.Clear
END GenNet;
END SqlObxGen.
| Sql/Mod/ObxGen.odc |
MODULE SqlObxInit;
(**
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 Kernel, SqlDB;
CONST
protocol = "SqlOdbc";
id = ""; password = "";
datasource = "Test Database";
PROCEDURE Setup*;
VAR db: SqlDB.Database; res: INTEGER;
BEGIN
SqlDB.OpenDatabase(protocol, id, password, datasource, SqlDB.async, SqlDB.hideErrors, db, res);
IF db # NIL THEN
db.Exec("CREATE TABLE Companies (id INTEGER, name VARCHAR(255), ceo VARCHAR(255), employees INTEGER)");
db.Exec("CREATE TABLE Ownership (owner INTEGER, owned INTEGER, percent INTEGER)");
(* single company *)
db.Exec("INSERT INTO Companies VALUES (11, 'Test', 'Bill', 234)");
(* two companies (tree) *)
db.Exec("INSERT INTO Companies VALUES (12, 'Test', 'Bill', 234)");
db.Exec("INSERT INTO Companies VALUES (13, 'Test company AG', 'John', 45)");
db.Exec("INSERT INTO Ownership VALUES (12, 13, 100)");
(* four companies (with ring) *)
db.Exec("INSERT INTO Companies VALUES (14, 'Test', 'Bill', 234)");
db.Exec("INSERT INTO Companies VALUES (15, 'Test company AG', 'John', 45)");
db.Exec("INSERT INTO Companies VALUES (16, 'Test Services GmbH', 'Jim', 23000)");
db.Exec("INSERT INTO Companies VALUES (17, 'Test Commands & Co.', 'Mary', 523)");
db.Exec("INSERT INTO Ownership VALUES (14, 15, 50)");
db.Exec("INSERT INTO Ownership VALUES (15, 17, 100)");
db.Exec("INSERT INTO Ownership VALUES (16, 15, 50)");
db.Exec("INSERT INTO Ownership VALUES (15, 17, 100)");
(* four companies (tree) *)
db.Exec("INSERT INTO Companies VALUES (18, 'Test', 'Bill', 234)");
db.Exec("INSERT INTO Companies VALUES (19, 'Test company AG', 'John', 45)");
db.Exec("INSERT INTO Companies VALUES (20, 'Test Services GmbH', 'Jim', 23000)");
db.Exec("INSERT INTO Companies VALUES (21, 'Test Commands & Co.', 'Mary', 523)");
db.Exec("INSERT INTO Ownership VALUES (18, 19, 20)");
db.Exec("INSERT INTO Ownership VALUES (18, 20, 30)");
db.Exec("INSERT INTO Ownership VALUES (18, 21, 50)");
(* most complex example *)
db.Exec("INSERT INTO Companies VALUES (1, 'Test', 'Bill', 234)");
db.Exec("INSERT INTO Companies VALUES (2, 'Test company AG', 'John', 45)");
db.Exec("INSERT INTO Companies VALUES (3, 'Test Services GmbH', 'Jim', 23000)");
db.Exec("INSERT INTO Companies VALUES (4, 'Test Commands & Co.', 'Mary', 523)");
db.Exec("INSERT INTO Companies VALUES (5, 'Test Views KG', 'Frank', 17)");
db.Exec("INSERT INTO Companies VALUES (6, 'Test Genossenschaft', 'Hans', 2109)");
db.Exec("INSERT INTO Companies VALUES (7, 'Test Mentoring, Inc.', 'Marlis', 128)");
db.Exec("INSERT INTO Companies VALUES (8, 'Test Training Plc.', 'Paul', 4)");
db.Exec("INSERT INTO Companies VALUES (9, 'Test Trainers SA', 'Jean', 87)");
db.Exec("INSERT INTO Companies VALUES (10, 'Test Wrappers AB', 'Gordon', 912)");
db.Exec("INSERT INTO Ownership VALUES (1, 2, 100)");
db.Exec("INSERT INTO Ownership VALUES (1, 3, 100)");
db.Exec("INSERT INTO Ownership VALUES (2, 4, 100)");
db.Exec("INSERT INTO Ownership VALUES (2, 5, 100)");
db.Exec("INSERT INTO Ownership VALUES (3, 6, 100)");
db.Exec("INSERT INTO Ownership VALUES (3, 7, 100)");
db.Exec("INSERT INTO Ownership VALUES (7, 8, 100)");
db.Exec("INSERT INTO Ownership VALUES (5, 9, 49)");
db.Exec("INSERT INTO Ownership VALUES (8, 9, 51)");
db.Exec("INSERT INTO Ownership VALUES (9, 10, 100)");
db.Commit
END;
db := NIL;
Kernel.Cleanup (* garbage collector closes database *)
END Setup;
END SqlObxInit. | Sql/Mod/ObxInit.odc |
MODULE SqlObxNets;
(**
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 = "
- ...
"
**)
TYPE
Net* = POINTER TO NetDesc;
Node* = POINTER TO NodeDesc;
Company* = POINTER TO RECORD
id-: INTEGER;
name-, ceo-: ARRAY 32 OF CHAR;
employees-: INTEGER;
ownedBy-: Node; (* list of owner companies *)
owns-: Node; (* list of owned companies *)
time*: INTEGER; (* temporary data for layout algorithm *)
x*, y*: INTEGER; (* temporary data for layout algorithm *)
next: Company
END;
NodeDesc* = RECORD
next-: Node;
percent-: INTEGER;
company-: Company
END;
NetDesc* = RECORD
first: Company
END;
PROCEDURE AddCompany* (g: Net; id: INTEGER; name, ceo: ARRAY OF CHAR; employees: INTEGER);
VAR c: Company;
BEGIN
ASSERT(g # NIL, 20); ASSERT(id > 0, 21);
c := g.first; WHILE (c # NIL) & (c.id # id) DO c := c.next END;
IF c # NIL THEN
IF c.name = "" THEN
c.name := name$; c.ceo := ceo$; c.employees := employees;
ELSE
ASSERT((name = "") OR (c.name = name), 22)
END
ELSE
NEW(c); c.id := id; c.name := name$; c.ceo := ceo$; c.employees := employees;
c.next := g.first; g.first := c
END
END AddCompany;
PROCEDURE AddNode (VAR h: Node; percent: INTEGER; company: Company);
VAR n: Node;
BEGIN
NEW(n); n.percent := percent; n.company := company;
IF h = NIL THEN
h := n
ELSE
WHILE (h.percent >= percent) & (h.next # NIL) DO h := h.next END;
n.next := h.next; h.next := n
END
END AddNode;
PROCEDURE AddOwnership* (g: Net; owner, owned: INTEGER; percent: INTEGER);
VAR h0, h1: Company;
BEGIN
ASSERT(g # NIL, 20); ASSERT(owner > 0, 21); ASSERT(owned > 0, 22);
ASSERT(owned # owner, 23); ASSERT(percent > 0, 24); ASSERT(percent <= 100, 25);
h0 := g.first; WHILE (h0 # NIL) & (h0.id # owner) DO h0 := h0.next END;
IF h0 = NIL THEN
AddCompany(g, owner, "", "", 0);
h0 := g.first; WHILE (h0 # NIL) & (h0.id # owner) DO h0 := h0.next END; ASSERT(h0 # NIL, 100)
END;
h1 := g.first; WHILE (h1 # NIL) & (h1.id # owned) DO h1 := h1.next END;
IF h1 = NIL THEN
AddCompany(g, owned, "", "", 0);
h1 := g.first; WHILE (h1 # NIL) & (h1.id # owned) DO h1 := h1.next END; ASSERT(h1 # NIL, 100)
END;
AddNode(h1.ownedBy, percent, h0);
AddNode(h0.owns, percent, h1)
END AddOwnership;
PROCEDURE ThisCompany* (g: Net; id: INTEGER): Company;
VAR h: Company;
BEGIN
ASSERT(g # NIL, 20); ASSERT(id > 0, 21);
h := g.first; WHILE (h # NIL) & (h.id # id) DO h := h.next END;
RETURN h
END ThisCompany;
PROCEDURE CompanyAt* (g: Net; x, y, w, h: INTEGER): Company;
(* not a nice interface; could be improved *)
VAR p: Company;
BEGIN
ASSERT(g # NIL, 20);
p := g.first; WHILE (p # NIL) & ((x < p.x) OR (y < p.y) OR (x >= p.x + w) OR (y >= p.y + h)) DO p := p.next END;
RETURN p
END CompanyAt;
PROCEDURE New* (): Net;
VAR g: Net;
BEGIN
NEW(g); RETURN g
END New;
END SqlObxNets.
| Sql/Mod/ObxNets.odc |
MODULE SqlObxTab;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20070414, mf, references to dtF driver eliminated
"
issues = "
- ...
"
**)
IMPORT Dialog, Ports, Views, TextModels, TextViews, TextRulers, TextMappers, SqlDB;
CONST
protocol = "SqlOdbc3";
id = ""; password = "";
datasource = "Test Database";
colWidth = 30 * Ports.mm;
minCol = 4;
VAR
name*: ARRAY 64 OF CHAR;
PROCEDURE NewRuler (tabs: INTEGER): TextRulers.Ruler;
VAR p: TextRulers.Prop; i, w: INTEGER;
BEGIN
NEW(p);
IF tabs > LEN(p.tabs.tab) THEN tabs := LEN(p.tabs.tab)
ELSIF tabs < minCol THEN tabs := minCol
END;
p.valid := {TextRulers.right, TextRulers.tabs, TextRulers.opts};
p.opts.val := {TextRulers.rightFixed}; p.opts.mask := p.opts.val;
p.tabs.len := tabs - 1; i := 0; w := 0;
WHILE i < tabs - 1 DO
INC(w, colWidth); p.tabs.tab[i].stop := w; INC(i)
END;
INC(w, colWidth); p.right := w;
RETURN TextRulers.dir.NewFromProp(p)
END NewRuler;
PROCEDURE OpenViewer (t: TextModels.Model; title: Views.Title; ruler:TextRulers.Ruler);
VAR v: TextViews.View;
BEGIN
Dialog.MapString(title, title);
v := TextViews.dir.New(t);
IF ruler # NIL THEN v.SetDefaults(ruler, TextViews.dir.defAttr) END;
Views.OpenAux(v, title)
END OpenViewer;
PROCEDURE ShowTables*;
VAR db: SqlDB.Database; t, tabs: SqlDB.Table; res, row, col, n, max: INTEGER;
text: TextModels.Model; out: TextMappers.Formatter; data: SqlDB.Row;
BEGIN
text := TextModels.dir.New(); out.ConnectTo(text);
SqlDB.OpenDatabase(protocol, id, password, datasource, SqlDB.async, SqlDB.showErrors, db, res);
tabs := db.NewTable();
tabs.Exec("Show Tables");
n := 0; max := 0;
WHILE n < tabs.rows DO
tabs.Read(n, data);
name := data.fields[1]^$;
out.WriteLn;
out.WriteString("Table "); out.WriteString(name); out.WriteLn;
out.WriteLn;
t := db.NewTable();
t.Exec("select * from :!SqlObxTab.name");
row := SqlDB.names;
WHILE row < t.rows DO
t.Read(row, data); col := 0;
WHILE col < t.columns DO
out.WriteString(data.fields[col]^); out.WriteTab;
INC(col)
END;
out.WriteLn; INC(row)
END;
IF t.columns > max THEN max := t.columns END;
t.Clear; INC(n)
END;
OpenViewer(text, "Tables", NewRuler(max))
END ShowTables;
END SqlObxTab.
| Sql/Mod/ObxTab.odc |
MODULE SqlObxUI;
(**
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 Dialog, SqlDB, SqlObxDB;
(** generic **)
PROCEDURE ROGuard* (VAR par: Dialog.Par);
BEGIN
par.readOnly := TRUE
END ROGuard;
(** guards **)
PROCEDURE Invalid (): BOOLEAN;
BEGIN (* check whether record is legal (must be a very efficient check) *)
RETURN SqlObxDB.company.name = ""
END Invalid;
PROCEDURE CloseGuard* (VAR par: Dialog.Par);
BEGIN
IF SqlObxDB.dirty THEN par.disabled := TRUE END
END CloseGuard;
PROCEDURE InsertGuard* (VAR par: Dialog.Par);
BEGIN
IF SqlObxDB.Closed() THEN par.disabled := TRUE END;
IF ~SqlObxDB.dirty OR Invalid() THEN par.disabled := TRUE END
END InsertGuard;
PROCEDURE UpdateGuard* (VAR par: Dialog.Par);
BEGIN
IF SqlObxDB.Closed() THEN par.disabled := TRUE END;
IF ~SqlObxDB.dirty OR (SqlObxDB.company.id <= 0) OR Invalid() THEN par.disabled := TRUE END
END UpdateGuard;
PROCEDURE DeleteGuard* (VAR par: Dialog.Par);
BEGIN
IF SqlObxDB.Closed() THEN par.disabled := TRUE END;
IF SqlObxDB.dirty OR (SqlObxDB.company.id <= 0) THEN par.disabled := TRUE END
END DeleteGuard;
PROCEDURE RevertGuard* (VAR par: Dialog.Par);
BEGIN
IF SqlObxDB.Closed() THEN par.disabled := TRUE END;
IF ~SqlObxDB.dirty THEN par.disabled := TRUE END;
IF SqlObxDB.company.id > 0 THEN par.label := "Revert" ELSE par.label := "Clear" END
END RevertGuard;
PROCEDURE FindGuard* (VAR par: Dialog.Par);
BEGIN
IF SqlObxDB.Closed() THEN par.disabled := TRUE END;
IF SqlObxDB.dirty OR (SqlObxDB.searchId <= 0) THEN par.disabled := TRUE END
END FindGuard;
(** notifiers **)
PROCEDURE TypingNotifier* (op, from, to: INTEGER);
BEGIN
IF ~SqlObxDB.dirty & (op = Dialog.changed) & ~SqlObxDB.Closed() THEN
SqlObxDB.dirty := TRUE; Dialog.Update(SqlObxDB.company)
END
END TypingNotifier;
END SqlObxUI.
| Sql/Mod/ObxUI.odc |
MODULE SqlObxViews;
(**
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
Mechanisms, Fonts, Ports, Views, Controllers, Properties,
TextModels, TextMappers, TextViews, SqlObxNets;
CONST d = 3 * Ports.mm; w = 40 * Ports.mm; h = 6 * Ports.mm;
TYPE
View = POINTER TO RECORD (Views.View)
g: SqlObxNets.Net;
c: SqlObxNets.Company;
w, h: INTEGER
END;
(* drawing *)
PROCEDURE DrawCompany (f: Views.Frame; c: SqlObxNets.Company; first: BOOLEAN);
VAR s, sw, x, y, asc, dsc, fw: INTEGER; col: Ports.Color; fnt: Fonts.Font;
BEGIN
IF first THEN s := 2 * f.unit; col := Ports.red ELSE s := f.unit; col := Ports.black END;
x := c.x; y := c.y;
f.DrawRect(x, y, x + w, y + h, s, col);
fnt := Fonts.dir.Default();
sw := fnt.StringWidth(c.name);
fnt.GetBounds(asc, dsc,fw);
x := x + (w - sw) DIV 2; y := y + h DIV 2 + (asc + dsc) DIV 3;
f.DrawString(x, y, col, c.name, fnt)
END DrawCompany;
PROCEDURE Draw (c: SqlObxNets.Company; time: INTEGER; f: Views.Frame);
VAR p: SqlObxNets.Node; c0: SqlObxNets.Company;
BEGIN (* c.x and c.y must be set up *)
c.time := time;
p := c.owns;
WHILE p # NIL DO
c0 := p.company;
IF c0.time < time THEN
DrawCompany(f, c0, FALSE);
Draw(c0, time, f)
END;
f.DrawLine(c.x + w DIV 2, c.y + h, c0.x + w DIV 2, c0.y, f.unit, Ports.black);
p := p.next
END
END Draw;
(* mouse handling *)
PROCEDURE TestHit (v: View; x, y: INTEGER; VAR l, t, r, b: INTEGER; VAR inside: BOOLEAN;
VAR p: SqlObxNets.Company);
VAR c: SqlObxNets.Company;
BEGIN
c := SqlObxNets.CompanyAt(v.g, x, y, w, h);
IF c # NIL THEN
IF p = NIL THEN p := c; l := c.x; t := c.y; r := l + w; b := t + h END;
inside := p = c
ELSE
inside := FALSE
END
END TestHit;
PROCEDURE Text (s: ARRAY OF CHAR): TextViews.View;
VAR t: TextModels.Model; f: TextMappers.Formatter;
BEGIN
t := TextModels.dir.New();
f.ConnectTo(t); f.WriteString(s);
RETURN TextViews.dir.New(t)
END Text;
(* placement *)
PROCEDURE ShiftDown (c: SqlObxNets.Company; time: INTEGER; dy: INTEGER; VAR b: INTEGER);
VAR p: SqlObxNets.Node; c0: SqlObxNets.Company;
BEGIN
c.time := time; INC(c.y, dy);
IF c.y + h + d > b THEN b := c.y + h + d END;
p := c.owns;
WHILE p # NIL DO
c0 := p.company;
IF c0.time < time THEN ShiftDown(c0, time, dy, b) END;
p := p.next
END
END ShiftDown;
PROCEDURE Place (c: SqlObxNets.Company; x, y, t0: INTEGER; VAR time, r, b: INTEGER);
VAR p: SqlObxNets.Node; c0: SqlObxNets.Company;
BEGIN
(* place company c *)
c.time := time; c.x := x; c.y := y;
r := x + w + d;
y := y + h + d; IF y > b THEN b := y END;
(* handle companies owned by c *)
p := c.owns;
WHILE p # NIL DO
c0 := p.company;
IF c0.time < t0 THEN (* placement is not up-to-date *)
Place(c0, x, y, t0, time, r, b);
x := r (* placement above may have produced a block several companies wide *)
ELSIF c0.y < y THEN
INC(time); ShiftDown(c0, time, y - c0.y, b)
END;
p := p.next
END
END Place;
(* View *)
PROCEDURE (v: View) CopyFromSimpleView (source: Views.View);
BEGIN
WITH source: View DO
v.g := source.g;
v.c := source.c;
v.w := source.w;
v.h := source.h
END
END CopyFromSimpleView;
PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER);
VAR time: INTEGER;
BEGIN
IF v.g # NIL THEN
DrawCompany(f, v.c, TRUE);
time := v.c.time + 1; Draw(v.c, time, f)
END
END Restore;
PROCEDURE (v: View) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View);
VAR x, y, l, t, r, b, dx, dy: INTEGER; inside: BOOLEAN;
c: SqlObxNets.Company; destX, destY: INTEGER; dest: Views.Frame; op: INTEGER; buttons: SET;
tv: TextViews.View;
BEGIN
(* When the mouse is dragged from within one company to be dropped somewhere else,
the name of the company is dropped there as a text. This demonstrates how a drop
source of a drag & drop operation is implemented. *)
WITH msg: Controllers.PollOpsMsg DO
msg.type := "TextViews.StdView"
| msg: Controllers.TrackMsg DO
c := NIL; x := msg.x; y := msg.y;
TestHit(v, x, y, l, t, r, b, inside, c);
IF inside THEN
dx := x - c.x; dy := y - c.y ;
op := Mechanisms.copy;
tv := Text(c.name);
Mechanisms.TrackToDrop(f, tv, FALSE, w, h, dx, dy, dest, destX, destY, op, x, y, buttons);
IF op # Mechanisms.cancelDrop THEN
Controllers.Drop(x, y, f, msg.x, msg.y, tv, FALSE, w, h, dx, dy)
END
END
| msg: Controllers.PollDropMsg DO
IF msg.mark THEN
f.MarkRect(msg.x - msg.rx, msg.y - msg.ry, msg.x + msg.w - msg.rx,
msg.y + msg.h - msg.ry, f.dot, Ports.invert, msg.show)
END
ELSE (* ignore other messages *)
END
END HandleCtrlMsg;
PROCEDURE (v: View) HandlePropMsg (VAR msg: Properties.Message);
BEGIN
WITH msg: Properties.SizePref DO
IF msg.w = Views.undefined THEN msg.w := v.w END;
IF msg.h = Views.undefined THEN msg.h := v.h END
ELSE
END
END HandlePropMsg;
(* miscellaneous *)
PROCEDURE New* (g: SqlObxNets.Net; c: SqlObxNets.Company): Views.View;
VAR v: View;
BEGIN
ASSERT(g # NIL, 20); ASSERT(c # NIL, 21);
NEW(v); v.g := g; v.c := c;
c.time := 1;
Place(c, d, d, c.time, c.time, v.w, v.h);
RETURN v
END New;
END SqlObxViews.
| Sql/Mod/ObxViews.odc |
Sql/Rsrc/Browser.odc |
|
Sql/Rsrc/Company.odc |
|
Sql/Rsrc/Debug.odc |
|
MENU "#Sql:&SQL"
"#Sql:&Browser..." "" "StdCmds.OpenAuxDialog('Sql/Rsrc/Browser', '#Sql:Browser')" ""
"#Sql:&Execute" "" "SqlBrowser.ExecuteSel" "TextCmds.SelectionGuard"
"#Sql:&Debug Options..." "" "StdCmds.OpenAuxDialog('Sql/Rsrc/Debug', '#Sql:Debug Options')" ""
SEPARATOR
"#Sql:&Insert Anchor" "" "SqlControls.DepositAnchor; StdCmds.PasteView" "StdCmds.PasteViewGuard"
"#Sql:&Insert Table" "" "SqlControls.DepositTable; StdCmds.PasteView" "StdCmds.PasteViewGuard"
"#Sql:&Open Table" "" "SqlControls.DepositTable; StdCmds.Open" ""
SEPARATOR
"#Sql:&Company..." "" "SqlObxDB.Open; StdCmds.OpenAuxDialog('Sql/Rsrc/Company', '#Sql:Company')" ""
"#Sql:&Ownership..." "" "SqlObxExt.Open; StdCmds.OpenAuxDialog('Sql/Rsrc/Owner', '#Sql:Ownership')" ""
"#Sql:&Help" "" "StdCmds.OpenBrowser('Sql/Docu/Dev-Man', '#Sql:Sql Docu')" ""
END
| Sql/Rsrc/Menus.odc |
Sql/Rsrc/Owner.odc |
|
STRINGS
&SQL SQL
&Browser... Browser...
&Execute Execute
&Company... Company...
&Ownership... Ownership...
&Insert Anchor Insert Anchor
&Insert Table Insert Table
&Open Table Open Table
&Debug Options... Debug Options...
&Help Help
Owner... Owner...
Browser Browser
Company Company
Ownership Ownership
Debug Options Debug Options
Sql Docu Sql Docu
NotFound ^0 not found
HasWrongType ^0 has wrong type
IsCloseOk Some entries are changed. Close anyway?
StatementExecuted statement executed
ExecutionFailed execution failed
ConnectionFailed connection failed
CannotLoadDriver cannot load driver
Result Result
Id: Id:
Password: Password:
Database: Database:
Driver: Driver:
Statement: Statement:
Execute Execute
Commit Commit
Show Debug Output for Show Debug Output for
| Sql/Rsrc/Strings.odc |
StdApi
DEFINITION StdApi;
IMPORT Views, Containers;
VAR
modeHook: PROCEDURE (c: Containers.Controller);
PROCEDURE CloseDialog (OUT closedView: Views.View);
PROCEDURE OpenAux (file, title: ARRAY OF CHAR; OUT v: Views.View);
PROCEDURE OpenAuxDialog (file, title: ARRAY OF CHAR; OUT v: Views.View);
PROCEDURE OpenBrowser (file, title: ARRAY OF CHAR; OUT v: Views.View);
PROCEDURE OpenCopyOf (file: ARRAY OF CHAR; OUT v: Views.View);
PROCEDURE OpenDoc (file: ARRAY OF CHAR; OUT v: Views.View);
PROCEDURE OpenToolDialog (file, title: ARRAY OF CHAR; OUT v: Views.View);
END StdApi.
StdApi is the programming interface to many of the services provided by StdCmds. Since StdCmds is intended to be used in menus, hyperlinks etc., it is not always suitable as a programming interface. StdApi provides the exact same functionality but with a more "programmable" interface.
VAR modeHook: PROCEDURE (c: Containers.Controller)
A hook for setting the mode of nested forms to the mode of the container, which is represented by its options in c.opts. Used e.g. in OpenAuxDialog and OpenToolDialog for giving nested forms a chance to set themselves into mask mode.
PROCEDURE CloseDialog (OUT closedView: Views.View)
This command closes the currently focused window. If the window is a document window and its contents dirty, an error message will be displayed. The root view of the closed window is returned in closedView. If CloseDialog failed NIL is returned.
PROCEDURE OpenAux (file, title: ARRAY OF CHAR; OUT v: Views.View)
Takes a file specification of a BlackBox document and a window title as parameters, and opens an auxiliary window with the specified title. Parameter file must be the path name of a file. The root view of the opened window is returned in v. If OpenAux fails NIL is returned in v.
Auxiliary windows are used for displaying temporary editable data.
PROCEDURE OpenAuxDialog (file, title: ARRAY OF CHAR; OUT v: Views.View)
Takes a file specification of a BlackBox document and a window title as parameters, and opens a dialog with the specified document. The dialog is opened as an auxiliary window. Parameter file must be the path name of a file. The root view of the opened window is returned in v. If OpenAuxDialog fails NIL is returned in v.
Auxiliary dialogs are used for self-contained dialogs, i.e., data entry masks or parameter entry masks for commands.
If a non-standard language is selected, 'Docu' files are first looked up in the subdirectory of the selected language and if not found, the standard language is used.
In contrast to OpenAux, OpenAuxDialog turns the opened document into mask mode if it is a container (-> Containers), and opens it into a dialog window if the underlying platform distinguishes between document and dialog windows (e.g. as in Windows).
PROCEDURE OpenBrowser (file, title: ARRAY OF CHAR; OUT v: Views.View)
Takes a file specification of a BlackBox document and a window title as parameters, and opens the specified document in an auxiliary window. The window contents is not editable, but can be selected. Parameter file must be the path name of a file. If the same file is already open in an existing browser document window, this window is brought to the top, instead of opening a new window. The root view of the opened window is returned in v. If OpenBrowser fails NIL is returned in v.
If a non-standard language is selected, 'Docu' files are first looked up in the subdirectory of the selected language and if not found, the standard language is used.
Browser windows are used for displaying documentation. It is possible to select and copy out browser window contents. It is possible to apply find & replace commands, the Info->Interface command, etc.
PROCEDURE OpenCopyOf (file: ARRAY OF CHAR; OUT v: Views.View)
Opens a new document and uses the document specified by file as a template to initialize the new document. If successful the root view of the new document is returned in v otherwise NIL is returned in v.
PROCEDURE OpenDoc (file: ARRAY OF CHAR; OUT v: Views.View)
Takes a file specification of a BlackBox document as parameter, and opens the document in a document window. Parameter file must be the path name of a file. If the same file is already open in an existing document window, this window is brought to the top, instead of opening a new window. The root view of the opened window (or window brought to the top) is returned in v. If OpenDoc fails NIL is returned in v.
Document windows are used for displaying persistent editable data.
PROCEDURE OpenToolDialog (file, title: ARRAY OF CHAR; OUT v: Views.View)
Takes a file specification of a BlackBox document and a window title as parameters, and opens a dialog with the specified document. The dialog is opened as tool window. Parameter file must be the path name of a file. The root view of the opened window is returned in v. If OpenAuxDialog fails NIL is returned in v.
Tool dialogs are used for dialogs which operate on document windows beneath them, e.g., a Find & Replace dialog which operates on a text under it. Otherwise it is identical to OpenAuxDialog.
| Std/Docu/Api.odc |
StdCFrames
This is a private module of BlackBox. Its existence is necessary for BlackBox to work correctly.
| Std/Docu/CFrames.odc |
StdClocks
DEFINITION StdClocks;
IMPORT Views;
PROCEDURE Deposit;
PROCEDURE New (): Views.View;
END StdClocks.
This module implements a simple clock view.
Typical menu command:
"Insert Clock" "" "StdClocks.Deposit; StdCmds.PasteView" "StdCmds.PasteViewGuard"
PROCEDURE New (): Views.View
Factory function for standard clocks.
PROCEDURE Deposit
Deposit command for standard clocks.
| Std/Docu/Clocks.odc |
StdCmds
DEFINITION StdCmds;
IMPORT Dialog, Ports, Fonts;
VAR
allocator: Dialog.String;
layout: RECORD
wType, hType: INTEGER;
width, height: REAL
END;
size: RECORD
size: INTEGER
END;
PROCEDURE Bold;
PROCEDURE BoldGuard (VAR par: Dialog.Par);
PROCEDURE CaretGuard (VAR par: Dialog.Par);
PROCEDURE Clear;
PROCEDURE CloseDialog;
PROCEDURE Color (color: Ports.Color);
PROCEDURE ColorGuard (color: INTEGER; VAR par: Dialog.Par);
PROCEDURE ContainerGuard (VAR par: Dialog.Par);
PROCEDURE CopyProp;
PROCEDURE DefaultFont;
PROCEDURE DefaultFontGuard (VAR par: Dialog.Par);
PROCEDURE DefaultOnDoubleClick (op, from, to: INTEGER);
PROCEDURE DeselectAll;
PROCEDURE Font (typeface: Fonts.Typeface);
PROCEDURE HeightGuard (VAR par: Dialog.Par);
PROCEDURE InitLayoutDialog;
PROCEDURE InitSizeDialog;
PROCEDURE Italic;
PROCEDURE ItalicGuard (VAR par: Dialog.Par);
PROCEDURE ModelViewGuard (VAR par: Dialog.Par);
PROCEDURE New;
PROCEDURE NewWindow;
PROCEDURE Open;
PROCEDURE OpenAsAuxDialog;
PROCEDURE OpenAsToolDialog;
PROCEDURE OpenAux (file, title: ARRAY OF CHAR);
PROCEDURE OpenAuxDialog (file, title: ARRAY OF CHAR);
PROCEDURE OpenBrowser (file, title: ARRAY OF CHAR);
PROCEDURE OpenDoc (file: ARRAY OF CHAR);
PROCEDURE OpenToolDialog (file, title: ARRAY OF CHAR);
PROCEDURE PasteCharGuard (VAR par: Dialog.Par);
PROCEDURE PasteLCharGuard (VAR par: Dialog.Par);
PROCEDURE PasteProp;
PROCEDURE PasteView;
PROCEDURE PasteViewGuard (VAR par: Dialog.Par);
PROCEDURE Plain;
PROCEDURE PlainGuard (VAR par: Dialog.Par);
PROCEDURE ReadOnlyGuard (VAR par: Dialog.Par);
PROCEDURE RecalcAllSizes;
PROCEDURE RecalcFocusSize;
PROCEDURE Redo;
PROCEDURE RedoGuard (VAR par: Dialog.Par);
PROCEDURE RestoreAll;
PROCEDURE SelectAll;
PROCEDURE SelectAllGuard (VAR par: Dialog.Par);
PROCEDURE SelectDocument;
PROCEDURE SelectNextView;
PROCEDURE SelectionGuard (VAR par: Dialog.Par);
PROCEDURE SetBrowserMode;
PROCEDURE SetBrowserModeGuard (VAR par: Dialog.Par);
PROCEDURE SetEditMode;
PROCEDURE SetEditModeGuard (VAR par: Dialog.Par);
PROCEDURE SetLayout;
PROCEDURE SetLayoutMode;
PROCEDURE SetLayoutModeGuard (VAR par: Dialog.Par);
PROCEDURE SetMaskMode;
PROCEDURE SetMaskModeGuard (VAR par: Dialog.Par);
PROCEDURE SetSize;
PROCEDURE ShowProp;
PROCEDURE ShowPropGuard (VAR par: Dialog.Par);
PROCEDURE SingletonGuard (VAR par: Dialog.Par);
PROCEDURE Size (size: INTEGER);
PROCEDURE SizeGuard (size: INTEGER; VAR par: Dialog.Par);
PROCEDURE Strikeout;
PROCEDURE StrikeoutGuard (VAR par: Dialog.Par);
PROCEDURE ToggleNoFocus;
PROCEDURE ToggleNoFocusGuard (VAR par: Dialog.Par);
PROCEDURE TypeNotifier (op, from, to: INTEGER);
PROCEDURE TypefaceGuard (VAR par: Dialog.Par);
PROCEDURE Underline;
PROCEDURE UnderlineGuard (VAR par: Dialog.Par);
PROCEDURE Undo;
PROCEDURE UndoGuard (VAR par: Dialog.Par);
PROCEDURE UpdateAll;
PROCEDURE WidthGuard (VAR par: Dialog.Par);
PROCEDURE WindowGuard (VAR par: Dialog.Par);
END StdCmds.
StdCmds is a command package which contains many commands and guards which are typically used in menu items (->StdMenuTool) or in hyperlinks (->StdLinks).
The module exports more commands which are not described here; these are the commands and guards for menu items of the Windows standard menus. See the Menus text for how these commands are used.
VAR allocator: Dialog.String
This string contains the command sequence that is executed when the user invokes the Files->New command. By default, it is set to "TextViews.Deposit; StdCmds.Open". This string may be changed in the Config module.
VAR layout: RECORD
Interactor for root view layout (Tools->Document Size...). The size of the outermost view of a document (root view) may be determined in several different ways. Either it is equal to the window size, to the paper size minus the margins defined in the PageSetup dialog, or to a particular fixed size. The vertical and horizontal directions can be defined independently.
wType, hType: INTEGER wType IN {0..2} & hType IN {0..2}
Determines whether the root view size (horizontical/vertical) has a fixed size (0), the size defined by the PageSetup dialog (1), or by the window (2).
width, height: REAL valid iff wType/hType = 1
The root view width/height in centimeters.
VAR size: RECORD
Interactor for setting the font size.
size: INTEGER size >= 6
Font size in points (-> Fonts).
VAR result: INTEGER;
Indicates whether the last Open* command was successful.
PROCEDURE Bold
PROCEDURE BoldGuard (VAR par: Dialog.Par)
PROCEDURE CaretGuard (VAR par: Dialog.Par)
Disables menu item if there is no current caret, i.e., no selection of length 0.
PROCEDURE Clear
PROCEDURE CloseDialog
This command can be used from within a control to close the window in which the control is embedded. It can only be used as reaction to interactive manipulation of the control, i.e., when the mouse is clicked in the control or when it receives keyboard input. If the window is a document window and its contents dirty, an error message will be displayed.
Pre
must be called in interaction with control 20
PROCEDURE Color (color: Ports.Color)
Set selection to the given color value (-> Ports.Color).
PROCEDURE ColorGuard (color: INTEGER; VAR par: Dialog.Par)
Guard for the Color command.
PROCEDURE CopyProp
Collect properties of current selection, so that they can be used later on for pasting them again.
PROCEDURE ContainerGuard (VAR par: Dialog.Par)
Guard for making sure that the focus is a container view (-> Containers.View).
PROCEDURE DefaultFont
Set selection to the default typeface.
PROCEDURE DefaultFontGuard (VAR par: Dialog.Par)
Guard for the DefaultFont command.
PROCEDURE DefaultOnDoubleClick (op, from, to: INTEGER)
A standard notifier which "clicks" the default button when its control is double-clicked. Typically, this is used in selection boxes or combo boxes.
PROCEDURE DeselectAll
Remove the selection in the focus view.
PROCEDURE Font (typeface: Fonts.Typeface)
PROCEDURE HeightGuard (VAR par: Dialog.Par)
Guard command which sets par.readOnly if layout.hType # 0, i.e., if mode is not "fixed".
PROCEDURE InitLayoutDialog
Initialization command for layout interactor.
PROCEDURE InitSizeDialog
Initialization command for size interactor.
PROCEDURE Italic
Set selection to italicized text.
PROCEDURE ItalicGuard (VAR par: Dialog.Par)
Guard for Italic command.
PROCEDURE ModelViewGuard (VAR par: Dialog.Par)
Guard for NewWindow command (checks that the focus view's ThisModel method does not return NIL).
PROCEDURE New
Open a new untitled document, using the command sequence in variable allocator.
PROCEDURE NewWindow
Guard: ModelViewGuard
Opens another window onto the same document as the front window's.
PROCEDURE Open
Guard: a view was deposited
Takes a deposited view from the global view queue and opens it in a new window.
PROCEDURE OpenAsAuxDialog
Opens another window onto the same document as the front window's; this window works as an auxiliary dialog box.
PROCEDURE OpenAsToolDialog
Opens another window onto the same document as the front window's; this window works as a tool dialog box.
PROCEDURE OpenAux (file, title: ARRAY OF CHAR)
Takes a file specification of a BlackBox document and a window title as parameters, and opens an auxiliary window with the specified title. Parameter file must be the path name of a file.
Auxiliary windows are used for displaying temporary editable data.
Example:
"StdCmds.OpenAux('Form/Rsrc/Menus', 'Form Menus')"
PROCEDURE OpenAuxDialog (file, title: ARRAY OF CHAR)
Takes a file specification of a BlackBox document and a window title as parameters, and opens a dialog with the specified document. The dialog is opened as an auxiliary window. Parameter file must be the path name of a file.
If a non-standard language is selected, 'Docu' files are first looked up in the subdirectory of the selected language and if not found, the standard language is used.
Auxiliary dialogs are used for self-contained dialogs, i.e., data entry masks or parameter entry masks for commands.
In contrast to OpenAux, OpenAuxDialog turns the opened document into mask mode if it is a container (-> Containers), and opens it into a dialog window if the underlying platform distinguishes between document and dialog windows (e.g. as in Windows).
Example:
"StdCmds.OpenAuxDialog('Form/Rsrc/Cmds', 'New Form')"
PROCEDURE OpenBrowser (file, title: ARRAY OF CHAR)
Takes a file specification of a BlackBox document and a window title as parameters, and opens the specified document in an auxiliary window. The window contents is not editable, but can be selected. Parameter file must be the path name of a file.
If a non-standard language is selected, 'Docu' files are first looked up in the subdirectory of the selected language and if not found, the standard language is used.
Browser windows are used for displaying documentation. It is possible to select and copy out browser window contents. It is possible to apply find & replace commands, the Info->Interface command, etc.
Example:
"StdCmds.OpenBrowser('Form/Docu/Models', 'FormModels Docu')"
PROCEDURE OpenDoc (file: ARRAY OF CHAR)
Takes a file specification of a BlackBox document as parameter, and opens the document in a document window. Parameter file must be the path name of a file. If the same file is already open in an existing document window, this window is brought to the top, instead of opening a new window.
Document windows are used for displaying persistent editable data.
Example:
"StdCmds.OpenDoc('System/Rsrc/Menus')"
PROCEDURE OpenToolDialog (file, title: ARRAY OF CHAR)
Takes a file specification of a BlackBox document and a window title as parameters, and opens a dialog with the specified document. The dialog is opened as tool window. Parameter file must be the path name of a file.
Tool dialogs are used for dialogs which operate on document windows beneath them, e.g., a Find & Replace dialog which operates on a text under it. Otherwise it is identical to OpenAuxDialog.
Example:
"DevInspector.InitDialog; StdCmds.OpenToolDialog('Dev/Rsrc/Inspect', 'Inspect')"
PROCEDURE PasteCharGuard (VAR par: Dialog.Par)
Disables menu item if entering a character is currently not possible.
PROCEDURE PasteLCharGuard (VAR par: Dialog.Par)
Obsolete.
PROCEDURE PasteProp
Guard: a property was collected (-> CopyProp)
Takes the previously copied properties and applies them to the current selection.
PROCEDURE PasteView
Guard: a view was deposited
Takes a deposited view from the global view queue and pastes it to the focus.
PROCEDURE PasteViewGuard (VAR par: Dialog.Par)
Disables menu item if pasting a view is currently not possible.
PROCEDURE Plain
Sets the selection to plain text (not italicized, not bold, not underlined).
PROCEDURE PlainGuard
Guard for the Plain command.
PROCEDURE ReadOnlyGuard (VAR par: Dialog.Par)
Makes a control read-only, by setting par.readOnly to TRUE.
PROCEDURE RecalcAllSizes
Recalculates the sizes of all visible views. Must be called after font metrics are changed.
PROCEDURE RecalcFocusSize
Recalculates the size of the focus view.
PROCEDURE Redo
Redo the most recently undone command.
PROCEDURE RedoGuard
Guard for the Redo command.
PROCEDURE RestoreAll
Forces a restoration of all visible views.
PROCEDURE SelectAll
Selects the whole contents of the focus view.
PROCEDURE SelectAllGuard
Guard for the SelectAll command.
PROCEDURE SelectDocument
Selects the root view (the outermost container) of the front window.
PROCEDURE SelectNextView
If a singleton view is selected in a container, this command selects the next view in the container in a round-robin fashion.
PROCEDURE SelectionGuard (VAR par: Dialog.Par)
Disables menu item if there is no current selection.
PROCEDURE SetBrowserMode
Guard: SetBrowserModeGuard
Sets the selected container in browser mode. If no container is selected the outer most container is set in browser mode. This mode is common for texts used for documentation purposes.
PROCEDURE SetBrowserModeGuard (VAR par: Dialog.Par)
Guard for procedure SetBrowserMode. Sets par.checked if appropriate.
PROCEDURE SetEditMode
Guard: SetEditModeGuard
Sets the selected container in edit mode. If no container is selected the outer most container is set in edit mode. This mode is common for editable texts.
PROCEDURE SetEditModeGuard (VAR par: Dialog.Par)
Guard for procedure SetEditMode. Sets par.checked if appropriate.
PROCEDURE SetLayout
Applies the interactor values in layout. To set up layout to the selected view, InitLayoutDialog needs to be called first.
PROCEDURE SetLayoutMode
Guard: SetLayoutModeGuard
Sets the selected container in layout mode. If no container is selected the outer most container is set in layout mode. This mode is common for editable forms.
PROCEDURE SetLayoutModeGuard (VAR par: Dialog.Par)
Guard for procedure SetLayoutMode. Sets par.checked if appropriate.
PROCEDURE SetMaskMode
Guard: SetMaskModeGuard
Sets the selected container in mask mode. If no container is selected the outer most container is set in mask mode. This mode is common for forms used as dialogs.
PROCEDURE SetMaskModeGuard (VAR par: Dialog.Par)
Guard for procedure SetMaskMode. Sets par.checked if appropriate.
PROCEDURE SetSize
Command for setting the selection to the size given in the size interactor.
PROCEDURE ShowProp
Shows the properties of the selection in the focus view.
PROCEDURE ShowPropGuard
Guard for the ShowProp command.
PROCEDURE SingletonGuard (VAR par: Dialog.Par)
Disables menu item if there is no current selection, or if the selection doesn't encompass exactly one embedded view.
PROCEDURE Size (size: INTEGER)
Sets the selection to the given size, in points (-> Fonts).
PROCEDURE SizeGuard (size: INTEGER; VAR par: Dialog.Par)
Guard for the Size command.
PROCEDURE Strikeout
Sets the selection to the strikeout style.
PROCEDURE StrikeoutGuard (VAR par: Dialog.Par)
Guard for the Strikeout command.
PROCEDURE ToggleNoFocus
Makes a focusable container non-focusable, or vice versa, by changing its mode in an appropriate way (-> Containers).
PROCEDURE ToggleNoFocusGuard (VAR par: Dialog.Par)
Guard for the ToggleNoFocus command.
PROCEDURE TypeNotifier (op, from, to: INTEGER)
PROCEDURE TypefaceGuard (VAR par: Dialog.Par)
Guard for the Font command.
PROCEDURE Underline
Sets the selection to the underline style.
PROCEDURE UnderlineGuard (VAR par: Dialog.Par)
Guard for the Underline command.
PROCEDURE Undo
Undoes the most recent command.
PROCEDURE UndoGuard (VAR par: Dialog.Par)
Guard for the Undo command.
PROCEDURE UpdateAll
PROCEDURE WidthGuard (VAR par: Dialog.Par)
Guard command which sets par.readOnly if layout.wType # 0, i.e., if mode is not "fixed".
PROCEDURE WindowGuard (VAR par: Dialog.Par)
| Std/Docu/Cmds.odc |
StdCoder
DEFINITION StdCoder;
IMPORT TextModels, Views, Dialog;
TYPE
ParList = RECORD
list: Dialog.Selection;
storeAs: Dialog.String
END;
VAR par: ParList;
PROCEDURE CloseDialog;
PROCEDURE Decode;
PROCEDURE DecodeAllFromText (text: TextModels.Model; beg: INTEGER; ask: BOOLEAN);
PROCEDURE EncodeDocument;
PROCEDURE EncodeFile;
PROCEDURE EncodeFileList;
PROCEDURE EncodeFocus;
PROCEDURE EncodeSelection;
PROCEDURE EncodedInText (text: TextModels.Model; beg: INTEGER): TextModels.Model;
PROCEDURE EncodedView (v: Views.View): TextModels.Model;
PROCEDURE ListEncodedMaterial;
PROCEDURE Select (op, from, to: INTEGER);
PROCEDURE StoreAll;
PROCEDURE StoreSelection;
PROCEDURE StoreSelectionGuard (VAR p: Dialog.Par);
PROCEDURE StoreSingle;
PROCEDURE StoreSingleGuard (VAR p: Dialog.Par);
END StdCoder.
StdCoder (or Coder for short) can be used to encode a document, a view, a text stretch, or files into a textual form. The encoding uses characters that are expected not to be changed by any mail system. White space characters (blanks, tabs, new lines, etc.) may be added or removed arbitrarily, because they are ignored upon decoding.
Upon decoding a document or a text stretch a new window will be opened. Files will be stored on disk.
Suggested menu items, as they are standard in menu Tools:
"Encode Document" "" "StdCoder.EncodeDocument" "StdCmds.WindowGuard"
"Encode Selection" "" "StdCoder.EncodeSelection" "TextCmds.SelectionGuard"
"Encode File..." "" "StdCoder.EncodeFile" ""
"Encode File List" "" "StdCoder.EncodeFileList" "TextCmds.SelectionGuard"
"Decode..." "" "StdCoder.Decode" "TextCmds.FocusGuard"
"About Encoded Material" "" "StdCoder.ListEncodedMaterial" "TextCmds.FocusGuard"
PROCEDURE EncodeDocument
Guard: StdCmds.WindowGuard
Encodes the document in the current front window and opens a new window with the generated code.
PROCEDURE EncodeSelection
Guard: TextCmds.SelectionGuard
Encodes the current text selection, and opens a new window with the generated code.
PROCEDURE EncodeFile
Encodes one file determined through the standard file opening dialog and opens a new window with the generated code.
PROCEDURE EncodeFileList
Guard: TextCmds.SelectionGuard
Encodes several files and opens a new window with the generated code.
A list of valid file names must be selected. File names must be specified with their complete path name relative to the BlackBox directory. Use the slash ("/") or backslash ("\") character to separate the individual parts of the path name. (Example: Std/Code/Coder .)
The path name is stored along with the encoding to allow for easy decoding of entire file packages. However, sometimes a file is kept in a different place than where it should be installed later. In such a case, a destination path name can be specified. The path name to be used during decoding can be given after an "arrow" ("=>").
Example: NewStd/Code/NewCoder => Std/Code/Coder will lead to encoding of the file NewCoder in the directory NewStd/Code, but for decoding the name Std/Code/Coder will be used.
PROCEDURE Decode
Guard: TextCmds.FocusGuard
Decodes the information in the encoded text contained by the front window. The command scans for "StdCoder.Decode" as a tag that marks the begin of a code sequence. This allows e-mail headers and other text to precede the actual code. If a text selection is active in the front window, scanning will start at the begin of that selection.
Depending on the kind of encoded data, that is, on the command used for encoding, one of the following actions will be taken:
- if a document was encoded (EncodeDocument, EncodeSelection), it is opened in a new window.
- if a single file was encoded (EncodeFile), the standard file store dialog is opened allowing the user to store the file.
- if a list of files was encoded (EncodeFileList), a special dialog is opened allowing the user to select files for decoding. The path names included during the encoding are shown in a list. One or several files can be selected from that list. After pressing a command button the selected files will be decoded. If only one file is selected, the path name can be changed or the standard file store dialog can be used to browse the directory hierarchy. Via another command button all files can be decoded and stored under the listed names, regardless of the selection.
Note: The dialog should always be closed using the cancel button to allow StdCoder to release resources allocated temporarily to manage the dialog.
PROCEDURE ListEncodedMaterial
Guard: TextCmds.FocusGuard
Opens a text informing about what is encoded in the text displyed by the focus window. Like Decode, the command scans for a tag that marks the beginning of a code sequence.
In the programming interface, two further procedures are available:
PROCEDURE DecodeAllFromText (text: TextModels.Model; beg: INTEGER; ask: BOOLEAN);
Works like Decode, but uses the passed text as source instead of the focus. At text position beg a search for the tag is started and the text following the tag is processed. Like with Decode, encoded documents are opened in windows and single files are stored via the standard store dialog. If the code was generated through EncodeFileList, the behavior depends on the value of the parameter ask. If it equals to TRUE, a dialog is displayed as done by Decode and the user is put into control. If it equals to FALSE, no dialog is displayed, but all files are decoded and installed under the name stored with them. This behavior corresponds to pressing the "Decode All" button in the dialog.
PROCEDURE EncodedView (v: Views.View): TextModels.Model;
Generates a text containing the encoding of the passed view.
PROCEDURE EncodedInText (text: TextModels.Model; beg: INTEGER): TextModels.Model;
Generates a text containing information about what is encoded in "text". | Std/Docu/Coder.odc |
StdConfig
DEFINITION StdConfig;
PROCEDURE Setup;
END StdConfig.
BlackBox attempts to call the command StdConfig.Setup during start-up. The call allows to customize the configuration of BlackBox. Module Config is provided in source form and can be changed by the programmer arbitrarily. The default implementation looks like this:
MODULE StdConfig;
IMPORT Dialog;
PROCEDURE Setup*;
VAR res: INTEGER;
BEGIN
(* ... various file and clipboard converters are installed here ... *)
(* creating workspace *)
Dialog.Call("StdLog.Open", "", res)
END Setup;
END StdConfig.
This configuration causes the log window to be opened upon startup. The command is called after the complete BlackBox library, framework, and standard subsystems are loaded. StdConfig may import any BlackBox module. If it isn't needed, module StdConfig can be deleted.
CurrentConfiguration
PROCEDURE Setup
This procedure implemented in order to customize the initial BlackBox configuration after start-up.
It is called after all standard services and menus have been installed.
Note that similar to StdConfig, there may (but need not) be a module Startup with a command Setup. It has a similar purpose as StdConfig, but is called before the higher levels (text subsystem, form subsystem, etc.) are loaded. Consequently, Startup may not import the higher levels of BlackBox. Normally, Startup does not exist. It is only used under special circumstances, e.g., to overwrite the variable Dialog.appName.
| Std/Docu/Config.odc |
StdDebug
DEFINITION StdDebug;
END StdDebug.
For a distribution version of a BlackBox application or component, use this limited version of the BlackBox debugger. This limited version doesn't allow to follow pointers and similar interactions, it only creates a passive display of the error state. Since this is a text document that can be saved, it enables the user to send error information to the developer (e.g., via StdCoder).
StdDebug is installed during startup of BlackBox, if the full DevDebug could not be found.
| Std/Docu/Debug.odc |
StdDialog
This is a private module of BlackBox. Its existence is necessary for BlackBox to work correctly.
| Std/Docu/Dialog.odc |
StdFolds
DEFINITION StdFolds;
IMPORT TextModels, Views, Dialog;
CONST collapsed = TRUE; expanded = FALSE;
TYPE
Label = ARRAY 32 OF CHAR;
Fold = POINTER TO RECORD (Views.View)
leftSide-, collapsed-: BOOLEAN;
label-: Label;
(fold: Fold) Flip, NEW;
(fold: Fold) FlipNested, NEW;
(fold: Fold) HiddenText (): TextModels.Model, NEW;
(fold: Fold) MatchingFold (): Fold, NEW
END;
Directory = POINTER TO ABSTRACT RECORD
(d: Directory) New (collapsed: BOOLEAN; label: Label;
hiddenText: TextModels.Model): Fold, NEW, ABSTRACT
END;
VAR
foldData: RECORD
nested, useFilter: BOOLEAN;
filter, newLabel: Label
END;
dir-, stdDir-: Directory;
PROCEDURE CollapseFolds (text: TextModels.Model; nested: BOOLEAN; IN label: ARRAY OF CHAR);
PROCEDURE ExpandFolds (text: TextModels.Model; nested: BOOLEAN; IN label: ARRAY OF CHAR);
PROCEDURE Collapse;
PROCEDURE Expand;
PROCEDURE ZoomOut;
PROCEDURE ZoomIn;
PROCEDURE Overlaps (text: TextModels.Model; beg, end: INTEGER): BOOLEAN;
PROCEDURE Insert (text: TextModels.Model; label: Label; beg, end: INTEGER; collapsed: BOOLEAN);
PROCEDURE CreateGuard (VAR par: Dialog.Par);
PROCEDURE Create (state: INTEGER);
PROCEDURE SetDir (d: Directory);
PROCEDURE FindFirstFold;
PROCEDURE FindNextFold;
PROCEDURE CollapseLabel;
PROCEDURE ExpandLabel;
PROCEDURE SetLabel;
PROCEDURE SetLabelGuard (VAR p: Dialog.Par);
PROCEDURE FindLabelGuard (VAR par: Dialog.Par);
END StdFolds.
Fold views, also called folds, are views that always appear in pairs. They are only meaningful when embedded in texts. A pair, called the left and right fold, brackets a stretch of text and represent a second piece of text that is hidden. By clicking at a fold with the mouse, the stretch of text between the left and right fold is replaced with the hidden text, and the text that originally appeared between the folds becomes the hidden text. Clicking a second time at the same fold restores the original state. Because the primary use of folds is to hide longer stretches of text and replace them with a usually much shorter placeholder, a fold is said to be either in expanded or collapsed state. Try it!
This is a piece of text enclosed by folds in expanded modetext between collapsed folds
Folds can be nested, but the stretch between one pair of folds must not partially overlap another. Hierarchically nested folds are often used in program texts. By hiding a sequence of statements and writing a short comment between the collapsed folds, the resulting program text can be explored interactively in a top-down manner. Try it with this example!
PROCEDURE Enter (id: INTEGER; name: TextMappers.String; value: REAL);
VAR n, h, p: Node;
BEGIN
NEW(n); n.id := id; n.name := name; n.value := value;create new node n
h := list; p := NIL;
WHILE (h # NIL) & (h.id <= id) DO p := h; h := h.next END;search position in list
IF p # NIL THEN
p.next := ninsert between p and h
ELSE
list := ninsert at beginning
END;
n.next := hinsert in list
END Enter;enter a new value into the list
Instead of clicking manually through a deep hierarchy of folds, you can hold down the ctrl key while clicking at the fold. This expands or collapses a fold and all nested folds.
The following menu entries operate on folds. Create Fold in menu Tools inserts a new pair of folds in the focus text. The current text selection in the focus text will be bracketed by the newly inserted folds, which are in expanded state. Expand All in menu Tools expands all folds in the focus text. Similarly, Collapse All collapses all folds in the focus text.
Fold... in menu Tools opens a property inspector that lets you manipulate the folds in the focus text. The inspector looks like this:
Create Expanded Fold creates an expanded fold in the same way as Create Fold in menu Tools. Create Collapsed Fold creates a collapsed fold.
Find First searches in the focus text for the first occurence of a fold. If Use Filter is not checked then the very first fold in the text is selected. If Use Filter is checked then Find First searches for a fold which has a label equal to the filter criteria specified in the Use Filter: field. Find Next finds the next fold using the same criteria as Find First.
Collapse collapses all folds in the focus text which comply to the search critera specified by Use Filter. If Nested is checked the folds are searched for contained folds and these are also collapsed. Expand expands folds using Use Filter and Nested in the same way as Collapse.
When a fold is found or when a fold in the focus text is selected by the user its label is displayd in the field Label:. The label can be changed by typing a new label into the field and clicking on Set Label.
To describe the pre- and postconditions of procedures exported from StdFolds, we use the following pseudo-procedures.
Pos(f) designates the position of the fold view f in its hosting text.
0 <= Pos(f) < text.Length().
Stretch(p1, p2) stands for the text stretch [p1, p2) if p1 < p2 holds, or if p2 <= p1, then it denotes the text stretch [p2, p1).
Flipped(f) denotes the fold f in its dual, "flipped" state.
f.state = collapsed <=> Flipped(f).state = expanded.
Typical menu commands (typically in the Tools menu, some commands may be omitted in the standard distribution):
MENU
"Create Fold" "" "StdFolds.Create(1)" "StdFolds.CreateGuard"
"Expand All" "" "StdFolds.Expand" "TextCmds.FocusGuard"
"Collapse All" "" "StdFolds.Collapse" "TextCmds.FocusGuard"
"Fold..." "" "StdCmds.OpenToolDialog('Std/Rsrc/Folds', 'Folds')" ""
END
CONST collapsed, expanded
Possible values of field Fold.collapsed.
TYPE Label
String type for label property values.
TYPE Fold (Views.View)
View type of a fold.
leftSide-: BOOLEAN
Determines whether the view is the left or right element of a pair.
collapsed-: BOOLEAN
Determines whether the fold view currently is in expanded or collapsed state.
label-: Label
A string indicating the label property of the fold. If the fold has no label associated with it, label = "" holds.
PROCEDURE (fold: Fold) Flip
NEW
Changes the state of fold. The text stretch S between fold and fold.MatchingFold() is replaced by the text fold.HiddenText(). The stretch S will be the new hidden text.
Pre
fold # NIL 20
Post
(fold.MatchingFold() # NIL) & fold.collapsed'
~fold.collapsed
(fold.MatchingFold() # NIL) & ~fold.collapsed'
fold.collapsed
fold.MatchingFold() = NIL
no effect
PROCEDURE (fold: Fold) FlipNested
NEW
Changes the state of fold, and all fold views f between fold and fold.MatchingFold() for which f.state = fold.state.
Pre
fold # NIL 20
Post
(fold.MatchingFold() # NIL) & fold.collapsed'
~fold.collapsed
For all folds f between fold and fold.MatchingFold(): ~f.collapsed
(fold.MatchingFold() # NIL) & ~fold.collapsed'
fold.collapsed
For all folds f between fold and fold.MatchingFold(): f.collapsed
fold.MatchingFold() = NIL
no effect
PROCEDURE (fold: Fold) HiddenText (): TextModels.Model
NEW
Returns the text stretch that is currently hidden by the pair (fold, fold.MatchingFold()). The text should not be modified. If the hidden text stretch is of length zero, NIL is returned.
Pre
fold # NIL 20
Post
fold.MatchingFold() # NIL
[ let p1 := Pos(Flipped(fold)), p2 := Pos(Flipped(fold).MatchingFold() ]
ABS(p2 - p1) = 1 => result = NIL
ABS(p2 - p1) > 1 => result is Stretch(p1, p2)
fold.MatchingFold() = NIL
result = NIL
PROCEDURE (fold: Fold) MatchingFold (): Fold
NEW
Returns the matching fold view to fold, or NIL if none can be found.
Pre
fold # NIL 20
Post
~(fold.context IS TextModels.Context)
result = NIL
fold.context IS TextModels.Context
(fold.kind = left) & (result.kind = right) & Pos(fold) < Pos(result)
& (For all folds f with Pos(fold) < Pos(f) < Pos(result):
(f.MatchingFold() # NIL) & (Pos(fold) < Pos(f.MatchingFold() < Pos(result))
OR (fold.kind = right) & (result.kind = left) & (Pos(fold) > Pos(result)
& (For all folds f with Pos(result) < Pos(f) < Pos(fold):
(f.Matching # NIL) & (Pos(result) < Pos(f.MatchingFold() < Pos(fold))
OR result = NIL
TYPE Directory
ABSTRACT
Directory for fold views.
PROCEDURE (d: Directory) New (collapsed: BOOLEAN; IN label: Label;
hiddenText: TextModels.Model): Fold
NEW, ABSTRACT
Create a new fold view in state collapsed, with label, and with the text hiddenText. If hiddenText is NIL, it is a right fold, otherwise it is a left fold.
Post
result.leftSide = (hiddenText # NIL)
result.collapsed = collapsed
result.label = label
result.HiddenText() = hiddenText
PROCEDURE CollapseFolds (text: TextModels.Model; nested: BOOLEAN;
IN label: ARRAY OF CHAR)
If nested holds and label = "", all folds f in text with ~f.collapsed are flipped. If ~nested, only the outermost folds in the nesting hierarchy are flipped. If label # "", only folds with f.label = label are flipped.
Pre
text # NIL 20
PROCEDURE ExpandFolds (text: TextModels.Model; nested: BOOLEAN;
IN label: ARRAY OF CHAR)
If nested holds and label = "", all folds f in text with f.collapsed are flipped. If ~nested, only the outermost folds in the nesting hierarchy are flipped. If label # "", only folds with f.label = label are flipped.
Pre
20 text # NIL
PROCEDURE Collapse
Guard: TextCmds.FocusGuard
Collapse all fold views in the focus text.
PROCEDURE Expand
Guard: TextCmds.FocusGuard
Expand all fold views in the focus text.
PROCEDURE ZoomOut
Guard: TextCmds.FocusGuard
Collapse all outermost expanded fold views in the focus text.
PROCEDURE ZoomIn
Guard: TextCmds.FocusGuard
Expand all outermost collapsed views in the focus text.
PROCEDURE Overlaps (text: TextModels.Model; beg, end: INTEGER): BOOLEAN
Returns TRUE if the text stretch [beg, end) in text partially overlaps a pair (f, f.MatchingFold()) of fold views.
Pre
text # NIL 20
(beg >= 0) & (end <= text.Length()) & (beg <= end) 21
PROCEDURE Insert (text: TextModels.Model; IN label: Label; beg, end: INTEGER; collapsed: BOOLEAN)
Inserts a new pair (f1, f2) of fold views into text. The new pair will bracket the text stretch [beg, end). Flag collapsed determines whether the fold is inserted in collapsed or in expanded state.
Pre
text # NIL 20
(beg >= 0) & (end <= text.Length()) & (beg <= end) 21
Post
the text stretch [beg, end) does not partially overlap a pair of folds
Pos(f1) = beg
Pos(f2) = end+1
f1.MatchingFold() = f2
f1.collapsed = f2.collapsed
f1.HiddenText() = NIL
the text stretch [beg, end) partially overlaps a pair of folds
nothing is done
PROCEDURE CreateGuard (VAR par: Dialog.Par)
Sets par.disabled to TRUE when the text selection in the current focus text partially overlaps a pair (f, Matching(f)) of fold views. par.disabled is also set to TRUE if the focus text is shown in browser mode or mask mode, that is if the text cannot be modified.
PROCEDURE Create (state: INTEGER)
If CreateGuard holds, creates a a new pair of fold views and inserts them into the focus text, bracketing the current text selection or the caret position. Calls Insert(FocusText, selBeg, selEnd, state).
state = 0 generates a collapsed fold, state = 1 generates an expanded fold.
Pre
state IN {0, 1)
Post
state = 0
result.collapsed
state = 1
~result.collapsed
PROCEDURE SetDir (d: Directory)
Set directory.
The following variables and procedures are only used for the property inspector of the StdFolds.View:
VAR
foldData: RECORD
nested, useFilter: BOOLEAN;
filter, newLabel: Label
END;
PROCEDURE FindFirstFold;
PROCEDURE FindNextFold;
PROCEDURE CollapseLabel;
PROCEDURE ExpandLabel;
PROCEDURE SetLabel;
PROCEDURE SetLabelGuard (VAR p: Dialog.Par);
PROCEDURE FindLabelGuard (VAR par: Dialog.Par);
| Std/Docu/Folds.odc |
StdGrids
DEFINITION StdGrids;
IMPORT Models, Views, Ports, Properties, StdWindows;
CONST
activate = 1;
append = -1;
divider = 1;
horizontal = TRUE;
remove = 0;
setTitle = 2;
stack = 0;
vertical = FALSE;
TYPE
Context = POINTER TO EXTENSIBLE RECORD (GenericContext)
filler-: View;
view-: Views.View;
title-: Views.Title;
(fc: Context) Consider (VAR p: Models.Proposal);
(c: Context) GetSize (OUT w, h: UCs)
END;
GenericContext = POINTER TO ABSTRACT RECORD (Models.Context)
(c: GenericContext) Normalize (): BOOLEAN;
(c: GenericContext) ThisModel (): Models.Model
END;
Param = POINTER TO RECORD
color, tabHeight: INTEGER;
bgColor, gutterColor, marksColor, closerColor: Ports.Color;
closerSide: BOOLEAN;
closerMark: ARRAY 3 OF CHAR;
boldenFront: BOOLEAN;
selectedBgColor, nonselectedBgColor, strokeColor, strokeColorShaded, markColor: Ports.Color;
markIsBottom: BOOLEAN;
margins, gutterWidth: INTEGER;
debug: BOOLEAN;
InitDefaults-, Init-: PROCEDURE (par: ANYPTR)
END;
View = POINTER TO ABSTRACT RECORD (Views.View)
kind-: BYTE;
ctx-: POINTER TO ARRAY OF Context;
canDrop: PROCEDURE (v: View; ind: INTEGER): BOOLEAN;
transferCopy: PROCEDURE (source: Views.View; toV: View; toF: Views.Frame): Views.View;
backdrop: Views.View
END;
Proposal = RECORD (Models.Proposal)
op: INTEGER;
title: Views.Title
END;
RemoveMsg = RECORD (Views.CtrlMessage)
processed: BOOLEAN
END;
TabVerb = PROCEDURE (c: Context);
TrackMsg = RECORD (Views.Message)
name: Views.Title;
cnt: INTEGER;
track: View;
frame: Views.Frame
END;
TrackPropMsg = RECORD (Views.PropMessage)
done, poll: BOOLEAN;
name: Views.Title
END;
WindowPref = RECORD (Properties.Preference)
win: StdWindows.Window
END;
VAR
gp: Param;
PROCEDURE Activate (c: Context);
PROCEDURE AppendDivTile (f: View; view: Views.View; size: UCs; pSize: INTEGER);
PROCEDURE AppendStackTab (f: View; view: Views.View; IN title: Views.Title);
PROCEDURE Focus (v: View): Context;
PROCEDURE Len (f: View): INTEGER;
PROCEDURE NewDivider (vertical: BOOLEAN): Divider;
PROCEDURE NewStack (): Stack;
PROCEDURE Remove (c: Context);
PROCEDURE ThisFiller (v: Views.View): View;
PROCEDURE Transfer (what: Views.View; where: View; pos: INTEGER);
END StdGrids.
Module allows to make composit grids from several views.
CONST horizontal
Possible value for parameter vertical in procedure NewDivider.
CONST vertical
Possible value for parameter vertical in procedure NewDivider.
CONST append
Possible value for parameter pos in procedure Transfer.
CONST divider, stack
Kind of View
CONST remove, activate, setTitle
Possible ...
PROCEDURE NewDivider (vertical: BOOLEAN): Divider;
Creates new element of grid, which devides area in two.
PROCEDURE NewStack (): Stack;
Creates new element of grid, which puts several views with tabs switching panel.
PROCEDURE AppendDivTile (f: View; view: Views.View; size: UCs; pSize: REAL);
Append grid element to view to f. Make it size in BB points of pSize in percents.
PROCEDURE AppendStackTab (f: View; view: Views.View; IN title: Views.Title);
PROCEDURE Activate (c: Context);
PROCEDURE Remove (c: Context);
PROCEDURE ThisFiller (v: Views.View): View;
PROCEDURE Transfer (what: Views.View; where: View; pos: INTEGER);
PROCEDURE Focus (v: View): Context;
PROCEDURE Len (f: View): INTEGER; | Std/Docu/Grids.odc |
StdHeaders
DEFINITION StdHeaders;
IMPORT Dialog, Views, Fonts, Properties;
CONST alternate = 0; number = 1; head = 2; foot = 3; showFoot = 4;
TYPE
Prop = POINTER TO RECORD (Properties.Property)
alternate: BOOLEAN;
showFoot: BOOLEAN;
number: NumberInfo;
head, foot: Banner
END;
Banner = RECORD
left, right: ARRAY 128 OF CHAR;
gap: INTEGER
END;
NumberInfo = RECORD
new: BOOLEAN;
first: INTEGER
END;
VAR
dialog: RECORD
alternate, showFoot: BOOLEAN;
number: NumberInfo;
head, foot: Banner
END;
PROCEDURE New (p: Prop; f: Fonts.Font): Views.View;
PROCEDURE Deposit;
PROCEDURE InitDialog;
PROCEDURE NewNumberGuard (VAR par: Dialog.Par);
PROCEDURE AlternateGuard (VAR par: Dialog.Par);
PROCEDURE HeaderGuard (VAR par: Dialog.Par);
PROCEDURE Set;
END StdHeaders.
This module implements views that can be embedded in BlackBox texts, to provide page headers and/or footers upon printing.
Typical menu command:
"Insert Header" "" "StdHeaders.Deposit; StdCmds.PasteView" "TextCmds.FocusGuard"
A header in a text is invisible, except if Text -> Show Marks has been executed. Selecting a header view and then executing Edit -> Show Properties... (or double-clicking on the view) opens a property sheet that allows to set the following properties:
- "alternate": if checked, this option causes left and right pages to be distinguished, so that they can have different headers and footers.
- "Show Foot": if checked, this option makes the header view display the footer, otherwise it displays the header (when it is visible at all).
- "Start with new page number": if checked, the user can enter the page number for the page in which the view is embedded. It allows to change page numbering within a single document.
- "Right Head", "Right Foot", "Left Head", "Left Foot": these are the properties of the right / left headers / footers. They are (one-line) strings. Optionally, these strings may contain macros, as described below.
- "Head gap", "Foot gap": determines the distance between header/footer and the text area, in points.
- "Font...": allows to set the font that is used for the headers and footers.
The following macros can be used in the header/footer strings:
&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
These macros are evaluated upon printing (or upon display, when the header view is visible). The macro "&;" indicates a split point, which is a position in the string where the string can be broken apart to allow for a better layout. For example, the string "Left margin&;Right margin" allows the string part "Left margin" to be positioned at the left side of the page, and the string "Right margin" at the right side of the page. The split point becomes a kind of "elastic spring" that pushes the left and right string parts apart.
CONST alternate, number, head, foot, showFoot
Property numbers for the properties that are supported by header views.
TYPE Prop (Properties.Property)
Property descriptor for header views.
alternate: BOOLEAN
Determines whether left and right pages have their own headers/footers.
showFoot: BOOLEAN
Determines whether a visible header view shows the header or the footer.
number: NumberInfo
Determines the way in which page numbers are shown.
head, foot: Banner
Determines the way in which headers and footers are shown.
TYPE Banner
Determines the header or footer of a page (or pair of pages if "alternate" is chosen).
left, right: ARRAY 128 OF CHAR
Strings for the left and right header/footer. Supports macros as described at the beginning of this text.
gap: INTEGER gap >= 0
Distance between header/footer and the body of the text.
TYPE NumberInfo
Determines the way pages are numbered.
new: BOOLEAN
Determines whether page numbering starts anew, using the page number first.
first: INTEGER first >= 0
The starting page number that is used for the page in which the header view is embedded.
VAR dialog
Interactor for the property sheet.
alternate: BOOLEAN
Determines whether left and right pages have their own headers/footers.
showFoot: BOOLEAN
Determines whether a visible header view shows the header or the footer.
number: NumberInfo
Determines the way in which page numbers are shown.
head, foot: Banner
Determines the way in which headers and footers are shown.
PROCEDURE New (p: Prop; f: Fonts.Font): Views.View
Create a new header view with the given properties.
PROCEDURE Deposit
Deposit command for header views.
The following procedures are used for the property sheet (Std/Rsrc/Headers).
PROCEDURE InitDialog
PROCEDURE NewNumberGuard (VAR par: Dialog.Par)
PROCEDURE AlternateGuard (VAR par: Dialog.Par)
PROCEDURE HeaderGuard (VAR par: Dialog.Par)
PROCEDURE Set
| Std/Docu/Headers.odc |
StdInterpreter
DEFINITION StdInterpreter;
END StdInterpreter.
Module StdInterpreter implements a plug-in service for BlackBox: an interpreter for some forms of Component Pascal procedure calls. The text string to be interpreted must conform to the following syntax:
Command = Call { ";" Call }.
Call = ModuleName "." ProcedureName [ "(" Parameter { "," Parameter } ")" ].
Parameter = Integer | String | Boolean.
Integer = Decimal | Hex.
Decimal = [ "-" ] Digit { Digit }.
Hex = [ "-" ] HexDigit { HexDigit } "H".
String = " ' " { Char } " ' ".
Boolean = "TRUE" | "FALSE".
The calls are executed in the given sequence. Parameters corresponding to integers must be of type INTEGER. Parameters corresponding to strings must be value or IN parameters of type ARRAY OF CHAR. The called procedures must not return a value.
For example, the following string can be used to call the three given procedures:
"TurtleDraw.GotoPos(35, 587); TurtleDraw.ShowPen; TurtleDraw.WriteString('Hello')".
PROCEDURE GotoPos (x, y: INTEGER);
PROCEDURE ShowPen;
PROCEDURE WriteText (IN text: ARRAY OF CHAR);
Such statement sequences are used mainly in menu command configurations and in control properties.
Module StdInterpreter is installed during startup of BlackBox. Its service is made available through the procedure Dialog.Call.
| Std/Docu/Interpreter.odc |
Links & Targets
The Links & Targets dialog is used for inspecting and, if the text document is editable, setting the properties of links and targets. Links and targets are text stretches within pairs of link or target objects that can be made visible with the menu item Text -> Show Marks and hidden with Text -> Hide Marks.
This dialog can be opened by pressing the Ctrl key together with the right mouse button on a link or target. Alternatively it can be opened by selecting a text stretch containing links or targets and executing the Properties context menu item.
Link Properties
Type: The read-only value Link shows that a link has been selected.
Link: The command or semicolon-separated command sequence associated with this link. Executing the link means to execute this command or command sequence. Please note that string arguments must be enclosed in single quotes.
Important commands used in a link are:
StdCmds.OpenBrowser('<pathAndName>', '<title>')
Open the specified file with the specified window title in browser mode, i.e. read-only.
StdCmds.OpenDoc('<pathAndName>')
Open the specified file as an editable document.
StdLinks.ShowTarget('<targetIdentifier>')
Scroll to the specified target within the current document.
Dialog.OpenExternal('<pathAndName>')
Open the specified file with the platform's default mechanism for the file's file name extension. This can also be used for opening a web URL by using the 'http:' or 'https:' prefix.
Examples:
StdCmds.OpenBrowser('System/Rsrc/Menus', 'system menus')
StdCmds.OpenDoc('System/Rsrc/Menus')
StdLinks.ShowTarget('section1')
Dialog.OpenExternal('http://blackboxframework.org')
Close: Specifies if the document containg the link is closed when the link is executed.
always means to always close the document.
if Shift-Key is pressed means to close the document only when the Shift key is pressed. This is the default behavior.
never means to never close the document even if the Shift key is pressed. This is appropriate for example when scrolling to a different text position within the same document with the StdLinks.ShowTarget command.
Target Properties
Type: The read-only value Target shows that a target has been selected.
Target: The target identifier that can be used to scroll to this target by means of a StdLinks.ShowTarget('<targetIdentifier>') command.
Command Buttons
OK Applies the properties to the selected view(s) and closes the dialog box.
Cancel Closes the dialog box without applying the properties.
Apply Like OK but does not close the dialog box.
Help Opens this help text.
| Std/Docu/Links-Dialog.odc |
StdLinks
DEFINITION StdLinks;
IMPORT Dialog, Views;
TYPE
Link = POINTER TO RECORD (Views.View)
leftSide-: BOOLEAN;
(v: Link) GetCmd (OUT cmd: ARRAY OF CHAR), NEW
END;
Target = POINTER TO RECORD (Views.View)
leftSide-: BOOLEAN;
(t: Target) GetIdent (OUT ident: ARRAY OF CHAR), NEW
END;
Directory = POINTER TO ABSTRACT RECORD
(d: Directory) NewLink (IN cmd: ARRAY OF CHAR): Link, NEW, ABSTRACT;
(d: Directory) NewTarget (IN ident: ARRAY OF CHAR): Target, NEW, ABSTRACT
END;
VAR
par-: Link;
dir-, stdDir-: Directory;
PROCEDURE CreateGuard (VAR par: Dialog.Par);
PROCEDURE CreateLink;
PROCEDURE CreateTarget;
PROCEDURE ShowTarget (ident: ARRAY OF CHAR);
PROCEDURE SetDir (d: Directory);
END StdLinks.
Link views, also called links, are views that always appear in pairs. They are only meaningful when embedded in texts. A pair brackets a stretch of text and contains a command. This an example of a link:
Alinktotheusermanual
If you do not see anything special to the left and right of the above text stretch, use Text->ShowMarks to make the views visible.
If you click on either the left or right link view, the command associated with the link is executed. Moreover, the entire text stretch between the link pair is active also. The mouse cursor changes its shape when it points to the active stretch.
If you hold down the Ctrl key when clicking the right mouse button on a link, a dialog is opened that allows for inspecting and editing the link's properties. The Link property contains the command (or command sequence) of the link. The Close property defines if the document that contains the link is closed when the link is executed. This dialog is described more fully in Links & Targets.
If you hold down the Ctrl key when clicking the left mouse button on a link, the two views are transformed into a textual form:
<StdCmds.OpenBrowser('System/Docu/User-Man', 'User Manual')>Alinktotheusermanual<>
The syntax is "<" command sequence ">" text stretch "<" ">". The command sequence usually consists of a StdCmds.OpenBrowser command. However, any command may be used, e.g., like in the following specification:
<Dialog.Beep; Dialog.Beep>beepbeep<>
To turn this specification into an active text stretch, select it (from and including the first "<", to and including the last ">") and then execute Tools->CreateLink.
A possibly simpler way to create this link is to enter, then select, the text "beep beep" (without the quotes), then use the menu option Tools->Create Link; then type into the Link: field "Dialog.Beep; Dialog.Beep" (without the quotes); then click Apply. The blue coloring and underlining are applied automatically.
You may have noticed that the name "link" thus just denotes the most typical use of link views. They are not inherently specialized for text linking. The behavior is completely determined by the command sequence associated with them.
In order to use link views for hypertext linking, it must be possible to use link commands which open a particular piece of text. The standard command for this purpose is StdCmds.OpenBrowser. For example, the command "StdCmds.OpenBrowser('Obx/Docu/Sys-Map', 'Map to the Obx Subsystem')" opens the Obx map text in browser mode.
Sometimes it is useful to have a command which, as a reaction to activating it via a link view, scrolls the text in which the link view is embedded, to a certain target position. This target position can be marked with a pair of target views, which are created and handled in a similar way as link views. The command to scroll to a certain target view is ShowTarget. To determine which target to show, a target contains an arbitrary identifier name.
For example, the link view with the specification
<StdLinks.ShowTarget('first target')>showtarget<>
creates a link to a target given by the specification
<first target>this is the first target<>
MENU
"Create Link" "" "StdLinks.CreateLink" "StdLinks.CreateGuard"
"Create Target" "" "StdLinks.CreateTarget" "StdLinks.CreateGuard"
END
TYPE Link (Views.View)
View type for links.
leftSide-: BOOLEAN
Tells whether it is a left or a right view.
PROCEDURE (v: Link) GetCmd (OUT cmd: ARRAY OF CHAR)
NEW
Returns the link's command.
Post
leftSide = (cmd # "")
TYPE Target (Views.View)
View type for targets.
leftSide-: BOOLEAN
Tells whether it is a left or a right view.
PROCEDURE (t: Target) GetIdent (OUT ident: ARRAY OF CHAR)
NEW
Returns the target's identifier.
Post
leftSide = (ident # "")
TYPE Directory
ABSTRACT
Directory type for link/target views.
PROCEDURE (d: Directory) NewLink (IN cmd: ARRAY OF CHAR): Link
NEW, ABSTRACT
Returns a new link view with cmd as command string. It is a left view if cmd # "", otherwise a right view.
PROCEDURE (d: Directory) NewTarget (IN ident: ARRAY OF CHAR): Target
NEW, ABSTRACT
Returns a new target view with ident as identifier string. It is a left view if ident # "", otherwise a right view.
VAR par-: Link par # NIL exactly during the currently executed link command
A command in a link can get access to its (left) link view, and thus to its context, via this variable during the execution of the command.
VAR dir-, stdDir-: Directory
Link/target directories.
PROCEDURE CreateGuard (VAR par: Dialog.Par)
Menu guard procedure used for CreateLink and CreateTarget. par.disabled remains FALSE (i.e. the menu entry is enabled) if the focus view is a text view and has a selection.
PROCEDURE CreateLink
Insert a link into the focus text. If the selected text does not follow the special syntax described below, it is converted into a link (blue and underlined and embedded within a left and a right link view) and the link's property editor is opened.
If the selected text follows the syntax "<" command sequence ">" arbitrary text "<>", were the command sequence must not contain a ">" character, a link including the command sequence is inserted. The stretch "<" command sequence ">" is replaced with the left link view, the stretch "<>" is replaced with the right link view.
The link views can be shown/hidden with Text->ShowMarks and Text->HideMarks, respectively. To inspect or edit the command sequence of a link, click with the right mouse button on a link. Alternatively, click on one of the link views with the Ctrl key pressed. This replaces the views with the special syntax for creating the link.
PROCEDURE CreateTarget
Insert a target into the focus text. If the selected text does not follow the special syntax described below, it is converted into a target (embedded within a left and a right target view) and the target's property editor is opened.
If the selected text follows the syntax "<" target identifier ">" arbitrary text "<>", were the target identifier must not contain a ">" character, a target including the target identifier is inserted. The stretch "<" target identifier ">" is replaced with the left target view, the stretch "<>" is replaced with the right target view.
Target views can be shown/hidden with Text->ShowMarks and Text->HideMarks, respectively. To inspect or edit the identifier of a target, hold down the Ctrl key and click with the right mouse button on a target. Alternatively, click the left mouse button on one of the target views with the Ctrl key pressed. This replaces the views with the special syntax for creating the target.
PROCEDURE ShowTarget (ident: ARRAY OF CHAR)
Searches the first target view in the focus text whose target identifier equals ident. If one is found, the text is scrolled such that the target view is shown on the first line, and the text stretch between the left and right target views is selected. (Note: if the text is opened in mask mode, the selection is not visible.)
PROCEDURE SetDir (d: Directory)
Sets the link/target view directory.
| Std/Docu/Links.odc |
StdLoader
This module has a private interface, it is only used internally.
| Std/Docu/Loader.odc |
StdLog
DEFINITION StdLog;
IMPORT TextViews, Views, TextRulers, TextModels;
CONST
charCode = -1; decimal = 10; hexadecimal = -2;
hideBase = FALSE; showBase = TRUE;
VAR
buf-: TextModels.Model;
defruler-: TextRulers.Ruler;
dir-: TextViews.Directory;
text-: TextModels.Model;
PROCEDURE Bool (x: BOOLEAN);
PROCEDURE Char (ch: CHAR);
PROCEDURE Int (i: INTEGER);
PROCEDURE IntForm (x: LONGINT; base, minWidth: INTEGER; fillCh: CHAR; showBase: BOOLEAN);
PROCEDURE Real (x: REAL);
PROCEDURE RealForm (x: REAL; precision, minW, expW: INTEGER; fillCh: CHAR);
PROCEDURE Set (x: SET);
PROCEDURE String (IN str: ARRAY OF CHAR);
PROCEDURE ParamMsg (IN msg, p0, p1, p2: ARRAY OF CHAR);
PROCEDURE Msg (IN msg: ARRAY OF CHAR);
PROCEDURE Tab;
PROCEDURE Para;
PROCEDURE Ln;
PROCEDURE View (v: Views.View);
PROCEDURE ViewForm (v: Views.View; w, h: INTEGER);
PROCEDURE New;
PROCEDURE Open;
PROCEDURE Clear;
PROCEDURE NewView (): TextViews.View;
PROCEDURE SetDefaultRuler (ruler: TextRulers.Ruler);
PROCEDURE SetDir (d: TextViews.Directory);
END StdLog.
Module StdLog provides a log text and procedures that simplify writing into the log text. Typically, log windows are only used during development, not for end user environments. The log window is opened by the following statement in procedure StdConfig.Setup:
Dialog.Call("StdLog.Open", "", res)
CONST charCode
Possible value for parameter base of IntForm, asking for formatting integers following the syntax of Component Pascal numerical character literals. (For example, 0DX is the code for line, and 37X the code for "7".)
CONST decimal
Possible value for parameter base of IntForm, asking for formatting integers as decimal literals.
CONST hexadecimal
Possible value for parameter base of IntForm, asking for formatting integers as hexadecimal literals.
CONST hideBase
Possible value for parameter showBase of IntForm, asking for suppression of the base indicator.
CONST showBase
Possible value for parameter showBase of IntForm, asking for output of the base indicator.
PROCEDURE Bool (x: BOOLEAN)
Writes a Boolean value to the log.
Except for performance, equivalent to:
IF x THEN String("$TRUE") ELSE String("$FALSE") END
PROCEDURE Char (ch: CHAR)
Writes a character value to the log. For control characters the numerical literal form enclosed in spaces is written (e.g., " 9X " for a tab code).
Note that it is much more efficient to use String if more than one character needs to be written.
PROCEDURE Int (i: INTEGER)
Writes an integer value to the log.
Except for performance, equivalent to:
IntForm(x, decimal, 0, digitspace, showBase)
where digitspace = 8FX.
PROCEDURE IntForm (x: LONGINT; base, minWidth: INTEGER; fillCh: CHAR; showBase: BOOLEAN)
Write integer x. The numeral string used to represent the number is relative to base base. The total representation form 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 nondecimal, the base can be requested to form part of the representation using showBase. The special value base = charCode renders the base suffix "X", while base = hexadecimal renders the suffix "H". All other nondecimal bases are represented by a trailing "%" followed by the decimal numerical literal representing the base value itself. Nondecimal representations of negative integers are formed using a basecomplement form of width minWidth. E.g., x = -3 renders for base = 16 and minWidth = 2 as "FD".
Pre
(base = charCode) OR (base = hexadecimal) OR ((base >= 2) & (base <= 16)) 20
minWidth >= 0 22
PROCEDURE Real (x: REAL)
Writes a real value to the log.
Except for performance, equivalent to:
WriteRealForm(x, 16, 0, 0, digitspace)
where digitspace = 8FX.
PROCEDURE RealForm (x: REAL; precision, minW, expW: INTEGER; fillCh: CHAR)
Write real x. The numeral string used 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.
For more details, see also the description of Strings.RealToStringForm.
Pre
precision > 0 20
0 <= minW 21
expW <= 3 22
PROCEDURE Set (x: SET)
Writes a set value to the log.
Except for performance, equivalent to:
VAR i: INTEGER;
Char("{"); i := MIN(SET);
WHILE x # {} DO
IF i IN x THEN
Int(i); EXCL(x, i);
IF (i + 2 <= MAX(SET)) & (i + 1 IN x) & (i + 2 IN x) THEN
String("..");
x := x - {i + 1, i + 2}; INC(i, 3);
WHILE (i <= MAX(SET)) & (i IN x) DO EXCL(x, i); INC(i) END;
Int(i - 1)
END;
IF x # {} THEN String(", ") END
END;
INC(i)
END;
Char("}")
PROCEDURE String (IN str: ARRAY OF CHAR)
Writes a string value to the log.
PROCEDURE ParamMsg (IN msg, p0, p1, p2: ARRAY OF CHAR)
Writes a parameterized message string value mapped by the Dialog.MapParamString facility to the log.
PROCEDURE Msg (IN msg: ARRAY OF CHAR)
Writes a message string value mapped by the Dialog.MapParamString facility to the log.
Except for performance, equivalent to:
ParamMsg(msg, "", "", "")
PROCEDURE Tab
Writes a tab character (9X) to the log.
PROCEDURE Para
Writes a paragraph character (0EX) to the log. Afterwards, it makes sure that the current end of the log text is visible.
PROCEDURE Ln
Writes a carriage return character (0DX) to the log. Afterwards, it makes sure that the current end of the log text is visible.
PROCEDURE View (v: Views.View)
Writes a view to the log. The size of the view is determined by the text container in cooperation with the view itself.
PROCEDURE ViewForm (v: Views.View; w, h: INTEGER)
Writes a view to the log, and forces it to a particular size given in w and h in universal units.
PROCEDURE New
Used internally.
PROCEDURE Open
Opens a log window if none is open, otherwise it brings the log window to the top.
PROCEDURE Clear
Clears the log text.
PROCEDURE NewView (): TextViews.View
Used internally.
PROCEDURE SetDefaultRuler (ruler: TextRulers.Ruler)
Sets the default ruler.
Pre
ruler # NIL 20
Post
defruler = ruler
PROCEDURE SetDir (d: TextViews.Directory)
Set up the directory object for log text views.
Pre
d # NIL 20
Post
dir = d
VAR buf-: TextModels.Model
The buffer used internally for minimizing screen refreshes.
VAR defruler-: TextRulers.Ruler
The log text's default ruler.
VAR dir-: TextViews.Directory
Used internally.
VAR text-: TextModels.Model
The log text.
| Std/Docu/Log.odc |
StdMenuTool
DEFINITION StdMenuTool;
IMPORT TextModels;
PROCEDURE UpdateFromText (text: TextModels.Model);
PROCEDURE UpdateMenus;
PROCEDURE UpdateAllMenus;
PROCEDURE ListAllMenus;
PROCEDURE ThisMenu;
END StdMenuTool.
The menu tool is used during startup of BlackBox to set up the menus.
Typical menu entries:
MENU
"&Menus" "" "StdCmds.OpenDoc('System/Rsrc/Menus')" ""
"&All Menus" "" "StdMenuTool.ListAllMenus" ""
"&Update Menus" "" "StdMenuTool.UpdateMenus" "TextCmds.FocusGuard"
"U&pdate All Menus" "" "StdMenuTool.UpdateAllMenus" ""
END
PROCEDURE UpdateFromText (text: TextModels.Model)
Clears all menus and builds up a new menu bar according to the menu specification in text.
PROCEDURE UpdateMenus
Guard: TextCmds.FocusGuard
Clears all menus and builds up a new menu bar according to the new menu specification in the focus text.
PROCEDURE UpdateAllMenus
Clears all menus and builds up a new menu bar according to the menu specification in System/Rsrc/Menus.
PROCEDURE ListAllMenus
Builds up a text with hyperlinks to all available menu configuration texts, i.e., each subsystem's /Rsrc/Menus text.
PROCEDURE ThisMenu
Used internally (in the hyperlinks of the INCLUDE statements).
| Std/Docu/MenuTool.odc |
StdRasters
DEFINITION StdRasters;
IMPORT Files, Ports, Stores, Models, Views;
CONST
bilinear = 1;
deep = TRUE;
nearest = 0;
noSwap = FALSE;
reference = TRUE;
shallow = FALSE;
swap = TRUE;
TYPE
Directory = POINTER TO ABSTRACT RECORD
type-: Files.Type;
(d: Directory) HandlesFType (IN type: Files.Type): BOOLEAN, NEW, ABSTRACT;
(d: Directory) New (): Raster, NEW, ABSTRACT
END;
Image = POINTER TO RECORD
width, height, dpiX, dpiY: INTEGER;
data: POINTER TO RasterData
END;
ImageLoader = POINTER TO ABSTRACT RECORD
(ldr: ImageLoader) Detect (rd: Files.Reader): BOOLEAN, NEW, ABSTRACT;
(ldr: ImageLoader) GetInfo (rd: Files.Reader): Image, NEW, ABSTRACT;
(ldr: ImageLoader) Load (rd: Files.Reader): Image, NEW, ABSTRACT
END;
Model = POINTER TO RECORD (Models.Model)
raster-: Raster;
type-: Files.Type;
(m: Model) CopyFrom- (source: Stores.Store);
(m: Model) Externalize- (VAR wr: Stores.Writer);
(m: Model) Internalize- (VAR rd: Stores.Reader)
END;
Raster = POINTER TO ABSTRACT RECORD (Ports.Raster)
rd-: Files.Reader;
beg-, end-: INTEGER;
(r: Raster) InitFileRange-, NEW, EMPTY
END;
View = POINTER TO RECORD (Views.View)
(v: View) CopyFromModelView- (source: Views.View; model: Models.Model);
(v: View) Externalize- (VAR wr: Stores.Writer);
(v: View) HandlePropMsg- (VAR msg: Views.PropMessage);
(v: View) Internalize- (VAR rd: Stores.Reader);
(v: View) Restore (f: Views.Frame; _l, _t, _r, _b: INTEGER)
END;
RasterData = ARRAY OF Ports.Color;
PROCEDURE AddDirectory (d: Directory; type: Files.Type; loader: ImageLoader);
PROCEDURE CanHandle (IN ftype: Files.Type): BOOLEAN;
PROCEDURE Import (f: Files.File; OUT s: Stores.Store);
PROCEDURE InitFromFileRange (r: Raster; rd: Files.Reader; beg, end: INTEGER; copy: BOOLEAN);
PROCEDURE Load (r: Raster): Image;
PROCEDURE New (type: Files.Type): Raster;
PROCEDURE NewModel (r: Raster; IN type: Files.Type): Model;
PROCEDURE NewModelFromSpec (loc: Files.Locator; IN fname: Files.Name; reference: BOOLEAN): Model;
PROCEDURE NewView (m: Model): View;
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);
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);
END StdRasters.
TYPE
Image
Model <> Raster 1:1 Model <<> Raster N:1
If rasters are immutable, N:1 will do. But if they are not - which they may very well be not immutable, shall we desire to add any sophistication - then M:1 is no good.
Raster has a storage presentation (most likely, a packed one), and a memory presentation. The latter is actually of no interest to, well, any parts of the system except for where rasters are actually drawn or edited. Thus, when a raster is to be copied, this refers only to the storage presentation.
As a storage presentation, a file range will suffice. And it doesn't have to reside in memory! Thus, when a Raster is copied, a new file (range) for writing has to be provided. Until the copied Raster is externalized (at which point it is provided with an actual Stores.Writer), it's file range can be... well, actually, it can reside in a temporary file!!! Which is a) reasonable and b) very quick to do and c) could be replaced with in-memory files, shall there be a need for that!!! Whohoa! And there is no need to mess with file names, due to the fantastic BB file notion! Awesome! | Std/Docu/Rasters.odc |
Subsets and Splits