diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/.project gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/.project --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/.project 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/.project 2021-09-14 19:01:29.000000000 +0000 @@ -31,7 +31,7 @@ Description="Integrated Development Environment for Gambas" Authors="Benoît Minisini\nFabien Bodard\nCharlie Reinl\nJosé Luis Redrejo\nRobert Rowe\nTobias Boege" Arguments=[["-L"],["-t","/home/benoit/gambas/git/master/app/src/gambas3"],["--help"]] -Environment="GB_GUI=gb.gtk3\n GTK_DEBUG=interactive" +Environment="GB_GUI=gb.gtk3\n GTK_DEBUG=interactive\nGB_NO_JIT=1" TabSize=2 Translate=1 Language=en diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/.src/Component/CComponent.class gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/.src/Component/CComponent.class --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/.src/Component/CComponent.class 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/.src/Component/CComponent.class 2021-09-14 19:01:29.000000000 +0000 @@ -161,6 +161,7 @@ If {Library} Then hLibraryInfo = CLibraryInfo[Path] + hLibraryInfo.GetInfo() sPath = Temp$() File.Save(sPath, hLibraryInfo.Info) diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/.src/Editor/Form/CControl.class gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/.src/Editor/Form/CControl.class --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/.src/Editor/Form/CControl.class 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/.src/Editor/Form/CControl.class 2021-09-14 19:01:29.000000000 +0000 @@ -530,6 +530,10 @@ Else vRealVal = Picture.Load(File.Dir(Project.Path) &/ vRealVal) Endif + + Case "Image" + + vRealVal = Image.Load(File.Dir(Project.Path) &/ vRealVal) Case "Animation" diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/.src/Editor/Form/FMenu.class gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/.src/Editor/Form/FMenu.class --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/.src/Editor/Form/FMenu.class 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/.src/Editor/Form/FMenu.class 2021-09-14 19:01:29.000000000 +0000 @@ -1109,7 +1109,7 @@ X += D Width -= D Paint.Font.Italic = True - Paint.FillRect(X, Y + Height / 2, Paint.TextSize(sText).Width, 1, If(Row = gvwMenu.Row, Color.SelectedBackground, Color.TextBackground)) + Paint.FillRect(X, Y + Height / 2, Paint.TextSize(sText).Width, 1, If(Row = gvwMenu.Row, Color.LightBackground, Color.TextBackground)) Else @@ -1138,7 +1138,7 @@ gvwMenu.Data.Foreground = GetMenuColor($aMenu[Row]) - If Row = gvwMenu.Row Then gvwMenu.Data.Background = Color.SelectedBackground + If Row = gvwMenu.Row Then gvwMenu.Data.Background = Color.LightBackground If .Level = 0 Then gvwMenu.Data.Font.Bold = True diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/.src/Family/Report/CoordBox.class gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/.src/Family/Report/CoordBox.class --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/.src/Family/Report/CoordBox.class 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/.src/Family/Report/CoordBox.class 2021-09-14 19:01:29.000000000 +0000 @@ -170,25 +170,35 @@ Private Sub Border_Write(Value As Boolean) $bBorder = Value - $hBackground.Padding = If(Value, Style.TextBoxFrameWidth, 0) + $hBackground.Padding = If(Value, Style.FrameWidth, 0) Me.Refresh End Public Sub Background_Draw() - Dim iBg As Integer = Color.TextBackground + Dim iCol As Integer + Dim iState As Integer - If Me.Background <> Color.Default Then iBg = Me.Background + iCol = Style.BackgroundOf($hTextBox) - If $bBorder Then - Style.PaintBox(0, 0, Me.W, Me.H, Style.StateOf($hTextBox), iBg) + If $bBorder Then + + iState = Style.StateOf($hBackground) + If $hTextBox.HasFocus Then iState = iState Or Style.HasFocus + If $hBackground.Hovered Then iState = iState Or Style.Hovered + Style.PaintBox(0, 0, Paint.W, Paint.H, iState, iCol) + Else - Paint.FillRect(0, 0, Me.W, Me.H, iBg) + + Paint.FillRect(0, 0, Paint.W, Paint.H, iCol) + Endif End + + Private Function Editor_Read() As MaskBox Return $hTextBox diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/.src/FMain.class gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/.src/FMain.class --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/.src/FMain.class 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/.src/FMain.class 2021-09-14 19:01:29.000000000 +0000 @@ -96,7 +96,6 @@ 'tvwProject_LostFocus frmWelcome = New FWelcome(dwgWelcome) - frmWelcome.Hide Project.UseInheritance = Settings["/UseInheritance", True] btnUseInheritance.Value = Project.UseInheritance @@ -105,10 +104,9 @@ End -Public Sub Welcome() +Public Sub HideWelcome() - frmWelcome.Show - frmWelcome.SetFocus + frmWelcome.Hide End diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/.src/FMain.form gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/.src/FMain.form --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/.src/FMain.form 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/.src/FMain.form 2021-09-14 19:01:29.000000000 +0000 @@ -1391,6 +1391,7 @@ } { panProperty SidePanel MoveScaled(97,1,32,65) + Visible = False ToolTip = ("Properties") Arrangement = Arrange.Vertical Action = "property" diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/.src/Help/FHelpBrowser.class gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/.src/Help/FHelpBrowser.class --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/.src/Help/FHelpBrowser.class 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/.src/Help/FHelpBrowser.class 2021-09-14 19:01:29.000000000 +0000 @@ -285,10 +285,12 @@ Public Sub btnPrint_Click() - Printer1.OutputFile = "~/print.pdf" - $bPrint = False - If Printer1.Configure() Then Return - webHelp.Current.Print(Printer1) + ' Printer1.OutputFile = "~/print.pdf" + ' $bPrint = False + ' If Printer1.Configure() Then Return + ' webHelp.Current.Print(Printer1) + + webHelp.ExecJavascript("window.print();") End diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/.src/Help/FHelpBrowser.form gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/.src/Help/FHelpBrowser.form --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/.src/Help/FHelpBrowser.form 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/.src/Help/FHelpBrowser.form 2021-09-14 19:01:29.000000000 +0000 @@ -73,11 +73,12 @@ #Translate = False ToolTip = "Gambas web site" AutoResize = True - Text = "http://gambas.sourceforge.net" + Text = "Gambas web site" Picture = Picture["icon:/small/gambas"] } { btnPrint ToolButton MoveScaled(84,0,8,4) + Visible = False AutoResize = True Text = ("Print") Picture = Picture["icon:/small/print"] diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/.src/Help/FTips.class gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/.src/Help/FTips.class --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/.src/Help/FTips.class 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/.src/Help/FTips.class 2021-09-14 19:01:29.000000000 +0000 @@ -9,7 +9,7 @@ Dim hFic As File Dim sLig As String - hFic = Open "tips/tips.en" + hFic = Open "tips/tips.en.txt" While Not Eof(hFic) Line Input #hFic, sLig @@ -61,7 +61,7 @@ iPos = RInStr(sLang, ".") If iPos Then sLang = Left(sLang, iPos - 1) - sFile = "tips/tips." & sLang + sFile = "tips/tips." & sLang & ".txt" If Not Exist(sFile) Then iPos = InStr(sLang, "_") If iPos Then @@ -70,13 +70,13 @@ Endif Endif If Not Exist(sFile) Then - sFile = "tips/tips.en" + sFile = "tips/tips.en.txt" Endif sTip = File.Load(sFile) iPos = InStr(sTip, "[" & $aOrder[$iTip - 1] & "]") If iPos = 0 Then - sTip = File.Load("tips/tips.en") + sTip = File.Load("tips/tips.en.txt") Endif iPos = InStr(sTip, "[" & $aOrder[$iTip - 1] & "]") If iPos = 0 Then Return diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/.src/Project/Library/CLibraryInfo.class gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/.src/Project/Library/CLibraryInfo.class --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/.src/Project/Library/CLibraryInfo.class 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/.src/Project/Library/CLibraryInfo.class 2021-09-14 19:01:29.000000000 +0000 @@ -71,6 +71,7 @@ Else sSolve = sPath If sSolve Not Ends ".gambas" Then sSolve &= ".gambas" + If File.IsRelative(sSolve) Then sSolve = File.RealPath(Project.Dir &/ sSolve) Endif 'sSolve = File.SetExt(sSolve, "gambas") @@ -105,6 +106,7 @@ Path = sPath If Not sPath Or If Not Exist(sPath) Then + Error "gambas3: warning: library not found: "; Name NotFound = True Return Endif diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/.src/Project.module gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/.src/Project.module --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/.src/Project.module 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/.src/Project.module 2021-09-14 19:01:29.000000000 +0000 @@ -418,7 +418,9 @@ FMain.Show If sPath Then + If File.IsRelative(sPath) Then sPath = Application.Dir &/ sPath + If IsDir(sPath) Then Project.Open(sPath) For Each sPath In aOpenFile @@ -429,17 +431,19 @@ Else FMain.ShowWarning(("File not found!") & "\n\n" & sPath & "") Endif + If Not Project.Dir Then FMain.Close Dec Application.Busy Return Endif + + FMain.HideWelcome + Endif RefreshActivate - If Not sPath Then FMain.Welcome - Dec Application.Busy If Settings["/ShowTipOnStartup", True] Then diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.ca gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.ca --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.ca 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.ca 1970-01-01 00:00:00.000000000 +0000 @@ -1,463 +0,0 @@ -[WELCOME] - -

Benvingut a Gambas !

- -

Gambas és un entorn gràfic de desenvolupament basat en un intèrpret Basic avançat.

- -

El propòsit de Gambas és permetre crear aplicacions potents de manera fàcil i ràpida. Però la netedat dels vostres programes resta sota la vostra responsabilitat...

- -

Gaudiu-lo !

- -

Benoît Minisini
-g4mba5@gmail.com

- - -[STARTUP] - -

Cada projecte ha de tenir una classe d'inici. Aquesta classe d'inici ha de tenir definit un mètode públic i estàtic anomenat Main sense arguments, el qual actuarà com a mètode d'inici del vostre programa.

- -

Podeu definir la classe d'inici fent clic sobre ella amb el botó dret del ratolí a l'arbre de projecte, i seleccionant Classe d'inici al menú contextual.

- -

No és necessari definir un mètode Main en un formulari d'inici, per que ja en te un de predefinit.

- -

Aquest mètode d'inici predefinit instancia el formulari i el mostra, igual que a Visual Basic™.

- - -[OPEN] - -

La instrucció OPEN de Gambas no fa el mateix que la de Visual Basic. No retorna el fitxer com un integer, si no com un objecte File.

- -

Per tant, en comptes d'escriure :

- -
DIM handle AS Integer
-...
-OPEN "elmeufitxer" FOR READ AS #handle
- -

heu d'escriure :

- -
DIM handle AS File
-...
-handle = OPEN "elmeufitxer" FOR READ
- - -[CATDIR] - -

Sabeu que podeu concatenar noms de directori i noms de fitxer amb l'operador "&/"? Aquest operador afegeix si cal els separadors de directoris, així que el camí resultant és perfecte.

- -

Per exemple:

- -
PRINT "/home/gambas" &/ ".bashrc"
-/home/gambas/.bashrc
-
-PRINT "/home/gambas/" &/ "/tmp" &/ "foo.bar"
-/home/gambas/tmp/foo.bar
-
- -

No és meravellós ?

- - -[EXEC] - -

Podeu crear un fitxer executable de tot el vostre projecte. Seleccioneu Crea executable dins el menú Projecte.

- -

Quan Gambas crea un fitxer executable, el posa per defecte dins del directori del vostre projecte. El nom de l'executable és el mateix que el del vostre projecte.

- - -[PATH] -

-Els camins relatius tenen un significat especial a Gambas. -Sempre fan referència a fitxers dintre dels vostres projectes. -

-No existeix el concepte de directori actual, ni paraula clau com CHDIR per canviar-lo. -

-Aneu amb compte: només heu de fer servir camins relatius per accedir als fitxers del projecte, ja que els camins absoluts deixaran de funcionar quan creeu un executable. - - -[GLOBAL] - -No hi han variables globals a Gambas! -

-Com a solució temporal, poseu-les dins del mòdul principal i declareu-les com a PUBLIC. -

-Si en comptes d'un mòdul principal teniu un formulari principal al vostre projecte, llavors declareu-les com a STATIC PUBLIC. -

-Per accedir a aquestes variables heu de fer servir el nom de mòdul principal ò del formulari: ElMeuModulPrincipal.LaMevaVariableGlobal ò ElMeuFormulariPrincipal.LaMevaVariableGlobal. - - -[EMPTY] - -

Per saber si una cadena és buida, no és necessari fer servir la funció Len(). Ho poseu comprovar directament ja que una cadena buida és FALSE i una cadena no buida és TRUE.

- -

Per exemple, en comptes de fer :

- -
IF Len(LaMevaCadena) > 0 THEN ...
-IF Len(LaMevaCadena) = 0 THEN ...
- -

Heu de fer :

- -
IF LaMevaCadena THEN ...
-IF NOT LaMevaCadena THEN ...
- - -[TRANSLATE] - -

Les aplicacions del Gambas son totalment traduïbles, permetent que indiqueu quines cadenes s'han de traduir i quines no.

-

Per a marcar una cadena com a traduïble, només l'heu de tancar entre parèntesis:

- -

PRINT ("Traduïu-me")
-PRINT "Però no em traduïu!"
- - -[SUBST] - -

La substitució és molt útil per a la internacionalització de la vostra aplicació. -Es fa amb l'instrucció Subst().

- -

Té com a mínim 2 paràmetres. El primer és la màscara de text a on s'aplica la substitució. Després hi són les vostres variables, a on la primera té el número 1. S'usa d'aquesta manera: &1, &2, ...

- -
Subst(("Substitució de &1, &2 i &3"), "primer", "segon", "tercer")
-
-'...retornarà això:
-'Substitució de primer, segon i tercer
- - -[EVENT] - -

Tots els controls i tots els objectes que poden rebre esdeveniments, tenen un observador d'esdeveniments i un nom de grup d'esdeveniment.

- -

L'observador d'esdeveniments captura tots els esdeveniments rebuts per l'objecte, i el nom de grup de l'esdeveniment és el prefixe del procediment encarregat de gestionar l'esdeveniment.

- -

Per defecte, l'observador d'esdeveniments és l'objecte a on heu creat el control, i el nom de grup és el nom del control.

- -

D'aquesta manera, un formulari rep tots els esdeveniments produïts sobre el control que heu creat dins d'ell.

- -
' Gambas form
-Public Sub _new()
-  Dim hButton As Button
-  hButton = New Button(Me) As "ElMeuBoto"
-End
-
-Public Sub ElMeuBoto_Click()
-  Print "Heu fet clic a ElMeuBoto!"
-End
-
- - -[GROUP] - -

Tot control te la propietat (Group). Quan aquesta propietat es fa servir, el prefix del nom del gestor d'esdeveniments és el nom del grup i no el nom del control.

- -

Suposem que teniu un Botó anomenat btnAction amb el gestor d'esdeveniments Click següent :

- -
PUBLIC SUB btnAction_Click()
- -

Si definiu la propietat (Group) de btnAction com a ElMeuGrup, llavors el gestor d'esdeveniments que rebrà els esdeveniments del botó serà el següent :

- -
PUBLIC SUB ElMeuGrup_Click()
- -

Aquesta propietat us permet gestionar els esdeveniments de diversos controls en una sola funció. I els controls del mateix grup no han de ser del mateix tipus !

- -

Nota : Els veterans del vell Visual Basic reconeixeran el concepte de control array, però en una implementació més potent. :-)

- - -[FORM] - -

A Gambas, un formulari és el seu propi observador d'esdeveniments, de manera que podeu gestionar directament els seus esdeveniments (com Resize, Activate, ...) dins del seu propi codi de classe.

- -

D'aquesta manera, els novells provinents de Visual Basic no es desorientaran :-).

- - -[EMBED] - -

A Gambas podeu fer que qualsevol formulari estigui incrustat dins d'altres formularis !

- -

Per fer servir aquesta poderosa eina, només heu d'instanciar el formulari passant un contenidor pare com a últim argument del constructor.

- -

Per exemple :

-

DIM hForm AS MyDialog
-DIM hSuperControl AS MyForm

-' Crea un quadre de diàleg
-hForm = NEW MyDialog
-' Insereix un formulari dins d'aquest quadre de diàleg
-' Observeu que aquest formulari rep dos paràmetres abans del contenidor
-hSuperControl = NEW MyForm(Param1, Param2, MyDialog)
-' Mou i canvia la mida del formulari
-hSuperControl.Move(8, 8, 128, 64)
-

- -

Aneu amb compte: un formulari incrustat dins d'un altre formulari segueix sent un formulari, i per tant el seu propi observador d'esdeveniments.

- - -[TAG] - -

Cada control te una propietat anomenada Tag. Aquesta propietat és per al programador, i pot contenir qualsevol dada VARIANT que trobeu pertinent.

- -

Això és molt útil quan voleu distingir controls del mateix grup dins d'un gestor d'esdeveniments comú.

- - - -[LAST] - -

La paraula clau LAST retorna l'últim control que ha rebut un esdeveniment. Això és molt útil quan vulgueu escriure un gestor d'esdeveniments que sigui independent de qualsevol nom de control.

- -

Per exemple, suposem que voleu escriure un programa calculadora. -Heu definit deu botons, un per cada dígit, tots dins del mateix group "Digit". El valor Tag de cada control és el que es mostrarà en el botó. El vostre gestor d'esdeveniments tindria un aspecte com això :

- -

PUBLIC SUB Digit_Click()

-  Display = Display & LAST.Tag
-  RefreshDisplay

-END

- - -[LEFT] - -

Les ben conegudes rutines de BASIC Left$, Right$ i Mid$ tenen un comportament molt útil a Gambas

- -

El segon paràmetre de Left$ i Right$ és opcional, i és 1 per defecte.

- -

Left$("Gambas") retorna "G"
-Right$("Gambas") retorna "s"

- -

Aquest segon paràmetre pot ser negatiu, i llavors dona el nombre de caràcters que no es mostraran.

- -

Left$("Gambas", -2) retorna "Gamb"
-Right$("Gambas", -2) retorna "mbas"

- -

Així mateix, el tercer argument de Mid$ pot ser negatiu, i llavors representa el nombre de caràcters des del final de la cadena que no es mostraran.

- -

Mid$("Gambas", 2, -2) retorna "amb" - - -[OBSERVER] - -

La classe Observer us permet interceptar tots els esdeveniments produïts per un objecte abans de que siguin enviats.

- -
MyTextBox = NEW TextBox(ME) AS "MyTextBox"
-MyObserver = NEW Observer(MyTextBox) AS "MyObserver"
-...
-PUBLIC SUB MyObserver_KeyPress()
-  DEBUG "Obtingut primer"
-END
-
-PUBLIC SUB MyTextBox_KeyPress()
-  DEBUG "Obtingut després"
-END
- -L'Observer pot canceŀlar l'esdeveniment per prevenir que efectivament es produeixi. - - -[STRING] - -

Gambas fa servir el joc de caràcters UTF-8 per representar cadenes a la memòria.

- -

Però totes les funcions estàndard de cadenes del Gambas treballen amb ASCII: -Left, Mid, Right, UCase... - -

Si voleu manipular cadenes UTF-8, heu de fer servir els mètodes de la classe estàtica String, els quals tenen el mateix nom que els seus homòlegs estàndards. - -

PRINT Len("pròleg");; Left$("pròleg", 4)
-7 prò
-PRINT String.Len("pròleg");; String.Left("pròleg", 4)
-6 pròl
- - -[ASSIGNMENT] - -

El Gambas implementa les dreceres d'assignació tal com els programadors de C/C++ fan servir també. - -

LaMevaVariable += 2 és una equivalència de LaMevaVariable = LaMevaVariable + 2 - -

LaMevaVariable &= "Pròleg" és una equivalència de LaMevaVariable = LaMevaVariable & "Pròleg" - -

etc... - - -[DEBUG] - -

Podeu fer servir l'instrucció DEBUG per a imprimir missatges de depuració a la consola (és a dir, la sortida d'errors estàndard). Es comporta exactament igual a la instrucció PRINT. - -

Aquests son missatges prefixats amb el nom de la classe, nom del mètode i número de línia de la instrucció DEBUG. - -

Els missatges de depuració es suprimeixen automàticament quan es crea un executable sense informació de depuració. - - -[TRY] - -

La gestió d'errors al Gambas es fa amb les següents instruccions: -TRY, ERROR, CATCH, i FINALLY. - -

TRY prova d'executar la sentència sense llançar l'error. La instrucció ERROR es fa servir just després de saber si la sentència s'ha executat correctament. - -

TRY ElMeuFitxer = OPEN "/etc/password" FOR WRITE
-IF ERROR THEN PRINT "No puc fer el que vull!"
- - -[CATCH] - -

La gestió d'errors al Gambas es fa amb les següents instruccions: -TRY, ERROR, CATCH, i FINALLY. - -

CATCH indica el principi de la part de gestió d'errors d'una funció o procediment. -Es posa al final del codi de la funció. - -

El part del catch s'executa si es produeix un error entre el principi i el final de la funció. - -

Si es produeix un error dins la part del catch, aquest és tractat normalment. - -

SUB ProcessFile(FileName AS STRING)
-  ...
-  OPEN FileName FOR READ AS #hFile
-  ...
-  CLOSE #hFile
-CATCH ' S'executa només si hi ha un error
-  PRINT "No es pot processar el fitxer "; FileName
-END
- - -[FINALLY] - -

La gestió d'errors al Gambas es fa amb les següents instruccions: -TRY, ERROR, CATCH, i FINALLY. - -

FINALLY inclou el codi que s'executa al final de la funció, fins i tot si s'ha produït un error durant la seva execució. - -

La part finally no és obligatòria. Si hi ha una part catch a la funció, la part finally l'ha de precedir. - -

Si es produeix un error dins la part del finally, aquest és tractat normalment. - -

SUB ProcessFile(FileName AS STRING)
-  ...
-  OPEN FileName FOR READ AS #hFile
-  ...
-FINALLY ' S'executa sempre, fins i tot si s'ha produït un error
-  CLOSE #hFile
-CATCH ' S'executa només si hi ha un error
-  PRINT "No es pot processar el fitxer "; FileName
-END
- - -[OPTIONAL] - -

Les funcions i procediments al Gambas poden tenir paràmetres opcionals.

- -

Els paràmetres són opcionals simplement posant l'indicador OPTIONAL just a davant de la variable

- -
PRIVATE SUB LaMevaFuncio(param AS String, OPTIONAL optim AS String)
-  ...
-  PRINT param & " requerit, '" & optim "' opcional"
-  ...
-END
-
-'cridant la funció:
-
-LaMevaFuncio("parametre") 'sense argument opcional (si no cal)
-LaMevaFuncio("parametre", "parametre_opcional")
-
- - -[ARRAY] - -

Al Gambas podeu recórrer fàcilment una matriu d'una coŀlecció de variables amb la funció FOR EACH.

- -

Exemple:

- -
DIM xml AS NEW XmlDocument
-DIM node AS XmlNode
-DIM i AS Integer
-
-'Obre l'xml
-xml.Open("pokus.xml")
-'Children s'indexa via [i], perquè és una matriu
-FOR i = 0 TO xml.Root.Children.Count - 1
-  'Attributes es recorren via FOR EACH, perquè és una coŀlecció
-  FOR EACH node IN xml.Root.Children[i].Attributes
-    DEBUG node.Name;; Node.Value
-  NEXT
-NEXT
- - -[ICON] - -

Podeu fer servir les icones internes per a crear una interfície més agradable de la vostra aplicació, les quals estan disponibles en diverses mides (des de 16x16 fins a 128x128)

- -

Per exemple:

- -
Imatge1.Picture = Picture["icon:/32/warning"]
- - -[SETTINGS] - -

Si necessiteu desar la configuració del vostre programa (tal com la mida i posició de la finestra), llavors esteu de sort. Això és molt elegant i fàcil de fer a Gambas.

- -

Podeu desar tota la configuració d'un objecte, o només una propietat.

- -

Exemple:

- -
'Desa la posició d'un objecte
-Settings.Write(ME)
-
-'Carrega l'objecte
-Settings.Read(ME)
-
-'Desa la propietat
-Settings["win/x"] = ME.X
-
-'Llegeix la propietat
-'podeu utilitzar el valor per defecte com aquest: ["win/x", 0]
-ME.X = Settings["win/x"]
-
- -

Atenció: heu d'incloure el component: gb.settings

- - -[EDITOR] - -

Alguns consells de l'editor...

- -

Dues classes de comentaris

- -
' Comentari normal
-
'' Comentari en negreta
- -

Els comentaris en negreta es fan servir per a documentar el vostre codi.

- -

Com utilitzar fragments de codi

- -

Si escriviu main i després premeu la tecla TAB, s'insereix automàticament al vostre codi una funció d'inici Main estàtica pública. - -

Si escriviu ds i després premeu la tecla TAB, s'insereix automàticament una declaració de variable del tipus string, i seguidament ja podeu escriure el nom de la variable. - -

Els fragments de codi són totalment configurables des del diàleg de les opcions globals de l'IDE. - - -[END] - -

Ja heu llegit tots els consells del dia. Espero que us hàgiu convertit en un expert en Gambas! :-)

- -

Si voleu contribuir, envieu nous consells a l'adreça següent :

-

g4mba5@gmail.com

- -

Gràcies per endavant !

- - - - -[MESSAGE] - -

Per a informar als usuaris, podeu usar les classes del Gambas Message i Balloon. Message prové dels components (QT, GTK+)i el Balloon de gb.form.

- -

Message i Balloon tenen els següents tipus possibles: Message.Delete(), .Error(), .Info(), .Question() i .Warning()

- -

A cada botó del diàleg Message podeu establir les vostres pròpies etiquetes. Després de prémer el botó, us tornarà un valor numèric (de 1 a X, depenent del tipus i la quantitat de botons).

- -
DEBUG Message.Info("Bon dia món!")  'retornarà 1
-
-Message("Bon dia món!")  'El mateix però el formulari més curt
- -

Mentre creeu el Balloon heu de definir el contenidor pare. -Opcionalment podeu definir el temps de mostra en ms, i la posició X,Y.

- -
Balloon.Info("Bon dia món!", ME)
-'Mostrarà el «ballon» dins el formulari principal
-
-'més reduït sense icona: Balloon("Bon dia món!", ME)
diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.ca.txt gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.ca.txt --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.ca.txt 1970-01-01 00:00:00.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.ca.txt 2021-09-14 19:01:29.000000000 +0000 @@ -0,0 +1,463 @@ +[WELCOME] + +

Benvingut a Gambas !

+ +

Gambas és un entorn gràfic de desenvolupament basat en un intèrpret Basic avançat.

+ +

El propòsit de Gambas és permetre crear aplicacions potents de manera fàcil i ràpida. Però la netedat dels vostres programes resta sota la vostra responsabilitat...

+ +

Gaudiu-lo !

+ +

Benoît Minisini
+g4mba5@gmail.com

+ + +[STARTUP] + +

Cada projecte ha de tenir una classe d'inici. Aquesta classe d'inici ha de tenir definit un mètode públic i estàtic anomenat Main sense arguments, el qual actuarà com a mètode d'inici del vostre programa.

+ +

Podeu definir la classe d'inici fent clic sobre ella amb el botó dret del ratolí a l'arbre de projecte, i seleccionant Classe d'inici al menú contextual.

+ +

No és necessari definir un mètode Main en un formulari d'inici, per que ja en te un de predefinit.

+ +

Aquest mètode d'inici predefinit instancia el formulari i el mostra, igual que a Visual Basic™.

+ + +[OPEN] + +

La instrucció OPEN de Gambas no fa el mateix que la de Visual Basic. No retorna el fitxer com un integer, si no com un objecte File.

+ +

Per tant, en comptes d'escriure :

+ +
DIM handle AS Integer
+...
+OPEN "elmeufitxer" FOR READ AS #handle
+ +

heu d'escriure :

+ +
DIM handle AS File
+...
+handle = OPEN "elmeufitxer" FOR READ
+ + +[CATDIR] + +

Sabeu que podeu concatenar noms de directori i noms de fitxer amb l'operador "&/"? Aquest operador afegeix si cal els separadors de directoris, així que el camí resultant és perfecte.

+ +

Per exemple:

+ +
PRINT "/home/gambas" &/ ".bashrc"
+/home/gambas/.bashrc
+
+PRINT "/home/gambas/" &/ "/tmp" &/ "foo.bar"
+/home/gambas/tmp/foo.bar
+
+ +

No és meravellós ?

+ + +[EXEC] + +

Podeu crear un fitxer executable de tot el vostre projecte. Seleccioneu Crea executable dins el menú Projecte.

+ +

Quan Gambas crea un fitxer executable, el posa per defecte dins del directori del vostre projecte. El nom de l'executable és el mateix que el del vostre projecte.

+ + +[PATH] +

+Els camins relatius tenen un significat especial a Gambas. +Sempre fan referència a fitxers dintre dels vostres projectes. +

+No existeix el concepte de directori actual, ni paraula clau com CHDIR per canviar-lo. +

+Aneu amb compte: només heu de fer servir camins relatius per accedir als fitxers del projecte, ja que els camins absoluts deixaran de funcionar quan creeu un executable. + + +[GLOBAL] + +No hi han variables globals a Gambas! +

+Com a solució temporal, poseu-les dins del mòdul principal i declareu-les com a PUBLIC. +

+Si en comptes d'un mòdul principal teniu un formulari principal al vostre projecte, llavors declareu-les com a STATIC PUBLIC. +

+Per accedir a aquestes variables heu de fer servir el nom de mòdul principal ò del formulari: ElMeuModulPrincipal.LaMevaVariableGlobal ò ElMeuFormulariPrincipal.LaMevaVariableGlobal. + + +[EMPTY] + +

Per saber si una cadena és buida, no és necessari fer servir la funció Len(). Ho poseu comprovar directament ja que una cadena buida és FALSE i una cadena no buida és TRUE.

+ +

Per exemple, en comptes de fer :

+ +
IF Len(LaMevaCadena) > 0 THEN ...
+IF Len(LaMevaCadena) = 0 THEN ...
+ +

Heu de fer :

+ +
IF LaMevaCadena THEN ...
+IF NOT LaMevaCadena THEN ...
+ + +[TRANSLATE] + +

Les aplicacions del Gambas son totalment traduïbles, permetent que indiqueu quines cadenes s'han de traduir i quines no.

+

Per a marcar una cadena com a traduïble, només l'heu de tancar entre parèntesis:

+ +

PRINT ("Traduïu-me")
+PRINT "Però no em traduïu!"
+ + +[SUBST] + +

La substitució és molt útil per a la internacionalització de la vostra aplicació. +Es fa amb l'instrucció Subst().

+ +

Té com a mínim 2 paràmetres. El primer és la màscara de text a on s'aplica la substitució. Després hi són les vostres variables, a on la primera té el número 1. S'usa d'aquesta manera: &1, &2, ...

+ +
Subst(("Substitució de &1, &2 i &3"), "primer", "segon", "tercer")
+
+'...retornarà això:
+'Substitució de primer, segon i tercer
+ + +[EVENT] + +

Tots els controls i tots els objectes que poden rebre esdeveniments, tenen un observador d'esdeveniments i un nom de grup d'esdeveniment.

+ +

L'observador d'esdeveniments captura tots els esdeveniments rebuts per l'objecte, i el nom de grup de l'esdeveniment és el prefixe del procediment encarregat de gestionar l'esdeveniment.

+ +

Per defecte, l'observador d'esdeveniments és l'objecte a on heu creat el control, i el nom de grup és el nom del control.

+ +

D'aquesta manera, un formulari rep tots els esdeveniments produïts sobre el control que heu creat dins d'ell.

+ +
' Gambas form
+Public Sub _new()
+  Dim hButton As Button
+  hButton = New Button(Me) As "ElMeuBoto"
+End
+
+Public Sub ElMeuBoto_Click()
+  Print "Heu fet clic a ElMeuBoto!"
+End
+
+ + +[GROUP] + +

Tot control te la propietat (Group). Quan aquesta propietat es fa servir, el prefix del nom del gestor d'esdeveniments és el nom del grup i no el nom del control.

+ +

Suposem que teniu un Botó anomenat btnAction amb el gestor d'esdeveniments Click següent :

+ +
PUBLIC SUB btnAction_Click()
+ +

Si definiu la propietat (Group) de btnAction com a ElMeuGrup, llavors el gestor d'esdeveniments que rebrà els esdeveniments del botó serà el següent :

+ +
PUBLIC SUB ElMeuGrup_Click()
+ +

Aquesta propietat us permet gestionar els esdeveniments de diversos controls en una sola funció. I els controls del mateix grup no han de ser del mateix tipus !

+ +

Nota : Els veterans del vell Visual Basic reconeixeran el concepte de control array, però en una implementació més potent. :-)

+ + +[FORM] + +

A Gambas, un formulari és el seu propi observador d'esdeveniments, de manera que podeu gestionar directament els seus esdeveniments (com Resize, Activate, ...) dins del seu propi codi de classe.

+ +

D'aquesta manera, els novells provinents de Visual Basic no es desorientaran :-).

+ + +[EMBED] + +

A Gambas podeu fer que qualsevol formulari estigui incrustat dins d'altres formularis !

+ +

Per fer servir aquesta poderosa eina, només heu d'instanciar el formulari passant un contenidor pare com a últim argument del constructor.

+ +

Per exemple :

+

DIM hForm AS MyDialog
+DIM hSuperControl AS MyForm

+' Crea un quadre de diàleg
+hForm = NEW MyDialog
+' Insereix un formulari dins d'aquest quadre de diàleg
+' Observeu que aquest formulari rep dos paràmetres abans del contenidor
+hSuperControl = NEW MyForm(Param1, Param2, MyDialog)
+' Mou i canvia la mida del formulari
+hSuperControl.Move(8, 8, 128, 64)
+

+ +

Aneu amb compte: un formulari incrustat dins d'un altre formulari segueix sent un formulari, i per tant el seu propi observador d'esdeveniments.

+ + +[TAG] + +

Cada control te una propietat anomenada Tag. Aquesta propietat és per al programador, i pot contenir qualsevol dada VARIANT que trobeu pertinent.

+ +

Això és molt útil quan voleu distingir controls del mateix grup dins d'un gestor d'esdeveniments comú.

+ + + +[LAST] + +

La paraula clau LAST retorna l'últim control que ha rebut un esdeveniment. Això és molt útil quan vulgueu escriure un gestor d'esdeveniments que sigui independent de qualsevol nom de control.

+ +

Per exemple, suposem que voleu escriure un programa calculadora. +Heu definit deu botons, un per cada dígit, tots dins del mateix group "Digit". El valor Tag de cada control és el que es mostrarà en el botó. El vostre gestor d'esdeveniments tindria un aspecte com això :

+ +

PUBLIC SUB Digit_Click()

+  Display = Display & LAST.Tag
+  RefreshDisplay

+END

+ + +[LEFT] + +

Les ben conegudes rutines de BASIC Left$, Right$ i Mid$ tenen un comportament molt útil a Gambas

+ +

El segon paràmetre de Left$ i Right$ és opcional, i és 1 per defecte.

+ +

Left$("Gambas") retorna "G"
+Right$("Gambas") retorna "s"

+ +

Aquest segon paràmetre pot ser negatiu, i llavors dona el nombre de caràcters que no es mostraran.

+ +

Left$("Gambas", -2) retorna "Gamb"
+Right$("Gambas", -2) retorna "mbas"

+ +

Així mateix, el tercer argument de Mid$ pot ser negatiu, i llavors representa el nombre de caràcters des del final de la cadena que no es mostraran.

+ +

Mid$("Gambas", 2, -2) retorna "amb" + + +[OBSERVER] + +

La classe Observer us permet interceptar tots els esdeveniments produïts per un objecte abans de que siguin enviats.

+ +
MyTextBox = NEW TextBox(ME) AS "MyTextBox"
+MyObserver = NEW Observer(MyTextBox) AS "MyObserver"
+...
+PUBLIC SUB MyObserver_KeyPress()
+  DEBUG "Obtingut primer"
+END
+
+PUBLIC SUB MyTextBox_KeyPress()
+  DEBUG "Obtingut després"
+END
+ +L'Observer pot canceŀlar l'esdeveniment per prevenir que efectivament es produeixi. + + +[STRING] + +

Gambas fa servir el joc de caràcters UTF-8 per representar cadenes a la memòria.

+ +

Però totes les funcions estàndard de cadenes del Gambas treballen amb ASCII: +Left, Mid, Right, UCase... + +

Si voleu manipular cadenes UTF-8, heu de fer servir els mètodes de la classe estàtica String, els quals tenen el mateix nom que els seus homòlegs estàndards. + +

PRINT Len("pròleg");; Left$("pròleg", 4)
+7 prò
+PRINT String.Len("pròleg");; String.Left("pròleg", 4)
+6 pròl
+ + +[ASSIGNMENT] + +

El Gambas implementa les dreceres d'assignació tal com els programadors de C/C++ fan servir també. + +

LaMevaVariable += 2 és una equivalència de LaMevaVariable = LaMevaVariable + 2 + +

LaMevaVariable &= "Pròleg" és una equivalència de LaMevaVariable = LaMevaVariable & "Pròleg" + +

etc... + + +[DEBUG] + +

Podeu fer servir l'instrucció DEBUG per a imprimir missatges de depuració a la consola (és a dir, la sortida d'errors estàndard). Es comporta exactament igual a la instrucció PRINT. + +

Aquests son missatges prefixats amb el nom de la classe, nom del mètode i número de línia de la instrucció DEBUG. + +

Els missatges de depuració es suprimeixen automàticament quan es crea un executable sense informació de depuració. + + +[TRY] + +

La gestió d'errors al Gambas es fa amb les següents instruccions: +TRY, ERROR, CATCH, i FINALLY. + +

TRY prova d'executar la sentència sense llançar l'error. La instrucció ERROR es fa servir just després de saber si la sentència s'ha executat correctament. + +

TRY ElMeuFitxer = OPEN "/etc/password" FOR WRITE
+IF ERROR THEN PRINT "No puc fer el que vull!"
+ + +[CATCH] + +

La gestió d'errors al Gambas es fa amb les següents instruccions: +TRY, ERROR, CATCH, i FINALLY. + +

CATCH indica el principi de la part de gestió d'errors d'una funció o procediment. +Es posa al final del codi de la funció. + +

El part del catch s'executa si es produeix un error entre el principi i el final de la funció. + +

Si es produeix un error dins la part del catch, aquest és tractat normalment. + +

SUB ProcessFile(FileName AS STRING)
+  ...
+  OPEN FileName FOR READ AS #hFile
+  ...
+  CLOSE #hFile
+CATCH ' S'executa només si hi ha un error
+  PRINT "No es pot processar el fitxer "; FileName
+END
+ + +[FINALLY] + +

La gestió d'errors al Gambas es fa amb les següents instruccions: +TRY, ERROR, CATCH, i FINALLY. + +

FINALLY inclou el codi que s'executa al final de la funció, fins i tot si s'ha produït un error durant la seva execució. + +

La part finally no és obligatòria. Si hi ha una part catch a la funció, la part finally l'ha de precedir. + +

Si es produeix un error dins la part del finally, aquest és tractat normalment. + +

SUB ProcessFile(FileName AS STRING)
+  ...
+  OPEN FileName FOR READ AS #hFile
+  ...
+FINALLY ' S'executa sempre, fins i tot si s'ha produït un error
+  CLOSE #hFile
+CATCH ' S'executa només si hi ha un error
+  PRINT "No es pot processar el fitxer "; FileName
+END
+ + +[OPTIONAL] + +

Les funcions i procediments al Gambas poden tenir paràmetres opcionals.

+ +

Els paràmetres són opcionals simplement posant l'indicador OPTIONAL just a davant de la variable

+ +
PRIVATE SUB LaMevaFuncio(param AS String, OPTIONAL optim AS String)
+  ...
+  PRINT param & " requerit, '" & optim "' opcional"
+  ...
+END
+
+'cridant la funció:
+
+LaMevaFuncio("parametre") 'sense argument opcional (si no cal)
+LaMevaFuncio("parametre", "parametre_opcional")
+
+ + +[ARRAY] + +

Al Gambas podeu recórrer fàcilment una matriu d'una coŀlecció de variables amb la funció FOR EACH.

+ +

Exemple:

+ +
DIM xml AS NEW XmlDocument
+DIM node AS XmlNode
+DIM i AS Integer
+
+'Obre l'xml
+xml.Open("pokus.xml")
+'Children s'indexa via [i], perquè és una matriu
+FOR i = 0 TO xml.Root.Children.Count - 1
+  'Attributes es recorren via FOR EACH, perquè és una coŀlecció
+  FOR EACH node IN xml.Root.Children[i].Attributes
+    DEBUG node.Name;; Node.Value
+  NEXT
+NEXT
+ + +[ICON] + +

Podeu fer servir les icones internes per a crear una interfície més agradable de la vostra aplicació, les quals estan disponibles en diverses mides (des de 16x16 fins a 128x128)

+ +

Per exemple:

+ +
Imatge1.Picture = Picture["icon:/32/warning"]
+ + +[SETTINGS] + +

Si necessiteu desar la configuració del vostre programa (tal com la mida i posició de la finestra), llavors esteu de sort. Això és molt elegant i fàcil de fer a Gambas.

+ +

Podeu desar tota la configuració d'un objecte, o només una propietat.

+ +

Exemple:

+ +
'Desa la posició d'un objecte
+Settings.Write(ME)
+
+'Carrega l'objecte
+Settings.Read(ME)
+
+'Desa la propietat
+Settings["win/x"] = ME.X
+
+'Llegeix la propietat
+'podeu utilitzar el valor per defecte com aquest: ["win/x", 0]
+ME.X = Settings["win/x"]
+
+ +

Atenció: heu d'incloure el component: gb.settings

+ + +[EDITOR] + +

Alguns consells de l'editor...

+ +

Dues classes de comentaris

+ +
' Comentari normal
+
'' Comentari en negreta
+ +

Els comentaris en negreta es fan servir per a documentar el vostre codi.

+ +

Com utilitzar fragments de codi

+ +

Si escriviu main i després premeu la tecla TAB, s'insereix automàticament al vostre codi una funció d'inici Main estàtica pública. + +

Si escriviu ds i després premeu la tecla TAB, s'insereix automàticament una declaració de variable del tipus string, i seguidament ja podeu escriure el nom de la variable. + +

Els fragments de codi són totalment configurables des del diàleg de les opcions globals de l'IDE. + + +[END] + +

Ja heu llegit tots els consells del dia. Espero que us hàgiu convertit en un expert en Gambas! :-)

+ +

Si voleu contribuir, envieu nous consells a l'adreça següent :

+

g4mba5@gmail.com

+ +

Gràcies per endavant !

+ + + + +[MESSAGE] + +

Per a informar als usuaris, podeu usar les classes del Gambas Message i Balloon. Message prové dels components (QT, GTK+)i el Balloon de gb.form.

+ +

Message i Balloon tenen els següents tipus possibles: Message.Delete(), .Error(), .Info(), .Question() i .Warning()

+ +

A cada botó del diàleg Message podeu establir les vostres pròpies etiquetes. Després de prémer el botó, us tornarà un valor numèric (de 1 a X, depenent del tipus i la quantitat de botons).

+ +
DEBUG Message.Info("Bon dia món!")  'retornarà 1
+
+Message("Bon dia món!")  'El mateix però el formulari més curt
+ +

Mentre creeu el Balloon heu de definir el contenidor pare. +Opcionalment podeu definir el temps de mostra en ms, i la posició X,Y.

+ +
Balloon.Info("Bon dia món!", ME)
+'Mostrarà el «ballon» dins el formulari principal
+
+'més reduït sense icona: Balloon("Bon dia món!", ME)
diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.cs gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.cs --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.cs 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.cs 1970-01-01 00:00:00.000000000 +0000 @@ -1,547 +0,0 @@ -[WELCOME] - -

Vítej v Gambasu !

- -

Gambas je grafické vývojové -prostředí založené na pokročilém Basic interpretovy.

- -

Cílem Gambasu je umožnit Vám, vytvářet -užitečné programy snadno a rychle. Ale čistota těchto programů -zůstává na vaší plné odpovědnosti...

- -

Užijte si to !

- -

Benoît Minisini
-g4mba5@gmail.com

- - -[STARTUP] - -

Každý projekt musí mít hlavní třídu. Hlavní třída definuje -veřejnou statickou metodu nazvanou Main, argumentů, -která bude fungovat jako spouštěcí metoda vašeho programu.

- -

Hlavní třídu můžete nastavit tak, že ve stromu projektu kliknete -pravým tlačítkem myši a v popup menu vyberete položku Hlavní třída.

- -

Po startu není nutné nastavovat methodu Main, protože je již přednastavená.

- -

Tato metoda je zodpovědná za vytváření instance a poté zobrazení formuláře, jako ve -Visual Basic™.

- - -[OPEN] - -

Instrukci OPEN nemůžete použít v Gambasu -stejně jako ve Visual Basic. Soubor totiž nevrácí integer, -ale objekt File.

- -

Takže místo:

- -
DIM handle AS Integer
-...
-OPEN "myfile" FOR READ AS #handle
- -

musíte psát:

- -
DIM handle AS File
-...
-handle = OPEN "myfile" FOR READ
- - -[CATDIR] - -Víte, že můžete spojit názvy adresářů a souborů operatorem &/ ? -

Tento operátor se v případě potřeby postará -o správné přidání oddělovače '/' do cesty.

- -

Například:

- -
PRINT "/home/gambas" &/ ".bashrc"
-/home/gambas/.bashrc
-
-PRINT "/home/gambas/" &/ "/tmp" &/ "foo.bar"
-/home/gambas/tmp/foo.bar
-
- -

No není to úžasné ?

- - -[EXEC] - -

Z celého projektu můžete vytvořit spustitelný soubor. Klikni v -menu Projekt a Vytvořit/Spustitelný....

- -

Když Gambas vytvoří spustitelný soubor, tak jej defaultně vloží -do stejné složky ve které se nachází projekt. -Spustitelný soubor má pak stejné jméno jako projekt.

- - -[PATH] - -

Relativní cesta má v Gambasu zvláštní význam. -Vždy se totiž odkazuje na soubory uvnitř svého projektů.

- -

Neexistuje žádný koncept akuálního adresáře, -ani žádné slovo pro změnu jako CHDIR.

- -

Buť tedy opatrný: musíš použít relativní cesty pouze pro přístup k -souborům projektu. Protože absolutní cesty již nefungují ve vytvořeném spustitelném programu.

- - -[GLOBAL] - -

V Gambasu nejsou globální proměnné!

- -

Jako dočasné řešení, je můžete vkládat do hlavního modulu a deklarovat je -jako PUBLIC.

- -

Pokud nemáte hlavní modul, ale hlavní formulář, -pak deklarujte jako STATIC PUBLIC.

- -

Pro přístup k těmto proměnným, musíte používat název modulu -nebo formuláře: MyMainModule.MyGlobalVariable nebo -MyMainForm.MyGlobalVariable.

- - -[EMPTY] - -

Chcete-li jestli je řetězec prázdný, není nutné srovnání s "" nebo používat -funkci Len(). Je možné testovat přímo, protože prázdný řetězec -je ekvivalentní k FALSE a neprázdný řetězec je ekvivalentní k TRUE.

- -

Například, než psát:

- -
IF Len(MyString) > 0 THEN ...
-IF Len(MyString) = 0 THEN ...
- -

Místo toho můžete psát:

- -
IF MyString THEN ...
-IF NOT MyString THEN ...
- - -[TRANSLATE] - -

Program napsaný v Gambasu je přeložitelný do jakéhokoli jazyka, -za předpokladu, že uvedete, které řezezce musí být přeloženy, a které ne.

-

Chcete-li označit řetězec pro překlad, stačí je uzavřít mezi kulaté závorky:

- -

PRINT ("Mě přelož")
-PRINT "Ale mě nepřekládej!"
- - -[EVENT] - -

Každý ovládací prvek či objekt, kterému lze přiřadit událost, má -pozorovatele událostí a událost název skupiny.

- -

Pozorovatel události zachytává každou událost vyvolanou objektem. Název skupiny -událostí tvoří prefix volané procedury, která se stará o vykonání události.

- -

Defaultně je pozorovatel události tvořen mateřským objektem kontrolního prvku -a název skupiny je tvořen názvem kontrolního prvku.

- -

Touto cestou formulář dostává všechny události vyvolané vnitřními prvky.

- -
' Gambas form
-DIM hButton AS Button
-
-PUBLIC SUB _new()
-  hButton = NEW Button(ME) AS "MyButton"
-END
-
-PUBLIC SUB MyButton_Click()
-  PRINT "You have clicked MyButton !"
-END
-
- - -[FORM] - -

V Gambasu, je formulář vlastní pozorovatel událostí, takže si -může svoje události spravovat přímo (jako Resize, -Activate, ...) ve svém vlastním kódu.

- -

Tímto způsobem, nováčci přícházející z Visual Basic -a nejsou dezorientovaný :-).

- - -[EMBED] - -

Do formuláře Gambasu můžete vložit jakýkoliv jiný formulář !

- -

Stačí předat rodičovský kontejner formuláře jako poslední argument konstruktoru.

- -

Například:

-

DIM hForm AS MyDialog
-DIM hSuperControl AS MyForm

-' Vytvoření dialogu
-hForm = NEW MyDialog
-' Vložení formuláře do tohoto dialogu
-' Všimněte si, formulář má ještě dva parametry před rodičovským kontejner
-hSuperControl = NEW MyForm(Param1, Param2, MyDialog)
-' Nastavení polohy a velikosti formuláře
-hSuperControl.Move(8, 8, 128, 64)
-

- -

Buďte opatrní: formulář vložený do jiného formuláře je stále formulářem, -a tak ma i vlastního pozorovatele událostí.

- - -[GROUP] - -

Každý ovládací prvek ma vlastnost (Group) [skupinová akce]. -Pokud je tato vlastnost nastavena, tak název skupiny je předpona pro zpracování událostí -a ne název ovladacího prvku.

- -

Předpokládejme, že máte Button nazvaný btnAction -s následným zpracováním událostí Click:

- -
PUBLIC SUB btnAction_Click()
- -

Pokud nastavíte vlastnost (Group) v btnAction na -MyGroup, pak zpracování událostí bude od tlačítka příjímat -následující událost:

- -
PUBLIC SUB MyGroup_Click()
- -

Tato vlastnost umožňuje zpracovávat události z různých ovládacích prvků -v jedné funkci. A ovladací prvky vůbec nemusí být stejné!

- -

Poznámka: Zkušený veterán Visual Basicu možná pozná -pojem control array, ale v mnohem silnější implementaci. :-)

- - -[TAG] - -

Kazdý ovládací prvek má vlastnost Tag. Tato vlastnost je pro -programátory, a může obsahovat jakoukoli VARIANTu dat, -kterou považujete za relevantní.

- -

Je to velmi užitečné, když chcete odlišit různé ovládací prvky -stejné skupiny při společném zpracování událostí.

- - -[LAST] - -

Klíčové slovo LAST vrací objekt posledního ovládacího prveku, od kterého -obdržel událost. Je to velmi užitečné, pokud chcete psát obsluhu událostí, -která je nezávislá na názvech prvků.

- -

Například, předpokládejme, že chceme napsat program kalkulačky. -Máte nadefinovaná tlačítka pro každé z deseti čísel. Každé je -ve stejné skupině (group) "Digit". Tag každého prvku -má nastaveno číslo, které je na tlačítku. Zpracování události pak -může vypadat takhle:

- -

PUBLIC SUB Digit_Click()

-  Display = Display & LAST.Tag
-  RefreshDisplay

-END

- - -[LEFT] - -

Známé rutiny BASICu jako Left$, Right$ -a Mid$ jsou i v Gambasu

- -

Druhý parametr Left$ a Right$ je volitelný, -a defultni hodnota je 1.

- -

Left$("Gambas") vrací "G"
-Right$("Gambas") vrací "s"

- -

Tento druhý parametr může být i záporný, a -pak udává počet znaků od konce řetězce.

- -

Left$("Gambas", -2) vrací "Gamb"
-Right$("Gambas", -2) vrací "mbas"

- -

Podobně, tak třetí parametr v Mid$ může být záporný, a -pak udává počet znaků od konce řetězce.

- -

Mid$("Gambas", 2, -2) vrací "amb"

- - -[OBSERVER] - -

Třída Observer (pozorovatel událostí) vám umožňuje zachytit všechny události -vyvolané objekty ještě před tím než jsou skutečně poslány.

- -
MyTextBox = NEW TextBox(ME) AS "MyTextBox"
-MyObserver = NEW Observer(MyTextBox) AS "MyObserver"
-...
-PUBLIC SUB MyObserver_KeyPress()
-  DEBUG "Spuštěno první"
-END
-
-PUBLIC SUB MyTextBox_KeyPress()
-  DEBUG "Spuštěno další"
-END
- -

Pozorovatel událostí může zastavit událost, v zájmu ochrany objektu.

- - -[STRING] - -

Gambas používá pro reprezentaci řetězců v paměti znakovou sadu UTF-8.

- -

Ale všechny standartní řetezcové funkce pracují s ASCII: -Left, Mid, Right, UCase...

- -

Pokud chcete pracovat s UTF-8 řetězci, musíte používat metody statické třídy String, -které mají stejné názvy jako jejich standartní protějšky.

- -
PRINT Len("bébé");; Left$("bébé", 3)
-6 bé
-PRINT String.Len("bébé");; String.Left("bébé", 3)
-4 béb
- - -[ASSIGNMENT] - -

Gambas implementuje zkrácené přiřazování na -které jsou zvykli programátoři z C/C++.

- -

MyVariable += 2 je ekvivalent -MyVariable = MyVariable + 2

- -

MyVariable *= 4 je ekvivalent -MyVariable = MyVariable * 4

- -

MyVariable &= "Great" je ekvivalent -MyVariable = MyVariable & "Great"

- -

A tak dále...

- - -[DEBUG] - -

Také můžete používat instrukci DEBUG pro tisk ladících zpráv do -konzole (tedy standartní chybový výstup). Chová se stejně jako instrukce PRINT.

- -

Tyto zprávy obsahuji název třídy, název metody a číslo řádku -z místa volání instrukce DEBUG.

- -

Při vytváření spustitelného souboru jsou ladící zprávy automaticky odstraněny.

- - -[TRY] - -

Správa řízení chyb je v Gambasu řízena skrze instrukce: -TRY, ERROR, CATCH, a FINALLY. - -

TRY se pokusí provést výraz bez chyb. Instrukce ERROR -se používá aby se vědělo, jestli byl výraz proveden správně.

- -
TRY MyFile = OPEN "/etc/password" FOR WRITE
-IF ERROR THEN PRINT "Nemůžu dělat, to co chci!"
- - -[CATCH] - -

Správa řízení chyb je v Gambasu řízena skrze instrukce: -TRY, ERROR, CATCH, a FINALLY.

- -

CATCH označuje začátek řízení chyb části funkce nebo procedůry. -Píše se na konec kodu funkce.

- -

Catch blok se provede jen tehdy, když se uvnitř výkoného bloku kodu, vyskytne chyba.

- -

Vyskatne-li se chyba během provádění bloku catch, je běžně zobrazena.

- -
SUB ProcessFile(FileName AS STRING)
-  ...
-  OPEN FileName FOR READ AS #hFile
-  ...
-  CLOSE #hFile
-CATCH ' Vykonán pouze v případě, že se vyskytla chyba
-  PRINT "Nemůže zpracovat soubor "; FileName
-END
- - -[FINALLY] - -

Správa řízení chyb je v Gambasu řízena skrze instrukce: -TRY, ERROR, CATCH, a FINALLY.

- -

FINALLY zavádí kód vykonání na konci funkce, -i když byla chyba vyvolána během jejího plnění.

- -

Finally blok není povinný. Je-li tu blok Catch blok ve funkci, -tak musí finally blok předcházet.

- -

Vyvstane-li chyba během provádění Finally bloku, je běžně zobrazena.

- -
SUB ProcessFile(FileName AS STRING)
-  ...
-  Open FileName For Read As #hFile
-  ...
-Finally ' Provedeno vždy, i když byla chyba vyvolána
-
-  Close #hFile
-  
-Catch ' Vykonán pouze v případě, že se vyskytla chyba
-  
-  Print "Cannot print file "; FileName
-  
-End
- - -[OPTIONAL] - -

Funke a procedry v Gambasu mohou mít volitelné parametry.

- -

Provádí se to tak že se před název proměnné napíše instrkukce OPTIONAL. -A ta oznamuje že je parametr volitelný.

- -
PRIVATE SUB MyFunction(param AS String, OPTIONAL optim AS String)
-  ...
-  PRINT "povinný " & param & ", nepovinný '" & optim "'"
-  ...
-END
-
-'volání v kodu:
-
-MyFunction("parametr") 'není-li za potřebí tak se nemusí volat
-MyFunction("parametr", "param")
-
- - -[ARRAY] - -

V Gambasu se dají procházet proměnné (typu array, collection) za pomocí FOR EACH -(pro collection a pole) nebo FOR cyklus (pro pole)

- -

Například:

- -
DIM xml AS NEW XmlDocument
-DIM node AS XmlNode
-DIM i AS Integer
-
-'otevre xml
-xml.Open("pokus.xml")
-'Children se musi indexovat přes [i]!, je to array
-FOR i = 0 TO xml.Root.Children.Count - 1
-  'Attributes se musí procházet přes FOR EACH, je to collection
-  FOR EACH node IN xml.Root.Children[i].Attributes
-    DEBUG node.Name;; Node.Value
-  NEXT
-NEXT
- - -[ICON] - -

Můžete použít i vestavěné ikony pro doplnění krásy své aplikace, -a máte zde i například na výběr rozměr od 16x16 až po 128x128

- -

Například:

- -
Image1.Picture = Picture["icon:/32/warning"]
-Image2.Picture = Picture["icon:/small/error"]
-
- -

Pozor: musíte mít zapnutou komponentu: gb.form. - - -[SETTINGS] - -

Pokud si potřebujete uložit konfigurací programu, -jako je třeba velikost a poloha okna, je to jednodušší než jste čekaly.

- -

Můžete ukládat konfiguraci celého objektu, nebo jen jeho dílčí hodnotu.

- -

Například:

- -
'uložení polohy onjektu
-Settings.Write(ME)
-
-'Načtení objektu
-Settings.Read(ME)
-
-'Uložení hodnoty
-Settings["win/x"] = ME.X
-
-'Načtení hodnoty
-'lze zadat i defaultni hodnotu: ["win/x", 0]
-ME.X = Settings["win/x"]
-
- -

Pozor: musíte mít zapnutou komponentu: gb.settings

- - -[MESSAGE] - -

V Gambasu můžete pro informování uživatele užít následující třídy: -Message a Balloon. -Message je z komponenty (QT, GTK+), a Balloon z gb.form.

- -

Třída Message a Balloon má možné typy: -Message.Delete(), .Error(), .Info(), .Question() a .Warning()

- -

U každého Message jdou nastavit i vlastní popisky tlačítek, po zmáčknutí tlačítka v dialogu je -vrácena číselná hodnota tlačítka od 1 do X, dle typu a počtu tlačítek.

- -
DEBUG Message.Info("Ahoj světe!")  'vrátí číslo 1
-
-Message("Ahoj světe!")  'To samé zkráceně
- -

Při vytváření Balloon se musí uvést rodičovský kontejner, volitelně jde nastavit i pozice X a Y, -lze nastavit i prodleva zobrazení v ms a font.

- -
Balloon.Info("Ahoj světe!", ME)  'zobrazí bublinu na hlavním formuláři
-
-'lze zkátit na: Balloon("Ahoj světe!", ME) ale pak je bez ikony
-
- - -[SUBST] - -

Pro jednoduší překlad textů v gambasu je možno použít substituci, -instrkukce Subst().

- -

Má minimalné 2 parametry, kde první je textová maska na kterou se substituce aplikuje, -další parametry jsou vaše proměnné, kde první vložený parametr má pořadové číslo 1. -Jako substituční znak se užívá &1, &2, ..., číslo je dle pořadí vložené proměnné.

- -
Subst(("Nahrazeni za &1, &2 a &3"), "prvni", "druhou", "dalsi")
-
-'vypise:
-'Nahrazeni za prvni a za druhou, dalsi
- - -[EDITOR] - -

Několik typů v editoru:

- -

Dva typy komentářů:

- -
'normální komentář
-
''tučný komentář
- -

Tučné komentáře jsou používány pro dokumentování kódu.

- -

Jak používat úryvky kodu:
- -'napíšete: -

main
-'a pak zmáčknete tabulátor, a doplní se útržek kódu,
-'podle toho jak je v nastavení definován -

- -

Úryvky kodu jsou zcela konfigurovatelné z globálního dialogu nastavení IDE.

- - -[END] - -

Přečetly jste všechny tipy dnů. Doufám, že jste se stal -nyní odborníkem na Gambas ! :-)

- -

Pokud chcete přidat nové tipy z vaší vlastní zkušenosti, -neváhejte a pošlete je na adresu:

- -

g4mba5@gmail.com

- -

Díky předem !

- diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.cs.txt gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.cs.txt --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.cs.txt 1970-01-01 00:00:00.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.cs.txt 2021-09-14 19:01:29.000000000 +0000 @@ -0,0 +1,547 @@ +[WELCOME] + +

Vítej v Gambasu !

+ +

Gambas je grafické vývojové +prostředí založené na pokročilém Basic interpretovy.

+ +

Cílem Gambasu je umožnit Vám, vytvářet +užitečné programy snadno a rychle. Ale čistota těchto programů +zůstává na vaší plné odpovědnosti...

+ +

Užijte si to !

+ +

Benoît Minisini
+g4mba5@gmail.com

+ + +[STARTUP] + +

Každý projekt musí mít hlavní třídu. Hlavní třída definuje +veřejnou statickou metodu nazvanou Main, argumentů, +která bude fungovat jako spouštěcí metoda vašeho programu.

+ +

Hlavní třídu můžete nastavit tak, že ve stromu projektu kliknete +pravým tlačítkem myši a v popup menu vyberete položku Hlavní třída.

+ +

Po startu není nutné nastavovat methodu Main, protože je již přednastavená.

+ +

Tato metoda je zodpovědná za vytváření instance a poté zobrazení formuláře, jako ve +Visual Basic™.

+ + +[OPEN] + +

Instrukci OPEN nemůžete použít v Gambasu +stejně jako ve Visual Basic. Soubor totiž nevrácí integer, +ale objekt File.

+ +

Takže místo:

+ +
DIM handle AS Integer
+...
+OPEN "myfile" FOR READ AS #handle
+ +

musíte psát:

+ +
DIM handle AS File
+...
+handle = OPEN "myfile" FOR READ
+ + +[CATDIR] + +Víte, že můžete spojit názvy adresářů a souborů operatorem &/ ? +

Tento operátor se v případě potřeby postará +o správné přidání oddělovače '/' do cesty.

+ +

Například:

+ +
PRINT "/home/gambas" &/ ".bashrc"
+/home/gambas/.bashrc
+
+PRINT "/home/gambas/" &/ "/tmp" &/ "foo.bar"
+/home/gambas/tmp/foo.bar
+
+ +

No není to úžasné ?

+ + +[EXEC] + +

Z celého projektu můžete vytvořit spustitelný soubor. Klikni v +menu Projekt a Vytvořit/Spustitelný....

+ +

Když Gambas vytvoří spustitelný soubor, tak jej defaultně vloží +do stejné složky ve které se nachází projekt. +Spustitelný soubor má pak stejné jméno jako projekt.

+ + +[PATH] + +

Relativní cesta má v Gambasu zvláštní význam. +Vždy se totiž odkazuje na soubory uvnitř svého projektů.

+ +

Neexistuje žádný koncept akuálního adresáře, +ani žádné slovo pro změnu jako CHDIR.

+ +

Buť tedy opatrný: musíš použít relativní cesty pouze pro přístup k +souborům projektu. Protože absolutní cesty již nefungují ve vytvořeném spustitelném programu.

+ + +[GLOBAL] + +

V Gambasu nejsou globální proměnné!

+ +

Jako dočasné řešení, je můžete vkládat do hlavního modulu a deklarovat je +jako PUBLIC.

+ +

Pokud nemáte hlavní modul, ale hlavní formulář, +pak deklarujte jako STATIC PUBLIC.

+ +

Pro přístup k těmto proměnným, musíte používat název modulu +nebo formuláře: MyMainModule.MyGlobalVariable nebo +MyMainForm.MyGlobalVariable.

+ + +[EMPTY] + +

Chcete-li jestli je řetězec prázdný, není nutné srovnání s "" nebo používat +funkci Len(). Je možné testovat přímo, protože prázdný řetězec +je ekvivalentní k FALSE a neprázdný řetězec je ekvivalentní k TRUE.

+ +

Například, než psát:

+ +
IF Len(MyString) > 0 THEN ...
+IF Len(MyString) = 0 THEN ...
+ +

Místo toho můžete psát:

+ +
IF MyString THEN ...
+IF NOT MyString THEN ...
+ + +[TRANSLATE] + +

Program napsaný v Gambasu je přeložitelný do jakéhokoli jazyka, +za předpokladu, že uvedete, které řezezce musí být přeloženy, a které ne.

+

Chcete-li označit řetězec pro překlad, stačí je uzavřít mezi kulaté závorky:

+ +

PRINT ("Mě přelož")
+PRINT "Ale mě nepřekládej!"
+ + +[EVENT] + +

Každý ovládací prvek či objekt, kterému lze přiřadit událost, má +pozorovatele událostí a událost název skupiny.

+ +

Pozorovatel události zachytává každou událost vyvolanou objektem. Název skupiny +událostí tvoří prefix volané procedury, která se stará o vykonání události.

+ +

Defaultně je pozorovatel události tvořen mateřským objektem kontrolního prvku +a název skupiny je tvořen názvem kontrolního prvku.

+ +

Touto cestou formulář dostává všechny události vyvolané vnitřními prvky.

+ +
' Gambas form
+DIM hButton AS Button
+
+PUBLIC SUB _new()
+  hButton = NEW Button(ME) AS "MyButton"
+END
+
+PUBLIC SUB MyButton_Click()
+  PRINT "You have clicked MyButton !"
+END
+
+ + +[FORM] + +

V Gambasu, je formulář vlastní pozorovatel událostí, takže si +může svoje události spravovat přímo (jako Resize, +Activate, ...) ve svém vlastním kódu.

+ +

Tímto způsobem, nováčci přícházející z Visual Basic +a nejsou dezorientovaný :-).

+ + +[EMBED] + +

Do formuláře Gambasu můžete vložit jakýkoliv jiný formulář !

+ +

Stačí předat rodičovský kontejner formuláře jako poslední argument konstruktoru.

+ +

Například:

+

DIM hForm AS MyDialog
+DIM hSuperControl AS MyForm

+' Vytvoření dialogu
+hForm = NEW MyDialog
+' Vložení formuláře do tohoto dialogu
+' Všimněte si, formulář má ještě dva parametry před rodičovským kontejner
+hSuperControl = NEW MyForm(Param1, Param2, MyDialog)
+' Nastavení polohy a velikosti formuláře
+hSuperControl.Move(8, 8, 128, 64)
+

+ +

Buďte opatrní: formulář vložený do jiného formuláře je stále formulářem, +a tak ma i vlastního pozorovatele událostí.

+ + +[GROUP] + +

Každý ovládací prvek ma vlastnost (Group) [skupinová akce]. +Pokud je tato vlastnost nastavena, tak název skupiny je předpona pro zpracování událostí +a ne název ovladacího prvku.

+ +

Předpokládejme, že máte Button nazvaný btnAction +s následným zpracováním událostí Click:

+ +
PUBLIC SUB btnAction_Click()
+ +

Pokud nastavíte vlastnost (Group) v btnAction na +MyGroup, pak zpracování událostí bude od tlačítka příjímat +následující událost:

+ +
PUBLIC SUB MyGroup_Click()
+ +

Tato vlastnost umožňuje zpracovávat události z různých ovládacích prvků +v jedné funkci. A ovladací prvky vůbec nemusí být stejné!

+ +

Poznámka: Zkušený veterán Visual Basicu možná pozná +pojem control array, ale v mnohem silnější implementaci. :-)

+ + +[TAG] + +

Kazdý ovládací prvek má vlastnost Tag. Tato vlastnost je pro +programátory, a může obsahovat jakoukoli VARIANTu dat, +kterou považujete za relevantní.

+ +

Je to velmi užitečné, když chcete odlišit různé ovládací prvky +stejné skupiny při společném zpracování událostí.

+ + +[LAST] + +

Klíčové slovo LAST vrací objekt posledního ovládacího prveku, od kterého +obdržel událost. Je to velmi užitečné, pokud chcete psát obsluhu událostí, +která je nezávislá na názvech prvků.

+ +

Například, předpokládejme, že chceme napsat program kalkulačky. +Máte nadefinovaná tlačítka pro každé z deseti čísel. Každé je +ve stejné skupině (group) "Digit". Tag každého prvku +má nastaveno číslo, které je na tlačítku. Zpracování události pak +může vypadat takhle:

+ +

PUBLIC SUB Digit_Click()

+  Display = Display & LAST.Tag
+  RefreshDisplay

+END

+ + +[LEFT] + +

Známé rutiny BASICu jako Left$, Right$ +a Mid$ jsou i v Gambasu

+ +

Druhý parametr Left$ a Right$ je volitelný, +a defultni hodnota je 1.

+ +

Left$("Gambas") vrací "G"
+Right$("Gambas") vrací "s"

+ +

Tento druhý parametr může být i záporný, a +pak udává počet znaků od konce řetězce.

+ +

Left$("Gambas", -2) vrací "Gamb"
+Right$("Gambas", -2) vrací "mbas"

+ +

Podobně, tak třetí parametr v Mid$ může být záporný, a +pak udává počet znaků od konce řetězce.

+ +

Mid$("Gambas", 2, -2) vrací "amb"

+ + +[OBSERVER] + +

Třída Observer (pozorovatel událostí) vám umožňuje zachytit všechny události +vyvolané objekty ještě před tím než jsou skutečně poslány.

+ +
MyTextBox = NEW TextBox(ME) AS "MyTextBox"
+MyObserver = NEW Observer(MyTextBox) AS "MyObserver"
+...
+PUBLIC SUB MyObserver_KeyPress()
+  DEBUG "Spuštěno první"
+END
+
+PUBLIC SUB MyTextBox_KeyPress()
+  DEBUG "Spuštěno další"
+END
+ +

Pozorovatel událostí může zastavit událost, v zájmu ochrany objektu.

+ + +[STRING] + +

Gambas používá pro reprezentaci řetězců v paměti znakovou sadu UTF-8.

+ +

Ale všechny standartní řetezcové funkce pracují s ASCII: +Left, Mid, Right, UCase...

+ +

Pokud chcete pracovat s UTF-8 řetězci, musíte používat metody statické třídy String, +které mají stejné názvy jako jejich standartní protějšky.

+ +
PRINT Len("bébé");; Left$("bébé", 3)
+6 bé
+PRINT String.Len("bébé");; String.Left("bébé", 3)
+4 béb
+ + +[ASSIGNMENT] + +

Gambas implementuje zkrácené přiřazování na +které jsou zvykli programátoři z C/C++.

+ +

MyVariable += 2 je ekvivalent +MyVariable = MyVariable + 2

+ +

MyVariable *= 4 je ekvivalent +MyVariable = MyVariable * 4

+ +

MyVariable &= "Great" je ekvivalent +MyVariable = MyVariable & "Great"

+ +

A tak dále...

+ + +[DEBUG] + +

Také můžete používat instrukci DEBUG pro tisk ladících zpráv do +konzole (tedy standartní chybový výstup). Chová se stejně jako instrukce PRINT.

+ +

Tyto zprávy obsahuji název třídy, název metody a číslo řádku +z místa volání instrukce DEBUG.

+ +

Při vytváření spustitelného souboru jsou ladící zprávy automaticky odstraněny.

+ + +[TRY] + +

Správa řízení chyb je v Gambasu řízena skrze instrukce: +TRY, ERROR, CATCH, a FINALLY. + +

TRY se pokusí provést výraz bez chyb. Instrukce ERROR +se používá aby se vědělo, jestli byl výraz proveden správně.

+ +
TRY MyFile = OPEN "/etc/password" FOR WRITE
+IF ERROR THEN PRINT "Nemůžu dělat, to co chci!"
+ + +[CATCH] + +

Správa řízení chyb je v Gambasu řízena skrze instrukce: +TRY, ERROR, CATCH, a FINALLY.

+ +

CATCH označuje začátek řízení chyb části funkce nebo procedůry. +Píše se na konec kodu funkce.

+ +

Catch blok se provede jen tehdy, když se uvnitř výkoného bloku kodu, vyskytne chyba.

+ +

Vyskatne-li se chyba během provádění bloku catch, je běžně zobrazena.

+ +
SUB ProcessFile(FileName AS STRING)
+  ...
+  OPEN FileName FOR READ AS #hFile
+  ...
+  CLOSE #hFile
+CATCH ' Vykonán pouze v případě, že se vyskytla chyba
+  PRINT "Nemůže zpracovat soubor "; FileName
+END
+ + +[FINALLY] + +

Správa řízení chyb je v Gambasu řízena skrze instrukce: +TRY, ERROR, CATCH, a FINALLY.

+ +

FINALLY zavádí kód vykonání na konci funkce, +i když byla chyba vyvolána během jejího plnění.

+ +

Finally blok není povinný. Je-li tu blok Catch blok ve funkci, +tak musí finally blok předcházet.

+ +

Vyvstane-li chyba během provádění Finally bloku, je běžně zobrazena.

+ +
SUB ProcessFile(FileName AS STRING)
+  ...
+  Open FileName For Read As #hFile
+  ...
+Finally ' Provedeno vždy, i když byla chyba vyvolána
+
+  Close #hFile
+  
+Catch ' Vykonán pouze v případě, že se vyskytla chyba
+  
+  Print "Cannot print file "; FileName
+  
+End
+ + +[OPTIONAL] + +

Funke a procedry v Gambasu mohou mít volitelné parametry.

+ +

Provádí se to tak že se před název proměnné napíše instrkukce OPTIONAL. +A ta oznamuje že je parametr volitelný.

+ +
PRIVATE SUB MyFunction(param AS String, OPTIONAL optim AS String)
+  ...
+  PRINT "povinný " & param & ", nepovinný '" & optim "'"
+  ...
+END
+
+'volání v kodu:
+
+MyFunction("parametr") 'není-li za potřebí tak se nemusí volat
+MyFunction("parametr", "param")
+
+ + +[ARRAY] + +

V Gambasu se dají procházet proměnné (typu array, collection) za pomocí FOR EACH +(pro collection a pole) nebo FOR cyklus (pro pole)

+ +

Například:

+ +
DIM xml AS NEW XmlDocument
+DIM node AS XmlNode
+DIM i AS Integer
+
+'otevre xml
+xml.Open("pokus.xml")
+'Children se musi indexovat přes [i]!, je to array
+FOR i = 0 TO xml.Root.Children.Count - 1
+  'Attributes se musí procházet přes FOR EACH, je to collection
+  FOR EACH node IN xml.Root.Children[i].Attributes
+    DEBUG node.Name;; Node.Value
+  NEXT
+NEXT
+ + +[ICON] + +

Můžete použít i vestavěné ikony pro doplnění krásy své aplikace, +a máte zde i například na výběr rozměr od 16x16 až po 128x128

+ +

Například:

+ +
Image1.Picture = Picture["icon:/32/warning"]
+Image2.Picture = Picture["icon:/small/error"]
+
+ +

Pozor: musíte mít zapnutou komponentu: gb.form. + + +[SETTINGS] + +

Pokud si potřebujete uložit konfigurací programu, +jako je třeba velikost a poloha okna, je to jednodušší než jste čekaly.

+ +

Můžete ukládat konfiguraci celého objektu, nebo jen jeho dílčí hodnotu.

+ +

Například:

+ +
'uložení polohy onjektu
+Settings.Write(ME)
+
+'Načtení objektu
+Settings.Read(ME)
+
+'Uložení hodnoty
+Settings["win/x"] = ME.X
+
+'Načtení hodnoty
+'lze zadat i defaultni hodnotu: ["win/x", 0]
+ME.X = Settings["win/x"]
+
+ +

Pozor: musíte mít zapnutou komponentu: gb.settings

+ + +[MESSAGE] + +

V Gambasu můžete pro informování uživatele užít následující třídy: +Message a Balloon. +Message je z komponenty (QT, GTK+), a Balloon z gb.form.

+ +

Třída Message a Balloon má možné typy: +Message.Delete(), .Error(), .Info(), .Question() a .Warning()

+ +

U každého Message jdou nastavit i vlastní popisky tlačítek, po zmáčknutí tlačítka v dialogu je +vrácena číselná hodnota tlačítka od 1 do X, dle typu a počtu tlačítek.

+ +
DEBUG Message.Info("Ahoj světe!")  'vrátí číslo 1
+
+Message("Ahoj světe!")  'To samé zkráceně
+ +

Při vytváření Balloon se musí uvést rodičovský kontejner, volitelně jde nastavit i pozice X a Y, +lze nastavit i prodleva zobrazení v ms a font.

+ +
Balloon.Info("Ahoj světe!", ME)  'zobrazí bublinu na hlavním formuláři
+
+'lze zkátit na: Balloon("Ahoj světe!", ME) ale pak je bez ikony
+
+ + +[SUBST] + +

Pro jednoduší překlad textů v gambasu je možno použít substituci, +instrkukce Subst().

+ +

Má minimalné 2 parametry, kde první je textová maska na kterou se substituce aplikuje, +další parametry jsou vaše proměnné, kde první vložený parametr má pořadové číslo 1. +Jako substituční znak se užívá &1, &2, ..., číslo je dle pořadí vložené proměnné.

+ +
Subst(("Nahrazeni za &1, &2 a &3"), "prvni", "druhou", "dalsi")
+
+'vypise:
+'Nahrazeni za prvni a za druhou, dalsi
+ + +[EDITOR] + +

Několik typů v editoru:

+ +

Dva typy komentářů:

+ +
'normální komentář
+
''tučný komentář
+ +

Tučné komentáře jsou používány pro dokumentování kódu.

+ +

Jak používat úryvky kodu:
+ +'napíšete: +

main
+'a pak zmáčknete tabulátor, a doplní se útržek kódu,
+'podle toho jak je v nastavení definován +

+ +

Úryvky kodu jsou zcela konfigurovatelné z globálního dialogu nastavení IDE.

+ + +[END] + +

Přečetly jste všechny tipy dnů. Doufám, že jste se stal +nyní odborníkem na Gambas ! :-)

+ +

Pokud chcete přidat nové tipy z vaší vlastní zkušenosti, +neváhejte a pošlete je na adresu:

+ +

g4mba5@gmail.com

+ +

Díky předem !

+ diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.de gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.de --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.de 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.de 1970-01-01 00:00:00.000000000 +0000 @@ -1,417 +0,0 @@ -[WELCOME] - -

Willkommen zu Gambas!

- -

Gambas ist eine graphische IDE, die auf einem modernen Basic-Interpreter basiert.

- -

Gambas möchte Sie in die Lage versetzen, schnell und einfach komplexe Programme zu schreiben. -Sauberes Programmieren bleibt natürlich Ihr Verantwortungsbereich...

- -

Viel Spaß damit!

- -

Benoît Minisini
-g4mba5@gmail.com

- - -[STARTUP] - -

Jedes Projekt braucht eine Startklasse. Diese muss eine -gemeinsame (statische) Methode namens Main ohne Argumente definieren, -die dann als Startpunkt für die Anwendung fungiert.

- -

Sie können die Startklasse definieren, indem Sie im Projektfenster mit der rechten Maustaste -darauf klicken und Startklasse im Popupmenü auswählen.

- -

Wenn die Startklasse ein Formular ist, muss sie keine Methode Main besitzen, -da ein Formular bereits eine vorgefertigte mitbringt.

- -

Diese vordefinierte Methode tut dasselbe wie es in Visual -Basic™ Standard ist: Das Formular wird instanziert und -angezeigt.

- - -[OPEN] - -

Die OPEN-Anweisung von Gambas funktioniert nicht -wie die in Visual Basic™. Sie liefert keine Dateinummer zurück, -sondern ein File-Objekt.

- -

Also, anstatt

- -
DIM handle AS Integer
-...
-OPEN "myfile" FOR READ AS #handle
- -

schreiben Sie:

- -
DIM handle AS File
-...
-handle = OPEN "myfile" FOR READ
- - -[CATDIR] - -

Wussten Sie, dass Sie Verzeichnis- und Dateinamen mit dem -&/-Operator -zusammenhängen können? Dieser Operator kümmert sich automatisch um die -Schrägstriche, sodass -im Ergebnis weder welche fehlen noch doppelt vorhanden sind.

- -

Zum Beispiel:

- -
PRINT "/home/gambas" &/ ".bashrc"
-/home/gambas/.bashrc
-
-PRINT "/home/gambas/" &/ "/tmp" &/ "foo.bar"
-/home/gambas/tmp/foo.bar
-
- -

Ist das nicht praktisch?

- - -[EXEC] - -

Sie können eine ausführbare Datei aus Ihrem gesamten Projekt machen. -Wählen Sie Ausführbare Datei erstellen aus dem Menü Projekt.

- -

Wenn Gambas eine ausführbare Datei erstellt, legt es das Ergebnis -direkt im Verzeichnis Ihres Projekts ab. Der Name der Datei ist der des Projekts.

- - -[PATH] -

-Relative Pfade haben in Gambas eine spezielle Bedeutung. -Sie verweisen immer auf Dateien innerhalb Ihrer Projekte. -

-Es gibt kein Konzept von current directory, und keinen Befehl wie -CHDIR, um es zu ändern. -

-Vorsicht: um Projektdateien zu öffnen, dürfen Sie nur relative -Pfadangaben verwenden, weil absolute Pfadangaben nicht mehr vorhanden sind, -wenn Sie eine ausführbare Datei erstellt haben. - - -[GLOBAL] - -In Gambas gibt es keine globalen Variablen! -

-Hilfsweise können Sie solche Variablen im Modul Main definieren und als -PUBLIC deklarieren. -

-Wenn Sie in Ihrem Projekt kein Modul Main haben, sondern ein Formular -Main, dann deklarieren Sie sie dort als STATIC PUBLIC. -

-Um diese Variablen zu verwenden, müssen Sie den Namen des Moduls/Formulars -Main angeben: MyMainModule.MyGlobalVariable oder -MyMainForm.MyGlobalVariable. - - -[EMPTY] - -

Wenn Sie prüfen wollen, ob ein String leer ist, müssen Sie nicht die -Len()-Funktion verwenden. Sie können den String direkt mit IF -testen, da ein leerer String FALSE und ein nicht-leerer TRUE -ergibt.

- -

Also, anstatt

- -
IF Len(MyString) > 0 THEN ...
-IF Len(MyString) = 0 THEN ...
- -

sollten Sie schreiben:

- -
IF MyString THEN ...
-IF NOT MyString THEN ...
- - -[TRANSLATE] - -

Gambas-Anwendungen sind übersetzbar, vorausgesetzt Sie geben an, welche -Ausdrücke übersetzt werden sollen und welche nicht.

-

Um Ausdrücke zum Übersetzen zu markieren, setzen Sie sie einfach in -Klammern:

- -

PRINT ("Übersetze mich")
-PRINT "Aber mich nicht übersetzen!"
- - -[EVENT] - -

Jedes Steuerelement und jedes Objekt kann Events auslösen. Es besitzt -einen Event-Observer und einen Event-Gruppennamen.

- -

Der Event-Observer fängt jedes vom Objekt ausgelöste Event auf, und -der Event-Gruppenname ist das Präfix des Methodennamens, der beim Auslösen -des Events aufgerufen wird.

- -

Standardmäßig ist der Event-Observer das Objekt, in dem Sie das Steuerelement -erstellt haben, und der Gruppenname ist der Name des Elements.

- -

Auf diese Art und Weise erhält ein Formular die Events aller seiner -Steuerelemente.

- -
' Gambas form
-DIM hButton AS Button
-
-PUBLIC SUB _new()
-  hButton = NEW Button(ME) AS "MyButton"
-END
-
-PUBLIC SUB MyButton_Click()
-  PRINT "Sie haben auf MyButton geklickt!"
-END
-
- - -[FORM] - -

In Gambas ist ein Formular sein eigener Event-Observer, -sodass Sie seine Events (wie Resize, Activate etc.) im -Code der Klasse selbst managen können.

- -

Auf diese Weise werden auch Umsteiger von Visual Basic™ -nicht orientierungslos :-).

- - -[EMBED] - -

Sie können jedes Formular in andere Formulare mit Gambas -einbetten!

- -

Um so etwas mächtiges zu tun, erstellen Sie einfach eine Instanz des Formulars, -wobei Sie als letztes Argument für den Konstruktor den Container für die Form angeben.

- -

Zum Beispiel:

-

DIM hForm AS MyDialog
-DIM hSuperControl AS MyForm

-' Dialog erstellen
-hForm = NEW MyDialog
-' Formular in den Dialog einfügen
-' Achtung: Diese Form hat zwei Konstruktorargumente vor dem Containerargument
-hSuperControl = NEW MyForm(Param1, Param2, MyDialog)
-' Die Form auf die richtige Größe bringen
-hSuperControl.Move(8, 8, 128, 64)
-

- -

Achtung: Eine eingebettete Form ist immer noch ihr eigener Event-Observer und -erhält damit ihre Events selbst!

- - -[GROUP] - -

Jedes Steuerelement hat eine (Group)-Eigenschaft. Wenn diese Eigenschaft -gesetzt ist, ist das Präfix des Eventhandlers eben dieser Gruppenname und nicht -der Namen des Elements.

- -

Nehmen wir an, Sie haben einen Button namens btnAction mit -folgendem Click-Eventhandler:

- -
PUBLIC SUB btnAction_Click()
- -

Wenn Sie die (Group)-Eigenschaft auf MyGroup setzen, sieht der -Eventhandler, der die Events des Buttons erhält, so aus:

- -
PUBLIC SUB MyGroup_Click()
- -

Dadurch können Sie die Events von verschiedenen Steuerelementen in einer -einzelnen Funktion behandeln. Die Steuerelemente einer Gruppe müssen nicht vom -selben Typ sein!

- -

Bemerkung: Der Visual Basic™-Veteran mag das Konzept der -Control Arrays wiedererkennen, aber in einer leistungsfähigeren Implementation. :-)

- - -[TAG] - -

Jedes Steuerelement hat eine Tag-Eigenschaft, genau wie in -Visual Basic™. Sie erfüllt für das Objekt selbst keinen Zweck, -sondern kann vom Programmierer benutzt werden, um irgendwelche VARIANT-Daten -zu speichern, die er für nützlich hält.

- -

Das ist zum Beispiel praktisch, wenn Sie mehrere Steuerelemente derselben Gruppe -in einem Eventhandler unterscheiden wollen.

- - -[LAST] - -

Das LAST-Schlüsselwort gibt das letzte Steuerelement zurück, -das ein Event ausgelöst hat. Dies ist sehr nützlich, wenn Sie einen Eventhandler -schreiben wollen, der vom Namen eines Elements unabhängig ist.

- -

Zum Beispiel, wenn Sie einen Taschenrechner schreiben wollen, können Sie zehn -Buttons erstellen, einen für jede Ziffer, und jeden in derselben Gruppe namens "Digit". -Angenommen, Sie setzen die Tag-Eigenschaft von jedem Button auf die Ziffer, die er -repräsentiert, dann können Sie folgenden Eventhandler schreiben:

- -

PUBLIC SUB Digit_Click()

-  Display = Display & LAST.Tag
-  RefreshDisplay

-END

- - -[LEFT] - -

Die bekannten BASIC-Routinen Left$, Right$ -und Mid$ sind in Gambas verbessert:

- -

Der zweite Parameter von Left$ und Right$ ist optional, und -standardmäßig 1.

- -

Left$("Gambas") ergibt "G"
-Right$("Gambas") ergibt "s"

- -

Er kann auch negativ sein und gibt so die Anzahl Zeichen an, die nicht -zurückgegeben werden sollen.

- -

Left$("Gambas", -2) ergibt "Gamb"
-Right$("Gambas", -2) ergibt "mbas"

- -Genauso kann das dritte Argument von Mid$ negativ sein und gibt -dann die Anzahl an Zeichen vom Ende des Strings an, die nicht zurückgegeben werden sollen.

- -

Mid$("Gambas", 2, -2) ergibt "amb" - - -[OBSERVER] - -

Die Observer-Klasse erlaubt es, alle Ereignisse eines Objekts -abzufangen, bevor sie tatsächlich gesendet werden.

- -
MyTextBox = NEW TextBox(ME) AS "MyTextBox"
-MyObserver = NEW Observer(MyTextBox) AS "MyObserver"
-...
-PUBLIC SUB MyObserver_KeyPress()
-  DEBUG "Got it first"
-END
-
-PUBLIC SUB MyTextBox_KeyPress()
-  DEBUG "Got it next"
-END
- -Der Observer kann ein Ereignis abbrechen, um zu vermeiden, dass ein -Objekt es überhaupt auslöst. - - -[STRING] - -

Gambas verwendet den UTF-8-Zeichensatz, um Ausdrücke im -Arbeitsspeicher zu verwalten.

- -

Aber alle standardmäßigen Stringfunktionen von Gambas verwenden -ASCII: -Left, Mid, Right, UCase... - -

Wenn Sie UTF-8-Ausdrücke bearbeiten wollen, müssen Sie die Methoden der -statischen String-Klasse verwenden, die den gleichen Namen haben wie -ihre standardmäßigen Entsprechungen. - -

PRINT Len("bébé");; Left$("bébé", 3)
-6 bé
-PRINT String.Len("bébé");; String.Left("bébé", 3)
-4 béb
- - -[ASSIGNMENT] - -

Gambas hat die Zuweisungs-Abkürzungen eingebaut, die C/C++ Programmierer -gewohnt sind. - -

MyVariable += 2 ist gleichbedeutend mit MyVariable = -MyVariable + 2 - -

MyVariable &= "Great" ist dasselbe wie -MyVariable = MyVariable & "Great" - -

Und so weiter... - - -[DEBUG] - -

Sie können die DEBUG-Anweisung benützen, um Debug-Meldungen auf -der Konsole auszugeben (vor allem die standardmäßigen Fehlerausgaben). Das -funktioniert genau so wie die PRINT-Anweisung. - -

Bei diesen Meldungen wird die Klasse, Methode und Zeilennummer der -DEBUG-Anweisung vorangestellt. - -

Die Debug-Meldungen werden automatisch gelöscht, wenn eine ausführbare -Datei ohne Debug-Informationen erstellt wird. - - -[TRY] - -

Die Fehlerbehandlung wird in Gambas mit folgenden Befehlen ausgeführt: -TRY, ERROR, CATCH, und -FINALLY. - -

TRY versucht, einen Befehl auszuführen, ohne einen Fehler -auszulösen. Die Anweisung ERROR wird direkt danach verwendet, um -zu prüfen, ob der Befehl korrekt ausgeführt werden konnte. - -

TRY MyFile = OPEN "/etc/password" FOR WRITE
-IF ERROR THEN PRINT "Ich kann nicht!"
- - -[CATCH] - -

Die Fehlerbehandlung wird in Gambas mit folgenden Befehlen ausgeführt: -TRY, ERROR, CATCH, und -FINALLY. - -

CATCH zeigt den Beginn einer Fehlerbehandlungsroutine in einer -Funktion oder Prozedur an. -Dieser Befehl wird ans Ende des Codes gestellt. - -

Die CATCH-Anweisung wird ausgeführt, wenn ein Fehler zwischen dem Anfang -und dem Ende der Funktion oder Prozedur auftritt. - -

Wenn während der Verarbeitung der CATCH-Anweisung ein Fehler auftritt, -wird er er normal angezeigt. - -

SUB ProcessFile(FileName AS STRING)
-  ...
-  OPEN FileName FOR READ AS #hFile
-  ...
-  CLOSE #hFile
-CATCH ' wird nur ausgeführt, wenn ein Fehler auftritt
-  PRINT "Kann Datei nicht laden "; FileName
-END
- - -[FINALLY] - -

Die Fehlerbehandlung wird in Gambas mit folgenden Befehlen ausgeführt: -TRY, ERROR, CATCH, und -FINALLY. - -

FINALLY leitet den Code am Ende der Funktion ein, der -ausgeführt wird, selbst wenn ein Fehler in der Funktion aufgetreten ist. - -

Der Abschnitt FINALLY ist nicht obligatorisch. Wenn in der Funktion eine -CATCH-Anweisung vorkommt, muss FINALLY davor stehen. - -

Wenn im FINALLY-Abschnitt ein Fehler auftritt, wird er normal angezeigt. - -

SUB ProcessFile(FileName AS STRING)
-  ...
-  OPEN FileName FOR READ AS #hFile
-  ...
-FINALLY ' wird immer ausgeführt, auch wenn ein Fehler auftritt
-  CLOSE #hFile
-CATCH ' wird nur bei einem Fehler ausgeführt
-  PRINT "Kann die Datei nicht ausgeben "; FileName
-END
- - -[END] - -

Jetzt haben Sie alle Tipps des Tages gelesen. Ich hoffe, Sie sind jetzt ein -Gambas-Experte geworden! :-)

- -

Wenn Sie neue Tipps beisteuern wollen, senden Sie sie an folgende Adresse:

-

g4mba5@gmail.com

- -

Danke im Voraus!

- -

Deutsche Übersetzung der Tipps: Georg Brandl, g.brandl@gmx.net

- diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.de.txt gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.de.txt --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.de.txt 1970-01-01 00:00:00.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.de.txt 2021-09-14 19:01:29.000000000 +0000 @@ -0,0 +1,417 @@ +[WELCOME] + +

Willkommen zu Gambas!

+ +

Gambas ist eine graphische IDE, die auf einem modernen Basic-Interpreter basiert.

+ +

Gambas möchte Sie in die Lage versetzen, schnell und einfach komplexe Programme zu schreiben. +Sauberes Programmieren bleibt natürlich Ihr Verantwortungsbereich...

+ +

Viel Spaß damit!

+ +

Benoît Minisini
+g4mba5@gmail.com

+ + +[STARTUP] + +

Jedes Projekt braucht eine Startklasse. Diese muss eine +gemeinsame (statische) Methode namens Main ohne Argumente definieren, +die dann als Startpunkt für die Anwendung fungiert.

+ +

Sie können die Startklasse definieren, indem Sie im Projektfenster mit der rechten Maustaste +darauf klicken und Startklasse im Popupmenü auswählen.

+ +

Wenn die Startklasse ein Formular ist, muss sie keine Methode Main besitzen, +da ein Formular bereits eine vorgefertigte mitbringt.

+ +

Diese vordefinierte Methode tut dasselbe wie es in Visual +Basic™ Standard ist: Das Formular wird instanziert und +angezeigt.

+ + +[OPEN] + +

Die OPEN-Anweisung von Gambas funktioniert nicht +wie die in Visual Basic™. Sie liefert keine Dateinummer zurück, +sondern ein File-Objekt.

+ +

Also, anstatt

+ +
DIM handle AS Integer
+...
+OPEN "myfile" FOR READ AS #handle
+ +

schreiben Sie:

+ +
DIM handle AS File
+...
+handle = OPEN "myfile" FOR READ
+ + +[CATDIR] + +

Wussten Sie, dass Sie Verzeichnis- und Dateinamen mit dem +&/-Operator +zusammenhängen können? Dieser Operator kümmert sich automatisch um die +Schrägstriche, sodass +im Ergebnis weder welche fehlen noch doppelt vorhanden sind.

+ +

Zum Beispiel:

+ +
PRINT "/home/gambas" &/ ".bashrc"
+/home/gambas/.bashrc
+
+PRINT "/home/gambas/" &/ "/tmp" &/ "foo.bar"
+/home/gambas/tmp/foo.bar
+
+ +

Ist das nicht praktisch?

+ + +[EXEC] + +

Sie können eine ausführbare Datei aus Ihrem gesamten Projekt machen. +Wählen Sie Ausführbare Datei erstellen aus dem Menü Projekt.

+ +

Wenn Gambas eine ausführbare Datei erstellt, legt es das Ergebnis +direkt im Verzeichnis Ihres Projekts ab. Der Name der Datei ist der des Projekts.

+ + +[PATH] +

+Relative Pfade haben in Gambas eine spezielle Bedeutung. +Sie verweisen immer auf Dateien innerhalb Ihrer Projekte. +

+Es gibt kein Konzept von current directory, und keinen Befehl wie +CHDIR, um es zu ändern. +

+Vorsicht: um Projektdateien zu öffnen, dürfen Sie nur relative +Pfadangaben verwenden, weil absolute Pfadangaben nicht mehr vorhanden sind, +wenn Sie eine ausführbare Datei erstellt haben. + + +[GLOBAL] + +In Gambas gibt es keine globalen Variablen! +

+Hilfsweise können Sie solche Variablen im Modul Main definieren und als +PUBLIC deklarieren. +

+Wenn Sie in Ihrem Projekt kein Modul Main haben, sondern ein Formular +Main, dann deklarieren Sie sie dort als STATIC PUBLIC. +

+Um diese Variablen zu verwenden, müssen Sie den Namen des Moduls/Formulars +Main angeben: MyMainModule.MyGlobalVariable oder +MyMainForm.MyGlobalVariable. + + +[EMPTY] + +

Wenn Sie prüfen wollen, ob ein String leer ist, müssen Sie nicht die +Len()-Funktion verwenden. Sie können den String direkt mit IF +testen, da ein leerer String FALSE und ein nicht-leerer TRUE +ergibt.

+ +

Also, anstatt

+ +
IF Len(MyString) > 0 THEN ...
+IF Len(MyString) = 0 THEN ...
+ +

sollten Sie schreiben:

+ +
IF MyString THEN ...
+IF NOT MyString THEN ...
+ + +[TRANSLATE] + +

Gambas-Anwendungen sind übersetzbar, vorausgesetzt Sie geben an, welche +Ausdrücke übersetzt werden sollen und welche nicht.

+

Um Ausdrücke zum Übersetzen zu markieren, setzen Sie sie einfach in +Klammern:

+ +

PRINT ("Übersetze mich")
+PRINT "Aber mich nicht übersetzen!"
+ + +[EVENT] + +

Jedes Steuerelement und jedes Objekt kann Events auslösen. Es besitzt +einen Event-Observer und einen Event-Gruppennamen.

+ +

Der Event-Observer fängt jedes vom Objekt ausgelöste Event auf, und +der Event-Gruppenname ist das Präfix des Methodennamens, der beim Auslösen +des Events aufgerufen wird.

+ +

Standardmäßig ist der Event-Observer das Objekt, in dem Sie das Steuerelement +erstellt haben, und der Gruppenname ist der Name des Elements.

+ +

Auf diese Art und Weise erhält ein Formular die Events aller seiner +Steuerelemente.

+ +
' Gambas form
+DIM hButton AS Button
+
+PUBLIC SUB _new()
+  hButton = NEW Button(ME) AS "MyButton"
+END
+
+PUBLIC SUB MyButton_Click()
+  PRINT "Sie haben auf MyButton geklickt!"
+END
+
+ + +[FORM] + +

In Gambas ist ein Formular sein eigener Event-Observer, +sodass Sie seine Events (wie Resize, Activate etc.) im +Code der Klasse selbst managen können.

+ +

Auf diese Weise werden auch Umsteiger von Visual Basic™ +nicht orientierungslos :-).

+ + +[EMBED] + +

Sie können jedes Formular in andere Formulare mit Gambas +einbetten!

+ +

Um so etwas mächtiges zu tun, erstellen Sie einfach eine Instanz des Formulars, +wobei Sie als letztes Argument für den Konstruktor den Container für die Form angeben.

+ +

Zum Beispiel:

+

DIM hForm AS MyDialog
+DIM hSuperControl AS MyForm

+' Dialog erstellen
+hForm = NEW MyDialog
+' Formular in den Dialog einfügen
+' Achtung: Diese Form hat zwei Konstruktorargumente vor dem Containerargument
+hSuperControl = NEW MyForm(Param1, Param2, MyDialog)
+' Die Form auf die richtige Größe bringen
+hSuperControl.Move(8, 8, 128, 64)
+

+ +

Achtung: Eine eingebettete Form ist immer noch ihr eigener Event-Observer und +erhält damit ihre Events selbst!

+ + +[GROUP] + +

Jedes Steuerelement hat eine (Group)-Eigenschaft. Wenn diese Eigenschaft +gesetzt ist, ist das Präfix des Eventhandlers eben dieser Gruppenname und nicht +der Namen des Elements.

+ +

Nehmen wir an, Sie haben einen Button namens btnAction mit +folgendem Click-Eventhandler:

+ +
PUBLIC SUB btnAction_Click()
+ +

Wenn Sie die (Group)-Eigenschaft auf MyGroup setzen, sieht der +Eventhandler, der die Events des Buttons erhält, so aus:

+ +
PUBLIC SUB MyGroup_Click()
+ +

Dadurch können Sie die Events von verschiedenen Steuerelementen in einer +einzelnen Funktion behandeln. Die Steuerelemente einer Gruppe müssen nicht vom +selben Typ sein!

+ +

Bemerkung: Der Visual Basic™-Veteran mag das Konzept der +Control Arrays wiedererkennen, aber in einer leistungsfähigeren Implementation. :-)

+ + +[TAG] + +

Jedes Steuerelement hat eine Tag-Eigenschaft, genau wie in +Visual Basic™. Sie erfüllt für das Objekt selbst keinen Zweck, +sondern kann vom Programmierer benutzt werden, um irgendwelche VARIANT-Daten +zu speichern, die er für nützlich hält.

+ +

Das ist zum Beispiel praktisch, wenn Sie mehrere Steuerelemente derselben Gruppe +in einem Eventhandler unterscheiden wollen.

+ + +[LAST] + +

Das LAST-Schlüsselwort gibt das letzte Steuerelement zurück, +das ein Event ausgelöst hat. Dies ist sehr nützlich, wenn Sie einen Eventhandler +schreiben wollen, der vom Namen eines Elements unabhängig ist.

+ +

Zum Beispiel, wenn Sie einen Taschenrechner schreiben wollen, können Sie zehn +Buttons erstellen, einen für jede Ziffer, und jeden in derselben Gruppe namens "Digit". +Angenommen, Sie setzen die Tag-Eigenschaft von jedem Button auf die Ziffer, die er +repräsentiert, dann können Sie folgenden Eventhandler schreiben:

+ +

PUBLIC SUB Digit_Click()

+  Display = Display & LAST.Tag
+  RefreshDisplay

+END

+ + +[LEFT] + +

Die bekannten BASIC-Routinen Left$, Right$ +und Mid$ sind in Gambas verbessert:

+ +

Der zweite Parameter von Left$ und Right$ ist optional, und +standardmäßig 1.

+ +

Left$("Gambas") ergibt "G"
+Right$("Gambas") ergibt "s"

+ +

Er kann auch negativ sein und gibt so die Anzahl Zeichen an, die nicht +zurückgegeben werden sollen.

+ +

Left$("Gambas", -2) ergibt "Gamb"
+Right$("Gambas", -2) ergibt "mbas"

+ +Genauso kann das dritte Argument von Mid$ negativ sein und gibt +dann die Anzahl an Zeichen vom Ende des Strings an, die nicht zurückgegeben werden sollen.

+ +

Mid$("Gambas", 2, -2) ergibt "amb" + + +[OBSERVER] + +

Die Observer-Klasse erlaubt es, alle Ereignisse eines Objekts +abzufangen, bevor sie tatsächlich gesendet werden.

+ +
MyTextBox = NEW TextBox(ME) AS "MyTextBox"
+MyObserver = NEW Observer(MyTextBox) AS "MyObserver"
+...
+PUBLIC SUB MyObserver_KeyPress()
+  DEBUG "Got it first"
+END
+
+PUBLIC SUB MyTextBox_KeyPress()
+  DEBUG "Got it next"
+END
+ +Der Observer kann ein Ereignis abbrechen, um zu vermeiden, dass ein +Objekt es überhaupt auslöst. + + +[STRING] + +

Gambas verwendet den UTF-8-Zeichensatz, um Ausdrücke im +Arbeitsspeicher zu verwalten.

+ +

Aber alle standardmäßigen Stringfunktionen von Gambas verwenden +ASCII: +Left, Mid, Right, UCase... + +

Wenn Sie UTF-8-Ausdrücke bearbeiten wollen, müssen Sie die Methoden der +statischen String-Klasse verwenden, die den gleichen Namen haben wie +ihre standardmäßigen Entsprechungen. + +

PRINT Len("bébé");; Left$("bébé", 3)
+6 bé
+PRINT String.Len("bébé");; String.Left("bébé", 3)
+4 béb
+ + +[ASSIGNMENT] + +

Gambas hat die Zuweisungs-Abkürzungen eingebaut, die C/C++ Programmierer +gewohnt sind. + +

MyVariable += 2 ist gleichbedeutend mit MyVariable = +MyVariable + 2 + +

MyVariable &= "Great" ist dasselbe wie +MyVariable = MyVariable & "Great" + +

Und so weiter... + + +[DEBUG] + +

Sie können die DEBUG-Anweisung benützen, um Debug-Meldungen auf +der Konsole auszugeben (vor allem die standardmäßigen Fehlerausgaben). Das +funktioniert genau so wie die PRINT-Anweisung. + +

Bei diesen Meldungen wird die Klasse, Methode und Zeilennummer der +DEBUG-Anweisung vorangestellt. + +

Die Debug-Meldungen werden automatisch gelöscht, wenn eine ausführbare +Datei ohne Debug-Informationen erstellt wird. + + +[TRY] + +

Die Fehlerbehandlung wird in Gambas mit folgenden Befehlen ausgeführt: +TRY, ERROR, CATCH, und +FINALLY. + +

TRY versucht, einen Befehl auszuführen, ohne einen Fehler +auszulösen. Die Anweisung ERROR wird direkt danach verwendet, um +zu prüfen, ob der Befehl korrekt ausgeführt werden konnte. + +

TRY MyFile = OPEN "/etc/password" FOR WRITE
+IF ERROR THEN PRINT "Ich kann nicht!"
+ + +[CATCH] + +

Die Fehlerbehandlung wird in Gambas mit folgenden Befehlen ausgeführt: +TRY, ERROR, CATCH, und +FINALLY. + +

CATCH zeigt den Beginn einer Fehlerbehandlungsroutine in einer +Funktion oder Prozedur an. +Dieser Befehl wird ans Ende des Codes gestellt. + +

Die CATCH-Anweisung wird ausgeführt, wenn ein Fehler zwischen dem Anfang +und dem Ende der Funktion oder Prozedur auftritt. + +

Wenn während der Verarbeitung der CATCH-Anweisung ein Fehler auftritt, +wird er er normal angezeigt. + +

SUB ProcessFile(FileName AS STRING)
+  ...
+  OPEN FileName FOR READ AS #hFile
+  ...
+  CLOSE #hFile
+CATCH ' wird nur ausgeführt, wenn ein Fehler auftritt
+  PRINT "Kann Datei nicht laden "; FileName
+END
+ + +[FINALLY] + +

Die Fehlerbehandlung wird in Gambas mit folgenden Befehlen ausgeführt: +TRY, ERROR, CATCH, und +FINALLY. + +

FINALLY leitet den Code am Ende der Funktion ein, der +ausgeführt wird, selbst wenn ein Fehler in der Funktion aufgetreten ist. + +

Der Abschnitt FINALLY ist nicht obligatorisch. Wenn in der Funktion eine +CATCH-Anweisung vorkommt, muss FINALLY davor stehen. + +

Wenn im FINALLY-Abschnitt ein Fehler auftritt, wird er normal angezeigt. + +

SUB ProcessFile(FileName AS STRING)
+  ...
+  OPEN FileName FOR READ AS #hFile
+  ...
+FINALLY ' wird immer ausgeführt, auch wenn ein Fehler auftritt
+  CLOSE #hFile
+CATCH ' wird nur bei einem Fehler ausgeführt
+  PRINT "Kann die Datei nicht ausgeben "; FileName
+END
+ + +[END] + +

Jetzt haben Sie alle Tipps des Tages gelesen. Ich hoffe, Sie sind jetzt ein +Gambas-Experte geworden! :-)

+ +

Wenn Sie neue Tipps beisteuern wollen, senden Sie sie an folgende Adresse:

+

g4mba5@gmail.com

+ +

Danke im Voraus!

+ +

Deutsche Übersetzung der Tipps: Georg Brandl, g.brandl@gmx.net

+ diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.en gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.en --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.en 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.en 1970-01-01 00:00:00.000000000 +0000 @@ -1,592 +0,0 @@ -[WELCOME] - -

Welcome to Gambas!

- -

Gambas is a graphical development -environment based on an advanced Basic interpreter.

- -

Gambas aims at enabling you to make -powerful programs easily and quickly. But clean programs -remain on your own responsibility...

- -

Enjoy it !

- -

Benoît Minisini
-g4mba5@gmail.com


- - -[STARTUP] - -

Startup class

- -

Each project must have a startup class. This -startup class must define a static public method named Main -with no arguments, that will act as the startup method of -your program.

- -

You can define the startup class by clicking on it with the -right mouse button in the project tree, and by selecting -Startup class in the popup menu.

- -

It is not necessary to define a Main method in a startup -form, because it already has a predefined one.

- -

This predefined startup method instanciates the form and shows it, like in -Visual Basic™.

- - -[OPEN] - -

Open

- -

The Open instruction of Gambas does not -work like the Visual Basic™ one. It does not return the file -as an integer, but as a File object.

- -

So, instead of typing :

- -
Dim handle As Integer
-...
-Open "myfile" For Read As #handle
- -

you must type :

- -
Dim handle As File
-...
-handle = Open "myfile" For Read
- - -[CATDIR] - -

Path concatenation

- -

Do you know that you can concatenate directory names and -file names with the &/ operator ? This operator -deals with the trailing slashes so that the resulting path is -perfect.

- -

For example:

- -
Print "/home/gambas" &/ ".bashrc"
-→ /home/gambas/.bashrc
-
-Print "/home/gambas/" &/ "/tmp" &/ "foo.bar"
-→ /home/gambas/tmp/foo.bar
-
- -

Isn't it marvelous ?

- - -[EXEC] - -

Executable

- -

You can make an executable file from your entire project. Select -Make executable in the Project menu.

- -

When Gambas makes an executable file, it puts -the result in the directory of your project by default. -The executable name has the same name as your project.

- - -[PATH] - -

Relative paths

- -

Relative paths have a special meaning in Gambas. -They always refer to files inside your projects.

-

-There is no concept of current directory, and no keyword like -CHDIR to change it.

-

-Be careful: you must use relative paths only for accessing -project files, because absolute paths won't work anymore when -you make an executable.

- - -[GLOBAL] - -

Global variables

- -There is no global variables in Gambas! -

-As a workaround, put them in your main module and declare them -as Public.

-

-If you do not have a main module in your project, but a main -form, then declare them as Static Public.

-

-To access these variables, you must use the name of the main module -or form: MyMainModule.MyGlobalVariable or -MyMainForm.MyGlobalVariable.

- - -[EMPTY] - -

Empty strings

- -

To know if a string is empty, it is not necessary to use the -Len() function. You can directly test it, as an empty string -is False and a non-empty string is True.

- -

For example, instead of doing :

- -
If Len(MyString) > 0 Then ...
-If Len(MyString) = 0 Then ...
- -

You should do :

- -
If MyString THEN ...
-If Not MyString THEN ...
- - -[TRANSLATE] - -

Translation

- -

Gambas applications are fully translatable, provided that you tell it -which strings must be translated, and which one must not.

-

To mark strings as translatable, just enclose them between braces:

- -
Print ("Translate me")
-Print "But do not translate me!"
- - -[SUBST] - -

Subst$

- -

The Subst$() function is very useful to internationalize your application.

- -

It takes at least two arguments. The first one is the text mask which the substitution applies on. -The other ones are the substitution arguments, numbered from one.

- -

Each &X pattern in the substitution string will be replaced by the Xth substitution argument. -For example:

- -
Print Subst(("Substitution of &1, &2 and &3"),
-  "first", "second", "third")
-
-→ Substitution of first, second and third
- - -[EVENT] - -

Event Handlers

- -

Every control, and every object that can raise events, has an -event observer and an event group name.

- -

The event observer catches every event raised by the object, and -the event group name is the prefix of the procedure called to manage -the event. That function is called event handler.

- -

By default, this event observer is the object where you have -created the control, and the group name is the name of the control.

- -

This way, a form receives all events raised by the controls you -created inside.

- -
' Gambas form
-Dim hButton As Button
-
-Public Sub _new()
-  hButton = New Button(Me) As "MyButton"
-End
-
-Public Sub MyButton_Click()
-  Print "You have clicked MyButton !"
-End
-
- - -[GROUP] - -

Control groups

- -

Every control has a (Group) property. When this property -is set, the prefix of the event handler name is the name of the group -and not the name of the control.

- -

Let's suppose you have a Button named btnAction -with the following Click event handler :

- -
Public SubbtnAction_Click()
- -

If you set the (Group) property of btnAction to -"MyGroup", then the event handler that will receive events from -the button will be the following :

- -
Pubic Sub MyGroup_Click()
- -

This property lets you handle events of different controls in -a single function. And the controls of the same group do not need -to have the same type !

- -

Note : The old Visual Basic™ veteran may recognize -the concept of control array, but in a more powerful -implementation. :-)

- - -[FORM] - -

Forms

- -

In Gambas, a form is its own event observer, so that -you can directly manage its events (like Resize, -Activate, ...) into its own class code.

- -

This way, newbies coming from Visual Basic™ are not -disorientated :-).

- - -[EMBED] - -

Embedding forms

- -

You can embed any form into other forms with Gambas!

- -

To do such a powerful thing, just instanciate the form by passing -a parent container as last argument of the constructor.

- -

For example:

-
Dim hForm As MyDialog
-Dim hSuperControl As MyForm
-' Create a dialog
-hForm = New MyDialog
-' Insert a form into this dialog
-' Note that this form takes two parameters before the container
-hSuperControl = New MyForm(Param1, Param2, MyDialog)
-' Moves and resizes the form
-hSuperControl.Move(8, 8, 128, 64)
-
- -

Be careful: a form embedded into another form is still a form, and -so is its own event observer.

- - -[TAG] - -

Tag Property

- -

Each control has a Tag property. This property is for the -programmer, and can contain any Variant data that you find -relevant.

- -

This is very useful, when you want to distinguish controls of the -same group in a common event handler.

- - -[LAST] - -

Last

- -

The Last keyword returns the last control that has -received an event. This is very useful when you want to write an -event handler that is independent of any control name.

- -

For example, let's suppose you want to write a calculator program. -You have defined ten buttons, one for each digit, each one in the -same control group "Digit". The Tag of each control is set to -the digit drawn in the button.

- -

Your event handler may look like that :

- -
Public Sub Digit_Click()
-
-  Display = Display & Last.Tag
-  RefreshDisplay
-END
-
- - -[LEFT] - -

Left$ / Mid$ / Right$

- -

The well known BASIC routines Left$, Right$ -and Mid$ have useful behaviours in Gambas

- -

The second parameter of Left$ and Right$ is -optional, and is one by default.

- -

Left$("Gambas") returns "G"
-Right$("Gambas") returns "s"

- -

This second parameter can be negative, and then gives the number -of characters not to extract.

- -

Left$("Gambas", -2) returns "Gamb"
-Right$("Gambas", -2) returns "mbas"

- -

Likewise, the third argument of Mid$ can be negative, and -then gives the number of characters from the end of the string -not to extract.

- -

Mid$("Gambas", 2, -2) returns "amb"

- - -[OBSERVER] - -

Observer

- -

The Observer class allows you to intercept all events raised -by an object before they are actually sent.

- -
MyTextBox = New TextBox(Me) As "MyTextBox"
-MyObserver = New Observer(MyTextBox) As "MyObserver"
-...
-Public Sub MyObserver_KeyPress()
-  Debug "Got it first"
-End
-
-Public Sub MyTextBox_KeyPress()
-  Debug "Got it next"
-End
- -

The observer can cancel the event with Stop Event to prevent the object from effectively -raising it.

- - -[STRING] - -

UTF-8 Strings

- -

Gambas uses the UTF-8 charset to represent strings in memory.

- -

But all standard string functions deal with ASCII only: -Left, Mid, Right, UCase...

- -

If you want to deal with UTF-8 strings, you have to use the methods of the -String static class, which have the same name as their standard counterparts.

- -
Print Len("bébé");; Left$("bébé", 3)
-→ 6 bé
-
-Print String.Len("bébé");; String.Left("bébé", 3)
-→ 4 béb
- - -[ASSIGNMENT] - -

Assignments

- -

Gambas implements the assignment shortcuts that the C/C++ programmers are used to.

- -
MyVariable += 2
-MyVariable *= 4
-MyVariable &= "Great"
-is an equivalent of -
MyVariable = MyVariable + 2
-MyVariable = MyVariable * 4
-MyVariable = MyVariable & "Great"
- -

And so on...

- - -[DEBUG] - -

Debug

- -

You can use the Debug instruction to print debugging messages to the -console (namely the standard error output). It behaves exactly like the Print -instruction.

- -

These messages are prefixed with the class name, method name and line number of -the Debug instruction. If you don't want that prefix, you can use the Error -instruction instead of Debug.

- -

The debugging messages are automatically removed when creating an executable -without debugging information.

- - -[TRY] - -

Error management (1)

- -

Error management in Gambasis done with the following instructions: -Try, Error, Catch, and Finally.

- -

Try tries to execute a statement without raising an error. The Error -keyword is used just after to know if the statement was executed correctly.

- -
Try MyFile = Open "/etc/password" For Write
-If Error Then Print "I cannot do what I want!"
- - -[CATCH] - -

Error management (2)

- -

Error management in Gambasis done with the following instructions: -Try, Error, Catch, and Finally.

- -

Catch indicates the beginning of the error management part of a function or procedure. -It is put at the end of the function code.

- -

The catch part is executed when an error is raised between the beginning of the function execution -and its end.

- -

If an error is raised during the execution of the catch part, it is normally propagated.

- -
Sub ProcessFile(FileName As String)
-  ...
-  Open FileName For Read As #hFile
-  ...
-  Close #hFile
-  
-Catch ' Executed only if there is an error
-
-  Print "Cannot process file "; FileName
-
-End
- - -[FINALLY] - -

Error management (3)

- -

Error management in Gambasis done with the following instructions: -Try, Error, Catch, and Finally.

- -

Finally introduces the code executed at the end of the function, even if an error was -raised during its execution.

- -

The finally part is not mandatory. If there is a catch part in the function, the finally part must precede it.

- -

If an error is raised during the execution of the finally part, it is normally propagated.

- -
Sub ProcessFile(FileName As String)
-  ...
-  Open FileName For Read As #hFile
-  ...
-Finally ' Always executed, even if a error is raised
-
-  Close #hFile
-  
-Catch ' Executed only if there is an error
-  
-  Print "Cannot print file "; FileName
-  
-End
- - -[OPTIONAL] - -

Optional

- -

Functions and procedures in Gambas can have optional arguments.

- -

Optional arguments are done simply by putting down the Optional -keyword just before the argument name.

- -

Optional arguments can have an explicit default value too.

- -
Private Sub MyFunction(Param AS String, Optional Optim AS String = "Default")
-  ...
-  Print "Required: "; param; ", Optional: "; optim
-  ...
-End
- - -[ARRAY] - -

For Each

- -

In Gambas you can easily loop through an array, a collection, or many other -enumerable classes with the For Each instruction.

- -

For example:

- -
Dim Xml As New XmlDocument
-Dim Node As XmlNode
-Dim I As Integer
-
-' Open XML file
-Xml.Open("pokus.xml")
-' Children is indexed via [i], since it's an array
-For I = 0 To Xml.Root.Children.Count - 1
-  'Attributes are looped via For Each, since it's a collection
-  For Each Node In Xml.Root.Children[i].Attributes
-    Print Node.Name;; Node.Value
-  Next
-Next
- - -[ICON] - -

Default Icons

- -

You can use built in icons for nicer GUI of your application, which are available -in several predefined sizes ("small", "medium", "large",...) -or absolute sizes (from 16x16 to 256x256).

- -

For example:

- -
Image1.Picture = Picture["icon:/32/warning"]
-Image2.Picture = Picture["icon:/small/error"]
-
- -

Warning: the gb.form component is required.

- - -[SETTINGS] - -

Settings

- -

If you need to store the configuration of your program (like the geometry of your forms), -then you are a lucky guy. It's very easy and elegant in Gambas. :-)

- -

To save the position of a form:

-
Settings.Write(TheForm)
- -

To recall it:

-
Settings.Read(TheForm)
- -To save any settings: -
Settings["Slot/Key"] = Value
- -And to read the settings back: -
Value = Settings["Slot/Key", DefaultValue]
- -These settings are stored in the ~/.config/gambas3/<MyApplication>.conf file, -where <MyApplication> is the name of your project. - -

Warning: The gb.settings component is required.

- - -[EDITOR] - -

Here is a few editor tips...

- -

Two Types Of Comments

- -
' Normal comment
-
'' Bold comment
- -

Bold comments are used for documenting your code.

- -

How To Use Code Snippets

- -

Let's type main then the TAB key. A static public Main -startup function is automatically inserted in your code.

- -

Let's type ds then the TAB key. A local string variable declaration is -automatically inserted, and you can type the variable name immediately.

- -

Code snippets are entirely configurable from the Preferences dialog of IDE's Tools menu.

- - -[END] - -

That's All Folks!

- -

You have read all the tips of the days. I hope you have became -a Gambas expert now ! :-)

- -

If you want to contribute, send new tips to the following -address:

-

user@lists.gambas-basic.org

- -

Thanks beforehand !

- diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.en.txt gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.en.txt --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.en.txt 1970-01-01 00:00:00.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.en.txt 2021-09-14 19:01:29.000000000 +0000 @@ -0,0 +1,592 @@ +[WELCOME] + +

Welcome to Gambas!

+ +

Gambas is a graphical development +environment based on an advanced Basic interpreter.

+ +

Gambas aims at enabling you to make +powerful programs easily and quickly. But clean programs +remain on your own responsibility...

+ +

Enjoy it !

+ +

Benoît Minisini
+g4mba5@gmail.com


+ + +[STARTUP] + +

Startup class

+ +

Each project must have a startup class. This +startup class must define a static public method named Main +with no arguments, that will act as the startup method of +your program.

+ +

You can define the startup class by clicking on it with the +right mouse button in the project tree, and by selecting +Startup class in the popup menu.

+ +

It is not necessary to define a Main method in a startup +form, because it already has a predefined one.

+ +

This predefined startup method instanciates the form and shows it, like in +Visual Basic™.

+ + +[OPEN] + +

Open

+ +

The Open instruction of Gambas does not +work like the Visual Basic™ one. It does not return the file +as an integer, but as a File object.

+ +

So, instead of typing :

+ +
Dim handle As Integer
+...
+Open "myfile" For Read As #handle
+ +

you must type :

+ +
Dim handle As File
+...
+handle = Open "myfile" For Read
+ + +[CATDIR] + +

Path concatenation

+ +

Do you know that you can concatenate directory names and +file names with the &/ operator ? This operator +deals with the trailing slashes so that the resulting path is +perfect.

+ +

For example:

+ +
Print "/home/gambas" &/ ".bashrc"
+→ /home/gambas/.bashrc
+
+Print "/home/gambas/" &/ "/tmp" &/ "foo.bar"
+→ /home/gambas/tmp/foo.bar
+
+ +

Isn't it marvelous ?

+ + +[EXEC] + +

Executable

+ +

You can make an executable file from your entire project. Select +Make executable in the Project menu.

+ +

When Gambas makes an executable file, it puts +the result in the directory of your project by default. +The executable name has the same name as your project.

+ + +[PATH] + +

Relative paths

+ +

Relative paths have a special meaning in Gambas. +They always refer to files inside your projects.

+

+There is no concept of current directory, and no keyword like +CHDIR to change it.

+

+Be careful: you must use relative paths only for accessing +project files, because absolute paths won't work anymore when +you make an executable.

+ + +[GLOBAL] + +

Global variables

+ +There is no global variables in Gambas! +

+As a workaround, put them in your main module and declare them +as Public.

+

+If you do not have a main module in your project, but a main +form, then declare them as Static Public.

+

+To access these variables, you must use the name of the main module +or form: MyMainModule.MyGlobalVariable or +MyMainForm.MyGlobalVariable.

+ + +[EMPTY] + +

Empty strings

+ +

To know if a string is empty, it is not necessary to use the +Len() function. You can directly test it, as an empty string +is False and a non-empty string is True.

+ +

For example, instead of doing :

+ +
If Len(MyString) > 0 Then ...
+If Len(MyString) = 0 Then ...
+ +

You should do :

+ +
If MyString THEN ...
+If Not MyString THEN ...
+ + +[TRANSLATE] + +

Translation

+ +

Gambas applications are fully translatable, provided that you tell it +which strings must be translated, and which one must not.

+

To mark strings as translatable, just enclose them between braces:

+ +
Print ("Translate me")
+Print "But do not translate me!"
+ + +[SUBST] + +

Subst$

+ +

The Subst$() function is very useful to internationalize your application.

+ +

It takes at least two arguments. The first one is the text mask which the substitution applies on. +The other ones are the substitution arguments, numbered from one.

+ +

Each &X pattern in the substitution string will be replaced by the Xth substitution argument. +For example:

+ +
Print Subst(("Substitution of &1, &2 and &3"),
+  "first", "second", "third")
+
+→ Substitution of first, second and third
+ + +[EVENT] + +

Event Handlers

+ +

Every control, and every object that can raise events, has an +event observer and an event group name.

+ +

The event observer catches every event raised by the object, and +the event group name is the prefix of the procedure called to manage +the event. That function is called event handler.

+ +

By default, this event observer is the object where you have +created the control, and the group name is the name of the control.

+ +

This way, a form receives all events raised by the controls you +created inside.

+ +
' Gambas form
+Dim hButton As Button
+
+Public Sub _new()
+  hButton = New Button(Me) As "MyButton"
+End
+
+Public Sub MyButton_Click()
+  Print "You have clicked MyButton !"
+End
+
+ + +[GROUP] + +

Control groups

+ +

Every control has a (Group) property. When this property +is set, the prefix of the event handler name is the name of the group +and not the name of the control.

+ +

Let's suppose you have a Button named btnAction +with the following Click event handler :

+ +
Public SubbtnAction_Click()
+ +

If you set the (Group) property of btnAction to +"MyGroup", then the event handler that will receive events from +the button will be the following :

+ +
Pubic Sub MyGroup_Click()
+ +

This property lets you handle events of different controls in +a single function. And the controls of the same group do not need +to have the same type !

+ +

Note : The old Visual Basic™ veteran may recognize +the concept of control array, but in a more powerful +implementation. :-)

+ + +[FORM] + +

Forms

+ +

In Gambas, a form is its own event observer, so that +you can directly manage its events (like Resize, +Activate, ...) into its own class code.

+ +

This way, newbies coming from Visual Basic™ are not +disorientated :-).

+ + +[EMBED] + +

Embedding forms

+ +

You can embed any form into other forms with Gambas!

+ +

To do such a powerful thing, just instanciate the form by passing +a parent container as last argument of the constructor.

+ +

For example:

+
Dim hForm As MyDialog
+Dim hSuperControl As MyForm
+' Create a dialog
+hForm = New MyDialog
+' Insert a form into this dialog
+' Note that this form takes two parameters before the container
+hSuperControl = New MyForm(Param1, Param2, MyDialog)
+' Moves and resizes the form
+hSuperControl.Move(8, 8, 128, 64)
+
+ +

Be careful: a form embedded into another form is still a form, and +so is its own event observer.

+ + +[TAG] + +

Tag Property

+ +

Each control has a Tag property. This property is for the +programmer, and can contain any Variant data that you find +relevant.

+ +

This is very useful, when you want to distinguish controls of the +same group in a common event handler.

+ + +[LAST] + +

Last

+ +

The Last keyword returns the last control that has +received an event. This is very useful when you want to write an +event handler that is independent of any control name.

+ +

For example, let's suppose you want to write a calculator program. +You have defined ten buttons, one for each digit, each one in the +same control group "Digit". The Tag of each control is set to +the digit drawn in the button.

+ +

Your event handler may look like that :

+ +
Public Sub Digit_Click()
+
+  Display = Display & Last.Tag
+  RefreshDisplay
+END
+
+ + +[LEFT] + +

Left$ / Mid$ / Right$

+ +

The well known BASIC routines Left$, Right$ +and Mid$ have useful behaviours in Gambas

+ +

The second parameter of Left$ and Right$ is +optional, and is one by default.

+ +

Left$("Gambas") returns "G"
+Right$("Gambas") returns "s"

+ +

This second parameter can be negative, and then gives the number +of characters not to extract.

+ +

Left$("Gambas", -2) returns "Gamb"
+Right$("Gambas", -2) returns "mbas"

+ +

Likewise, the third argument of Mid$ can be negative, and +then gives the number of characters from the end of the string +not to extract.

+ +

Mid$("Gambas", 2, -2) returns "amb"

+ + +[OBSERVER] + +

Observer

+ +

The Observer class allows you to intercept all events raised +by an object before they are actually sent.

+ +
MyTextBox = New TextBox(Me) As "MyTextBox"
+MyObserver = New Observer(MyTextBox) As "MyObserver"
+...
+Public Sub MyObserver_KeyPress()
+  Debug "Got it first"
+End
+
+Public Sub MyTextBox_KeyPress()
+  Debug "Got it next"
+End
+ +

The observer can cancel the event with Stop Event to prevent the object from effectively +raising it.

+ + +[STRING] + +

UTF-8 Strings

+ +

Gambas uses the UTF-8 charset to represent strings in memory.

+ +

But all standard string functions deal with ASCII only: +Left, Mid, Right, UCase...

+ +

If you want to deal with UTF-8 strings, you have to use the methods of the +String static class, which have the same name as their standard counterparts.

+ +
Print Len("bébé");; Left$("bébé", 3)
+→ 6 bé
+
+Print String.Len("bébé");; String.Left("bébé", 3)
+→ 4 béb
+ + +[ASSIGNMENT] + +

Assignments

+ +

Gambas implements the assignment shortcuts that the C/C++ programmers are used to.

+ +
MyVariable += 2
+MyVariable *= 4
+MyVariable &= "Great"
+is an equivalent of +
MyVariable = MyVariable + 2
+MyVariable = MyVariable * 4
+MyVariable = MyVariable & "Great"
+ +

And so on...

+ + +[DEBUG] + +

Debug

+ +

You can use the Debug instruction to print debugging messages to the +console (namely the standard error output). It behaves exactly like the Print +instruction.

+ +

These messages are prefixed with the class name, method name and line number of +the Debug instruction. If you don't want that prefix, you can use the Error +instruction instead of Debug.

+ +

The debugging messages are automatically removed when creating an executable +without debugging information.

+ + +[TRY] + +

Error management (1)

+ +

Error management in Gambasis done with the following instructions: +Try, Error, Catch, and Finally.

+ +

Try tries to execute a statement without raising an error. The Error +keyword is used just after to know if the statement was executed correctly.

+ +
Try MyFile = Open "/etc/password" For Write
+If Error Then Print "I cannot do what I want!"
+ + +[CATCH] + +

Error management (2)

+ +

Error management in Gambasis done with the following instructions: +Try, Error, Catch, and Finally.

+ +

Catch indicates the beginning of the error management part of a function or procedure. +It is put at the end of the function code.

+ +

The catch part is executed when an error is raised between the beginning of the function execution +and its end.

+ +

If an error is raised during the execution of the catch part, it is normally propagated.

+ +
Sub ProcessFile(FileName As String)
+  ...
+  Open FileName For Read As #hFile
+  ...
+  Close #hFile
+  
+Catch ' Executed only if there is an error
+
+  Print "Cannot process file "; FileName
+
+End
+ + +[FINALLY] + +

Error management (3)

+ +

Error management in Gambasis done with the following instructions: +Try, Error, Catch, and Finally.

+ +

Finally introduces the code executed at the end of the function, even if an error was +raised during its execution.

+ +

The finally part is not mandatory. If there is a catch part in the function, the finally part must precede it.

+ +

If an error is raised during the execution of the finally part, it is normally propagated.

+ +
Sub ProcessFile(FileName As String)
+  ...
+  Open FileName For Read As #hFile
+  ...
+Finally ' Always executed, even if a error is raised
+
+  Close #hFile
+  
+Catch ' Executed only if there is an error
+  
+  Print "Cannot print file "; FileName
+  
+End
+ + +[OPTIONAL] + +

Optional

+ +

Functions and procedures in Gambas can have optional arguments.

+ +

Optional arguments are done simply by putting down the Optional +keyword just before the argument name.

+ +

Optional arguments can have an explicit default value too.

+ +
Private Sub MyFunction(Param AS String, Optional Optim AS String = "Default")
+  ...
+  Print "Required: "; param; ", Optional: "; optim
+  ...
+End
+ + +[ARRAY] + +

For Each

+ +

In Gambas you can easily loop through an array, a collection, or many other +enumerable classes with the For Each instruction.

+ +

For example:

+ +
Dim Xml As New XmlDocument
+Dim Node As XmlNode
+Dim I As Integer
+
+' Open XML file
+Xml.Open("pokus.xml")
+' Children is indexed via [i], since it's an array
+For I = 0 To Xml.Root.Children.Count - 1
+  'Attributes are looped via For Each, since it's a collection
+  For Each Node In Xml.Root.Children[i].Attributes
+    Print Node.Name;; Node.Value
+  Next
+Next
+ + +[ICON] + +

Default Icons

+ +

You can use built in icons for nicer GUI of your application, which are available +in several predefined sizes ("small", "medium", "large",...) +or absolute sizes (from 16x16 to 256x256).

+ +

For example:

+ +
Image1.Picture = Picture["icon:/32/warning"]
+Image2.Picture = Picture["icon:/small/error"]
+
+ +

Warning: the gb.form component is required.

+ + +[SETTINGS] + +

Settings

+ +

If you need to store the configuration of your program (like the geometry of your forms), +then you are a lucky guy. It's very easy and elegant in Gambas. :-)

+ +

To save the position of a form:

+
Settings.Write(TheForm)
+ +

To recall it:

+
Settings.Read(TheForm)
+ +To save any settings: +
Settings["Slot/Key"] = Value
+ +And to read the settings back: +
Value = Settings["Slot/Key", DefaultValue]
+ +These settings are stored in the ~/.config/gambas3/<MyApplication>.conf file, +where <MyApplication> is the name of your project. + +

Warning: The gb.settings component is required.

+ + +[EDITOR] + +

Here is a few editor tips...

+ +

Two Types Of Comments

+ +' Normal comment
+'' Bold comment + +

Bold comments are used for documenting your code.

+ +

How To Use Code Snippets

+ +

Let's type main then the TAB key. A static public Main +startup function is automatically inserted in your code.

+ +

Let's type ds then the TAB key. A local string variable declaration is +automatically inserted, and you can type the variable name immediately.

+ +

Code snippets are entirely configurable from the Preferences dialog of IDE's Tools menu.

+ + +[END] + +

That's All Folks!

+ +

You have read all the tips of the days. I hope you have became +a Gambas expert now ! :-)

+ +

If you want to contribute, send new tips to the following +address:

+

user@lists.gambas-basic.org

+ +

Thanks beforehand !

+ diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.es gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.es --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.es 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.es 1970-01-01 00:00:00.000000000 +0000 @@ -1,302 +0,0 @@ -[WELCOME] - -

¡Bienvenido a Gambas!

- -

Gambas es un ambiente integrado de desarrollo basado en un intérprete Basic avanzado.

- -

Gambas pretende permitirle crear poderosos programas rápida y fácilmente. Pero la claridad de éstos programas es su propia responsabilidad...

- -

¡Disfrútelo!

- -

Benoît Minisini
g4mba5@gmail.com

- -[STARTUP] - -

Cada proyecto debe tener una clase de inicio. Ésta clase de inicio debe definir un método estático y público llamado Main sin argumentos, que actuará como el método de inicio de su programa.

- -

Usted puede definir la clase de inicio haciendo click sobre ella con el botón derecho del ratón en el árbol del proyecto, y seleccionado Clase de inicio en el menú contextual.

- -

No es necesario definir un método Main en un formulario de inicio, porque éste ya tiene uno predefinido.

- -

Éste método predefinido de inicio instancia el formulario y lo muestra, como en Visual Basic™.

- -[OPEN] - -

La instrucción OPEN de Gambas no trabaja como la de Visual Basic™. Ésta no retorna el archivo como un entero, sino como un objeto File.

- -

Así que, en lugar de escribir:

- -
DIM handle AS Integer
-...
-OPEN "myfile" FOR READ AS #handle
- -

debe escribir:

- -
DIM handle AS File
-...
-handle = OPEN "myfile" FOR READ
- -[CATDIR] - -

¿Sabía que puede concatenar nombres de directorios y nombres de archivos con el operador &/? Éste operador maneja las barras inclinadas de tal forma que la ruta resultante es perfecta.

- -

Por ejemplo:

- -
PRINT "/home/gambas" &/ ".bashrc"
-/home/gambas/.bashrc
-
-PRINT "/home/gambas/" &/ "/tmp" &/ "foo.bar"
-/home/gambas/tmp/foo.bar
-
- -

¿No es maravilloso?

- -[EXEC] - -

Usted puede crear un archivo ejecutable del proyecto entero. Seleccione Crear ejecutable en el menú Proyecto.

- -

Cuando Gambas hace un archivo ejecutable, por defecto pone el resultado en el directorio del proyecto. El nombre del ejecutable tiene el mismo nombre de su proyecto.

- -[PATH] - -

Las rutas relativas tienen un significado especial en Gambas. Ellas siempre se refieren a archivos dentro de sus proyectos.

- -

No existe el concepto de directorio actual, ni palabra reservada como CHDIR para cambiarlo.

- -

Tenga cuidado: debe utilizar rutas relativas sólo para acceder archivos del proyecto, porque las rutas absolutas no trabajarán más cuando usted cree un ejecutable.

- -[GLOBAL] - -

¡No hay variables globales en Gambas!

- -

Como apoyo, póngalas en su módulo principal y declárelas como PUBLIC.

- -

Si no tiene un módulo principal en su proyecto, pero sí un formulario principal, entonces declárelas como STATIC PUBLIC.

- -

Para acceder a esas variables, debe utilizar el nombre del módulo o formulario principal: MyMainModule.MyGlobalVariable o MyMainForm.MyGlobalVariable.

- - -[EMPTY] - -

Para saber si una cadena está vacía, no es necesario usar la función Len(). Usted puede probarla directamente, ya que una cadena vacía es FALSE y una no vacía es TRUE.

- -

Por ejemplo, en lugar de hacer:

- -
IF Len(MyString) > 0 THEN ...
-IF Len(MyString) = 0 THEN ...
- -

Usted podría hacer:

- -
IF MyString THEN ...
-IF NOT MyString THEN ...
- -[TRANSLATE] - -

Las aplicaciones Gambas son completamente traducibles, usted decide cual cadena debe ser traducida, y cual no.

- -

Para marcar una cadena como traducible, sólo enciérrela entre paréntesis:

- -
PRINT ("Tradúceme")
-PRINT "¡Pero no me traduzcas a mi!"
- -[EVENT] - -

Cada control, y cada objeto que puede lanzar eventos, tiene un observador de eventos y un nombre de grupo de evento.

- -

El observador de eventos atrapa cada evento lanzado por el objeto, y el grupo de nombre es el prefijo del procedimiento llamado para manejar el evento.

- -

Por defecto, este observador de eventos es el objeto donde usted creó el control, y el nombre de grupo es el nombre del control.

- -

De esta forma, un formulario recibe todos los eventos lanzados por los controles que usted creó dentro de él.

- -
' Gambas form
-DIM hButton AS Button
-
-PUBLIC SUB _new()
-  hButton = NEW Button(ME) AS "MyButton"
-END
-
-PUBLIC SUB MyButton_Click()
-  PRINT "¡Usted ha presionado MyButton!"
-END
-
- -[FORM] - -

En Gambas, un formulario es su propio observador de eventos, así que usted puede manejar sus eventos directamente (como Resize, Activate, ...) dentro su propio código de clase.

- -

De esta forma, los novatos que vengan de Visual Basic™ no estarán desorientados :-).

- -[EMBED] - -

¡Usted puede incrustar cualquier formulario dentro de otros con Gambas!

- -

Para hacer una cosa tan poderosa, sólo instancie el formulario pasando un contenedor padre como último argumento del constructor.

- -

Por ejemplo:

-

DIM hForm AS MyDialog
-DIM hSuperControl AS MyForm

-' Crear un dialigo
-hForm = NEW MyDialog
-' Insertar un formulario dentro de éste dialogo
-' Note que éste formualario toma dos parámetros antes del contenedor
-hSuperControl = NEW MyForm(Param1, Param2, MyDialog)
-' Mover y redimensionar el formulario
-hSuperControl.Move(8, 8, 128, 64)
-

- -

Tenga cuidado: un formulario incrustado dentro de otro es aún un formulario, y entonces es su propio observador de eventos.

- -[GROUP] - -

Cada control tiene una propiedad (Group). Cuando ésta propiedad es configurada, el prefirjo del nombre del manejador de eventos es el nombre del grupo y no el nombre del control.

- -

Supongamos que tiene un Butón llamado btnAction con el siguiente manejador de eventos Click:

- -
PUBLIC SUB btnAction_Click()
- -

Si usted configura la propiedad (Group) de btnAction a MyGroup, entonces el manejador de eventos que recibirá los eventos del botón será el siguiente:

- -
PUBLIC SUB MyGroup_Click()
- -

Esta propiedad permite manejar eventos de diferentes controles en una función. ¡Y los controles del mismo nombre de grupo no tienen que ser del mismo tipo!

- -

Nota: Los viejos veteranos de Visual Basic™ podrían reconocer el concepto de arreglo de controles, pero en una implementación más poderosa. :-)

- -[TAG] - -

Cada control tiene una propiedad Tag. Ésta propiedad es para el programador, y puede contener cualquier dato de tipo VARIANT que usted pueda encontrar relevante.

- -

Ésto es muy útil, cuando quiere distinguir controles del mismo grupo en un manejador de eventos común.

- -[LAST] - -

La palabra clave LAST retorna el último control que ha recibido un evento. Ésto es muy últil cuando usted quiere escribir un manejador de eventos que es independiente de cada nombre de control.

- -

Por ejemplo, supongamos que usted quiere escribir un programa de una calculadora. Usted ha definido diez botones, uno para cada dígito, cada uno en el mismo group "Digit". El Tag de cada control es configurado para el dígito dibujado en el botón. Su manejador de eventos podría lucir así:

- -

PUBLIC SUB Digit_Click()

-  Display = Display & LAST.Tag
-  RefreshDisplay

-END

- - -[LEFT] - -

Las bien conocidas rutinas BASIC Left$, Right$ y Mid$ tienen conductas útiles en Gambas.

- -

El segundo parámetro de Left$ y Right$ es opcional, y es uno por defecto.

- -

Left$("Gambas") retorna "G"
Right$("Gambas") retorna "s"

- -

El segundo parámetro puede ser negativo, y entonces da el número de caracteres a no extraer.

- -

Left$("Gambas", -2) retorna "Gamb"
Right$("Gambas", -2) retorna "mbas"

- -

Asimismo, el tercer argumento de Mid$ puede ser negativo, y entonces da el número de caracteres desde el final de la cadena a no extraer.

- -

Mid$("Gambas", 2, -2) retorna "amb" - -[OBSERVER] - -

El clase Observer le permite interceptar todos los eventos lanzados por un objeto antes que de que sean enviados.

- -
MyTextBox = NEW TextBox(ME) AS "MyTextBox"
-MyObserver = NEW Observer(MyTextBox) AS "MyObserver"
-...
-PUBLIC SUB MyObserver_KeyPress()
-  DEBUG "Tengo ésto primero"
-END
-
-PUBLIC SUB MyTextBox_KeyPress()
-  DEBUG "Tengo ésto después"
-END
- -

El observador puede cancelar el evento para prevenir que el objeto eventualmente lo lance.

- -[STRING] - -

Gambas usa el juego de caracteres UTF-8 para representar cadenas en la memoria.

- -

Pero todas las funciones de cadena estándar de Gambas trabajan con ASCII: Left, Mid, Right, UCase...

- -

Si quiere manipular una cadena UTF-8, tiene que usar los métodos de la clase estática String, la cual tiene el mismo nombre de sus homólogos estándar.

- -
PRINT Len("bébé");; Left$("bébé", 3)
-6 bé
-PRINT String.Len("bébé");; String.Left("bébé", 3)
-4 béb
- -[ASSIGNMENT] - -

Gambas implementa los atajos de asignación a los que los programadores de C/C++ están acostumbrados.

- -

MyVariable += 2 es equivalente a MyVariable = MyVariable + 2

- -

MyVariable &= "Great" es equivalente a MyVariable = MyVariable & "Great"

- -

Así consecutivamente...

- -[DEBUG] - -

Usted puede usar la instrucción DEBUG para imprimir mensajes de depurado en la consola (llamada la salida de errores estándar). Ésta se comporta exactamente como la instrucción PRINT.

- -

Los mensajes tienen el prefijo del nombre de la clase, nombre del método y número de línea de la instrucción DEBUG.

- -

Los mensajes de depurado son automáticamente removidos cuando se crea un ejecutable sin la información del depurado.

- -[TRY] - -

El manejo de Errores en Gambas es echo con las siguientes instrucciones: TRY, ERROR, CATCH, y FINALLY - -

TRY trata de ejecutar una sentencia sin lanzar un error. La instrucción ERROR es usada justo después para saber si la instrucción fue ejecutada correctamente.

- -
TRY MyFile = OPEN "/etc/password" FOR WRITE
-IF ERROR THEN PRINT "¡No puedo hacer lo que quiero!"
- -[CATCH] - -

El manejo de Errores en Gambas es echo con las siguientes instrucciones: TRY, ERROR, CATCH, y FINALLY.

- -

CATCH indica el inicio de la parte de manejo de errores de una función o procedimiento. Es puesto al final del código de la función.

- -

La parte catch es ejecutada cuando un error es lanzado entre el inicio de la ejecución de la función y su final.

- -

Si un error es lanzado durante la ejecución de la parte catch, éste es normalmente propagado.

- -
SUB ProcessFile(FileName AS STRING)
-  ...
-  OPEN FileName FOR READ AS #hFile
-  ...
-  CLOSE #hFile
-CATCH ' Ejecutado sólo si hay un error
-  PRINT "No se puede procesar el archivo "; FileName
-END
- -[FINALLY] - -

El manejo de Errores en Gambas es echo con las siguientes instrucciones: TRY, ERROR, CATCH, y FINALLY.

- -

FINALLY introduce el código ejecutado al final de la función, aunque un error haya sido lanzado durante su ejecución.

- -

La parte finally no es mandatoria. Si hay una parte catch en la función, la parte finally debe de precederle.

- -

Si un error es lanzado durante la ejecución de la parte finally, éste es normalmente propagado.

- -
SUB ProcessFile(FileName AS STRING)
-  ...
-  OPEN FileName FOR READ AS #hFile
-  ...
-FINALLY ' Siempre ejecutada, aunque un error sea lanzado
-  CLOSE #hFile
-CATCH ' Ejecutado sólo si hay un error
-  PRINT "No se puede imprimir el archivo "; FileName
-END
- -[END] - -

Usted ha leído todos los consejos de los días. ¡Espero que ahora se haya convertido en en experto en Gambas! :-)

- -

Si quiere contribuir, envíe nuevos consejos a la siguiente dirección:

- -

g4mba5@gmail.com

\ No newline at end of file diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.es.txt gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.es.txt --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.es.txt 1970-01-01 00:00:00.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.es.txt 2021-09-14 19:01:29.000000000 +0000 @@ -0,0 +1,302 @@ +[WELCOME] + +

¡Bienvenido a Gambas!

+ +

Gambas es un ambiente integrado de desarrollo basado en un intérprete Basic avanzado.

+ +

Gambas pretende permitirle crear poderosos programas rápida y fácilmente. Pero la claridad de éstos programas es su propia responsabilidad...

+ +

¡Disfrútelo!

+ +

Benoît Minisini
g4mba5@gmail.com

+ +[STARTUP] + +

Cada proyecto debe tener una clase de inicio. Ésta clase de inicio debe definir un método estático y público llamado Main sin argumentos, que actuará como el método de inicio de su programa.

+ +

Usted puede definir la clase de inicio haciendo click sobre ella con el botón derecho del ratón en el árbol del proyecto, y seleccionado Clase de inicio en el menú contextual.

+ +

No es necesario definir un método Main en un formulario de inicio, porque éste ya tiene uno predefinido.

+ +

Éste método predefinido de inicio instancia el formulario y lo muestra, como en Visual Basic™.

+ +[OPEN] + +

La instrucción OPEN de Gambas no trabaja como la de Visual Basic™. Ésta no retorna el archivo como un entero, sino como un objeto File.

+ +

Así que, en lugar de escribir:

+ +
DIM handle AS Integer
+...
+OPEN "myfile" FOR READ AS #handle
+ +

debe escribir:

+ +
DIM handle AS File
+...
+handle = OPEN "myfile" FOR READ
+ +[CATDIR] + +

¿Sabía que puede concatenar nombres de directorios y nombres de archivos con el operador &/? Éste operador maneja las barras inclinadas de tal forma que la ruta resultante es perfecta.

+ +

Por ejemplo:

+ +
PRINT "/home/gambas" &/ ".bashrc"
+/home/gambas/.bashrc
+
+PRINT "/home/gambas/" &/ "/tmp" &/ "foo.bar"
+/home/gambas/tmp/foo.bar
+
+ +

¿No es maravilloso?

+ +[EXEC] + +

Usted puede crear un archivo ejecutable del proyecto entero. Seleccione Crear ejecutable en el menú Proyecto.

+ +

Cuando Gambas hace un archivo ejecutable, por defecto pone el resultado en el directorio del proyecto. El nombre del ejecutable tiene el mismo nombre de su proyecto.

+ +[PATH] + +

Las rutas relativas tienen un significado especial en Gambas. Ellas siempre se refieren a archivos dentro de sus proyectos.

+ +

No existe el concepto de directorio actual, ni palabra reservada como CHDIR para cambiarlo.

+ +

Tenga cuidado: debe utilizar rutas relativas sólo para acceder archivos del proyecto, porque las rutas absolutas no trabajarán más cuando usted cree un ejecutable.

+ +[GLOBAL] + +

¡No hay variables globales en Gambas!

+ +

Como apoyo, póngalas en su módulo principal y declárelas como PUBLIC.

+ +

Si no tiene un módulo principal en su proyecto, pero sí un formulario principal, entonces declárelas como STATIC PUBLIC.

+ +

Para acceder a esas variables, debe utilizar el nombre del módulo o formulario principal: MyMainModule.MyGlobalVariable o MyMainForm.MyGlobalVariable.

+ + +[EMPTY] + +

Para saber si una cadena está vacía, no es necesario usar la función Len(). Usted puede probarla directamente, ya que una cadena vacía es FALSE y una no vacía es TRUE.

+ +

Por ejemplo, en lugar de hacer:

+ +
IF Len(MyString) > 0 THEN ...
+IF Len(MyString) = 0 THEN ...
+ +

Usted podría hacer:

+ +
IF MyString THEN ...
+IF NOT MyString THEN ...
+ +[TRANSLATE] + +

Las aplicaciones Gambas son completamente traducibles, usted decide cual cadena debe ser traducida, y cual no.

+ +

Para marcar una cadena como traducible, sólo enciérrela entre paréntesis:

+ +
PRINT ("Tradúceme")
+PRINT "¡Pero no me traduzcas a mi!"
+ +[EVENT] + +

Cada control, y cada objeto que puede lanzar eventos, tiene un observador de eventos y un nombre de grupo de evento.

+ +

El observador de eventos atrapa cada evento lanzado por el objeto, y el grupo de nombre es el prefijo del procedimiento llamado para manejar el evento.

+ +

Por defecto, este observador de eventos es el objeto donde usted creó el control, y el nombre de grupo es el nombre del control.

+ +

De esta forma, un formulario recibe todos los eventos lanzados por los controles que usted creó dentro de él.

+ +
' Gambas form
+DIM hButton AS Button
+
+PUBLIC SUB _new()
+  hButton = NEW Button(ME) AS "MyButton"
+END
+
+PUBLIC SUB MyButton_Click()
+  PRINT "¡Usted ha presionado MyButton!"
+END
+
+ +[FORM] + +

En Gambas, un formulario es su propio observador de eventos, así que usted puede manejar sus eventos directamente (como Resize, Activate, ...) dentro su propio código de clase.

+ +

De esta forma, los novatos que vengan de Visual Basic™ no estarán desorientados :-).

+ +[EMBED] + +

¡Usted puede incrustar cualquier formulario dentro de otros con Gambas!

+ +

Para hacer una cosa tan poderosa, sólo instancie el formulario pasando un contenedor padre como último argumento del constructor.

+ +

Por ejemplo:

+

DIM hForm AS MyDialog
+DIM hSuperControl AS MyForm

+' Crear un dialigo
+hForm = NEW MyDialog
+' Insertar un formulario dentro de éste dialogo
+' Note que éste formualario toma dos parámetros antes del contenedor
+hSuperControl = NEW MyForm(Param1, Param2, MyDialog)
+' Mover y redimensionar el formulario
+hSuperControl.Move(8, 8, 128, 64)
+

+ +

Tenga cuidado: un formulario incrustado dentro de otro es aún un formulario, y entonces es su propio observador de eventos.

+ +[GROUP] + +

Cada control tiene una propiedad (Group). Cuando ésta propiedad es configurada, el prefirjo del nombre del manejador de eventos es el nombre del grupo y no el nombre del control.

+ +

Supongamos que tiene un Butón llamado btnAction con el siguiente manejador de eventos Click:

+ +
PUBLIC SUB btnAction_Click()
+ +

Si usted configura la propiedad (Group) de btnAction a MyGroup, entonces el manejador de eventos que recibirá los eventos del botón será el siguiente:

+ +
PUBLIC SUB MyGroup_Click()
+ +

Esta propiedad permite manejar eventos de diferentes controles en una función. ¡Y los controles del mismo nombre de grupo no tienen que ser del mismo tipo!

+ +

Nota: Los viejos veteranos de Visual Basic™ podrían reconocer el concepto de arreglo de controles, pero en una implementación más poderosa. :-)

+ +[TAG] + +

Cada control tiene una propiedad Tag. Ésta propiedad es para el programador, y puede contener cualquier dato de tipo VARIANT que usted pueda encontrar relevante.

+ +

Ésto es muy útil, cuando quiere distinguir controles del mismo grupo en un manejador de eventos común.

+ +[LAST] + +

La palabra clave LAST retorna el último control que ha recibido un evento. Ésto es muy últil cuando usted quiere escribir un manejador de eventos que es independiente de cada nombre de control.

+ +

Por ejemplo, supongamos que usted quiere escribir un programa de una calculadora. Usted ha definido diez botones, uno para cada dígito, cada uno en el mismo group "Digit". El Tag de cada control es configurado para el dígito dibujado en el botón. Su manejador de eventos podría lucir así:

+ +

PUBLIC SUB Digit_Click()

+  Display = Display & LAST.Tag
+  RefreshDisplay

+END

+ + +[LEFT] + +

Las bien conocidas rutinas BASIC Left$, Right$ y Mid$ tienen conductas útiles en Gambas.

+ +

El segundo parámetro de Left$ y Right$ es opcional, y es uno por defecto.

+ +

Left$("Gambas") retorna "G"
Right$("Gambas") retorna "s"

+ +

El segundo parámetro puede ser negativo, y entonces da el número de caracteres a no extraer.

+ +

Left$("Gambas", -2) retorna "Gamb"
Right$("Gambas", -2) retorna "mbas"

+ +

Asimismo, el tercer argumento de Mid$ puede ser negativo, y entonces da el número de caracteres desde el final de la cadena a no extraer.

+ +

Mid$("Gambas", 2, -2) retorna "amb" + +[OBSERVER] + +

El clase Observer le permite interceptar todos los eventos lanzados por un objeto antes que de que sean enviados.

+ +
MyTextBox = NEW TextBox(ME) AS "MyTextBox"
+MyObserver = NEW Observer(MyTextBox) AS "MyObserver"
+...
+PUBLIC SUB MyObserver_KeyPress()
+  DEBUG "Tengo ésto primero"
+END
+
+PUBLIC SUB MyTextBox_KeyPress()
+  DEBUG "Tengo ésto después"
+END
+ +

El observador puede cancelar el evento para prevenir que el objeto eventualmente lo lance.

+ +[STRING] + +

Gambas usa el juego de caracteres UTF-8 para representar cadenas en la memoria.

+ +

Pero todas las funciones de cadena estándar de Gambas trabajan con ASCII: Left, Mid, Right, UCase...

+ +

Si quiere manipular una cadena UTF-8, tiene que usar los métodos de la clase estática String, la cual tiene el mismo nombre de sus homólogos estándar.

+ +
PRINT Len("bébé");; Left$("bébé", 3)
+6 bé
+PRINT String.Len("bébé");; String.Left("bébé", 3)
+4 béb
+ +[ASSIGNMENT] + +

Gambas implementa los atajos de asignación a los que los programadores de C/C++ están acostumbrados.

+ +

MyVariable += 2 es equivalente a MyVariable = MyVariable + 2

+ +

MyVariable &= "Great" es equivalente a MyVariable = MyVariable & "Great"

+ +

Así consecutivamente...

+ +[DEBUG] + +

Usted puede usar la instrucción DEBUG para imprimir mensajes de depurado en la consola (llamada la salida de errores estándar). Ésta se comporta exactamente como la instrucción PRINT.

+ +

Los mensajes tienen el prefijo del nombre de la clase, nombre del método y número de línea de la instrucción DEBUG.

+ +

Los mensajes de depurado son automáticamente removidos cuando se crea un ejecutable sin la información del depurado.

+ +[TRY] + +

El manejo de Errores en Gambas es echo con las siguientes instrucciones: TRY, ERROR, CATCH, y FINALLY + +

TRY trata de ejecutar una sentencia sin lanzar un error. La instrucción ERROR es usada justo después para saber si la instrucción fue ejecutada correctamente.

+ +
TRY MyFile = OPEN "/etc/password" FOR WRITE
+IF ERROR THEN PRINT "¡No puedo hacer lo que quiero!"
+ +[CATCH] + +

El manejo de Errores en Gambas es echo con las siguientes instrucciones: TRY, ERROR, CATCH, y FINALLY.

+ +

CATCH indica el inicio de la parte de manejo de errores de una función o procedimiento. Es puesto al final del código de la función.

+ +

La parte catch es ejecutada cuando un error es lanzado entre el inicio de la ejecución de la función y su final.

+ +

Si un error es lanzado durante la ejecución de la parte catch, éste es normalmente propagado.

+ +
SUB ProcessFile(FileName AS STRING)
+  ...
+  OPEN FileName FOR READ AS #hFile
+  ...
+  CLOSE #hFile
+CATCH ' Ejecutado sólo si hay un error
+  PRINT "No se puede procesar el archivo "; FileName
+END
+ +[FINALLY] + +

El manejo de Errores en Gambas es echo con las siguientes instrucciones: TRY, ERROR, CATCH, y FINALLY.

+ +

FINALLY introduce el código ejecutado al final de la función, aunque un error haya sido lanzado durante su ejecución.

+ +

La parte finally no es mandatoria. Si hay una parte catch en la función, la parte finally debe de precederle.

+ +

Si un error es lanzado durante la ejecución de la parte finally, éste es normalmente propagado.

+ +
SUB ProcessFile(FileName AS STRING)
+  ...
+  OPEN FileName FOR READ AS #hFile
+  ...
+FINALLY ' Siempre ejecutada, aunque un error sea lanzado
+  CLOSE #hFile
+CATCH ' Ejecutado sólo si hay un error
+  PRINT "No se puede imprimir el archivo "; FileName
+END
+ +[END] + +

Usted ha leído todos los consejos de los días. ¡Espero que ahora se haya convertido en en experto en Gambas! :-)

+ +

Si quiere contribuir, envíe nuevos consejos a la siguiente dirección:

+ +

g4mba5@gmail.com

\ No newline at end of file diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.fr gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.fr --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.fr 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.fr 1970-01-01 00:00:00.000000000 +0000 @@ -1,604 +0,0 @@ -[WELCOME] - -

Bienvenue dans Gambas !

- -

Gambas est un environnement graphique de développement -basé sur un interpréteur Basic avancé.

- -

Le but de Gambas est de vous permettre de concevoir de -puissants programmes, et ce facilement et rapidement. Mais la propreté de ces -programmes reste sous votre entière responsabilité...

- -

En espérant que vous l'apprécierez !

- -

Benoît Minisini
-g4mba5@gmail.com

- - -[STARTUP] - -

Classe de démarrage

- -

Tout projet doit avoir une classe de démarrage. Cette classe -de démarrage doit posséder une méthode publique statique appelée -Main ne possédant aucun paramètre. Celle-ci agira alors comme -méthode de démarrage de votre programme.

- -

Pour définir la classe de démarrage, cliquez dessus avec le bouton -droit dans l'arbre du projet, et cochez l'entrée Classe de -démarrage dans le menu contextuel.

- -

Il n'est pas nécessaire de définir la méthode Main dans un -formulaire de démarrage, car celui-ci en possède une par défaut.

- -

Cette méthode de démarrage par défaut se charge d'instancier puis -d'afficher le formulaire, à la manière de Visual Basic™. -

- - -[EXEC] - -

Exécutable

- -Vous pouvez créer un fichier exécutable à partir de votre projet. -Pour cela, sélectionnez Générer l'exécutable... dans le menu -Projet. -

-L'exécutable est placé par défaut dans le répertoire du projet. -Il porte le même nom que le projet. - - -[OPEN] - -

Open

- -L'instruction Open de Gambas ne fonctionne -pas comme celle de Visual Basic™. Elle ne retourne -pas le fichier ouvert sous forme d'un entier, mais d'un objet de -la classe File. -

-Ainsi, au lieu de taper : -

Dim Handle As Integer
-...
-Open "mon-fichier.txt" For Read As #Handle
-

-Vous devez taper : -

Dim Handle As File
-...
-Handle = Open "mon-fichier.txt" For Read
- - -[CATDIR] - -

Concaténation de chemins

- -Savez-vous que vous pouvez concaténer des noms de répertoires et -de fichiers avec l'opérateur &/ ? -

-Cet opérateur s'occupe d'ajouter le caractère de délimitation -de répertoire '/' lorsque c'est nécessaire. -

-Par exemple : -

Print "/home/gambas" &/ ".bashrc"
-→ /home/gambas/.bashrc
-
-Print "/home/gambas/" &/ "/tmp" &/ "foo.bar"
-→ /home/gambas/tmp/foo.bar
-
-

N'est-ce pas merveilleux ? :-) - - -[PATH] - -

Chemins relatifs

- -Les chemins relatifs ont une signification particulière dans Gambas. -Ils font référence aux fichiers situés à l'intérieur de votre projet. -

-Il n'y a pas de concept de répertoire courant, et aucune instruction -telle que CHDIR qui serait susceptible de le modifier. -

-Attention : vous devez toujours utiliser des chemins relatifs pour -accéder aux fichiers de votre projet, car les chemins absolus vers ces -fichiers n'ont plus de signification lorsque le projet est transformé -en exécutable. - - -[GLOBAL] - -

Variables globales

- -Il n'y a pas de variables globales en Gambas ! -

-Par contre, vous pouvez placer les variables auxquelles vous désirez accéder depuis -n'importe quelle partie de votre projet à l'intérieur de votre module principal en les déclarant Public. -

-Si vous n'avez pas de module principal, mais un formulaire principal, -déclarez-les comme Static Public. -

-Pour accéder à ces variables, vous devez utiliser le nom du module ou du -formulaire principal ainsi : - -

MonModulePrincipal.MaVariableGlobale -

ou bien -

MonFormulairePrincipal.MaVariableGlobale - - -[EMPTY] - -

Chaînes vides

- -Pour savoir si une chaîne est vide, il n'est pas nécessaire d'effectuer -une comparaison avec "" ou bien d'utiliser la fonction -Len(). Il est possible de la tester directement, car une -chaîne vide est équivalente à False et une chaîne non-vide -est équivalente à True. -

-Par exemple, plutôt que de faire : -

If Len(MaChaine) > 0 Then ...
-If Len(MaChaine) = 0 Then ...
-

-Vous devriez plutôt faire : -

If MaChaine Then ...
-If Not MaChaine Then ...
- - -[TRANSLATE] - -

Traduction

- -

Un programme écrit en Gambas est traduisible dans n'importe quel langue, -à condition que vous indiquiez parmi les chaînes de caractères du programme -lesquelles doivent être traduites, et lesquelles ne le doivent pas.

- -

Pour indiquer quelles chaînes doivent être traduites, il suffit de les -écrire entre parenthèses:

- -
Print ("Traduisez-moi")
-Print "Mais ne me traduisez pas!"
- - -[SUBST] - -

Subst$

- -

La fonction Subst$() est très utile pour internationaliser votre application. - -

Elle prend au moins deux arguments. Le premier est le masque de texte à l'intérieur duquel les -substitutions vont s'appliquer. Les autres sont les substitutions, numérotées en commençant par un. - -

Chaque occurence &X de la chaîne de substitution sera remplacée par le Xème -argument à substituer. Par exemple : - -

Print Subst(("Substitution de &1, &2 et &3"),
-  "premier", "deuxième", "troisième")
-
-→ Substitution de premier, deuxième et troisième
- - -[EVENT] - -

Gestionnaires d'évènements

- -Chaque contrôle, et chaque objet pouvant générer des évènements, possède -un observateur d'évènement et un nom de groupe d'évènement. -

-L'observateur d'évènement reçoit chaque évènement généré par un objet, et -le nom de groupe d'évènenement est le préfixe de la fonction qui sera -appelée pour gérer l'évènement. Cette fonction est appelée gestionnaire -d'évènements. -

-Par défaut, l'observateur d'évènement est l'objet à l'intérieur duquel -vous avez créé le contrôle, et le nom de groupe est le nom du contrôle. -

-De cette manière, un formulaire recevra tous les évènements des contrôles -lui appartenant. -

-

' Gambas form
-Dim hButton As Button
-
-Public Sub _new()
-  hButton = New Button(Me) As "MonBouton"
-End
-
-Public Sub MonButton_Click()
-  Print "Vous avez cliqué sur MonBouton !"
-End
-
- - -[FORM] - -

Formulaires

- -En Gambas, un formulaire est son propre observateur d'évènements, afin -que vous puissez directement gérer ses évènements (comme Resize, -Activate, ...) dans le code même de la classe associée. -

-De cette manière, les débutants venant de Visual Basic™ ne sont -pas désorientés :-). - - -[EMBED] - -

Formulaires imbriqués

- -

Vous pouvez imbriquer un formulaire à l'intérieur d'un autre en -Gambas ! Pour cela, instanciez simplement votre formulaire en lui passant -un conteneur parent en argument supplémentaire.

- -

Par exemple :

-

Dim hForm As MyDialog
-Dim hSuperControl As MyForm
-
-' Création d'une boîte dialogue
-hForm = New MyDialog
-' Insertion d'un formulaire dans le dialogue
-' Notez que le constructeur du formulaire prend deux arguments avant 
-' le conteneur
-hSuperControl = New MyForm(Param1, Param2, MyDialog)
-' Déplacement et redimensionnement du formulaire
-hSuperControl.Move(8, 8, 128, 64)
-
- -

Attention : un formulaire imbriqué reste un formulaire, et par conséquent -est son propre observateur d'évènements.

- - -[GROUP] - -

Groupes de contrôles

- -

Chaque contrôle possède une propriété (Group). Lorsque cette propriété est -définie, le préfixe de chaque gestionnaire d'évènement devient le nom de ce groupe -et non plus le nom du contrôle.

- -

Supposons qu'on ait un Button appelé btnAction avec le gestionnaire -d'évènement Click suivant :

- -
Public Sub btnAction_Click()
- -

Si vous définissez la propriété (Group) de btnAction à "MyGroup", -alors le gestionnaire d'évènement sera le suivant :

- -
Public Sub MyGroup_Click()
- -

Cette propriété vous permet de gérer les évènements de différents contrôles au sein -d'une seule fonction. Et les contrôles d'un même groupe peuvent être de types différents !

- -

Remarque : le bon vieux vétéran du Visual Basic reconnaîtra éventuellement -le concept de tableau de contrôle, mais dans une implémentation bien plus puissante. :-)

- -[TAG] - -

La propriété Tag

- -

Chaque contrôle possède une propriété Tag. Cette propriété est -destinée au programmeur, et peut contenir n'importe quel donnée de type Variant -que vous trouverez adéquate.

- -

Ceci est très utile si, par exemple, vous voulez distinguer les contrôles d'un -même groupe au sein de leur gestionnaire d'évènement commun.

- - -[LAST] - -

Last

- -

Le mot-clef Last retourne le dernier contrôle ayant reçu -un évènement. Ceci est très utile si vous voulez écrire un gestionnaire -d'évènement indépendant d'un nom de contrôle.

- -

Par exemple, supposons que vous voulez programmez une calculatrice. -Vous avez défini dix boutons, un pour chaque chiffre, tous dans le même -groupe "Digit". La propriété Tag de chaque bouton -contient le chiffre dessiné sur le bouton.

- -

Votre gestionnaire d'évènement ressemblera à ceci :

- -
Public Sub Digit_Click()
-
-  Display = Display & Last.Tag
-  RefreshDisplay
-
-End
- - -[LEFT] - -

Left$ / Mid$ / Right$

- -

Les fonctions BASIC bien connues que sont Left$, Right$ -et Mid$ possèdent des syntaxes spécifiques bien utiles en Gambas. - -

Le deuxième argument de Left$ et de Right$ est optionnel, -et vaut un par défaut.

- -

Left$("Gambas") retourne "G".
-Right$("Gambas") retourne "s".

- -

Ce second argument peut être négatif. Il donne alors le nombre de -caractères à ne pas extraire.

- -

Left$("Gambas", -2) retourne "Gamb".
-Right$("Gambas", -2) retourne "mbas".

- -

De même, le troisième argument de Mid$ peut être négatif. Il -donne alors le nombre de caractères depuis la fin de la chaîne à ne pas extraire.

- -

Mid$("Gambas", 2, -2) retourne "amb".

- - -[OBSERVER] - -

Observer

- -

La classe Observer vous permet d'intercepter n'importe quel évènement -de n'importe quel objet avant même qu'il ait été effectivement émis.

- -
MyTextBox = New TextBox(Me) As "MyTextBox"
-MyObserver = New Observer(MyTextBox) As "MyObserver"
-...
-Public Sub MyObserver_KeyPress()
-  Debug "Reçu en premier"
-End
-
-Public Sub MyTextBox_KeyPress()
-  Debug "Reçu en dernier"
-End
- -L'observateur peut annuler l'évènement avec Stop Event pour -empêcher son émission. - - -[STRING] - -

Chaînes UTF-8

- -

Gambas utilise le jeu de caractères UTF-8 pour représenter -les chaînes de caractères en mémoire. - -

Mais les fonctions de traitement de chaînes de caractères standardes ne -fonctionnent qu'avec de l'ASCII : -Left, Mid, Right, UCase... - -

Si vous voulez manipuler des chaînes de caractères UTF-8, vous devez utiliser -les méthodes de la classe statique String, qui possèdent les mêmes noms -que leur équivalent standardes. - -

Print Len("bébé");; Left$("bébé", 3)
-→ 6 bé
-
-Print String.Len("bébé");; String.Left("bébé", 3)
-→ 4 béb
- - -[ASSIGNMENT] - -

Assignations

- -

Gambas implémente les raccourcis d'assignation auxquels les programmeurs C/C++ sont habitués. - -

MyVariable += 2
-MyVariable *= 4
-MyVariable &= "Great"
-équivaut à -
MyVariable = MyVariable + 2
-MyVariable = MyVariable * 4
-MyVariable = MyVariable & "Great"
- -

Et ainsi de suite... - - -[DEBUG] - -

Debug

- -

Vous pouvez utiliser l'instruction Debug pour imprimer des messages de débogage -sur la console (c'est-à-dire la sortie erreur standard). Elle se comporte exactement comme -l'instruction Print. - -

Ces messages sont prefixés avec le nom de la classe, le nom de la méthode et le numéro de ligne -de l'instruction Debug. Si vous ne voulez pas de ce préfixe, vous pouvez utiliser -l'instruction Error à la place de Debug. - -

Les messages de débogages sont automatiquement ignorés lorsque vous créez un exécutable -privé des informations de débogage. - - -[TRY] - -

Gestion des erreurs (1)

- -

La gestion des erreurs en Gambas s'effectue à l'aide des instructions suivantes : -Try, Error, Catch, et Finally. - -

Try essaie d'exécuter une instruction sans déclencher d'erreur. Le mot-clef Error -est utilisé juste après pour savoir si l'instruction s'est exécutée correctement. - -

Try MyFile = Open "/etc/password" For Write
-If Error Then Print "Je ne peux pas faire tout ce que je veux !"
- - -[CATCH] - -

Gestion des erreurs (2)

- -

La gestion des erreurs en Gambas s'effectue à l'aide des instructions suivantes : -Try, Error, Catch, et Finally. - -

Catch marque le début du gestionnaire d'erreurs d'une fonction ou d'une procédure. -Il doit être placé à la fin du code de la fonction. - -

Ce gestionnaire d'erreur est exécuté lorsqu'une erreur est levée entre le début et la fin de -l'exécution de la fonction. - -

Si une erreur survient pendant l'exécution du gestionnaire d'erreur, elle est propagée normalement. - -

Sub ProcessFile(FileName As String)
-  ...
-  Open FileName For Read As #hFile
-  ...
-  Close #hFile
-  
-Catch ' Exécuté seulement si il y'a eu une erreur
-
-  Print "Impossible de traiter le fichier "; FileName
-
-End
- - -[FINALLY] - -

Gestion des erreurs (3)

- -

La gestion des erreurs en Gambas s'effectue à l'aide des instructions suivantes : -Try, Error, Catch, et Finally. - -

Finally introduit une partie de code exécutée à la fin de la fonction dans tous les cas, -même si une erreur a été levée pendant l'exécution de la fonciton. - -

L'utilisation de Finally est facultative. Mais si l'instruction Catch est utilisée, -alors Finally doit obligatoirement la précéder. - -

Si une erreur survient pendant l'exécution du code introduit par Finally, elle est propagée -normalement. - -

Sub ProcessFile(FileName As String)
-  ...
-  Open FileName For Read As #hFile
-  ...
-Finally ' Toujours exécuté, même s'il y a eu une erreur
-
-  Close #hFile
-  
-Catch ' Exécuté seulement en cas d'erreur
-  
-  Print "Cannot print file "; FileName
-  
-End
- - -[OPTIONAL] - -

Optional

- -

Les fonctions ou procédures de Gambas peuvent avoir des arguments optionels. - -

Les arguments sont rendus optionnels en les prefixant simplement avec le mot-clef -Optional. - -

Les arguments optionnels peuvent aussi avoir une valeur par défaut explicite. - -

Private Sub MyFunction(Param AS String, Optional Optim AS String = "Default")
-  ...
-  Print "Obligatoire: "; param; ", Optionnel: "; optim
-  ...
-End
- - -[ARRAY] - -

For Each

- -

En Gambas vous pouvez facilement enumérer le contenu d'un tableau, d'une -collection, ou de toute autre classe enumérable, avec l'instruction For Each. - -

Par exemple : - -

Dim Xml As New XmlDocument
-Dim Node As XmlNode
-Dim I As Integer
-
-' Ouverture du fichier XML
-Xml.Open("pokus.xml")
-' Les noeuds enfants sont indexés avec [I], car il s'agit
-' d'un tableau
-For I = 0 To Xml.Root.Children.Count - 1
-  ' Les attributs sont énumérés avec For Each, car il s'agit
-  ' d'une collection
-  For Each Node In Xml.Root.Children[i].Attributes
-    Print Node.Name;; Node.Value
-  Next
-Next
- - -[ICON] - -

Icônes prédéfinies

- -

Vous pouvez utiliser les icônes prédéfinies pour améliorer l'apparence de vos interfaces. -Ces icônes sont disponibles en tailles prédéfinies ("small", "medium", "large",...) -ou bien en tailles absolues (de 16x16 à 256x256). - -

Par exemple : - -

Image1.Picture = Picture["icon:/32/warning"]
-Image2.Picture = Picture["icon:/small/error"]
-
- -

Attention : le composant gb.form est requis. - - -[SETTINGS] - -

Settings

- -

Si vous avez besoin de mémoriser la configuration de votre programme (comme la géométrie de vos formulaires) -alors vous être chanceux. C'est très simple et très élégant à faire en Gambas. :-) - -

Pour enregistrer la position d'un formulaire : -

Settings.Write(TheForm)
- -

Pour la rappeler : -

Settings.Read(TheForm)
- -

Pour enregistrer un élément de configuration : -

Settings["Slot/Key"] = Value
- -

Et pour le rappeler : -

Value = Settings["Slot/Key", DefaultValue]
- -La configuration est enregistrée dans le fichier ~/.config/gambas3/<MonApplication>.conf, -où <MonApplication> est le nom de votre projet. - -

Attention : Le composant gb.settings est requis. - - -[EDITOR] - -

Voici quelques astuces de l'éditeur... - -

Deux types de commentaires

- -
' Commentaire normal
-
'' Commentaire en gras
- -

Les commentaires en gras sont utilisés pour documenter votre code. - -

Comment utiliser les fragments de code

- -

Saisissez main puis appuyez sur la touche TAB. Une fonction de démarrage -publique et statique Main est automatiquement insérée dans votre code. - -

Saisissez ds puis appuyez sur la touche TAB. Une déclaration de variable -locale de type String est insérée automatiquement, et vous pouvez saisir le nom -de la variable immédiatement. - -

Les fragments code sont intégralement configurables depuis la boîte de dialogue des -options globales de l'environnement de développement. - - -[END] - -

C'est terminé !

- -

Vous avez lu toutes les astuces du jour. J'espère que vous êtes -devenu un expert Gambas maintenant ! :-)

- -

Si vous désirez ajouter de nouvelles astuces de votre cru, -n'hésitez-pas à les envoyer à l'adresse suivante :

- -

g4mba5@gmail.com

- -

Merci d'avance !

diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.fr.txt gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.fr.txt --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.fr.txt 1970-01-01 00:00:00.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.fr.txt 2021-09-14 19:01:29.000000000 +0000 @@ -0,0 +1,604 @@ +[WELCOME] + +

Bienvenue dans Gambas !

+ +

Gambas est un environnement graphique de développement +basé sur un interpréteur Basic avancé.

+ +

Le but de Gambas est de vous permettre de concevoir de +puissants programmes, et ce facilement et rapidement. Mais la propreté de ces +programmes reste sous votre entière responsabilité...

+ +

En espérant que vous l'apprécierez !

+ +

Benoît Minisini
+g4mba5@gmail.com

+ + +[STARTUP] + +

Classe de démarrage

+ +

Tout projet doit avoir une classe de démarrage. Cette classe +de démarrage doit posséder une méthode publique statique appelée +Main ne possédant aucun paramètre. Celle-ci agira alors comme +méthode de démarrage de votre programme.

+ +

Pour définir la classe de démarrage, cliquez dessus avec le bouton +droit dans l'arbre du projet, et cochez l'entrée Classe de +démarrage dans le menu contextuel.

+ +

Il n'est pas nécessaire de définir la méthode Main dans un +formulaire de démarrage, car celui-ci en possède une par défaut.

+ +

Cette méthode de démarrage par défaut se charge d'instancier puis +d'afficher le formulaire, à la manière de Visual Basic™. +

+ + +[EXEC] + +

Exécutable

+ +Vous pouvez créer un fichier exécutable à partir de votre projet. +Pour cela, sélectionnez Générer l'exécutable... dans le menu +Projet. +

+L'exécutable est placé par défaut dans le répertoire du projet. +Il porte le même nom que le projet. + + +[OPEN] + +

Open

+ +L'instruction Open de Gambas ne fonctionne +pas comme celle de Visual Basic™. Elle ne retourne +pas le fichier ouvert sous forme d'un entier, mais d'un objet de +la classe File. +

+Ainsi, au lieu de taper : +

Dim Handle As Integer
+...
+Open "mon-fichier.txt" For Read As #Handle
+

+Vous devez taper : +

Dim Handle As File
+...
+Handle = Open "mon-fichier.txt" For Read
+ + +[CATDIR] + +

Concaténation de chemins

+ +Savez-vous que vous pouvez concaténer des noms de répertoires et +de fichiers avec l'opérateur &/ ? +

+Cet opérateur s'occupe d'ajouter le caractère de délimitation +de répertoire '/' lorsque c'est nécessaire. +

+Par exemple : +

Print "/home/gambas" &/ ".bashrc"
+→ /home/gambas/.bashrc
+
+Print "/home/gambas/" &/ "/tmp" &/ "foo.bar"
+→ /home/gambas/tmp/foo.bar
+
+

N'est-ce pas merveilleux ? :-) + + +[PATH] + +

Chemins relatifs

+ +Les chemins relatifs ont une signification particulière dans Gambas. +Ils font référence aux fichiers situés à l'intérieur de votre projet. +

+Il n'y a pas de concept de répertoire courant, et aucune instruction +telle que CHDIR qui serait susceptible de le modifier. +

+Attention : vous devez toujours utiliser des chemins relatifs pour +accéder aux fichiers de votre projet, car les chemins absolus vers ces +fichiers n'ont plus de signification lorsque le projet est transformé +en exécutable. + + +[GLOBAL] + +

Variables globales

+ +Il n'y a pas de variables globales en Gambas ! +

+Par contre, vous pouvez placer les variables auxquelles vous désirez accéder depuis +n'importe quelle partie de votre projet à l'intérieur de votre module principal en les déclarant Public. +

+Si vous n'avez pas de module principal, mais un formulaire principal, +déclarez-les comme Static Public. +

+Pour accéder à ces variables, vous devez utiliser le nom du module ou du +formulaire principal ainsi : + +

MonModulePrincipal.MaVariableGlobale +

ou bien +

MonFormulairePrincipal.MaVariableGlobale + + +[EMPTY] + +

Chaînes vides

+ +Pour savoir si une chaîne est vide, il n'est pas nécessaire d'effectuer +une comparaison avec "" ou bien d'utiliser la fonction +Len(). Il est possible de la tester directement, car une +chaîne vide est équivalente à False et une chaîne non-vide +est équivalente à True. +

+Par exemple, plutôt que de faire : +

If Len(MaChaine) > 0 Then ...
+If Len(MaChaine) = 0 Then ...
+

+Vous devriez plutôt faire : +

If MaChaine Then ...
+If Not MaChaine Then ...
+ + +[TRANSLATE] + +

Traduction

+ +

Un programme écrit en Gambas est traduisible dans n'importe quel langue, +à condition que vous indiquiez parmi les chaînes de caractères du programme +lesquelles doivent être traduites, et lesquelles ne le doivent pas.

+ +

Pour indiquer quelles chaînes doivent être traduites, il suffit de les +écrire entre parenthèses:

+ +
Print ("Traduisez-moi")
+Print "Mais ne me traduisez pas!"
+ + +[SUBST] + +

Subst$

+ +

La fonction Subst$() est très utile pour internationaliser votre application. + +

Elle prend au moins deux arguments. Le premier est le masque de texte à l'intérieur duquel les +substitutions vont s'appliquer. Les autres sont les substitutions, numérotées en commençant par un. + +

Chaque occurence &X de la chaîne de substitution sera remplacée par le Xème +argument à substituer. Par exemple : + +

Print Subst(("Substitution de &1, &2 et &3"),
+  "premier", "deuxième", "troisième")
+
+→ Substitution de premier, deuxième et troisième
+ + +[EVENT] + +

Gestionnaires d'évènements

+ +Chaque contrôle, et chaque objet pouvant générer des évènements, possède +un observateur d'évènement et un nom de groupe d'évènement. +

+L'observateur d'évènement reçoit chaque évènement généré par un objet, et +le nom de groupe d'évènenement est le préfixe de la fonction qui sera +appelée pour gérer l'évènement. Cette fonction est appelée gestionnaire +d'évènements. +

+Par défaut, l'observateur d'évènement est l'objet à l'intérieur duquel +vous avez créé le contrôle, et le nom de groupe est le nom du contrôle. +

+De cette manière, un formulaire recevra tous les évènements des contrôles +lui appartenant. +

+

' Gambas form
+Dim hButton As Button
+
+Public Sub _new()
+  hButton = New Button(Me) As "MonBouton"
+End
+
+Public Sub MonButton_Click()
+  Print "Vous avez cliqué sur MonBouton !"
+End
+
+ + +[FORM] + +

Formulaires

+ +En Gambas, un formulaire est son propre observateur d'évènements, afin +que vous puissez directement gérer ses évènements (comme Resize, +Activate, ...) dans le code même de la classe associée. +

+De cette manière, les débutants venant de Visual Basic™ ne sont +pas désorientés :-). + + +[EMBED] + +

Formulaires imbriqués

+ +

Vous pouvez imbriquer un formulaire à l'intérieur d'un autre en +Gambas ! Pour cela, instanciez simplement votre formulaire en lui passant +un conteneur parent en argument supplémentaire.

+ +

Par exemple :

+

Dim hForm As MyDialog
+Dim hSuperControl As MyForm
+
+' Création d'une boîte dialogue
+hForm = New MyDialog
+' Insertion d'un formulaire dans le dialogue
+' Notez que le constructeur du formulaire prend deux arguments avant 
+' le conteneur
+hSuperControl = New MyForm(Param1, Param2, MyDialog)
+' Déplacement et redimensionnement du formulaire
+hSuperControl.Move(8, 8, 128, 64)
+
+ +

Attention : un formulaire imbriqué reste un formulaire, et par conséquent +est son propre observateur d'évènements.

+ + +[GROUP] + +

Groupes de contrôles

+ +

Chaque contrôle possède une propriété (Group). Lorsque cette propriété est +définie, le préfixe de chaque gestionnaire d'évènement devient le nom de ce groupe +et non plus le nom du contrôle.

+ +

Supposons qu'on ait un Button appelé btnAction avec le gestionnaire +d'évènement Click suivant :

+ +
Public Sub btnAction_Click()
+ +

Si vous définissez la propriété (Group) de btnAction à "MyGroup", +alors le gestionnaire d'évènement sera le suivant :

+ +
Public Sub MyGroup_Click()
+ +

Cette propriété vous permet de gérer les évènements de différents contrôles au sein +d'une seule fonction. Et les contrôles d'un même groupe peuvent être de types différents !

+ +

Remarque : le bon vieux vétéran du Visual Basic reconnaîtra éventuellement +le concept de tableau de contrôle, mais dans une implémentation bien plus puissante. :-)

+ +[TAG] + +

La propriété Tag

+ +

Chaque contrôle possède une propriété Tag. Cette propriété est +destinée au programmeur, et peut contenir n'importe quel donnée de type Variant +que vous trouverez adéquate.

+ +

Ceci est très utile si, par exemple, vous voulez distinguer les contrôles d'un +même groupe au sein de leur gestionnaire d'évènement commun.

+ + +[LAST] + +

Last

+ +

Le mot-clef Last retourne le dernier contrôle ayant reçu +un évènement. Ceci est très utile si vous voulez écrire un gestionnaire +d'évènement indépendant d'un nom de contrôle.

+ +

Par exemple, supposons que vous voulez programmez une calculatrice. +Vous avez défini dix boutons, un pour chaque chiffre, tous dans le même +groupe "Digit". La propriété Tag de chaque bouton +contient le chiffre dessiné sur le bouton.

+ +

Votre gestionnaire d'évènement ressemblera à ceci :

+ +
Public Sub Digit_Click()
+
+  Display = Display & Last.Tag
+  RefreshDisplay
+
+End
+ + +[LEFT] + +

Left$ / Mid$ / Right$

+ +

Les fonctions BASIC bien connues que sont Left$, Right$ +et Mid$ possèdent des syntaxes spécifiques bien utiles en Gambas. + +

Le deuxième argument de Left$ et de Right$ est optionnel, +et vaut un par défaut.

+ +

Left$("Gambas") retourne "G".
+Right$("Gambas") retourne "s".

+ +

Ce second argument peut être négatif. Il donne alors le nombre de +caractères à ne pas extraire.

+ +

Left$("Gambas", -2) retourne "Gamb".
+Right$("Gambas", -2) retourne "mbas".

+ +

De même, le troisième argument de Mid$ peut être négatif. Il +donne alors le nombre de caractères depuis la fin de la chaîne à ne pas extraire.

+ +

Mid$("Gambas", 2, -2) retourne "amb".

+ + +[OBSERVER] + +

Observer

+ +

La classe Observer vous permet d'intercepter n'importe quel évènement +de n'importe quel objet avant même qu'il ait été effectivement émis.

+ +
MyTextBox = New TextBox(Me) As "MyTextBox"
+MyObserver = New Observer(MyTextBox) As "MyObserver"
+...
+Public Sub MyObserver_KeyPress()
+  Debug "Reçu en premier"
+End
+
+Public Sub MyTextBox_KeyPress()
+  Debug "Reçu en dernier"
+End
+ +L'observateur peut annuler l'évènement avec Stop Event pour +empêcher son émission. + + +[STRING] + +

Chaînes UTF-8

+ +

Gambas utilise le jeu de caractères UTF-8 pour représenter +les chaînes de caractères en mémoire. + +

Mais les fonctions de traitement de chaînes de caractères standardes ne +fonctionnent qu'avec de l'ASCII : +Left, Mid, Right, UCase... + +

Si vous voulez manipuler des chaînes de caractères UTF-8, vous devez utiliser +les méthodes de la classe statique String, qui possèdent les mêmes noms +que leur équivalent standardes. + +

Print Len("bébé");; Left$("bébé", 3)
+→ 6 bé
+
+Print String.Len("bébé");; String.Left("bébé", 3)
+→ 4 béb
+ + +[ASSIGNMENT] + +

Assignations

+ +

Gambas implémente les raccourcis d'assignation auxquels les programmeurs C/C++ sont habitués. + +

MyVariable += 2
+MyVariable *= 4
+MyVariable &= "Great"
+équivaut à +
MyVariable = MyVariable + 2
+MyVariable = MyVariable * 4
+MyVariable = MyVariable & "Great"
+ +

Et ainsi de suite... + + +[DEBUG] + +

Debug

+ +

Vous pouvez utiliser l'instruction Debug pour imprimer des messages de débogage +sur la console (c'est-à-dire la sortie erreur standard). Elle se comporte exactement comme +l'instruction Print. + +

Ces messages sont prefixés avec le nom de la classe, le nom de la méthode et le numéro de ligne +de l'instruction Debug. Si vous ne voulez pas de ce préfixe, vous pouvez utiliser +l'instruction Error à la place de Debug. + +

Les messages de débogages sont automatiquement ignorés lorsque vous créez un exécutable +privé des informations de débogage. + + +[TRY] + +

Gestion des erreurs (1)

+ +

La gestion des erreurs en Gambas s'effectue à l'aide des instructions suivantes : +Try, Error, Catch, et Finally. + +

Try essaie d'exécuter une instruction sans déclencher d'erreur. Le mot-clef Error +est utilisé juste après pour savoir si l'instruction s'est exécutée correctement. + +

Try MyFile = Open "/etc/password" For Write
+If Error Then Print "Je ne peux pas faire tout ce que je veux !"
+ + +[CATCH] + +

Gestion des erreurs (2)

+ +

La gestion des erreurs en Gambas s'effectue à l'aide des instructions suivantes : +Try, Error, Catch, et Finally. + +

Catch marque le début du gestionnaire d'erreurs d'une fonction ou d'une procédure. +Il doit être placé à la fin du code de la fonction. + +

Ce gestionnaire d'erreur est exécuté lorsqu'une erreur est levée entre le début et la fin de +l'exécution de la fonction. + +

Si une erreur survient pendant l'exécution du gestionnaire d'erreur, elle est propagée normalement. + +

Sub ProcessFile(FileName As String)
+  ...
+  Open FileName For Read As #hFile
+  ...
+  Close #hFile
+  
+Catch ' Exécuté seulement si il y'a eu une erreur
+
+  Print "Impossible de traiter le fichier "; FileName
+
+End
+ + +[FINALLY] + +

Gestion des erreurs (3)

+ +

La gestion des erreurs en Gambas s'effectue à l'aide des instructions suivantes : +Try, Error, Catch, et Finally. + +

Finally introduit une partie de code exécutée à la fin de la fonction dans tous les cas, +même si une erreur a été levée pendant l'exécution de la fonciton. + +

L'utilisation de Finally est facultative. Mais si l'instruction Catch est utilisée, +alors Finally doit obligatoirement la précéder. + +

Si une erreur survient pendant l'exécution du code introduit par Finally, elle est propagée +normalement. + +

Sub ProcessFile(FileName As String)
+  ...
+  Open FileName For Read As #hFile
+  ...
+Finally ' Toujours exécuté, même s'il y a eu une erreur
+
+  Close #hFile
+  
+Catch ' Exécuté seulement en cas d'erreur
+  
+  Print "Cannot print file "; FileName
+  
+End
+ + +[OPTIONAL] + +

Optional

+ +

Les fonctions ou procédures de Gambas peuvent avoir des arguments optionels. + +

Les arguments sont rendus optionnels en les prefixant simplement avec le mot-clef +Optional. + +

Les arguments optionnels peuvent aussi avoir une valeur par défaut explicite. + +

Private Sub MyFunction(Param AS String, Optional Optim AS String = "Default")
+  ...
+  Print "Obligatoire: "; param; ", Optionnel: "; optim
+  ...
+End
+ + +[ARRAY] + +

For Each

+ +

En Gambas vous pouvez facilement enumérer le contenu d'un tableau, d'une +collection, ou de toute autre classe enumérable, avec l'instruction For Each. + +

Par exemple : + +

Dim Xml As New XmlDocument
+Dim Node As XmlNode
+Dim I As Integer
+
+' Ouverture du fichier XML
+Xml.Open("pokus.xml")
+' Les noeuds enfants sont indexés avec [I], car il s'agit
+' d'un tableau
+For I = 0 To Xml.Root.Children.Count - 1
+  ' Les attributs sont énumérés avec For Each, car il s'agit
+  ' d'une collection
+  For Each Node In Xml.Root.Children[i].Attributes
+    Print Node.Name;; Node.Value
+  Next
+Next
+ + +[ICON] + +

Icônes prédéfinies

+ +

Vous pouvez utiliser les icônes prédéfinies pour améliorer l'apparence de vos interfaces. +Ces icônes sont disponibles en tailles prédéfinies ("small", "medium", "large",...) +ou bien en tailles absolues (de 16x16 à 256x256). + +

Par exemple : + +

Image1.Picture = Picture["icon:/32/warning"]
+Image2.Picture = Picture["icon:/small/error"]
+
+ +

Attention : le composant gb.form est requis. + + +[SETTINGS] + +

Settings

+ +

Si vous avez besoin de mémoriser la configuration de votre programme (comme la géométrie de vos formulaires) +alors vous être chanceux. C'est très simple et très élégant à faire en Gambas. :-) + +

Pour enregistrer la position d'un formulaire : +

Settings.Write(TheForm)
+ +

Pour la rappeler : +

Settings.Read(TheForm)
+ +

Pour enregistrer un élément de configuration : +

Settings["Slot/Key"] = Value
+ +

Et pour le rappeler : +

Value = Settings["Slot/Key", DefaultValue]
+ +La configuration est enregistrée dans le fichier ~/.config/gambas3/<MonApplication>.conf, +où <MonApplication> est le nom de votre projet. + +

Attention : Le composant gb.settings est requis. + + +[EDITOR] + +

Voici quelques astuces de l'éditeur... + +

Deux types de commentaires

+ +' Commentaire normal
+'' Commentaire en gras + +

Les commentaires en gras sont utilisés pour documenter votre code. + +

Comment utiliser les fragments de code

+ +

Saisissez main puis appuyez sur la touche TAB. Une fonction de démarrage +publique et statique Main est automatiquement insérée dans votre code. + +

Saisissez ds puis appuyez sur la touche TAB. Une déclaration de variable +locale de type String est insérée automatiquement, et vous pouvez saisir le nom +de la variable immédiatement. + +

Les fragments code sont intégralement configurables depuis la boîte de dialogue des +options globales de l'environnement de développement.

+ + +[END] + +

C'est terminé !

+ +

Vous avez lu toutes les astuces du jour. J'espère que vous êtes +devenu un expert Gambas maintenant ! :-)

+ +

Si vous désirez ajouter de nouvelles astuces de votre cru, +n'hésitez-pas à les envoyer à l'adresse suivante :

+ +

g4mba5@gmail.com

+ +

Merci d'avance !

diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.it gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.it --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.it 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.it 1970-01-01 00:00:00.000000000 +0000 @@ -1,527 +0,0 @@ -[WELCOME] - -

Benvenuto in Gambas !

- -

Gambas è un ambiente grafico di sviluppo basato su un interprete avanzato -Basic.

- -

L'obiettivo di Gambas è quello di permettere di creare programmi potenti -in maniera facile e veloce. Ma la responsabilità di creare programmi puliti è tutta vostra...

- -

Spero vi piaccia!

- -

Benoît Minisini
-g4mba5@gmail.com




- - -[STARTUP] - -

Ogni progetto deve avere una classe di inizio. - Questa classe di inizio deve definire un metodo pubblico (public) e statico (static) - denominato Main senza argomenti, che si comporterà come il metodo di inizio del tuo programma

- -

Puoi definire la classe di inizio cliccando su di essa con il tasto destro del mouse e selezionando Classe di avvio -nel menù a cascata

- -

Non è necessario definire un metodo Main in un Form di avvio perché ne esiste già uno predefinito.

- -

Questo metodo predefinito inizializza il form e lo mostra, come in Visual Basic™.

- - -[OPEN] - -

L'Istruzione OPEN di Gambas non si comporta nella stessa maniera - che in Visual Basic. - Non ritorna il file come un Integer, ma come un ogetto File.

- -

In pratica, invece di digitare:

- -
DIM handle AS Integer
-...
-OPEN "ilmiofile" FOR READ AS #handle
- -

Devi digitare :

- -
DIM handle AS File
-...
-handle = OPEN "ilmiofile" FOR READ
- - -[CATDIR] - -

Lo sapevi che puoi concatenare nomi di directory e nomi di file -con l'operatore &/? -Questo operatore aggiunge se necessario la slash ("/") in maniera tale che -l'indirizzo risultante sia perfetto.

- -

Per esempio :

- -
PRINT "/home/gambas" &/ ".bashrc"
-/home/gambas/.bashrc
-
-PRINT "/home/gambas/" &/ "/tmp" &/ "foo.bar"
-/home/gambas/tmp/foo.bar
-
- -

Non è stupendo ?

- -[EXEC] - -

Puoi realizzare un file eseguibile di tutto il tuo progetto. - Seleziona Crea eseguibile nel menu Progetto.

- -

Quando Gambas crea un file eseguibile, colloca il risultato direttamente -nella directory del tuo progetto e il nome del file eseguibile sarà quello del -tuo progetto

- - -[PATH] -

-I percorsi relativi hanno un significato speciale in Gambas. -Sono sempre riferiti a file dentro il tuo progetto. -

-Non c'è il concetto di directory corrente, e nessuna parola chiave come -CHDIR per cambiarla. -

-Attenzione: devi usare i percorsi relativi solo per accedere ai file di -progetto, perché i percorsi assoluti non funzioneranno quando crei l'eseguibile. - - -[GLOBAL] - -Non ci sono variabili globali in Gambas! -

-Come sostituto, dichiarale nel modulo principale come PUBLIC. -

-Se non hai un modulo principale nel tuo progetto, ma un form principale, -allora dichiarale come STATIC PUBLIC. -

-Per accedere a queste variabili, devi usare il nome del modulo principale -o form: MyMainModule.MyGlobalVariable o -MyMainForm.MyGlobalVariable. - -[EMPTY] - -

Per sapere se una stringa è vuota non è necessario usare la funzione Len() . - Puoi direttamente testare la stringa, visto che una stringa vuota è FALSE e una non vuota è TRUE.

- -

Per esempio, invece di :

- -
IF Len(Lamiastringa) > 0 THEN ...
-IF Len(Lamiastringa) = 0 THEN ...
- -

Puoi fare :

- -
IF Lamiastringa THEN ...
-IF NOT Lamiastringa THEN ...
- - -[TRANSLATE] - -

Traduzione

- -

Le applicazioni Gambas sono completamente traducibili, a condizione -che tu dica quali stringhe devono essere tradotte e quali no.

-

Per contrassegnare le stringhe come traducibili, racchiudile tra parentesi tonde:

- -

Print ("Traducimi")
-Print "Non tradurmi!"
- - -[SUBST] - -

Subst$

- -

La funzione Subst$() è molto utile per internazionalizzare la tua applicazione.

- -

Ci vogliono almeno due argomenti. Il primo è la maschera di testo su cui si applica la sostituzione. -Gli altri sono gli argomenti di sostituzione, numerati a partire da uno.

- -

Ogni modello &X nella stringa di sostituzione verrà sostituito dall'argomento di sostituzione X. -Per esempio:

- -
Print Subst(("Sostituzione di &1, &2 e &3"),
-  "primo", "secondo", "terzo")
-
-→ Sostituzione di primo, secondo e terzo
- -[EVENT] - -

Tutti i controlli e tutti gli oggetti che possono avere eventi, - hanno un Osservatore di eventi e un nome di gruppo del evento.

- -

L'osservatore di eventi coglie tutti gli eventi prodotti dall'oggetto, - e il nome del gruppo del evento è il prefisso del procedimento incaricato di gestire l'evento.

- -

Di default, questo osservatore di eventi è l'oggetto dove si è creato il controllo, - e il nome di gruppo è il nome del controllo.

- -

In questo modo, un form riceve tutti gli eventi prodotti dai controlli che tu ci hai creato dentro.

- -
' Gambas form
-
-DIM hButton AS Button
-
-PUBLIC SUB _new()
-  ...
-  hButton = NEW Button(ME) AS "Ilmiopulsante"
-  ...
-END
-
-PUBLIC SUB Ilmiopulsante_Click()
-  ...
-END
-
- - -[GROUP] - -

Tutti i controlli hanno una proprietà (Group). - Quando questa proprietà è utilizzata, il prefisso del gestore di eventi è il nome del - gruppo e non il nome del controllo.

-

Supponiamo di avere un Button chiamato btnAzione con il gestore di eventi Click -seguente :

- -
PUBLIC SUB btnAzione_Click()
- -

Se definisci la proprietà (Group) di btnAzione come IlMioGruppo, - Allora il gestore di eventi che riceverà gli eventi del pulsante sarà il seguente:

- -
PUBLIC SUB IlMioGruppo_Click()
- -

Questa proprietà permette di gestire vari eventi con una semplice funzione. - E i controlli dello stesso gruppo non devono per forza essere dello stesso tipo !!!

- -

Nota : I veterani del vecchio Visual Basic riconosceranno il concetto di control array, - soltanto che qui viene implementato in un modo più potente. :-)

- - -[FORM] - -

Un form è l'osservatore di eventi di se stesso, in questo modo puoi gestire direttamente i suoi eventi (Resize, Activate, ...) -dentro il codice della sua stessa classe.

- -

In questo modo, i nuovi arrivati da Visual Basic non si sentiranno persi :-).

- - -[EMBED] - -

Con Gambas puoi fare in modo che qualsiasi form venga -racchiuso in un altro form!

- -

Per fare una cosa così utile devi soltanto inizializzare il form passando -un contenitore padre come ultimo argomento nel costruttore.

- -

Per esempio :

-

DIM hForm AS MyDialog
-DIM hSuperControl AS MyForm

-' Crea un dialogo
-hForm = NEW MyDialog
-' Inserisce un form in questo dialogo
-' Nota che questo form riceve due parametri prima del contenitore
-hSuperControl = NEW MyForm(Param1, Param2, MyDialog)
-' Muove e ridimensiona il form
-hSuperControl.Move(8, 8, 128, 64)

- -

Ricorda che: un form racchiuso in un altro continua ad essere un form - e quindi osservatore di eventi di se stesso.

- - -[TAG] - -

Tutti i controlli hanno una proprietà chiamata Tag - Questa proprietà è pensata per essere usata dai programmatori e può contenere qualsiasi dato -VARIANT che credi utile.

- -

Questo è molto utile quando vuoi differenziare controlli dello stesso gruppo nello stesso gestore di eventi.

- - -[LAST] - -

La parola chiave LAST ritorna l'ultimo controllo che ha ricevuto un evento. - E' molto utile quando vuoi scrivere un gestore di eventi -che sia indipendente dal nome del controllo.

- -

Supponiamo di voler scrivere un programma calcolatrice. - Hai definito dieci pulsanti, uno per ogni numero e tutti con lo stesso group "Digit". - Il valore del Tag di ogni controllo sarà il numero visualizzato da ogni pulsante. - Il tuo gestore di eventi sarà più o meno così :

- -

PUBLIC SUB Digit_Click()

-  Display = Display & LAST.Tag
-  RefreshDisplay

-END

- - -[LEFT] - -

Le famose routine Left$, Right$, Mid$ di BASIC - hanno un comportamento molto utile in Gambas.

- -

Il secondo parametro di Left$ e Right$ è facoltativo, e per default è pari a uno.

- -

Left$("Gambas") ritorna "G"
-Right$("Gambas") ritorna "s"

- -

Il secondo parametro può essere negativo e in questo caso rappresenta il numero di caratteri da non ritornare.

- -

Left$("Gambas", -2) ritorna "Gamb"
-Right$("Gambas", -2) ritorna "mbas"

- -

Allo stesso modo, il terzo parametro di Mid$ può essere negativo, - e quindi rappresentare il numero di caratteri dalla fine della stringa da non ritornare.

- -

Mid$("Gambas", 2, -2) ritorna "amb" - - -[OBSERVER] - -

Observer

- -

La classe Observer ti consente di intercettare tutti gli eventi generati da un -oggetto prima che vengano effettivamente inviati.

- -
MyTextBox = New TextBox(Me) As "MyTextBox"
-MyObserver = New Observer(MyTextBox) As "MyObserver"
-...
-Public Sub MyObserver_KeyPress()
-  Debug "Got it first"
-End
-
-Public Sub MyTextBox_KeyPress()
-  Debug "Got it next"
-End
- -L'osservatore può annullare l'evento con Stop Event per prevenire l'oggetto dal -sollevarlo effettivamente. - - -[STRING] - -

UTF-8 Strings

- -

Gambas utilizza il set di caratteri UTF-8 per rappresentare le stringhe in memoria. - -

Ma tutte le funzioni di stringa standard riguardano solo ASCII: -Left, Mid, Right, UCase... - -

Se si desidera gestire le stringhe UTF-8, è necessario utilizzare i metodi della classe statica -String, che hanno lo stesso nome delle loro controparti standard. - -

Print Len("bébé");; Left$("bébé", 3)
-→ 6 bé
-
-Print String.Len("bébé");; String.Left("bébé", 3)
-→ 4 béb
- - -[ASSIGNMENT] - -

Assegnazioni

- -

Gambas implementa le scorciatoie di assegnazione a cui i programmatori C / C ++ sono abituati. - -

MyVariable += 2
-MyVariable *= 4
-MyVariable &= "Great"
-è un equivalente di -
MyVariable = MyVariable + 2
-MyVariable = MyVariable * 4
-MyVariable = MyVariable & "Great"
- -

E così via... - - -[DEBUG] - -

Debug

- -

È possibile utilizzare l'istruzione Debug per stampare messaggi di debug sulla -console (ovvero l'output di errore standard). Si comporta esattamente come l'istruzione Print. - -

Questi messaggi hanno come prefisso il nome della classe, il nome del metodo e il numero di -riga dell'istruzione Debug. Se non si desidera il prefisso, è possibile utilizzare -l'istruzione Error anziché Debug. - -

I messaggi di debug vengono automaticamente rimossi durante la creazione di -un eseguibile senza eseguire il debug delle informazioni. - - -[TRY] - -

Gestione degli errori (1)

- -

La gestione degli errori in Gambas viene eseguita con le seguenti istruzioni: -Try, Error, Catch, and Finally. - -

Try prova a eseguire una dichiarazione senza generare un errore. La parola chiave -Error viene utilizzata subito dopo per sapere se l'istruzione è stata eseguita correttamente. - -

Try MyFile = Open "/etc/password" For Write
-If Error Then Print "Non posso fare quello che voglio!"
- - -[CATCH] - -

Gestione degli errori (2)

- -

La gestione degli errori in Gambas viene eseguita con le seguenti istruzioni: -Try, Error, Catch, and Finally. - -

Catch indica l'inizio della parte di gestione degli errori di una funzione o procedura. -È messo alla fine del codice della funzione. - -

La parte catch viene eseguita quando viene generato un errore tra l'inizio dell'esecuzione della funzione e la sua fine. - -

Se viene sollevato un errore durante l'esecuzione della parte catch, l'errore viene propagato normalmente. - -

Sub ProcessFile(FileName As String)
-  ...
-  Open FileName For Read As #hFile
-  ...
-  Close #hFile
-  
-Catch ' Eseguito solo se c'è un errore
-
-  Print "Impossibile elaborare il file "; FileName
-
-End
- - -[FINALLY] - -

Gestione degli errori (3)

- -

La gestione degli errori in Gambas viene eseguita con le seguenti istruzioni: -Try, Error, Catch, and Finally. - -

Finally introduce il codice eseguito alla fine della funzione, anche se viene sollevato un errore durante l'esecuzione. - -

La parte finally non è obbligatoria. Se c'è una parte catch nella funzione, la parte finally deve precederla. - -

Se viene generato un errore durante l'esecuzione della parte finally, l'errore viene propagato normalmente. - -

Sub ProcessFile(FileName As String)
-  ...
-  Open FileName For Read As #hFile
-  ...
-Finally ' Viene sempre eseguito, anche se viene sollevato un errore
-
-  Close #hFile
-  
-Catch ' Eseguito solo se c'è un errore
-  
-  Print "Impossibile stampare il file "; FileName
-  
-End
- - -[OPTIONAL] - -

Optional

- -

Le funzioni e le procedure in Gambas possono avere argomenti opzionali.

- -

Gli argomenti opzionali vengono semplicemente fatti mettendo la parola chiave Optional subito prima del nome dell'argomento.

- -

Gli argomenti opzionali possono avere anche un valore predefinito esplicito.

- -
Private Sub MyFunction(Param AS String, Optional Optim AS String = "Default")
-  ...
-  Print "Necessario: "; param; ", Opzionale: "; optim
-  ...
-End
- - -[ARRAY] - -

For Each

- -

In Gambas puoi facilmente scorrere un array, una raccolta o molte altre classi enumerabili con l'istruzione For Each.

- -

Per esempio:

- -
Dim Xml As New XmlDocument
-Dim Node As XmlNode
-Dim I As Integer
-
-' Apre un file XML
-Xml.Open("pokus.xml")
-' I children sono indicizzati tramite [i], poiché si tratta di un array
-For I = 0 To Xml.Root.Children.Count - 1
-  ' Gli attributi vengono ciclati tramite For Each, poiché si tratta di una collection
-  For Each Node In Xml.Root.Children[i].Attributes
-    Print Node.Name;; Node.Value
-  Next
-Next
- - -[ICON] - -

Icone di default

- -

Puoi utilizzare le icone incorporate per una migliore GUI della tua applicazione, le icone sono disponibili in diverse dimensioni predefinite -("small", "medium", "large",...) o in dimensioni assolute (da 16x16 a 256x256).

- -

Per esempio: - -

Image1.Picture = Picture["icon:/32/warning"]
-Image2.Picture = Picture["icon:/small/error"]
-
- -

Attenzione: è richiesto il componente gb.form. - - -[SETTINGS] - -

Settings

- -

Se hai bisogno di memorizzare la configurazione del tuo programma (come la geometria dei tuoi form), allora sei un ragazzo fortunato. In Gambas è molto semplice ed elegante. :-) - -

Per salvare la posizione di un form: -

Settings.Write(TheForm)
- -

Per richiamarlo: -

Settings.Read(TheForm)
- -Per salvare qualsiasi impostazione: -
Settings["Slot/Key"] = Value
- -E per rileggerne le impostazioni: -
Value = Settings["Slot/Key", DefaultValue]
- -Queste impostazioni sono memorizzate nel file ~/.config/gambas3/<MyApplication>.conf, -dove <MyApplication> è il nome del tuo progetto. - -

Attenzione: è richiesto il componente gb.settings. - - -[EDITOR] - -

Ecco alcuni suggerimenti per l'editor...

- -

Due tipi di commenti

- -
' Commento normale
-
'' Commento in grassetto
- -

I commenti in grassetto sono usati per documentare il tuo codice.

- -

Come utilizzare i frammenti di codice

- -

Digita main quindi il tasto TAB. Una funzione statica e pubblica di avvio Main viene automaticamente inserita nel codice. - -

Digita ds quindi il tasto TAB. Una dichiarazione locale di variabile stringa viene inserita automaticamente ed è possibile digitare immediatamente il nome della variabile. - -

I frammenti di codice sono completamente configurabili dalla finestra di dialogo Preferenze del menu Strumenti dell'IDE. - - -[END] - -

Hai letto tutti i suggerimenti del giorno. Spero che ora tu sia un esperto di Gambas ! :-)

- -

Se vuoi contribuire, invia i nuovi consigli al seguente indirizzo :

-

user@lists.gambas-basic.org

- -

Grazie in anticipo !

- diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.it.txt gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.it.txt --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.it.txt 1970-01-01 00:00:00.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.it.txt 2021-09-14 19:01:29.000000000 +0000 @@ -0,0 +1,527 @@ +[WELCOME] + +

Benvenuto in Gambas !

+ +

Gambas è un ambiente grafico di sviluppo basato su un interprete avanzato +Basic.

+ +

L'obiettivo di Gambas è quello di permettere di creare programmi potenti +in maniera facile e veloce. Ma la responsabilità di creare programmi puliti è tutta vostra...

+ +

Spero vi piaccia!

+ +

Benoît Minisini
+g4mba5@gmail.com




+ + +[STARTUP] + +

Ogni progetto deve avere una classe di inizio. + Questa classe di inizio deve definire un metodo pubblico (public) e statico (static) + denominato Main senza argomenti, che si comporterà come il metodo di inizio del tuo programma

+ +

Puoi definire la classe di inizio cliccando su di essa con il tasto destro del mouse e selezionando Classe di avvio +nel menù a cascata

+ +

Non è necessario definire un metodo Main in un Form di avvio perché ne esiste già uno predefinito.

+ +

Questo metodo predefinito inizializza il form e lo mostra, come in Visual Basic™.

+ + +[OPEN] + +

L'Istruzione OPEN di Gambas non si comporta nella stessa maniera + che in Visual Basic. + Non ritorna il file come un Integer, ma come un ogetto File.

+ +

In pratica, invece di digitare:

+ +
DIM handle AS Integer
+...
+OPEN "ilmiofile" FOR READ AS #handle
+ +

Devi digitare :

+ +
DIM handle AS File
+...
+handle = OPEN "ilmiofile" FOR READ
+ + +[CATDIR] + +

Lo sapevi che puoi concatenare nomi di directory e nomi di file +con l'operatore &/? +Questo operatore aggiunge se necessario la slash ("/") in maniera tale che +l'indirizzo risultante sia perfetto.

+ +

Per esempio :

+ +
PRINT "/home/gambas" &/ ".bashrc"
+/home/gambas/.bashrc
+
+PRINT "/home/gambas/" &/ "/tmp" &/ "foo.bar"
+/home/gambas/tmp/foo.bar
+
+ +

Non è stupendo ?

+ +[EXEC] + +

Puoi realizzare un file eseguibile di tutto il tuo progetto. + Seleziona Crea eseguibile nel menu Progetto.

+ +

Quando Gambas crea un file eseguibile, colloca il risultato direttamente +nella directory del tuo progetto e il nome del file eseguibile sarà quello del +tuo progetto

+ + +[PATH] +

+I percorsi relativi hanno un significato speciale in Gambas. +Sono sempre riferiti a file dentro il tuo progetto. +

+Non c'è il concetto di directory corrente, e nessuna parola chiave come +CHDIR per cambiarla. +

+Attenzione: devi usare i percorsi relativi solo per accedere ai file di +progetto, perché i percorsi assoluti non funzioneranno quando crei l'eseguibile. + + +[GLOBAL] + +Non ci sono variabili globali in Gambas! +

+Come sostituto, dichiarale nel modulo principale come PUBLIC. +

+Se non hai un modulo principale nel tuo progetto, ma un form principale, +allora dichiarale come STATIC PUBLIC. +

+Per accedere a queste variabili, devi usare il nome del modulo principale +o form: MyMainModule.MyGlobalVariable o +MyMainForm.MyGlobalVariable. + +[EMPTY] + +

Per sapere se una stringa è vuota non è necessario usare la funzione Len() . + Puoi direttamente testare la stringa, visto che una stringa vuota è FALSE e una non vuota è TRUE.

+ +

Per esempio, invece di :

+ +
IF Len(Lamiastringa) > 0 THEN ...
+IF Len(Lamiastringa) = 0 THEN ...
+ +

Puoi fare :

+ +
IF Lamiastringa THEN ...
+IF NOT Lamiastringa THEN ...
+ + +[TRANSLATE] + +

Traduzione

+ +

Le applicazioni Gambas sono completamente traducibili, a condizione +che tu dica quali stringhe devono essere tradotte e quali no.

+

Per contrassegnare le stringhe come traducibili, racchiudile tra parentesi tonde:

+ +

Print ("Traducimi")
+Print "Non tradurmi!"
+ + +[SUBST] + +

Subst$

+ +

La funzione Subst$() è molto utile per internazionalizzare la tua applicazione.

+ +

Ci vogliono almeno due argomenti. Il primo è la maschera di testo su cui si applica la sostituzione. +Gli altri sono gli argomenti di sostituzione, numerati a partire da uno.

+ +

Ogni modello &X nella stringa di sostituzione verrà sostituito dall'argomento di sostituzione X. +Per esempio:

+ +
Print Subst(("Sostituzione di &1, &2 e &3"),
+  "primo", "secondo", "terzo")
+
+→ Sostituzione di primo, secondo e terzo
+ +[EVENT] + +

Tutti i controlli e tutti gli oggetti che possono avere eventi, + hanno un Osservatore di eventi e un nome di gruppo del evento.

+ +

L'osservatore di eventi coglie tutti gli eventi prodotti dall'oggetto, + e il nome del gruppo del evento è il prefisso del procedimento incaricato di gestire l'evento.

+ +

Di default, questo osservatore di eventi è l'oggetto dove si è creato il controllo, + e il nome di gruppo è il nome del controllo.

+ +

In questo modo, un form riceve tutti gli eventi prodotti dai controlli che tu ci hai creato dentro.

+ +
' Gambas form
+
+DIM hButton AS Button
+
+PUBLIC SUB _new()
+  ...
+  hButton = NEW Button(ME) AS "Ilmiopulsante"
+  ...
+END
+
+PUBLIC SUB Ilmiopulsante_Click()
+  ...
+END
+
+ + +[GROUP] + +

Tutti i controlli hanno una proprietà (Group). + Quando questa proprietà è utilizzata, il prefisso del gestore di eventi è il nome del + gruppo e non il nome del controllo.

+

Supponiamo di avere un Button chiamato btnAzione con il gestore di eventi Click +seguente :

+ +
PUBLIC SUB btnAzione_Click()
+ +

Se definisci la proprietà (Group) di btnAzione come IlMioGruppo, + Allora il gestore di eventi che riceverà gli eventi del pulsante sarà il seguente:

+ +
PUBLIC SUB IlMioGruppo_Click()
+ +

Questa proprietà permette di gestire vari eventi con una semplice funzione. + E i controlli dello stesso gruppo non devono per forza essere dello stesso tipo !!!

+ +

Nota : I veterani del vecchio Visual Basic riconosceranno il concetto di control array, + soltanto che qui viene implementato in un modo più potente. :-)

+ + +[FORM] + +

Un form è l'osservatore di eventi di se stesso, in questo modo puoi gestire direttamente i suoi eventi (Resize, Activate, ...) +dentro il codice della sua stessa classe.

+ +

In questo modo, i nuovi arrivati da Visual Basic non si sentiranno persi :-).

+ + +[EMBED] + +

Con Gambas puoi fare in modo che qualsiasi form venga +racchiuso in un altro form!

+ +

Per fare una cosa così utile devi soltanto inizializzare il form passando +un contenitore padre come ultimo argomento nel costruttore.

+ +

Per esempio :

+

DIM hForm AS MyDialog
+DIM hSuperControl AS MyForm

+' Crea un dialogo
+hForm = NEW MyDialog
+' Inserisce un form in questo dialogo
+' Nota che questo form riceve due parametri prima del contenitore
+hSuperControl = NEW MyForm(Param1, Param2, MyDialog)
+' Muove e ridimensiona il form
+hSuperControl.Move(8, 8, 128, 64)

+ +

Ricorda che: un form racchiuso in un altro continua ad essere un form + e quindi osservatore di eventi di se stesso.

+ + +[TAG] + +

Tutti i controlli hanno una proprietà chiamata Tag + Questa proprietà è pensata per essere usata dai programmatori e può contenere qualsiasi dato +VARIANT che credi utile.

+ +

Questo è molto utile quando vuoi differenziare controlli dello stesso gruppo nello stesso gestore di eventi.

+ + +[LAST] + +

La parola chiave LAST ritorna l'ultimo controllo che ha ricevuto un evento. + E' molto utile quando vuoi scrivere un gestore di eventi +che sia indipendente dal nome del controllo.

+ +

Supponiamo di voler scrivere un programma calcolatrice. + Hai definito dieci pulsanti, uno per ogni numero e tutti con lo stesso group "Digit". + Il valore del Tag di ogni controllo sarà il numero visualizzato da ogni pulsante. + Il tuo gestore di eventi sarà più o meno così :

+ +

PUBLIC SUB Digit_Click()

+  Display = Display & LAST.Tag
+  RefreshDisplay

+END

+ + +[LEFT] + +

Le famose routine Left$, Right$, Mid$ di BASIC + hanno un comportamento molto utile in Gambas.

+ +

Il secondo parametro di Left$ e Right$ è facoltativo, e per default è pari a uno.

+ +

Left$("Gambas") ritorna "G"
+Right$("Gambas") ritorna "s"

+ +

Il secondo parametro può essere negativo e in questo caso rappresenta il numero di caratteri da non ritornare.

+ +

Left$("Gambas", -2) ritorna "Gamb"
+Right$("Gambas", -2) ritorna "mbas"

+ +

Allo stesso modo, il terzo parametro di Mid$ può essere negativo, + e quindi rappresentare il numero di caratteri dalla fine della stringa da non ritornare.

+ +

Mid$("Gambas", 2, -2) ritorna "amb" + + +[OBSERVER] + +

Observer

+ +

La classe Observer ti consente di intercettare tutti gli eventi generati da un +oggetto prima che vengano effettivamente inviati.

+ +
MyTextBox = New TextBox(Me) As "MyTextBox"
+MyObserver = New Observer(MyTextBox) As "MyObserver"
+...
+Public Sub MyObserver_KeyPress()
+  Debug "Got it first"
+End
+
+Public Sub MyTextBox_KeyPress()
+  Debug "Got it next"
+End
+ +L'osservatore può annullare l'evento con Stop Event per prevenire l'oggetto dal +sollevarlo effettivamente. + + +[STRING] + +

UTF-8 Strings

+ +

Gambas utilizza il set di caratteri UTF-8 per rappresentare le stringhe in memoria. + +

Ma tutte le funzioni di stringa standard riguardano solo ASCII: +Left, Mid, Right, UCase... + +

Se si desidera gestire le stringhe UTF-8, è necessario utilizzare i metodi della classe statica +String, che hanno lo stesso nome delle loro controparti standard. + +

Print Len("bébé");; Left$("bébé", 3)
+→ 6 bé
+
+Print String.Len("bébé");; String.Left("bébé", 3)
+→ 4 béb
+ + +[ASSIGNMENT] + +

Assegnazioni

+ +

Gambas implementa le scorciatoie di assegnazione a cui i programmatori C / C ++ sono abituati. + +

MyVariable += 2
+MyVariable *= 4
+MyVariable &= "Great"
+è un equivalente di +
MyVariable = MyVariable + 2
+MyVariable = MyVariable * 4
+MyVariable = MyVariable & "Great"
+ +

E così via... + + +[DEBUG] + +

Debug

+ +

È possibile utilizzare l'istruzione Debug per stampare messaggi di debug sulla +console (ovvero l'output di errore standard). Si comporta esattamente come l'istruzione Print. + +

Questi messaggi hanno come prefisso il nome della classe, il nome del metodo e il numero di +riga dell'istruzione Debug. Se non si desidera il prefisso, è possibile utilizzare +l'istruzione Error anziché Debug. + +

I messaggi di debug vengono automaticamente rimossi durante la creazione di +un eseguibile senza eseguire il debug delle informazioni. + + +[TRY] + +

Gestione degli errori (1)

+ +

La gestione degli errori in Gambas viene eseguita con le seguenti istruzioni: +Try, Error, Catch, and Finally. + +

Try prova a eseguire una dichiarazione senza generare un errore. La parola chiave +Error viene utilizzata subito dopo per sapere se l'istruzione è stata eseguita correttamente. + +

Try MyFile = Open "/etc/password" For Write
+If Error Then Print "Non posso fare quello che voglio!"
+ + +[CATCH] + +

Gestione degli errori (2)

+ +

La gestione degli errori in Gambas viene eseguita con le seguenti istruzioni: +Try, Error, Catch, and Finally. + +

Catch indica l'inizio della parte di gestione degli errori di una funzione o procedura. +È messo alla fine del codice della funzione. + +

La parte catch viene eseguita quando viene generato un errore tra l'inizio dell'esecuzione della funzione e la sua fine. + +

Se viene sollevato un errore durante l'esecuzione della parte catch, l'errore viene propagato normalmente. + +

Sub ProcessFile(FileName As String)
+  ...
+  Open FileName For Read As #hFile
+  ...
+  Close #hFile
+  
+Catch ' Eseguito solo se c'è un errore
+
+  Print "Impossibile elaborare il file "; FileName
+
+End
+ + +[FINALLY] + +

Gestione degli errori (3)

+ +

La gestione degli errori in Gambas viene eseguita con le seguenti istruzioni: +Try, Error, Catch, and Finally. + +

Finally introduce il codice eseguito alla fine della funzione, anche se viene sollevato un errore durante l'esecuzione. + +

La parte finally non è obbligatoria. Se c'è una parte catch nella funzione, la parte finally deve precederla. + +

Se viene generato un errore durante l'esecuzione della parte finally, l'errore viene propagato normalmente. + +

Sub ProcessFile(FileName As String)
+  ...
+  Open FileName For Read As #hFile
+  ...
+Finally ' Viene sempre eseguito, anche se viene sollevato un errore
+
+  Close #hFile
+  
+Catch ' Eseguito solo se c'è un errore
+  
+  Print "Impossibile stampare il file "; FileName
+  
+End
+ + +[OPTIONAL] + +

Optional

+ +

Le funzioni e le procedure in Gambas possono avere argomenti opzionali.

+ +

Gli argomenti opzionali vengono semplicemente fatti mettendo la parola chiave Optional subito prima del nome dell'argomento.

+ +

Gli argomenti opzionali possono avere anche un valore predefinito esplicito.

+ +
Private Sub MyFunction(Param AS String, Optional Optim AS String = "Default")
+  ...
+  Print "Necessario: "; param; ", Opzionale: "; optim
+  ...
+End
+ + +[ARRAY] + +

For Each

+ +

In Gambas puoi facilmente scorrere un array, una raccolta o molte altre classi enumerabili con l'istruzione For Each.

+ +

Per esempio:

+ +
Dim Xml As New XmlDocument
+Dim Node As XmlNode
+Dim I As Integer
+
+' Apre un file XML
+Xml.Open("pokus.xml")
+' I children sono indicizzati tramite [i], poiché si tratta di un array
+For I = 0 To Xml.Root.Children.Count - 1
+  ' Gli attributi vengono ciclati tramite For Each, poiché si tratta di una collection
+  For Each Node In Xml.Root.Children[i].Attributes
+    Print Node.Name;; Node.Value
+  Next
+Next
+ + +[ICON] + +

Icone di default

+ +

Puoi utilizzare le icone incorporate per una migliore GUI della tua applicazione, le icone sono disponibili in diverse dimensioni predefinite +("small", "medium", "large",...) o in dimensioni assolute (da 16x16 a 256x256).

+ +

Per esempio: + +

Image1.Picture = Picture["icon:/32/warning"]
+Image2.Picture = Picture["icon:/small/error"]
+
+ +

Attenzione: è richiesto il componente gb.form. + + +[SETTINGS] + +

Settings

+ +

Se hai bisogno di memorizzare la configurazione del tuo programma (come la geometria dei tuoi form), allora sei un ragazzo fortunato. In Gambas è molto semplice ed elegante. :-) + +

Per salvare la posizione di un form: +

Settings.Write(TheForm)
+ +

Per richiamarlo: +

Settings.Read(TheForm)
+ +Per salvare qualsiasi impostazione: +
Settings["Slot/Key"] = Value
+ +E per rileggerne le impostazioni: +
Value = Settings["Slot/Key", DefaultValue]
+ +Queste impostazioni sono memorizzate nel file ~/.config/gambas3/<MyApplication>.conf, +dove <MyApplication> è il nome del tuo progetto. + +

Attenzione: è richiesto il componente gb.settings. + + +[EDITOR] + +

Ecco alcuni suggerimenti per l'editor...

+ +

Due tipi di commenti

+ +
' Commento normale
+
'' Commento in grassetto
+ +

I commenti in grassetto sono usati per documentare il tuo codice.

+ +

Come utilizzare i frammenti di codice

+ +

Digita main quindi il tasto TAB. Una funzione statica e pubblica di avvio Main viene automaticamente inserita nel codice. + +

Digita ds quindi il tasto TAB. Una dichiarazione locale di variabile stringa viene inserita automaticamente ed è possibile digitare immediatamente il nome della variabile. + +

I frammenti di codice sono completamente configurabili dalla finestra di dialogo Preferenze del menu Strumenti dell'IDE. + + +[END] + +

Hai letto tutti i suggerimenti del giorno. Spero che ora tu sia un esperto di Gambas ! :-)

+ +

Se vuoi contribuire, invia i nuovi consigli al seguente indirizzo :

+

user@lists.gambas-basic.org

+ +

Grazie in anticipo !

+ diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.nl gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.nl --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.nl 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.nl 1970-01-01 00:00:00.000000000 +0000 @@ -1,274 +0,0 @@ -[WELCOME] - -

Welkom bij Gambas !

- -

Gambas is een grafisch ontwikkel omgeving gebaseerd op een -geavanceerdd Basic interpreter.

- -

Gambas is geschreven om eenvoudig en snel -krachtige applicaties te ontwikkelen. Het bouwen van de -programmacode blijft je eigen verantwoordelijkheid...

- -

Veel plezier ermee !

- -

Benoît Minisini
-g4mba5@gmail.com

- - -[STARTUP] - -

Elk project moet een startup class hebben. Deze -startup class moet een piblieke methode Main hebben, -zonder argumenten. Deze Main methode fungeerd als -de opstart methode voor de applicatie.

- -

Je kunt de startup class definieren door in de projectboom -met de rechter muisknop op het object te klikken en -startup class in het popup menu te selecteren

- - - -

Het is niet nodig om een Main methode in een opstart -formulier te declareren, omdat het opstart formulier al een Main methode bevat.

- -

Deze reeds gedefinieerde Main methode initieerd het formulier, net zoals in -Visual Basic™.

- - -[OPEN] - -

De OPEN instructie van Gambas werkt niet zoals de Visual Basic variant. -Het retourneerd geen integer, maar een File object.

- -

Dus in plaats van:

- -
DIM handle AS Integer
-...
-OPEN "mijnfile" FOR READ AS #handle
- -

gebruik je :

- -
DIM handle AS File
-...
-handle = OPEN "mijnfile" FOR READ
- - -[CATDIR] - -

Weet je dat je directory- en filenamen kunt koppelen met de &/ operator ? -Deze operator lost alle problemen met eindigende slashes voor je op.

- -

Bijvoorbeeld:

- -
PRINT "/home/gambas" &/ ".bashrc"
-/home/gambas/.bashrc
-
-PRINT "/home/gambas/" &/ "/tmp" &/ "foo.bar"
-/home/gambas/tmp/foo.bar
-
- -

Is dit niet fantastisch ?

- - -[EXEC] - -

Je kunt een 'executable' file (binairy) maken van je gehele project. -Selecteer Make executable in het Project menu.

- -

Als Gambas een binairy file voor je maakt, plaatst het -het resultaat in de standaard directory van je project. -Deze executable krijgt dezelfde naam als het project.

- - -[PATH] -

-Relatieve paden hebben altijd een speciale betekenis in Gambas. -Ze refereren altijd naar bestanden in je project. -

-Er is geen concept als current directory, en geen commando als -CHDIR om het te veranderen. -

-Wees voorzichtig: je moet altijd relatieve paden gebruiken voor verwijzingen -naar andere files in het project, omdat volledige paden niet meer werken als er -een executable van het project gemaakt wordt.

- -[GLOBAL] - -Er zijn geen globale variabelen in Gambas! -

-Als oplossing kun je ze in je main module plaatsen en declareren als PUBLIC. -

-Als je geen main module hebt, maar een main form, declareer ze dan als STATIC PUBLIC. -

-Om bij deze variabelen te komen gebruik je de naam van de module: MijnMainModule.MijnGlobaleVariable of -MijnMainForm.MijnGlobaleVariable. - - -[EMPTY] - -

Om te kijken of een string leeg is hoef je geen gebruik te maken van de -Len() functie. Je kunt het direct testen: een lege string -is FALSE en een niet-lege string is TRUE.

- -

Bijvoorbeeld, in plaats van :

- -
IF Len(MijnString) > 0 THEN ...
-IF Len(MijnString) = 0 THEN ...
- -

Kun je sneller :

- -
IF MijnString THEN ...
-IF NOT MijnString THEN ...
- - -[EVENT] - -

Elke controller, en elk object dat een gebeurtenis (event) kan oproepen, heeft een -event observer en een event group name.

- -

De event observer ondervangt ieder event opgeroepen door het object, en -de 'event group name' is het voorvoegsel van de procedure die opgeroepen wordt om het -event af te handelen.

- -

Standaard is de event observer het object waar je de controller gemaakt hebt, en de -group name is de naam van de controller.

- -

Op deze manier ontvangt een formulier alle gebeurtenissen die door controllers op dit -formulier gemaakt zijn.

- -
' Gambas form
-DIM hButton AS Button
-
-PUBLIC SUB _new()
-  hButton = NEW Button(ME) AS "MyButton"
-END
-
-PUBLIC SUB MyButton_Click()
-  PRINT "You have clicked MyButton !"
-END
-
- - -[FORM] - -

In Gambas, is een formulier zijn eigen event observer, -zodat je gebeurtenissen als Resize, -Activate, ...) kunt afhandelen in zijn eigen class code.

- -

Op deze manier worden de newbies van Visual Basic niet teveel -afgeschrikt :-).

- - -[EMBED] - -

Je kunt bij Gambas een formulier in een ander formulier invoegen - !

- -

Om zo'n krachtige actie te doen hoef je enkel een ouder container (parent) mee te geven -als laatste parameter bij het oproepen van het formulier.

- -

Bij voorbeeld :

-

DIM hForm AS MijnDialog
-DIM hSuperControl AS MijnForm

-' Create a dialog
-hForm = NEW MijnDialog
-' Insert a form into this dialog
-' Note that this form takes two parameters before the container
-hSuperControl = NEW MijnForm(Param1, Param2, MijnDialog)
-' Moves and resizes the form
-hSuperControl.Move(8, 8, 128, 64)
-

- -

Let op: een formulier ingevoegd in een ander is nog steeds een formulier, -met zijn eigen event observer.

- - -[GROUP] - -

Elke controller heeft een (Group) eigenschap. -Als deze eigenschap wordt gebruikt wordt de naam van de groep gebuikt voor het -afhandelen van de events, en niet de naam van de controller. -

- -

Stel: we hebben een Button genaamd btnAction -Met de volgende Click event handler :

- -
PUBLIC SUB btnAction_Click()
- -

Als je de (Group) eigenschap van btnAction zet op -MijnGroup, dan wordt de event handlerdie alle events ontvangt:

- -
PUBLIC SUB MijnGroup_Click()
- -

Op deze manier kun je verschillende controllers dezelfde functie toekennen. -De controllers hoeven hiervoor niet eens van hetzelfde type te zijn!

- -

NB : Een oude Visual Basic veteraan zal het systeem van een -control array herkennen, maar dan in een krachtigere uitvoering :-).

- - -[TAG] - -

Elke controlller heeft een Tag eigenschap. Deze eigenschap is voor -de programmeur, en kan elke gewenste VARIANT gegevens bevatten die je -relevant vindt.

- -

Deze eigenschap is erg handig om verschillende controllers die bij elkaar -in dezelfde group zitten te onderscheiden -binnen de gezamenlijke event handler van deze group.

- - - -[LAST] - -

Het LAST commando retourneerd de laatst opgeroepen controller. -Dit is erg handis als je een event handler wilt schrijven die -onafhankelijk is van de controller naam.

- -

Bijvoorbeeld: Stel je wilt een rekenmachine programmeren. -Je hebt tien knoppen gedefinieerd, elk voor een cijfer, en de knoppen gehangen -aan de group "Digit". De Tag van elke controlller is gelijk aan het -getal op de button. Je event handler kan er dan zo uit zien :

- -

PUBLIC SUB Digit_Click()

-  Display = Display & LAST.Tag
-  RefreshDisplay

-END

- - -[LEFT] - -

De bekende BASIC routines Left$, Right$ -en Mid$ hebben handige functies in Gambas

- -

De tweede parameter van Left$ en Right$ is -optioneel, en is standaard 1.

- -

Left$("Gambas") retourneerd "G"
-Right$("Gambas") retourneerd "s"

- -

De tweede parameter mag negatief zijn, en geeft dan het aantal karakters dat -je niet wilt.

- -

Left$("Gambas", -2) retourneerd "Gamb"
-Right$("Gambas", -2) retourneerd "mbas"

- -

Vanzelfsprekend, het derde argument van Mid$ mag negatief zijn, en geeft -dan het aantal karakters vanaf het eind van de string dat genegeerd moet worden.

- -

Mid$("Gambas", 2, -2) retourneerd "amb" - - -[END] - -

Je hebt alle tips van de dag gelezen. Ik hoop dat je nu een Gambas -expert geworden bent ! :-)

- -

Als je tips toe te voegen hebt, zend je nieuwe tips dan naar het volgende -adres :

-

g4mba5@gmail.com

- -

Alvast bedankt !

- - - diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.nl.txt gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.nl.txt --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.nl.txt 1970-01-01 00:00:00.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.nl.txt 2021-09-14 19:01:29.000000000 +0000 @@ -0,0 +1,274 @@ +[WELCOME] + +

Welkom bij Gambas !

+ +

Gambas is een grafisch ontwikkel omgeving gebaseerd op een +geavanceerdd Basic interpreter.

+ +

Gambas is geschreven om eenvoudig en snel +krachtige applicaties te ontwikkelen. Het bouwen van de +programmacode blijft je eigen verantwoordelijkheid...

+ +

Veel plezier ermee !

+ +

Benoît Minisini
+g4mba5@gmail.com

+ + +[STARTUP] + +

Elk project moet een startup class hebben. Deze +startup class moet een piblieke methode Main hebben, +zonder argumenten. Deze Main methode fungeerd als +de opstart methode voor de applicatie.

+ +

Je kunt de startup class definieren door in de projectboom +met de rechter muisknop op het object te klikken en +startup class in het popup menu te selecteren

+ + + +

Het is niet nodig om een Main methode in een opstart +formulier te declareren, omdat het opstart formulier al een Main methode bevat.

+ +

Deze reeds gedefinieerde Main methode initieerd het formulier, net zoals in +Visual Basic™.

+ + +[OPEN] + +

De OPEN instructie van Gambas werkt niet zoals de Visual Basic variant. +Het retourneerd geen integer, maar een File object.

+ +

Dus in plaats van:

+ +
DIM handle AS Integer
+...
+OPEN "mijnfile" FOR READ AS #handle
+ +

gebruik je :

+ +
DIM handle AS File
+...
+handle = OPEN "mijnfile" FOR READ
+ + +[CATDIR] + +

Weet je dat je directory- en filenamen kunt koppelen met de &/ operator ? +Deze operator lost alle problemen met eindigende slashes voor je op.

+ +

Bijvoorbeeld:

+ +
PRINT "/home/gambas" &/ ".bashrc"
+/home/gambas/.bashrc
+
+PRINT "/home/gambas/" &/ "/tmp" &/ "foo.bar"
+/home/gambas/tmp/foo.bar
+
+ +

Is dit niet fantastisch ?

+ + +[EXEC] + +

Je kunt een 'executable' file (binairy) maken van je gehele project. +Selecteer Make executable in het Project menu.

+ +

Als Gambas een binairy file voor je maakt, plaatst het +het resultaat in de standaard directory van je project. +Deze executable krijgt dezelfde naam als het project.

+ + +[PATH] +

+Relatieve paden hebben altijd een speciale betekenis in Gambas. +Ze refereren altijd naar bestanden in je project. +

+Er is geen concept als current directory, en geen commando als +CHDIR om het te veranderen. +

+Wees voorzichtig: je moet altijd relatieve paden gebruiken voor verwijzingen +naar andere files in het project, omdat volledige paden niet meer werken als er +een executable van het project gemaakt wordt.

+ +[GLOBAL] + +Er zijn geen globale variabelen in Gambas! +

+Als oplossing kun je ze in je main module plaatsen en declareren als PUBLIC. +

+Als je geen main module hebt, maar een main form, declareer ze dan als STATIC PUBLIC. +

+Om bij deze variabelen te komen gebruik je de naam van de module: MijnMainModule.MijnGlobaleVariable of +MijnMainForm.MijnGlobaleVariable. + + +[EMPTY] + +

Om te kijken of een string leeg is hoef je geen gebruik te maken van de +Len() functie. Je kunt het direct testen: een lege string +is FALSE en een niet-lege string is TRUE.

+ +

Bijvoorbeeld, in plaats van :

+ +
IF Len(MijnString) > 0 THEN ...
+IF Len(MijnString) = 0 THEN ...
+ +

Kun je sneller :

+ +
IF MijnString THEN ...
+IF NOT MijnString THEN ...
+ + +[EVENT] + +

Elke controller, en elk object dat een gebeurtenis (event) kan oproepen, heeft een +event observer en een event group name.

+ +

De event observer ondervangt ieder event opgeroepen door het object, en +de 'event group name' is het voorvoegsel van de procedure die opgeroepen wordt om het +event af te handelen.

+ +

Standaard is de event observer het object waar je de controller gemaakt hebt, en de +group name is de naam van de controller.

+ +

Op deze manier ontvangt een formulier alle gebeurtenissen die door controllers op dit +formulier gemaakt zijn.

+ +
' Gambas form
+DIM hButton AS Button
+
+PUBLIC SUB _new()
+  hButton = NEW Button(ME) AS "MyButton"
+END
+
+PUBLIC SUB MyButton_Click()
+  PRINT "You have clicked MyButton !"
+END
+
+ + +[FORM] + +

In Gambas, is een formulier zijn eigen event observer, +zodat je gebeurtenissen als Resize, +Activate, ...) kunt afhandelen in zijn eigen class code.

+ +

Op deze manier worden de newbies van Visual Basic niet teveel +afgeschrikt :-).

+ + +[EMBED] + +

Je kunt bij Gambas een formulier in een ander formulier invoegen + !

+ +

Om zo'n krachtige actie te doen hoef je enkel een ouder container (parent) mee te geven +als laatste parameter bij het oproepen van het formulier.

+ +

Bij voorbeeld :

+

DIM hForm AS MijnDialog
+DIM hSuperControl AS MijnForm

+' Create a dialog
+hForm = NEW MijnDialog
+' Insert a form into this dialog
+' Note that this form takes two parameters before the container
+hSuperControl = NEW MijnForm(Param1, Param2, MijnDialog)
+' Moves and resizes the form
+hSuperControl.Move(8, 8, 128, 64)
+

+ +

Let op: een formulier ingevoegd in een ander is nog steeds een formulier, +met zijn eigen event observer.

+ + +[GROUP] + +

Elke controller heeft een (Group) eigenschap. +Als deze eigenschap wordt gebruikt wordt de naam van de groep gebuikt voor het +afhandelen van de events, en niet de naam van de controller. +

+ +

Stel: we hebben een Button genaamd btnAction +Met de volgende Click event handler :

+ +
PUBLIC SUB btnAction_Click()
+ +

Als je de (Group) eigenschap van btnAction zet op +MijnGroup, dan wordt de event handlerdie alle events ontvangt:

+ +
PUBLIC SUB MijnGroup_Click()
+ +

Op deze manier kun je verschillende controllers dezelfde functie toekennen. +De controllers hoeven hiervoor niet eens van hetzelfde type te zijn!

+ +

NB : Een oude Visual Basic veteraan zal het systeem van een +control array herkennen, maar dan in een krachtigere uitvoering :-).

+ + +[TAG] + +

Elke controlller heeft een Tag eigenschap. Deze eigenschap is voor +de programmeur, en kan elke gewenste VARIANT gegevens bevatten die je +relevant vindt.

+ +

Deze eigenschap is erg handig om verschillende controllers die bij elkaar +in dezelfde group zitten te onderscheiden +binnen de gezamenlijke event handler van deze group.

+ + + +[LAST] + +

Het LAST commando retourneerd de laatst opgeroepen controller. +Dit is erg handis als je een event handler wilt schrijven die +onafhankelijk is van de controller naam.

+ +

Bijvoorbeeld: Stel je wilt een rekenmachine programmeren. +Je hebt tien knoppen gedefinieerd, elk voor een cijfer, en de knoppen gehangen +aan de group "Digit". De Tag van elke controlller is gelijk aan het +getal op de button. Je event handler kan er dan zo uit zien :

+ +

PUBLIC SUB Digit_Click()

+  Display = Display & LAST.Tag
+  RefreshDisplay

+END

+ + +[LEFT] + +

De bekende BASIC routines Left$, Right$ +en Mid$ hebben handige functies in Gambas

+ +

De tweede parameter van Left$ en Right$ is +optioneel, en is standaard 1.

+ +

Left$("Gambas") retourneerd "G"
+Right$("Gambas") retourneerd "s"

+ +

De tweede parameter mag negatief zijn, en geeft dan het aantal karakters dat +je niet wilt.

+ +

Left$("Gambas", -2) retourneerd "Gamb"
+Right$("Gambas", -2) retourneerd "mbas"

+ +

Vanzelfsprekend, het derde argument van Mid$ mag negatief zijn, en geeft +dan het aantal karakters vanaf het eind van de string dat genegeerd moet worden.

+ +

Mid$("Gambas", 2, -2) retourneerd "amb" + + +[END] + +

Je hebt alle tips van de dag gelezen. Ik hoop dat je nu een Gambas +expert geworden bent ! :-)

+ +

Als je tips toe te voegen hebt, zend je nieuwe tips dan naar het volgende +adres :

+

g4mba5@gmail.com

+ +

Alvast bedankt !

+ + + diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.pl gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.pl --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.pl 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.pl 1970-01-01 00:00:00.000000000 +0000 @@ -1,280 +0,0 @@ -[WELCOME] - -

Witaj w Gambasie !

- -

Gambas jest zintegrowanym środowiskiem programistycznym - bazującym na zaawansowanym interpreterze Basica.

- -

Gambas umożliwi Ci łatwe i szybkie tworzenie programów. -Jednak to, czy programy będą ładne, funcjonalne i przejrzyste zależy tylko od Ciebie... -

- -

Miłej pracy !

- -

Benoît Minisini
-g4mba5@gmail.com

- - -[STARTUP] - -

Każdy projekt musi mieć klasę startową. Klasa -startowa musi definiować statyczną metodę publiczną o nazwie Main -bez argumentów, która uruchomi Twój program.

- -

Możesz zdefiniować klasę startową poprzez kliknięcie prawym klawiszem -myszki w drzewie projektu i wybrać opcję Klasa startowa w menu podręcznym.

- -

Nie jest konieczne definiowanie metody Main w formularzu -startowym, ponieważ jest już w nim predefiniowana.

- -

Ta predefiniowana metoda startowa inicjuje formularz i wyświetla go podobnie jak -w Visual Basic™.

- - -[OPEN] - -

W Gambasie instrukcja OPEN nie działa jak ta -w Visual Basicu. Nie zwraca pliku jako integer, ale jako obiekt File.

- -

Dlatego, zamiast pisać :

- -
DIM hPliku AS Integer
-...
-OPEN "MójPlik" FOR READ AS #hPliku
- -

musisz napisać :

- -
DIM hPliku AS File
-...
-hPliku = OPEN "MójPlik" FOR READ
- - -[CATDIR] - -

Czy wiesz, że możesz połączyć ścieżkę z nazwą pliku -używając operatora &/ ? Ten operator -połączy dwa łańcuchy znaków dodając między nimi '/', -jeśli wcześniej go tam nie było, lub zredukuje jego wielokrotność.

- -

Przykład:

- -
PRINT "/home/gambas" &/ ".bashrc"
-/home/gambas/.bashrc
-
-PRINT "/home/gambas/" &/ "/tmp" &/ "foo.bar"
-/home/gambas/tmp/foo.bar
-
- -

Czyż to nie wpaniałe ?

- - -[EXEC] - -

Z projektu możesz utworzyć plik uruchamialny. - Wybierz opcję Utwórz plik uruchamialny w menu Projekt.

- -

Kiedy Gambas stworzy plik uruchamialny umieści go -w domyślnym katalogu projektu. -Nazwa pliku uruchamialnego jest taka sama jak nazwa Twojego projektu.

- - -[PATH] -

-Ścieżki względne mają specjalne znaczenie w Gambasie. -Zawsze odwołują się do pliku wewnątrz Twojego projektu. - -

-Nie istnieje idea bieżącego katalogu i nie ma słowa kluczowego -takiego jak CHDIR, które pozwalałoby na zmianę katalogu roboczego. -

-Uwaga: musisz używać tylko ścieżek względnych do -dostępu do plików wewnątrz projektu, ponieważ ścieżki bezwględne - po utworzeniu pliku uruchamialnego nie będą działać poprawnie. - - -[GLOBAL] - -W Gambasie nie ma zmiennych globalnych! -

-Aby to obejść, zadeklaruj zmienne jako PUBLIC w module startowym. -

-Jeśli nie masz w projekcie modułu startowego tylko formularz -startowy, wtedy zadeklaruj zmienne jako STATIC PUBLIC. -

-Aby mieć dostęp do tych zmiennych musisz użyć nazwy modułu lub -formularza startowego przed nazwą zmiennej: -MójModułStartowy.MojaZmiennaGlobalna lub -MójFormularzStartowy.MojaZmiennaGlobalna. - - -[EMPTY] - -

Nie jest konieczne użycie funcji Len() aby się dowiedzieć czy -łańcuch znaków jest pusty. Możesz przetestować go bezpośrednio; -jeśli łańcuch jest pusty, to zostanie zwrócone FALSE, a jeśli nie jest pusty -zostanie zwrócone TRUE.

- -

Na przykład, zamiast :

- -
IF Len(MójŁańcuchZnaków) > 0 THEN ...
-IF Len(MójŁańcuchZnaków) = 0 THEN ...
- -

Możesz wpisać :

- -
IF MójŁańcuchZnaków THEN ...
-IF NOT MójŁańcuchZnaków THEN ...
- - -[EVENT] - -

Każda kontrolka i każdy obiekt, który może wywołać zdarzenie -posiada obserwatora zdarzenia (event observer) i -nazwę grupy zdarzenia.

- -

Obserwator zdarzenia wyłapuje każde zdarzenie wywołane przez obiekt, -a nazwa grupy zdarzenia jest prefiksem procedury wywołanej do zarządzania -zdarzeniem.

- -

Domyślnie, obserwator zdarzenia jest obiektem -utworzonej kontrolki, a nazwa grupy jest nazwą tej kontrolki. -

- -

W ten sposób formularz otrzymuje wszystkie zdarzenia wywołane przez -kontrolki utworzone wewnątrz tego formularza.

- -
' Gambas form
-DIM hPrzycisku AS Button
-
-PUBLIC SUB _new()
-  hPrzycisku = NEW Button(ME) AS "MójPrzycisk"
-END
-
-PUBLIC SUB MójPrzycisk_Click()
-  PRINT "Kliknąłeś w MójPrzycisk !"
-END
-
- - -[FORM] - -

W Gambasie formularz jest obserwatorem -własnych zdarzeń, w związku z czym możesz bezpośrednio zarządzać -jego zdarzeniami (takimi jak Resize, -Activate, ...) w kodzie jego własnej klasy.

- -

Dzięki temu początkujący w Gambasie, pracujący wcześniej w -Visual Basicu nie są zdezorientowani :-).

- - -[EMBED] - -

W Gambasie możesz osadzać dowolny formularz - w innym formularzu !

- -

Aby uzyskać tak wspaniałą funkcjonalność -wystarczy zainicjować formularz poprzez podanie -nadrzędnego kontenera jako ostatniego argumentu konstruktora.

- -

Przykład :

-

DIM hFormularza AS MójFormularz
-DIM hPodformularza AS MójPodformularz

-' Tworzenie formularza głównego
-hFormularza = NEW MójFormularz
-' Wstawienie podformularza do formularza głównego
-'Zauważ, że ten formularz pobiera dwa parametry przed kontenerem
-hPodformularza = NEW MójPodformularz(Param1, Param2, MójFormularz)
-' Przenieś i zmień wielkość formularza
-hPodformularza.Move(8, 8, 128, 64)
-

- -

Uwaga: formularz osadzony w innym formularzu jest nadal formularzem -i tym samym jest własnym obserwatorem zdarzeń.

- - -[GROUP] - -

Każda kontrolka posiada właściwość (Group). -Kiedy właściwość ta jest ustawiona, prefiks nazwy uchwytu zdarzenia -jest nazwą grupy, a nie nazwą kontrolki.

- -

Załóżmy, że masz Przycisk o nazwie btnMójPrzycisk -z następującym uchwytem zdarzenia Click:

- -
PUBLIC SUB btnMójPrzycisk_Click()
- -

Jesli ustawisz właściwość (Group) dla btnMójPrzycisk -na MojaGrupa wtedy uchwyt zdarzenia, który otrzyma -zdarzenia z przycisku będzie następujący:

- -
PUBLIC SUB MojaGrupa_Click()
- -

Ta właściwość pozwala Ci na wychwytywanie zdarzeń różnych kontrolek -w jednej funkcji, a kontrolki tej samej grupy nie muszą być tego samego typu !

- -

Notatka : Starzy weterani Visual Basica moga rozpoznać ideę -tablicy kontrolek (control array), ale w bardziej funkcjonalnej implementacji. :-)

- - -[TAG] - -

Każda kontrolka ma właściwość Tag. Ta właściwość jest przeznaczona -dla programistów i może zawierać dowolne dane typu VARIANT, które -uważa on za istotne.

- -

To jest bardzo użyteczne kiedy chcesz rozróżnić kontrolki tej samej grupy we -wspólnym uchwycie zdarzenia.

- - -[LAST] - -

Słowo kluczowe LAST zwraca ostatnią kontrolkę, która odebrała -zdarzenie. Jest to bardzo użyteczne kiedy chcesz napisać uchwyt zdarzenia, - który jest niezależny od nazwy kontrolki.

- -

Przykładowo, przypuśćmy, że chcesz napisać program kalkulator. -Zdefiniowałeś przyciski, po jednym dla każdej cyfry, każdy w tej samej grupie -o nazwie "Cyfry". Właściwość Tag każdej kontrolki zawiera cyfrę widoczną -na przycisku. Twój uchwyt zdarzenia może wyglądać tak:

- -

PUBLIC SUB Cyfry_Click()

-  Display = Display & LAST.Tag
-  RefreshDisplay

-END

- - -[LEFT] - -

Dobrze znane funkcje z BASICa: Left$, Right$ -i Mid$ mają dodatkową użyteczność w Gambasie.

- -

Drugi parametr Left$ i Right$ jest opcjonalny i domyślnie zwraca -jeden znak.

- -

Left$("Gambas") zwraca "G"
-Right$("Gambas") zwraca "s"

- -

Drugi parametr może być ujemny i wtedy funkcja zwraca wartość -bez określonej ilości niechcianych znaków.

- -

Left$("Gambas", -2) zwraca "Gamb"
-Right$("Gambas", -2) zwraca "mbas"

- -

Na podobnej zasadzie, trzeci argument funkcji Mid$ -może mieć również wartość ujemną.

- -

Mid$("Gambas", 2, -2) zwraca "amb" - - -[END] - -

Przeczytałeś wszystkie porady dnia. Mam nadzieję, że dzięki nim stałeś się -ekspertem programowania w Gambasie ! :-)

- -

Jesli chcesz dodać nowe porady, prześlij je na adres - :

-

g4mba5@gmail.com

- -

Z góry dziękuję !

- - - diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.pl.txt gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.pl.txt --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.pl.txt 1970-01-01 00:00:00.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.pl.txt 2021-09-14 19:01:29.000000000 +0000 @@ -0,0 +1,280 @@ +[WELCOME] + +

Witaj w Gambasie !

+ +

Gambas jest zintegrowanym środowiskiem programistycznym + bazującym na zaawansowanym interpreterze Basica.

+ +

Gambas umożliwi Ci łatwe i szybkie tworzenie programów. +Jednak to, czy programy będą ładne, funcjonalne i przejrzyste zależy tylko od Ciebie... +

+ +

Miłej pracy !

+ +

Benoît Minisini
+g4mba5@gmail.com

+ + +[STARTUP] + +

Każdy projekt musi mieć klasę startową. Klasa +startowa musi definiować statyczną metodę publiczną o nazwie Main +bez argumentów, która uruchomi Twój program.

+ +

Możesz zdefiniować klasę startową poprzez kliknięcie prawym klawiszem +myszki w drzewie projektu i wybrać opcję Klasa startowa w menu podręcznym.

+ +

Nie jest konieczne definiowanie metody Main w formularzu +startowym, ponieważ jest już w nim predefiniowana.

+ +

Ta predefiniowana metoda startowa inicjuje formularz i wyświetla go podobnie jak +w Visual Basic™.

+ + +[OPEN] + +

W Gambasie instrukcja OPEN nie działa jak ta +w Visual Basicu. Nie zwraca pliku jako integer, ale jako obiekt File.

+ +

Dlatego, zamiast pisać :

+ +
DIM hPliku AS Integer
+...
+OPEN "MójPlik" FOR READ AS #hPliku
+ +

musisz napisać :

+ +
DIM hPliku AS File
+...
+hPliku = OPEN "MójPlik" FOR READ
+ + +[CATDIR] + +

Czy wiesz, że możesz połączyć ścieżkę z nazwą pliku +używając operatora &/ ? Ten operator +połączy dwa łańcuchy znaków dodając między nimi '/', +jeśli wcześniej go tam nie było, lub zredukuje jego wielokrotność.

+ +

Przykład:

+ +
PRINT "/home/gambas" &/ ".bashrc"
+/home/gambas/.bashrc
+
+PRINT "/home/gambas/" &/ "/tmp" &/ "foo.bar"
+/home/gambas/tmp/foo.bar
+
+ +

Czyż to nie wpaniałe ?

+ + +[EXEC] + +

Z projektu możesz utworzyć plik uruchamialny. + Wybierz opcję Utwórz plik uruchamialny w menu Projekt.

+ +

Kiedy Gambas stworzy plik uruchamialny umieści go +w domyślnym katalogu projektu. +Nazwa pliku uruchamialnego jest taka sama jak nazwa Twojego projektu.

+ + +[PATH] +

+Ścieżki względne mają specjalne znaczenie w Gambasie. +Zawsze odwołują się do pliku wewnątrz Twojego projektu. + +

+Nie istnieje idea bieżącego katalogu i nie ma słowa kluczowego +takiego jak CHDIR, które pozwalałoby na zmianę katalogu roboczego. +

+Uwaga: musisz używać tylko ścieżek względnych do +dostępu do plików wewnątrz projektu, ponieważ ścieżki bezwględne + po utworzeniu pliku uruchamialnego nie będą działać poprawnie. + + +[GLOBAL] + +W Gambasie nie ma zmiennych globalnych! +

+Aby to obejść, zadeklaruj zmienne jako PUBLIC w module startowym. +

+Jeśli nie masz w projekcie modułu startowego tylko formularz +startowy, wtedy zadeklaruj zmienne jako STATIC PUBLIC. +

+Aby mieć dostęp do tych zmiennych musisz użyć nazwy modułu lub +formularza startowego przed nazwą zmiennej: +MójModułStartowy.MojaZmiennaGlobalna lub +MójFormularzStartowy.MojaZmiennaGlobalna. + + +[EMPTY] + +

Nie jest konieczne użycie funcji Len() aby się dowiedzieć czy +łańcuch znaków jest pusty. Możesz przetestować go bezpośrednio; +jeśli łańcuch jest pusty, to zostanie zwrócone FALSE, a jeśli nie jest pusty +zostanie zwrócone TRUE.

+ +

Na przykład, zamiast :

+ +
IF Len(MójŁańcuchZnaków) > 0 THEN ...
+IF Len(MójŁańcuchZnaków) = 0 THEN ...
+ +

Możesz wpisać :

+ +
IF MójŁańcuchZnaków THEN ...
+IF NOT MójŁańcuchZnaków THEN ...
+ + +[EVENT] + +

Każda kontrolka i każdy obiekt, który może wywołać zdarzenie +posiada obserwatora zdarzenia (event observer) i +nazwę grupy zdarzenia.

+ +

Obserwator zdarzenia wyłapuje każde zdarzenie wywołane przez obiekt, +a nazwa grupy zdarzenia jest prefiksem procedury wywołanej do zarządzania +zdarzeniem.

+ +

Domyślnie, obserwator zdarzenia jest obiektem +utworzonej kontrolki, a nazwa grupy jest nazwą tej kontrolki. +

+ +

W ten sposób formularz otrzymuje wszystkie zdarzenia wywołane przez +kontrolki utworzone wewnątrz tego formularza.

+ +
' Gambas form
+DIM hPrzycisku AS Button
+
+PUBLIC SUB _new()
+  hPrzycisku = NEW Button(ME) AS "MójPrzycisk"
+END
+
+PUBLIC SUB MójPrzycisk_Click()
+  PRINT "Kliknąłeś w MójPrzycisk !"
+END
+
+ + +[FORM] + +

W Gambasie formularz jest obserwatorem +własnych zdarzeń, w związku z czym możesz bezpośrednio zarządzać +jego zdarzeniami (takimi jak Resize, +Activate, ...) w kodzie jego własnej klasy.

+ +

Dzięki temu początkujący w Gambasie, pracujący wcześniej w +Visual Basicu nie są zdezorientowani :-).

+ + +[EMBED] + +

W Gambasie możesz osadzać dowolny formularz + w innym formularzu !

+ +

Aby uzyskać tak wspaniałą funkcjonalność +wystarczy zainicjować formularz poprzez podanie +nadrzędnego kontenera jako ostatniego argumentu konstruktora.

+ +

Przykład :

+

DIM hFormularza AS MójFormularz
+DIM hPodformularza AS MójPodformularz

+' Tworzenie formularza głównego
+hFormularza = NEW MójFormularz
+' Wstawienie podformularza do formularza głównego
+'Zauważ, że ten formularz pobiera dwa parametry przed kontenerem
+hPodformularza = NEW MójPodformularz(Param1, Param2, MójFormularz)
+' Przenieś i zmień wielkość formularza
+hPodformularza.Move(8, 8, 128, 64)
+

+ +

Uwaga: formularz osadzony w innym formularzu jest nadal formularzem +i tym samym jest własnym obserwatorem zdarzeń.

+ + +[GROUP] + +

Każda kontrolka posiada właściwość (Group). +Kiedy właściwość ta jest ustawiona, prefiks nazwy uchwytu zdarzenia +jest nazwą grupy, a nie nazwą kontrolki.

+ +

Załóżmy, że masz Przycisk o nazwie btnMójPrzycisk +z następującym uchwytem zdarzenia Click:

+ +
PUBLIC SUB btnMójPrzycisk_Click()
+ +

Jesli ustawisz właściwość (Group) dla btnMójPrzycisk +na MojaGrupa wtedy uchwyt zdarzenia, który otrzyma +zdarzenia z przycisku będzie następujący:

+ +
PUBLIC SUB MojaGrupa_Click()
+ +

Ta właściwość pozwala Ci na wychwytywanie zdarzeń różnych kontrolek +w jednej funkcji, a kontrolki tej samej grupy nie muszą być tego samego typu !

+ +

Notatka : Starzy weterani Visual Basica moga rozpoznać ideę +tablicy kontrolek (control array), ale w bardziej funkcjonalnej implementacji. :-)

+ + +[TAG] + +

Każda kontrolka ma właściwość Tag. Ta właściwość jest przeznaczona +dla programistów i może zawierać dowolne dane typu VARIANT, które +uważa on za istotne.

+ +

To jest bardzo użyteczne kiedy chcesz rozróżnić kontrolki tej samej grupy we +wspólnym uchwycie zdarzenia.

+ + +[LAST] + +

Słowo kluczowe LAST zwraca ostatnią kontrolkę, która odebrała +zdarzenie. Jest to bardzo użyteczne kiedy chcesz napisać uchwyt zdarzenia, + który jest niezależny od nazwy kontrolki.

+ +

Przykładowo, przypuśćmy, że chcesz napisać program kalkulator. +Zdefiniowałeś przyciski, po jednym dla każdej cyfry, każdy w tej samej grupie +o nazwie "Cyfry". Właściwość Tag każdej kontrolki zawiera cyfrę widoczną +na przycisku. Twój uchwyt zdarzenia może wyglądać tak:

+ +

PUBLIC SUB Cyfry_Click()

+  Display = Display & LAST.Tag
+  RefreshDisplay

+END

+ + +[LEFT] + +

Dobrze znane funkcje z BASICa: Left$, Right$ +i Mid$ mają dodatkową użyteczność w Gambasie.

+ +

Drugi parametr Left$ i Right$ jest opcjonalny i domyślnie zwraca +jeden znak.

+ +

Left$("Gambas") zwraca "G"
+Right$("Gambas") zwraca "s"

+ +

Drugi parametr może być ujemny i wtedy funkcja zwraca wartość +bez określonej ilości niechcianych znaków.

+ +

Left$("Gambas", -2) zwraca "Gamb"
+Right$("Gambas", -2) zwraca "mbas"

+ +

Na podobnej zasadzie, trzeci argument funkcji Mid$ +może mieć również wartość ujemną.

+ +

Mid$("Gambas", 2, -2) zwraca "amb" + + +[END] + +

Przeczytałeś wszystkie porady dnia. Mam nadzieję, że dzięki nim stałeś się +ekspertem programowania w Gambasie ! :-)

+ +

Jesli chcesz dodać nowe porady, prześlij je na adres + :

+

g4mba5@gmail.com

+ +

Z góry dziękuję !

+ + + diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.ru gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.ru --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.ru 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.ru 1970-01-01 00:00:00.000000000 +0000 @@ -1,578 +0,0 @@ -[WELCOME] - -

Добро пожаловать в Gambas!

- -

Gambas - это графическая среда разработки, -основанная на продвинутом интерпретаторе Basic.

- -

Цель Gambas - дать вам возможность легко и -быстро создавать мощные программы. Но чистые -программы остаются на вашей ответственности...

- -

Наслаждайтесь!

- -

Benoît Minisini
g4mba5@gmail.com


- - -[STARTUP] - -

Класс запуска

- -

Каждый проект должен иметь класс запуска. Этот класс -запуска должен определять статический открытый метод -с именем Main без аргументов, который будет действовать -как метод запуска вашей программы.

- -

Вы можете определить класс запуска, щёлкнув по -нему правой кнопкой мыши в дереве проекта и -выбрав класс запуска во всплывающем меню.

- -

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

- -

Этот предопределённый метод запуска создаёт экземпляр формы и показывает её как в -Visual Basic™.

- - -[OPEN] - -

Открыть

- -

Инструкция Open в Gambas не работает -как в Visual Basic™. Она не возвращает файл как целое число, -а как объект File.

- -

Итак, вместо того, чтобы написать:

- -
Dim handle As Integer
-...
-Open "myfile" For Read As #handle
- -

Вы должны написать:

- -
Dim handle As File
-...
-handle = Open "myfile" For Read
- - -[CATDIR] - -

Конкатенация путей

- -

Знаете ли вы, что вы можете объединить имена директорий -и файлов с помощью оператора &/? Этот -оператор имеет дело с косыми чертами, так что получающийся -путь идеален.

- -

Например:

- -
Print "/home/gambas" &/ ".bashrc"
-→ /home/gambas/.bashrc
-
-Print "/home/gambas/" &/ "/tmp" &/ "foo.bar"
-→ /home/gambas/tmp/foo.bar
- -

Разве это не чудесно?

- - -[EXEC] - -

Исполняемый файл

- -

Вы можете создать исполняемый файл из всего вашего проекта. -Выберите Создать исполняемый файл в меню Проект.

- -

Когда Gambas создаёт исполняемый файл, он по -умолчанию помещает результат в директорию вашего проекта. -Имя исполняемого файла совпадает с именем вашего проекта.

- - -[PATH] - -

Относительные пути

- -

Относительные пути имеют особое значение в Gambas. -Они всегда ссылаются на файлы внутри ваших проектов.

-

Нет понятия текущей директории и нет ключевого слова, такого как CHDIR, чтобы изменить её.

-

Будьте осторожны: вы должны использовать относительные пути -только для доступа к файлам проекта, потому что абсолютные пути -больше не будут работать, когда вы создаёте исполняемый файл.

- - -[GLOBAL] - -

Глобальные переменные

- -В Gambas нет глобальных переменных! -

В качестве обходного пути, поместите их в свой основной модуль -и объявите их как Public.

-

Если у вас нет основного модуля main в вашем проекте, но -есть основная форма, то объявите их как Static Public.

-

Чтобы получить доступ к этим переменным, необходимо использовать -имя основного модуля main или форму: MyMainModule.MyGlobalVariable -или MyMainForm.MyGlobalVariable.

- - -[EMPTY] - -

Пустые строки

- -

Чтобы узнать, является ли строка пустой, нет необходимости использовать -функцию Len(). Вы можете непосредственно проверить это, -так как пустая строка - False, а непустая строка - True.

- -

Например, вместо того, чтобы делать:

- -
If Len(MyString) > 0 Then ...
-If Len(MyString) = 0 Then ...
- -

Вы должны делать:

- -
If MyString THEN ...
-If Not MyString THEN ...
- - -[TRANSLATE] - -

Перевод

- -

Приложения Gambas полностью переводимое, при условии, что вы -сообщаете ему, какие строки должны быть переведены, а какие нет.

-

Чтобы пометить строки как переводимые, просто заключите их в круглые скобки:

- -
Print ("Translate me")
-Print "But do not translate me!"
- - -[SUBST] - -

Subst$

- -

Функция Subst$() очень полезна для интернационализации вашего приложения.

- -

Требуется как минимум два аргумента. Первый - это текстовая маска, к которой применяется подстановка. -Другие являются аргументами замещения, пронумерованными от одного.

- -

Каждый &X шаблон в строке замены будет заменён X-ым аргументом замены. -Например:

- -
Print Subst(("Substitution of &1, &2 and &3"),
-  "first", "second", "third")
-
-→ Substitution of first, second and third
- - -[EVENT] - -

Обработчики событий

- -

Каждый элемент управления и каждый объект, который может вызывать -события, имеет наблюдателя событий и имя группы событий.

- -

Наблюдатель событий перехватывает каждое событие, вызванное объектом, -а имя группы событий является префиксом процедуры, вызываемой для -управления событием. Эта функция называется обработчиком событий.

- -

По умолчанию этот наблюдатель событий является объектом, в котором вы -создали элемент управления, а имя группы - это имя элемента управления.

- -

Таким образом, форма получает все события, созданные -элементами управления, которые вы создали внутри.

- -
' Gambas form
-Dim hButton As Button
-
-Public Sub _new()
-  hButton = New Button(Me) As "MyButton"
-End
-
-Public Sub MyButton_Click()
-  Print "You have clicked MyButton !"
-End
- - -[GROUP] - -

Группы элементов управления

- -

Каждый элемент управления имеет свойство (Group). Когда это -свойство установлено, префикс имени обработчика события - это -имя группы, а не имя элемента управления.

- -

Предположим, у вас есть кнопка с именем btnAction со следующим обработчиком события Click:

- -
Public SubbtnAction_Click()
- -

Если вы установите свойство (Group) для btnAction -в значение "MyGroup", то обработчик событий, который будет -получать события от кнопки, будет выглядеть следующим образом:

- -
Pubic Sub MyGroup_Click()
- -

Это свойство позволяет обрабатывать события различных элементов -управления в одной функции. И элементы управления одной и той же -группы не обязательно должны быть одного типа!

- -

Примечание: Старый ветеран Visual Basic™ может -распознавать концепцию управляющего массива, но в более мощной -реализации. :-)

- - -[FORM] - -

Формы

- -

В Gambas форма является собственным наблюдателем событий, -так что вы можете напрямую управлять её событиями (такими как -Resize, Activate, ...) в своём собственном коде класса.

- -

Таким образом, новички из Visual Basic™ -не дезориентированы :-).

- - -[EMBED] - -

Встраивание форм

- -

Вы можете встроить любую форму в другие формы с Gambas!

- -

Чтобы сделать такую мощную вещь, просто создайте экземпляр формы, -передав родительский контейнер в качестве последнего аргумента конструктора.

- -

Например:

-
Dim hForm As MyDialog
-Dim hSuperControl As MyForm
-' Создать диалог
-hForm = New MyDialog
-' Вставьте форму в этот диалог
-' Обратите внимание, что эта форма принимает два параметра перед контейнером
-hSuperControl = New MyForm(Param1, Param2, MyDialog)
-' Переместить и изменить размер формы
-hSuperControl.Move(8, 8, 128, 64)
- -

Будьте осторожны: форма, встроенная в другую форму, всё ещё является формой, как и её собственный наблюдатель событий.

- - -[TAG] - -

Свойство тега

- -

Каждый элемент управления имеет свойство Tag. Это свойство -предназначено для программиста и может содержать любые данные -Variant, которые вы считаете уместными.

- -

Это очень полезно, когда вы хотите различить элементы управления -одной и той же группы в общем обработчике событий.

- - -[LAST] - -

Последний

- -

Ключевое слово Last возвращает последний элемент управления, -который получил событие. Это очень полезно, когда вы хотите написать -обработчик событий, который не зависит от имени элемента управления.

- -

Например, предположим, что вы хотите написать калькулятор. -Вы определили десять кнопок, по одной для каждой цифры, каждая -в одной группе элементов управления "Digit". Tag каждого элемента -управления устанавливается на цифру, нарисованную на кнопке.

- -

Ваш обработчик событий может выглядеть так:

- -
Public Sub Digit_Click()
-
-  Display = Display & Last.Tag
-  RefreshDisplay
-END
- - -[LEFT] - -

Left$ / Mid$ / Right$

- -

Хорошо известные базовые процедуры Left$, Right$Mid$ имеют полезное поведение в Gambas

- -

Второй параметр Left$ и Right$ является -опциональным и по умолчанию равен единице.

- -

Left$("Gambas") возвращает "G"
Right$("Gambas") возвращает "s"

- -

Этот второй параметр может быть отрицательным, а в таком случае -указывается количество символов, которые не нужно извлекать.

- -

Left$("Gambas", -2) возвращает "Gamb"
Right$("Gambas", -2) возвращает "mbas"

- -

Точно так же, третий аргумент Mid$ может быть -отрицательным, а в таком случае указывается количество символов -в конце строки, которые не нужно извлекать.

- -

Mid$("Gambas", 2, -2) возвращает "amb"

- - -[OBSERVER] - -

Наблюдатель

- -

Класс Observer позволяет вам перехватывать все события, -вызванные объектом, до того, как они действительно будут отправлены.

- -
MyTextBox = New TextBox(Me) As "MyTextBox"
-MyObserver = New Observer(MyTextBox) As "MyObserver"
-...
-Public Sub MyObserver_KeyPress()
-  Debug "Got it first"
-End
-
-Public Sub MyTextBox_KeyPress()
-  Debug "Got it next"
-End
- -

Наблюдатель может отменить событие с помощью Stop Event, чтобы не дать объекту эффективно -поднять его.

- - -[STRING] - -

Строки UTF-8

- -

Gambas использует кодировку UTF-8 для представления строк в памяти.

- -

Но все стандартные строковые функции имеют дело только с ASCII: -Left, Mid, Right, UCase...

- -

Если вы хотите работать со строками UTF-8, вы должны использовать методы -статического класса String, которые имеют то же имя, что и их стандартные аналоги.

- -
Print Len("bébé");; Left$("bébé", 3)
-→ 6 bé
-
-Print String.Len("bébé");; String.Left("bébé", 3)
-→ 4 béb
- - -[ASSIGNMENT] - -

Присваивания

- -

Gambas реализует ярлыки присваивания, к которым привыкли программисты C/C ++.

- -
MyVariable += 2
-MyVariable *= 4
-MyVariable &= "Great"
-является эквивалентом этого: -
MyVariable = MyVariable + 2
-MyVariable = MyVariable * 4
-MyVariable = MyVariable & "Great"
- -

И так далее...

- - -[DEBUG] - -

Отладка

- -

Вы можете использовать инструкцию Debug для вывода -сообщений отладки в консоль (то есть стандартный вывод ошибок). Она -ведёт себя так же, как инструкция Print.

- -

Эти сообщения имеют префикс имени класса, имени метода и номера строки -инструкции Debug. Если вам не нужен этот префикс, вы можете -использовать инструкцию Error -вместо Debug.

- -

Сообщения отладки автоматически удаляются при создании исполняемого файла -без отладочной информации.

- - -[TRY] - -

Управление ошибками (1)

- -

Управление ошибками в Gambas осуществляется с помощью следующих инструкций: -Try, Error, Catch и Finally.

- -

Try пытается выполнить инструкцию, не вызывая ошибки. Ключевое слово Error -используется только для того, чтобы узнать, правильно ли был выполнен оператор.

- -
Try MyFile = Open "/etc/password" For Write
-If Error Then Print "I cannot do what I want!"
- - -[CATCH] - -

Управление ошибками (2)

- -

Управление ошибками в Gambas осуществляется с помощью следующих инструкций: -Try, Error, Catch и Finally.

- -

Catch указывает начало части управления ошибками функции или процедуры. -Он ставится в конце кода функции.

- -

Часть catch выполняется при возникновении ошибки между началом -выполнения функции -и её концом.

- -

Если возникает ошибка во время выполнения части catch, она нормально распространяется.

- -
Sub ProcessFile(FileName As String)
-  ...
-  Open FileName For Read As #hFile
-  ...
-  Close #hFile
-  
-Catch ' Выполняется только в случае ошибки
-
-  Print "Cannot process file "; FileName
-
-End
- - -[FINALLY] - -

Управление ошибками (3)

- -

Управление ошибками в Gambas осуществляется с помощью следующих инструкций: -Try, Error, Catch и Finally.

- -

Finally представляет код, выполняемый в конце функции, даже если -во время её выполнения -возникла ошибка.

- -

Часть finally не является обязательной. Если в функции есть часть catch, то часть finally должна предшествовать ей.

- -

Если возникает ошибка во время выполнения части finally, она нормально распространяется.

- -
Sub ProcessFile(FileName As String)
-  ...
-  Open FileName For Read As #hFile
-  ...
-Finally ' Всегда выполняется, даже если возникла ошибка
-
-  Close #hFile
-  
-Catch ' Выполняется только в случае ошибки
-  
-  Print "Cannot print file "; FileName
-  
-End
- - -[OPTIONAL] - -

Опциональный

- -

Функции и процедуры в Gambas могут иметь опциональные аргументы.

- -

Опциональные аргументы можно сделать, просто указав ключевое слово -Optional непосредственно перед именем аргумента.

- -

Опциональные аргументы также могут иметь явное значение по умолчанию.

- -
Private Sub MyFunction(Param AS String, Optional Optim AS String = "Default")
-  ...
-  Print "Required: "; param; ", Optional: "; optim
-  ...
-End
- - -[ARRAY] - -

For Each

- -

В Gambas вы можете легко проходить через массив, коллекцию или -множество других перечисляемых классов с помощью инструкции For Each.

- -

Например:

- -
Dim Xml As New XmlDocument
-Dim Node As XmlNode
-Dim I As Integer
-
-' Открыть файл XML
-Xml.Open("pokus.xml")
-' Потомки индексируются через [i], так как это массив
-For I = 0 To Xml.Root.Children.Count - 1
-  'Атрибуты зацикливаются через For Each, так как это коллекция
-  For Each Node In Xml.Root.Children[i].Attributes
-    Print Node.Name;; Node.Value
-  Next
-Next
- - -[ICON] - -

Значки по умолчанию

- -

Вы можете использовать встроенные значки для более приятного графического -интерфейса вашего приложения, которые доступны в нескольких предопределённых -размерах («маленький/small», «средний/medium», «большой/large», ...) или абсолютных размерах (от 16x16 до 256x256).

- -

Например:

- -
Image1.Picture = Picture["icon:/32/warning"]
-Image2.Picture = Picture["icon:/small/error"]
- -

Предупреждение: требуется компонент gb.form.

- - -[SETTINGS] - -

Параметры

- -

Если вам нужно сохранить конфигурацию вашей программы (например, геометрию -ваших форм), то вы счастливчик. Это очень легко и элегантно в Gambas. :-)

- -

Чтобы сохранить положение формы:

-
Settings.Write(TheForm)
- -

Для того, чтобы вспомнить:

-
Settings.Read(TheForm)
- -Чтобы сохранить любые настройки: -
Settings["Slot/Key"] = Value
- -И прочитать настройки обратно: -
Value = Settings["Slot/Key", DefaultValue]
- -Эти настройки хранятся в файле ~/.config/gambas3/<MyApplication>.conf, -где <MyApplication> - это название вашего проекта. - -

Предупреждение: требуется компонент gb.settings.

- - -[EDITOR] - -

Вот несколько советов по редактору...

- -

Два типа комментариев

- -
' Нормальный комментарий
-
'' Жирный комментарий
- -

Жирные комментарии используются для документирования вашего кода.

- -

Как использовать фрагменты кода

- -

Давайте напечатаем main, затем нажмём клавишу TAB. Статическая -публичная функция запуска Main автоматически вставляется в ваш код.

- -

Давайте напечатаем ds, затем нажмём клавишу TAB. Объявление -локальной строковой переменной вставляется автоматически, и вы можете сразу же ввести имя переменной.

- -

Фрагменты кода полностью настраиваются в диалоговом окне «Предпочтения» меню «Инструменты» среды IDE.

- - -[END] - -

Это всё, друзья!

- -

Вы прочитали все полезные советы. Я надеюсь, что теперь вы -стали экспертом Gambas! :-)

- -

Если вы хотите внести свой вклад, отправьте новые советы по следующему -адресу:

-

user@lists.gambas-basic.org

- -

Заранее спасибо!

diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.ru.txt gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.ru.txt --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.ru.txt 1970-01-01 00:00:00.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.ru.txt 2021-09-14 19:01:29.000000000 +0000 @@ -0,0 +1,578 @@ +[WELCOME] + +

Добро пожаловать в Gambas!

+ +

Gambas - это графическая среда разработки, +основанная на продвинутом интерпретаторе Basic.

+ +

Цель Gambas - дать вам возможность легко и +быстро создавать мощные программы. Но чистые +программы остаются на вашей ответственности...

+ +

Наслаждайтесь!

+ +

Benoît Minisini
g4mba5@gmail.com


+ + +[STARTUP] + +

Класс запуска

+ +

Каждый проект должен иметь класс запуска. Этот класс +запуска должен определять статический открытый метод +с именем Main без аргументов, который будет действовать +как метод запуска вашей программы.

+ +

Вы можете определить класс запуска, щёлкнув по +нему правой кнопкой мыши в дереве проекта и +выбрав класс запуска во всплывающем меню.

+ +

Нет необходимости определять метод Main в форме +запуска, поскольку он уже имеет предопределённый метод.

+ +

Этот предопределённый метод запуска создаёт экземпляр формы и показывает её как в +Visual Basic™.

+ + +[OPEN] + +

Открыть

+ +

Инструкция Open в Gambas не работает +как в Visual Basic™. Она не возвращает файл как целое число, +а как объект File.

+ +

Итак, вместо того, чтобы написать:

+ +
Dim handle As Integer
+...
+Open "myfile" For Read As #handle
+ +

Вы должны написать:

+ +
Dim handle As File
+...
+handle = Open "myfile" For Read
+ + +[CATDIR] + +

Конкатенация путей

+ +

Знаете ли вы, что вы можете объединить имена директорий +и файлов с помощью оператора &/? Этот +оператор имеет дело с косыми чертами, так что получающийся +путь идеален.

+ +

Например:

+ +
Print "/home/gambas" &/ ".bashrc"
+→ /home/gambas/.bashrc
+
+Print "/home/gambas/" &/ "/tmp" &/ "foo.bar"
+→ /home/gambas/tmp/foo.bar
+ +

Разве это не чудесно?

+ + +[EXEC] + +

Исполняемый файл

+ +

Вы можете создать исполняемый файл из всего вашего проекта. +Выберите Создать исполняемый файл в меню Проект.

+ +

Когда Gambas создаёт исполняемый файл, он по +умолчанию помещает результат в директорию вашего проекта. +Имя исполняемого файла совпадает с именем вашего проекта.

+ + +[PATH] + +

Относительные пути

+ +

Относительные пути имеют особое значение в Gambas. +Они всегда ссылаются на файлы внутри ваших проектов.

+

Нет понятия текущей директории и нет ключевого слова, такого как CHDIR, чтобы изменить её.

+

Будьте осторожны: вы должны использовать относительные пути +только для доступа к файлам проекта, потому что абсолютные пути +больше не будут работать, когда вы создаёте исполняемый файл.

+ + +[GLOBAL] + +

Глобальные переменные

+ +В Gambas нет глобальных переменных! +

В качестве обходного пути, поместите их в свой основной модуль +и объявите их как Public.

+

Если у вас нет основного модуля main в вашем проекте, но +есть основная форма, то объявите их как Static Public.

+

Чтобы получить доступ к этим переменным, необходимо использовать +имя основного модуля main или форму: MyMainModule.MyGlobalVariable +или MyMainForm.MyGlobalVariable.

+ + +[EMPTY] + +

Пустые строки

+ +

Чтобы узнать, является ли строка пустой, нет необходимости использовать +функцию Len(). Вы можете непосредственно проверить это, +так как пустая строка - False, а непустая строка - True.

+ +

Например, вместо того, чтобы делать:

+ +
If Len(MyString) > 0 Then ...
+If Len(MyString) = 0 Then ...
+ +

Вы должны делать:

+ +
If MyString THEN ...
+If Not MyString THEN ...
+ + +[TRANSLATE] + +

Перевод

+ +

Приложения Gambas полностью переводимое, при условии, что вы +сообщаете ему, какие строки должны быть переведены, а какие нет.

+

Чтобы пометить строки как переводимые, просто заключите их в круглые скобки:

+ +
Print ("Translate me")
+Print "But do not translate me!"
+ + +[SUBST] + +

Subst$

+ +

Функция Subst$() очень полезна для интернационализации вашего приложения.

+ +

Требуется как минимум два аргумента. Первый - это текстовая маска, к которой применяется подстановка. +Другие являются аргументами замещения, пронумерованными от одного.

+ +

Каждый &X шаблон в строке замены будет заменён X-ым аргументом замены. +Например:

+ +
Print Subst(("Substitution of &1, &2 and &3"),
+  "first", "second", "third")
+
+→ Substitution of first, second and third
+ + +[EVENT] + +

Обработчики событий

+ +

Каждый элемент управления и каждый объект, который может вызывать +события, имеет наблюдателя событий и имя группы событий.

+ +

Наблюдатель событий перехватывает каждое событие, вызванное объектом, +а имя группы событий является префиксом процедуры, вызываемой для +управления событием. Эта функция называется обработчиком событий.

+ +

По умолчанию этот наблюдатель событий является объектом, в котором вы +создали элемент управления, а имя группы - это имя элемента управления.

+ +

Таким образом, форма получает все события, созданные +элементами управления, которые вы создали внутри.

+ +
' Gambas form
+Dim hButton As Button
+
+Public Sub _new()
+  hButton = New Button(Me) As "MyButton"
+End
+
+Public Sub MyButton_Click()
+  Print "You have clicked MyButton !"
+End
+ + +[GROUP] + +

Группы элементов управления

+ +

Каждый элемент управления имеет свойство (Group). Когда это +свойство установлено, префикс имени обработчика события - это +имя группы, а не имя элемента управления.

+ +

Предположим, у вас есть кнопка с именем btnAction со следующим обработчиком события Click:

+ +
Public SubbtnAction_Click()
+ +

Если вы установите свойство (Group) для btnAction +в значение "MyGroup", то обработчик событий, который будет +получать события от кнопки, будет выглядеть следующим образом:

+ +
Pubic Sub MyGroup_Click()
+ +

Это свойство позволяет обрабатывать события различных элементов +управления в одной функции. И элементы управления одной и той же +группы не обязательно должны быть одного типа!

+ +

Примечание: Старый ветеран Visual Basic™ может +распознавать концепцию управляющего массива, но в более мощной +реализации. :-)

+ + +[FORM] + +

Формы

+ +

В Gambas форма является собственным наблюдателем событий, +так что вы можете напрямую управлять её событиями (такими как +Resize, Activate, ...) в своём собственном коде класса.

+ +

Таким образом, новички из Visual Basic™ +не дезориентированы :-).

+ + +[EMBED] + +

Встраивание форм

+ +

Вы можете встроить любую форму в другие формы с Gambas!

+ +

Чтобы сделать такую мощную вещь, просто создайте экземпляр формы, +передав родительский контейнер в качестве последнего аргумента конструктора.

+ +

Например:

+
Dim hForm As MyDialog
+Dim hSuperControl As MyForm
+' Создать диалог
+hForm = New MyDialog
+' Вставьте форму в этот диалог
+' Обратите внимание, что эта форма принимает два параметра перед контейнером
+hSuperControl = New MyForm(Param1, Param2, MyDialog)
+' Переместить и изменить размер формы
+hSuperControl.Move(8, 8, 128, 64)
+ +

Будьте осторожны: форма, встроенная в другую форму, всё ещё является формой, как и её собственный наблюдатель событий.

+ + +[TAG] + +

Свойство тега

+ +

Каждый элемент управления имеет свойство Tag. Это свойство +предназначено для программиста и может содержать любые данные +Variant, которые вы считаете уместными.

+ +

Это очень полезно, когда вы хотите различить элементы управления +одной и той же группы в общем обработчике событий.

+ + +[LAST] + +

Последний

+ +

Ключевое слово Last возвращает последний элемент управления, +который получил событие. Это очень полезно, когда вы хотите написать +обработчик событий, который не зависит от имени элемента управления.

+ +

Например, предположим, что вы хотите написать калькулятор. +Вы определили десять кнопок, по одной для каждой цифры, каждая +в одной группе элементов управления "Digit". Tag каждого элемента +управления устанавливается на цифру, нарисованную на кнопке.

+ +

Ваш обработчик событий может выглядеть так:

+ +
Public Sub Digit_Click()
+
+  Display = Display & Last.Tag
+  RefreshDisplay
+END
+ + +[LEFT] + +

Left$ / Mid$ / Right$

+ +

Хорошо известные базовые процедуры Left$, Right$Mid$ имеют полезное поведение в Gambas

+ +

Второй параметр Left$ и Right$ является +опциональным и по умолчанию равен единице.

+ +

Left$("Gambas") возвращает "G"
Right$("Gambas") возвращает "s"

+ +

Этот второй параметр может быть отрицательным, а в таком случае +указывается количество символов, которые не нужно извлекать.

+ +

Left$("Gambas", -2) возвращает "Gamb"
Right$("Gambas", -2) возвращает "mbas"

+ +

Точно так же, третий аргумент Mid$ может быть +отрицательным, а в таком случае указывается количество символов +в конце строки, которые не нужно извлекать.

+ +

Mid$("Gambas", 2, -2) возвращает "amb"

+ + +[OBSERVER] + +

Наблюдатель

+ +

Класс Observer позволяет вам перехватывать все события, +вызванные объектом, до того, как они действительно будут отправлены.

+ +
MyTextBox = New TextBox(Me) As "MyTextBox"
+MyObserver = New Observer(MyTextBox) As "MyObserver"
+...
+Public Sub MyObserver_KeyPress()
+  Debug "Got it first"
+End
+
+Public Sub MyTextBox_KeyPress()
+  Debug "Got it next"
+End
+ +

Наблюдатель может отменить событие с помощью Stop Event, чтобы не дать объекту эффективно +поднять его.

+ + +[STRING] + +

Строки UTF-8

+ +

Gambas использует кодировку UTF-8 для представления строк в памяти.

+ +

Но все стандартные строковые функции имеют дело только с ASCII: +Left, Mid, Right, UCase...

+ +

Если вы хотите работать со строками UTF-8, вы должны использовать методы +статического класса String, которые имеют то же имя, что и их стандартные аналоги.

+ +
Print Len("bébé");; Left$("bébé", 3)
+→ 6 bé
+
+Print String.Len("bébé");; String.Left("bébé", 3)
+→ 4 béb
+ + +[ASSIGNMENT] + +

Присваивания

+ +

Gambas реализует ярлыки присваивания, к которым привыкли программисты C/C ++.

+ +
MyVariable += 2
+MyVariable *= 4
+MyVariable &= "Great"
+является эквивалентом этого: +
MyVariable = MyVariable + 2
+MyVariable = MyVariable * 4
+MyVariable = MyVariable & "Great"
+ +

И так далее...

+ + +[DEBUG] + +

Отладка

+ +

Вы можете использовать инструкцию Debug для вывода +сообщений отладки в консоль (то есть стандартный вывод ошибок). Она +ведёт себя так же, как инструкция Print.

+ +

Эти сообщения имеют префикс имени класса, имени метода и номера строки +инструкции Debug. Если вам не нужен этот префикс, вы можете +использовать инструкцию Error +вместо Debug.

+ +

Сообщения отладки автоматически удаляются при создании исполняемого файла +без отладочной информации.

+ + +[TRY] + +

Управление ошибками (1)

+ +

Управление ошибками в Gambas осуществляется с помощью следующих инструкций: +Try, Error, Catch и Finally.

+ +

Try пытается выполнить инструкцию, не вызывая ошибки. Ключевое слово Error +используется только для того, чтобы узнать, правильно ли был выполнен оператор.

+ +
Try MyFile = Open "/etc/password" For Write
+If Error Then Print "I cannot do what I want!"
+ + +[CATCH] + +

Управление ошибками (2)

+ +

Управление ошибками в Gambas осуществляется с помощью следующих инструкций: +Try, Error, Catch и Finally.

+ +

Catch указывает начало части управления ошибками функции или процедуры. +Он ставится в конце кода функции.

+ +

Часть catch выполняется при возникновении ошибки между началом +выполнения функции +и её концом.

+ +

Если возникает ошибка во время выполнения части catch, она нормально распространяется.

+ +
Sub ProcessFile(FileName As String)
+  ...
+  Open FileName For Read As #hFile
+  ...
+  Close #hFile
+  
+Catch ' Выполняется только в случае ошибки
+
+  Print "Cannot process file "; FileName
+
+End
+ + +[FINALLY] + +

Управление ошибками (3)

+ +

Управление ошибками в Gambas осуществляется с помощью следующих инструкций: +Try, Error, Catch и Finally.

+ +

Finally представляет код, выполняемый в конце функции, даже если +во время её выполнения +возникла ошибка.

+ +

Часть finally не является обязательной. Если в функции есть часть catch, то часть finally должна предшествовать ей.

+ +

Если возникает ошибка во время выполнения части finally, она нормально распространяется.

+ +
Sub ProcessFile(FileName As String)
+  ...
+  Open FileName For Read As #hFile
+  ...
+Finally ' Всегда выполняется, даже если возникла ошибка
+
+  Close #hFile
+  
+Catch ' Выполняется только в случае ошибки
+  
+  Print "Cannot print file "; FileName
+  
+End
+ + +[OPTIONAL] + +

Опциональный

+ +

Функции и процедуры в Gambas могут иметь опциональные аргументы.

+ +

Опциональные аргументы можно сделать, просто указав ключевое слово +Optional непосредственно перед именем аргумента.

+ +

Опциональные аргументы также могут иметь явное значение по умолчанию.

+ +
Private Sub MyFunction(Param AS String, Optional Optim AS String = "Default")
+  ...
+  Print "Required: "; param; ", Optional: "; optim
+  ...
+End
+ + +[ARRAY] + +

For Each

+ +

В Gambas вы можете легко проходить через массив, коллекцию или +множество других перечисляемых классов с помощью инструкции For Each.

+ +

Например:

+ +
Dim Xml As New XmlDocument
+Dim Node As XmlNode
+Dim I As Integer
+
+' Открыть файл XML
+Xml.Open("pokus.xml")
+' Потомки индексируются через [i], так как это массив
+For I = 0 To Xml.Root.Children.Count - 1
+  'Атрибуты зацикливаются через For Each, так как это коллекция
+  For Each Node In Xml.Root.Children[i].Attributes
+    Print Node.Name;; Node.Value
+  Next
+Next
+ + +[ICON] + +

Значки по умолчанию

+ +

Вы можете использовать встроенные значки для более приятного графического +интерфейса вашего приложения, которые доступны в нескольких предопределённых +размерах («маленький/small», «средний/medium», «большой/large», ...) или абсолютных размерах (от 16x16 до 256x256).

+ +

Например:

+ +
Image1.Picture = Picture["icon:/32/warning"]
+Image2.Picture = Picture["icon:/small/error"]
+ +

Предупреждение: требуется компонент gb.form.

+ + +[SETTINGS] + +

Параметры

+ +

Если вам нужно сохранить конфигурацию вашей программы (например, геометрию +ваших форм), то вы счастливчик. Это очень легко и элегантно в Gambas. :-)

+ +

Чтобы сохранить положение формы:

+
Settings.Write(TheForm)
+ +

Для того, чтобы вспомнить:

+
Settings.Read(TheForm)
+ +Чтобы сохранить любые настройки: +
Settings["Slot/Key"] = Value
+ +И прочитать настройки обратно: +
Value = Settings["Slot/Key", DefaultValue]
+ +Эти настройки хранятся в файле ~/.config/gambas3/<MyApplication>.conf, +где <MyApplication> - это название вашего проекта. + +

Предупреждение: требуется компонент gb.settings.

+ + +[EDITOR] + +

Вот несколько советов по редактору...

+ +

Два типа комментариев

+ +
' Нормальный комментарий
+
'' Жирный комментарий
+ +

Жирные комментарии используются для документирования вашего кода.

+ +

Как использовать фрагменты кода

+ +

Давайте напечатаем main, затем нажмём клавишу TAB. Статическая +публичная функция запуска Main автоматически вставляется в ваш код.

+ +

Давайте напечатаем ds, затем нажмём клавишу TAB. Объявление +локальной строковой переменной вставляется автоматически, и вы можете сразу же ввести имя переменной.

+ +

Фрагменты кода полностью настраиваются в диалоговом окне «Предпочтения» меню «Инструменты» среды IDE.

+ + +[END] + +

Это всё, друзья!

+ +

Вы прочитали все полезные советы. Я надеюсь, что теперь вы +стали экспертом Gambas! :-)

+ +

Если вы хотите внести свой вклад, отправьте новые советы по следующему +адресу:

+

user@lists.gambas-basic.org

+ +

Заранее спасибо!

diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.sl gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.sl --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.sl 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.sl 1970-01-01 00:00:00.000000000 +0000 @@ -1,236 +0,0 @@ -[WELCOME] - -

Dobrodošli v Gambas!

- -

Gambas je grafično razvojno okolje -temelječe na Basic interpreterju.

- -

Cilj Gambasa je omogočiti uporabniku hitro in -enostavno izdelavo zmogljivih programov. Čista in lepa koda seveda -ostaja tvoja odgovornost...

- -

Uživaj!

- -

Benoît Minisini
-g4mba5@gmail.com

- - -[STARTUP] - -

Vsak program mora imeti zagonski razred. V njem mora biti -določena javna metoda z imenom Main brez argumentov, ki bo -služila kot zagonska metoda programa.

- -

Zagonski razred lahko določiš z desnim klikom na razred v drevesu projekta -in nato v meniju izbereš Zagonski razred.

- -

Določitev metode Main v zagonski formi ni nujna, ker je ta metoda že vnaprej določena.

- -

Ta vnaprej določena metoda instancira in prikaže formo, prav kakor v -Visual Basicu™.

- - -[EXEC] - -

Iz celotnega projekta lahko izdelaš izvršljivo datoteko. V meniju -Projekt izberi Izdelaj izvršljivo datoteko.

- -

Gambas bo izdelal izvršlivo datoteko in jo zapisal v mapo, kjer je shranjen projekt. -Izvršljiva datoteka ima enako ime kot projekt.

- -[PATH] -

-Relativne poti imajo v Gambasu poseben pomen. -Vedno se nanašajo na datoteke znotraj projektov. -

-Koncepta trenutne mape ni, kot tudi ni ključne besede CHDIR za njeno spreminjanje. -

-Pozor: relativne poti uporabljaj samo za dostop do datotek projekta, ker absolutne poti ne bodo več delovale, ko bo izdelana izvršljiva datoteka. - - -[GLOBAL] - -V Gambasu ni globalnih spremenljivk! -

-To lahko obideš tako, da spremenljivke najaviš v glavnem modulu kot PUBLIC. -

-Če projekt nima glavnega modula, ima pa glavno formo, jih najavi tam kot STATIC PUBLIC. -

-Za dostopanje do takšnih spremenljivk moraš uporabiti ime modula ali forme: MojGlavniModule.MojaGlobalnaSpremenljivka ali -MojaGlavnaForma.MojaGlobalnaSpremenljivka. - - -[OPEN] - -

Ukaz OPEN v Gambasu ne deluje popolnoma enako kot v Visual Basicu, -ker ne vrača vrednosti tipa integer, ampak objekt tipa File.

- -

Tako je treba namesto

- -
DIM handle AS Integer
-...
-OPEN "mojaDatoteka" FOR READ AS #handle
- -

napisati

- -
DIM handle AS File
-...
-handle = OPEN "mojaDatoteka" FOR READ
- - -[CATDIR] - -

Ali veš, da lahko združuješ imena map z operatorjem &/? - Ta operator poskrbi za vodilne in sledilne poševnice tako, da je sestavljena pot vedno pravilna.

- -

Na primer:

- -
PRINT "/home/gambas" &/ ".bashrc"
-/home/gambas/.bashrc
-
-PRINT "/home/gambas/" &/ "/tmp" &/ "foo.bar"
-/home/gambas/tmp/foo.bar
-
- -

Lepo, ne?

- - -[EMPTY] - -

Za ugotavljanje ali je niz prazen, ni treba uporabiti funkcije Len(). -Ali je niz prazen, lahko preveriš neposredno, saj prazen niz vrne FALSE, neprazen pa TRUE.

- -

Namesto

- -
IF Len(mojNiz) > 0 THEN ...
-IF Len(mojNiz) = 0 THEN ...
- -

je tako bolje napisati

- -
IF mojNiz THEN ...
-IF NOT mojNiz THEN ...
- - -[EVENT] - -

Vsaka kontrola in vsak objekt, ki lahko sproža dogodke ima svoj -prestreznik dogodkov (event observer) in svoje ime skupine dogodkov (event group name).

- -

Prestreznik dogodkov prestreže vsak dogodek, ki ga sproži objekt, ime skupine dogodkov pa je predpona procedure, ki jo kličemo za upravljanje dogodka.

- -

Privzeto je, da je prestreznik dogodkov objekt, ki vsebuje kontrolo, ime skupine dogodkov pa je enako imenu kontrole.

- -

Na ta način lahko npr. forma prestreže vse dogodke, ki jih sprožijo kontrole na njej.

- -
' Gambas forma
-DIM hButton AS Button
-
-PUBLIC SUB _new()
-  hButton = NEW Button(ME) AS "MyButton"
-END
-
-PUBLIC SUB MyButton_Click()
-  PRINT "MyButton pritisnjen!"
-END
-
- - -[FORM] - -

V Gambasu predstavlja forma svoj lastni prestreznik dogodkov. Tako je možno neposredno upravljanje njenih dogodkov (kot so Resize, Activate itd.) v kodi njenega razreda.

- -

Tako se pribežniki iz Visual Basica ne počutijo izgubljene. :-)

- - -[EMBED] - -

V Gambasu je možno katerokoli formo vstaviti v druge forme. 

- -

Za izvedbo tega je treba instancirati formo tako, da ji podamo nadvsebnik kot zadnji argument konstruktorja.

- -

Na primer: 

-

DIM hForm AS MyDialog
-DIM hSuperControl AS MyForm

-' Ustvarimo pogovorno okno
-hForm = NEW MyDialog
-' Vstavimo formo v to pogovorno okno
-' (Forma ima pred vsebnikom še dva druga parametra)
-hSuperControl = NEW MyForm(Param1, Param2, MyDialog)
-' Premaknimo in razvlečimo formo
-hSuperControl.Move(8, 8, 128, 64)
-

- -

Pozor! Forma, vstavljena v drugo formo, je še vedno forma in je zato tudi svoj lastni prestreznik dogodkov.

- - -[GROUP] - -

Vsaka kontrola ima lastnost (Group). Ko nastavimo to lastnost, je predpona upravljalca dogodkov ime skupine in ne več ime kontrole.

- -

Imejmo na primer gumb z imenom btnAction -z naslednjim upravljalcem dogodka Click:

- -
PUBLIC SUB btnAction_Click()
- -

Če postavimo lastnost (Group) kontrole btnAction na -MyGroup, bo upravljalec dogodkov, ki bo sprejemal dogodke z našega gumba naslednji:

- -
PUBLIC SUB MyGroup_Click()
- -

Ta lastnost omogoča upravljanje dogodkov z različnih kontrol v eni sami funkciji. Pri tem ni treba, da so kontrole istega tipa.

- -

Opomba: Izkušeni Visual Basic veteran bo omenjeno prepoznal kot koncept polja kontrol (control array), vendar v mnogo močnejši izvedbi. :-)

- - -[TAG] - -

Vsaka kontrola ima lastnost Tag. Ta lastnost je namenjena programerju in lahko vsebuje kakršenkoli podatek tipa VARIANT, ki je pomemben za program.

- -

To je zelo uporabno, kadar je treba razlikovati kontrole znotraj skupine pri uporabi skupnega upravljalca dogodkov.

- - - -[LAST] - -

Ključna beseda LAST vrne zadnjo kontrolo, ki je prejela dogodek. -To je zelo uporabno, kadar želimo napisati upravljalca dogodkov, ki naj bo neodvisen od imena kontrole.

- -

Vzemimo, da želimo izdelati kalkulator. Določimo deset gumbov, svojega za vsako številko, in jim določimo skupino "Digit". Lastnost Tag za vsak gumb je številka, napisana na njem. Upravljalec dogodka za takšno skupino gumbov je tedaj lahko videti takole:

- -

PUBLIC SUB Digit_Click()

-  Display = Display & LAST.Tag
-  RefreshDisplay

-END

- - -[LEFT] - -

Dobro znane BASIC funkcije Left$, Right$ -in Mid$ imajo v Gambasu dodatno uporabnost.

- -

Drugi parameter pri Left$ in Right$ je neobvezen in ima privzeto vrednost 1:

- -

Left$("Gambas") vrne "G"
-Right$("Gambas") vrne "s"

- -

Drugi parameter ima lahko negativno vrednost. Tedaj predstavlja število znakov, ki naj jih funkcija ne vrne:

- -

Left$("Gambas", -2) vrne "Gamb"
-Right$("Gambas", -2) vrne "mbas"

- -

Negativen je lahko tudi tretji argument pri Mid$. Tedaj podaja število znakov s konca niza, ki naj jih funkcija ne vrne:

- -

Mid$("Gambas", 2, -2) vrne "amb" - - -[END] - -

Tukaj se Nasveti dneva končajo. Upam, da si po njihovem branju izvedenec za Gambas! :-)

- -

Če želiš prispevati, pošlji nove nasvete na naslov: 

-

g4mba5@gmail.com

- -

Hvala v naprej!

- - - diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.sl.txt gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.sl.txt --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.sl.txt 1970-01-01 00:00:00.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.sl.txt 2021-09-14 19:01:29.000000000 +0000 @@ -0,0 +1,236 @@ +[WELCOME] + +

Dobrodošli v Gambas!

+ +

Gambas je grafično razvojno okolje +temelječe na Basic interpreterju.

+ +

Cilj Gambasa je omogočiti uporabniku hitro in +enostavno izdelavo zmogljivih programov. Čista in lepa koda seveda +ostaja tvoja odgovornost...

+ +

Uživaj!

+ +

Benoît Minisini
+g4mba5@gmail.com

+ + +[STARTUP] + +

Vsak program mora imeti zagonski razred. V njem mora biti +določena javna metoda z imenom Main brez argumentov, ki bo +služila kot zagonska metoda programa.

+ +

Zagonski razred lahko določiš z desnim klikom na razred v drevesu projekta +in nato v meniju izbereš Zagonski razred.

+ +

Določitev metode Main v zagonski formi ni nujna, ker je ta metoda že vnaprej določena.

+ +

Ta vnaprej določena metoda instancira in prikaže formo, prav kakor v +Visual Basicu™.

+ + +[EXEC] + +

Iz celotnega projekta lahko izdelaš izvršljivo datoteko. V meniju +Projekt izberi Izdelaj izvršljivo datoteko.

+ +

Gambas bo izdelal izvršlivo datoteko in jo zapisal v mapo, kjer je shranjen projekt. +Izvršljiva datoteka ima enako ime kot projekt.

+ +[PATH] +

+Relativne poti imajo v Gambasu poseben pomen. +Vedno se nanašajo na datoteke znotraj projektov. +

+Koncepta trenutne mape ni, kot tudi ni ključne besede CHDIR za njeno spreminjanje. +

+Pozor: relativne poti uporabljaj samo za dostop do datotek projekta, ker absolutne poti ne bodo več delovale, ko bo izdelana izvršljiva datoteka. + + +[GLOBAL] + +V Gambasu ni globalnih spremenljivk! +

+To lahko obideš tako, da spremenljivke najaviš v glavnem modulu kot PUBLIC. +

+Če projekt nima glavnega modula, ima pa glavno formo, jih najavi tam kot STATIC PUBLIC. +

+Za dostopanje do takšnih spremenljivk moraš uporabiti ime modula ali forme: MojGlavniModule.MojaGlobalnaSpremenljivka ali +MojaGlavnaForma.MojaGlobalnaSpremenljivka. + + +[OPEN] + +

Ukaz OPEN v Gambasu ne deluje popolnoma enako kot v Visual Basicu, +ker ne vrača vrednosti tipa integer, ampak objekt tipa File.

+ +

Tako je treba namesto

+ +
DIM handle AS Integer
+...
+OPEN "mojaDatoteka" FOR READ AS #handle
+ +

napisati

+ +
DIM handle AS File
+...
+handle = OPEN "mojaDatoteka" FOR READ
+ + +[CATDIR] + +

Ali veš, da lahko združuješ imena map z operatorjem &/? + Ta operator poskrbi za vodilne in sledilne poševnice tako, da je sestavljena pot vedno pravilna.

+ +

Na primer:

+ +
PRINT "/home/gambas" &/ ".bashrc"
+/home/gambas/.bashrc
+
+PRINT "/home/gambas/" &/ "/tmp" &/ "foo.bar"
+/home/gambas/tmp/foo.bar
+
+ +

Lepo, ne?

+ + +[EMPTY] + +

Za ugotavljanje ali je niz prazen, ni treba uporabiti funkcije Len(). +Ali je niz prazen, lahko preveriš neposredno, saj prazen niz vrne FALSE, neprazen pa TRUE.

+ +

Namesto

+ +
IF Len(mojNiz) > 0 THEN ...
+IF Len(mojNiz) = 0 THEN ...
+ +

je tako bolje napisati

+ +
IF mojNiz THEN ...
+IF NOT mojNiz THEN ...
+ + +[EVENT] + +

Vsaka kontrola in vsak objekt, ki lahko sproža dogodke ima svoj +prestreznik dogodkov (event observer) in svoje ime skupine dogodkov (event group name).

+ +

Prestreznik dogodkov prestreže vsak dogodek, ki ga sproži objekt, ime skupine dogodkov pa je predpona procedure, ki jo kličemo za upravljanje dogodka.

+ +

Privzeto je, da je prestreznik dogodkov objekt, ki vsebuje kontrolo, ime skupine dogodkov pa je enako imenu kontrole.

+ +

Na ta način lahko npr. forma prestreže vse dogodke, ki jih sprožijo kontrole na njej.

+ +
' Gambas forma
+DIM hButton AS Button
+
+PUBLIC SUB _new()
+  hButton = NEW Button(ME) AS "MyButton"
+END
+
+PUBLIC SUB MyButton_Click()
+  PRINT "MyButton pritisnjen!"
+END
+
+ + +[FORM] + +

V Gambasu predstavlja forma svoj lastni prestreznik dogodkov. Tako je možno neposredno upravljanje njenih dogodkov (kot so Resize, Activate itd.) v kodi njenega razreda.

+ +

Tako se pribežniki iz Visual Basica ne počutijo izgubljene. :-)

+ + +[EMBED] + +

V Gambasu je možno katerokoli formo vstaviti v druge forme. 

+ +

Za izvedbo tega je treba instancirati formo tako, da ji podamo nadvsebnik kot zadnji argument konstruktorja.

+ +

Na primer: 

+

DIM hForm AS MyDialog
+DIM hSuperControl AS MyForm

+' Ustvarimo pogovorno okno
+hForm = NEW MyDialog
+' Vstavimo formo v to pogovorno okno
+' (Forma ima pred vsebnikom še dva druga parametra)
+hSuperControl = NEW MyForm(Param1, Param2, MyDialog)
+' Premaknimo in razvlečimo formo
+hSuperControl.Move(8, 8, 128, 64)
+

+ +

Pozor! Forma, vstavljena v drugo formo, je še vedno forma in je zato tudi svoj lastni prestreznik dogodkov.

+ + +[GROUP] + +

Vsaka kontrola ima lastnost (Group). Ko nastavimo to lastnost, je predpona upravljalca dogodkov ime skupine in ne več ime kontrole.

+ +

Imejmo na primer gumb z imenom btnAction +z naslednjim upravljalcem dogodka Click:

+ +
PUBLIC SUB btnAction_Click()
+ +

Če postavimo lastnost (Group) kontrole btnAction na +MyGroup, bo upravljalec dogodkov, ki bo sprejemal dogodke z našega gumba naslednji:

+ +
PUBLIC SUB MyGroup_Click()
+ +

Ta lastnost omogoča upravljanje dogodkov z različnih kontrol v eni sami funkciji. Pri tem ni treba, da so kontrole istega tipa.

+ +

Opomba: Izkušeni Visual Basic veteran bo omenjeno prepoznal kot koncept polja kontrol (control array), vendar v mnogo močnejši izvedbi. :-)

+ + +[TAG] + +

Vsaka kontrola ima lastnost Tag. Ta lastnost je namenjena programerju in lahko vsebuje kakršenkoli podatek tipa VARIANT, ki je pomemben za program.

+ +

To je zelo uporabno, kadar je treba razlikovati kontrole znotraj skupine pri uporabi skupnega upravljalca dogodkov.

+ + + +[LAST] + +

Ključna beseda LAST vrne zadnjo kontrolo, ki je prejela dogodek. +To je zelo uporabno, kadar želimo napisati upravljalca dogodkov, ki naj bo neodvisen od imena kontrole.

+ +

Vzemimo, da želimo izdelati kalkulator. Določimo deset gumbov, svojega za vsako številko, in jim določimo skupino "Digit". Lastnost Tag za vsak gumb je številka, napisana na njem. Upravljalec dogodka za takšno skupino gumbov je tedaj lahko videti takole:

+ +

PUBLIC SUB Digit_Click()

+  Display = Display & LAST.Tag
+  RefreshDisplay

+END

+ + +[LEFT] + +

Dobro znane BASIC funkcije Left$, Right$ +in Mid$ imajo v Gambasu dodatno uporabnost.

+ +

Drugi parameter pri Left$ in Right$ je neobvezen in ima privzeto vrednost 1:

+ +

Left$("Gambas") vrne "G"
+Right$("Gambas") vrne "s"

+ +

Drugi parameter ima lahko negativno vrednost. Tedaj predstavlja število znakov, ki naj jih funkcija ne vrne:

+ +

Left$("Gambas", -2) vrne "Gamb"
+Right$("Gambas", -2) vrne "mbas"

+ +

Negativen je lahko tudi tretji argument pri Mid$. Tedaj podaja število znakov s konca niza, ki naj jih funkcija ne vrne:

+ +

Mid$("Gambas", 2, -2) vrne "amb" + + +[END] + +

Tukaj se Nasveti dneva končajo. Upam, da si po njihovem branju izvedenec za Gambas! :-)

+ +

Če želiš prispevati, pošlji nove nasvete na naslov: 

+

g4mba5@gmail.com

+ +

Hvala v naprej!

+ + + diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.sv gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.sv --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.sv 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.sv 1970-01-01 00:00:00.000000000 +0000 @@ -1,401 +0,0 @@ -[WELCOME] - -

Välkommen till Gambas !

- -

Gambas är en grafiskt utvecklingsmiljö -grundad på en avancerad Basic interpretator.

- -

Gambas mål är att få dig att göra -kraftfulla program, enkelt och snabbt. Men rena strukturerade -program är ditt eget ansvar...

- -

Lycka till!

- -

Benoît Minisini
-g4mba5@gmail.com

- - -[STARTUP] - -

Varje projekt måste ha en startup class. Denna -startup-class måste definiera en statisk publik metod kallad Main -utan argument, som kommer att fungera som uppstartmetod för -ditt program.

- -

Du kan definiera startup-classen genom att klicka på den med -höger musknapp i projektträdet och genom att välja -Startup class i popup-menyn.

- -

Det är inte nödvändigt att definiera en Main-metod i ett startupp- -formulär, ty det har redan en fördefinierad sådan.

- -

Denna fördefinierade uppstartmetod instansierar formuläret och visar det, -som i Visual Basic™.

- - -[OPEN] - -

OPEN-instruktionen i Gambas fungerar inte på -samma sätt som den i Visual Basic. Den lämnar inte filen, -som ett heltal, utan som ett File-objekt.

- -

Så i stället för att skriva:

- -
DIM handle AS Integer
-...
-OPEN "myfile" FOR READ AS #handle
- -

måste du skriva:

- -
DIM handle AS File
-...
-handle = OPEN "myfile" FOR READ
- - -[CATDIR] - -

Vet du att du kan slå ihop mappnamn och -filnamn med &/-operatorn? Denna operator -tar hand om avslutande snedstreck "/" så att den resulterande sökvägen -blir perfekt.

- -

Till exempel:

- -
PRINT "/home/gambas" &/ ".bashrc"
-/home/gambas/.bashrc
-
-PRINT "/home/gambas/" &/ "/tmp" &/ "foo.bar"
-/home/gambas/tmp/foo.bar
-
- -

Är det inte förunderligt?

- - -[EXEC] - -

Du kan göra en körbar fil utgående från ditt hela projekt. Välj -Gör exekverbar i Projekt-menyn.

- -

När Gambas gör en körbar fil, läggs -resultatet i din projektmapp som standard. -Den körbara filen får samma namn som ditt projekt.

- - -[PATH] -

-Relativa sökvägar har speciell betydelse i Gambas. -De refererar alltid till filer inuti ditt projekt. -

-Det finns ingen innebörd i current directory och inget nyckelord som -CHDIR att ändra det. -

-Var försiktig: du måste använda relativ sökväg endast för att komma åt -projektfiler, ty absoluta sökvägar fungerar inte längre, när du gör en körbar fil. - - -[GLOBAL] - -Det finns inga globala variabler i Gambas! -

-Ett sätt att kringgå detta är att placera dem i din huvud/main-modul -och deklarera dem som PUBLIC. -

-Om du inte har en huvud/main-modul i ditt projekt, men ett huvud/main- -formulär, deklarera dem som STATIC PUBLIC. -

-För att komma åt dessa variabler, måste du använda namnet på huvudmodulen -eller huvudformuläret: MinMainModul.MinGlobalaVariabel or -MinMainForm.MinGlobalaVariabel. - - -[EMPTY] - -

För att veta om en sträng är tom, är det inte nödvändigt att använda -Len()-funktionen. Du kan testa den direkt, eftersom en tom sträng -är FALSE och en icke-tom sträng är TRUE.

- -

Till exempel, i stället för att göra:

- -
IF Len(MyString) > 0 THEN ...
-IF Len(MyString) = 0 THEN ...
- -

Bör du göra:

- -
IF MyString THEN ...
-IF NOT MyString THEN ...
- - -[TRANSLATE] - -

Gambastillämpningar är helt och hållet översättningsbara, förutsatt att du -talar om vilka strängar som skall översättas.

-

För att markera att en sträng är översättningsbar, så sätt den bara inom parantester:

- -

PRINT ("Översätt mig")
-PRINT "Men inte mig!"
- -[EVENT] - -

Varje kontroll och varje objekt, som kan ge avbrott, har en -avbrottshanterare och ett avbrotts-group name.

- -

Avbrottshanteraren fångar varje avbrott åstadkommet av objektet och -avbrottsgruppnamnet är prefix för den procedur, som anropas för att hantera -avbrottet.

- -

Som standard är denna avbrottshanterare det objekt där du har -skapat kontrollen och gruppnamnet är samma som kontrollens.

- -

På detta sätt får ett formulär mottaga alla avbrott som åstadkommits -av de kontroller du skapade inuti.

- -
' Gambas form
-DIM hButton AS Button
-
-PUBLIC SUB _new()
-  hButton = NEW Button(ME) AS "MyButton"
-END
-
-PUBLIC SUB MyButton_Click()
-  PRINT "You have clicked MyButton !"
-END
-
- - -[FORM] - -

I Gambas är ett formulär sin egen avbrottshanterare, så att -du direkt kan hantera dess avbrott (som Resize, -Activate, ...) in till dess egen klasskod.

- -

På detta sätt blir nybörjare, som kommer från Visual Basic inte -disorienterade :-).

- - -[EMBED] - -

Du kan inbädda vilket formulär som helst i andra formulär med Gambas - !

- -

För att åstadkomma en så kraftfull sak, bara instanciera formuläret genom att skicka -ett förälderbehållare (parent container) som sista argument hos konstruktorn (contructor).

- -

Till exempel :

-

DIM hForm AS MyDialog
-DIM hSuperControl AS MyForm

-' Skapa en dialog
-hForm = NEW MyDialog
-' Tag in ett formulär i denna dialog
-' Notera att detta formulär tar två parametrar före behållaren (container)
-hSuperControl = NEW MyForm(Param1, Param2, MyDialog)
-' Flytta och justera storlek på formuläret
-hSuperControl.Move(8, 8, 128, 64)
-

- -

Var uppmärksam: ett formulär inbäddat i ett annat är fortfarande ett formulär och -dessutom sin egen avbrottshanterare.

- - -[GROUP] - -

Varje kontroll har en (Group)-egenskap. När denna egenskap -sätts, är prefixet för avbrottshanterarens namn, namnet på gruppen -och inte namnet på kontrollen.

- -

Låt oss anta att vi har en Knapp kallad btnAction -med följande Click avbrottshanterare:

- -
PUBLIC SUB btnAction_Click()
- -

Om du sätter (Group)-egenskapen hos btnAction till -MyGroup, så kommer avbrotsshanteraren att mottaga avbrott från -knappen att se ut som:

- -
PUBLIC SUB MyGroup_Click()
- -

Denna egenskap låter dig hantera avbrott från skilda kontroller med -en enkel funktion och kontrollerna i samma grupp behöver inte ha samma typ!

- -

Notera : Den gamle Visual Basic-veteranen kan kanske känna igen -konceptet i kontroll array, men i en kraftfullare implementering. :-)

- - -[TAG] - -

Varje kontroll har en Tag-egenskap. Denna är till för -programmeraren och kan innehålla vilken VARIANT-data som du tycker är relevant.

- -

Detta är mycket användbart, när du vill åtskilja kontroller i -samma grupp i en gemensam avbrottshanterare.

- - - -[LAST] - -

Nyckelordet LAST returnerar den sista kontroll, som -har mottagit ett avbrott. Detta är mycket användbart om du vill skriva en -avbrottshanterare, som är oberoende av namn på kontroller.

- -

Till exempel, låt oss anta du vill skriva ett kalkylatorprogram. -Du har definierat tio knappar, en för varje siffra, var och en i -samma group "Digit". Tag-en för varje kontroll sätts till -siffran ritad i knappen. Din avbrottshanterare skulle kunna se ut som:

- -

PUBLIC SUB Digit_Click()

-  Display = Display & LAST.Tag
-  RefreshDisplay

-END

- - -[LEFT] - -

De välkända BASIC rutinerna Left$, Right$ -och Mid$ har användbara uppträdande i Gambas

- -

Andra parametern i Left$ och Right$ är -frivillig och sätts till ett som standard.

- -

Left$("Gambas") returnerar "G"
-Right$("Gambas") returnerar "s"

- -

Andra parametern kan vara negativ och betyder då antal -tecken som ej skall tas ut.

- -

Left$("Gambas", -2) returnerar "Gamb"
-Right$("Gambas", -2) returnerar "mbas"

- -

På samma sätt med tredje argumentet till Mid$ kan vara negativt och -ger då antal tecken från slutet på strängen som ej skall tas ut.

- -

Mid$("Gambas", 2, -2) returnerar "amb" - -[OBSERVER] - -

Observer-klassen tillåter dig att fånga upp alla händelser skapade -av ett objekt innan de verkligen sänds.

- -
MyTextBox = NEW TextBox(ME) AS "MyTextBox"
-MyObserver = NEW Observer(MyTextBox) AS "MyObserver"
-...
-PUBLIC SUB MyObserver_KeyPress()
-  DEBUG "Got it first"
-END
-
-PUBLIC SUB MyTextBox_KeyPress()
-  DEBUG "Got it next"
-END
- -"Observatören" kan avbryta händelsen för att förhindra att objektet att åstadkommer den (händelsen). - - -[STRING] - -

Gambas använder UTF-8-teckensätt för att representera strängar i minnet.

- -

Men alla Gambas standardsträngfunktioner hanterar ASCII: -Left, Mid, Right, UCase... - -

Om du vill manipulera UTF-8-strängar, måste du använda metoder hörande till -String-static klass, vilka har samma namn som deras motsvarande standard. - -

PRINT Len("bébé");; Left$("bébé", 3)
-6 bé
-PRINT String.Len("bébé");; String.Left("bébé", 3)
-4 béb
- - -[ASSIGNMENT] - -

Gambas implementerar förenklad tilldelning, som C/C++ programmerare är vana vid. - -

MyVariable += 2 är samma sak som MyVariable = MyVariable + 2 - -

MyVariable &= "Great" är samma sak som MyVariable = MyVariable & "Great" - -

och så vidare... - - -[DEBUG] - -

Du kan använda DEBUG-instruktionen till att skriva ut avlusningsmeddelandem -till konsolen (nämligen standard error output). Den uppför sig precis som PRINT- -instruktionen. - -

Dessa meddelanden föregås av klassnamn, metodnamn och radnummer för -DEBUG-instruktionen. - -

Debugmeddelandena tas automatiskt bort när en exekverbar fil -utan avlusningsinformation görs. - - -[TRY] - -

Felhantering i Gambas görs med följande instruktioner: -TRY, ERROR, CATCH och FINALLY. - -

TRY försöker utföra en sats utan att åstadkomma ett fel. ERROR- -instruktionen används just för att ta reda på om satsen utfördes korrekt. - -

TRY MyFile = OPEN "/etc/password" FOR WRITE
-IF ERROR THEN PRINT "I cannot do what I want!"
- - -[CATCH] - -

Felhantering i Gambas görs med följande instruktioner: -TRY, ERROR, CATCH och FINALLY. - -

CATCH utvisar början på felhanteringsdelen i en funktion eller procedur. -Den placeras i slutet på funktionskoden. - -

Catch-delen utförs när ett fel har åstadkommits mellan början på funktionen och dess slut. - - -

Om ett fel inträffar under utförande av catch-delen, fångas den. - -

SUB ProcessFile(FileName AS STRING)
-  ...
-  OPEN FileName FOR READ AS #hFile
-  ...
-  CLOSE #hFile
-CATCH ' Utförs endast om det finns ett fel
-  PRINT "Cannot process file "; FileName
-END
- - -[FINALLY] - -

Felhantering i Gambas görs med följande instruktioner: -TRY, ERROR, CATCH och FINALLY. - -

FINALLY inleder den kod, som utförs vid slutet av funktionen, även om ett fel åstadkomms under funktionsutförandet. - -

Finally-delen är inte obligatorisk. Om det finns en catch-del, så måste finally-delen föregå den. - -

Om ett fel inträffar under utförande av finally-delen, fortsättes normalt. - -

SUB ProcessFile(FileName AS STRING)
-  ...
-  OPEN FileName FOR READ AS #hFile
-  ...
-FINALLY ' Utförs alltid, även om fel inträffat
-  CLOSE #hFile
-CATCH ' Utförs endast om fel inträffat
-  PRINT "Cannot print file "; FileName
-END
- - - -[END] - -

Du har nu lästa alla Dagens Tips. Hoppas att du blivit -en Gambas-expert nu! :-)

- -

Om du vill bidraga, sänd nya tips till följande -adress :

-

g4mba5@gmail.com

- -

Tack på förhand!

- - - diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.sv.txt gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.sv.txt --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.sv.txt 1970-01-01 00:00:00.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.sv.txt 2021-09-14 19:01:29.000000000 +0000 @@ -0,0 +1,401 @@ +[WELCOME] + +

Välkommen till Gambas !

+ +

Gambas är en grafiskt utvecklingsmiljö +grundad på en avancerad Basic interpretator.

+ +

Gambas mål är att få dig att göra +kraftfulla program, enkelt och snabbt. Men rena strukturerade +program är ditt eget ansvar...

+ +

Lycka till!

+ +

Benoît Minisini
+g4mba5@gmail.com

+ + +[STARTUP] + +

Varje projekt måste ha en startup class. Denna +startup-class måste definiera en statisk publik metod kallad Main +utan argument, som kommer att fungera som uppstartmetod för +ditt program.

+ +

Du kan definiera startup-classen genom att klicka på den med +höger musknapp i projektträdet och genom att välja +Startup class i popup-menyn.

+ +

Det är inte nödvändigt att definiera en Main-metod i ett startupp- +formulär, ty det har redan en fördefinierad sådan.

+ +

Denna fördefinierade uppstartmetod instansierar formuläret och visar det, +som i Visual Basic™.

+ + +[OPEN] + +

OPEN-instruktionen i Gambas fungerar inte på +samma sätt som den i Visual Basic. Den lämnar inte filen, +som ett heltal, utan som ett File-objekt.

+ +

Så i stället för att skriva:

+ +
DIM handle AS Integer
+...
+OPEN "myfile" FOR READ AS #handle
+ +

måste du skriva:

+ +
DIM handle AS File
+...
+handle = OPEN "myfile" FOR READ
+ + +[CATDIR] + +

Vet du att du kan slå ihop mappnamn och +filnamn med &/-operatorn? Denna operator +tar hand om avslutande snedstreck "/" så att den resulterande sökvägen +blir perfekt.

+ +

Till exempel:

+ +
PRINT "/home/gambas" &/ ".bashrc"
+/home/gambas/.bashrc
+
+PRINT "/home/gambas/" &/ "/tmp" &/ "foo.bar"
+/home/gambas/tmp/foo.bar
+
+ +

Är det inte förunderligt?

+ + +[EXEC] + +

Du kan göra en körbar fil utgående från ditt hela projekt. Välj +Gör exekverbar i Projekt-menyn.

+ +

När Gambas gör en körbar fil, läggs +resultatet i din projektmapp som standard. +Den körbara filen får samma namn som ditt projekt.

+ + +[PATH] +

+Relativa sökvägar har speciell betydelse i Gambas. +De refererar alltid till filer inuti ditt projekt. +

+Det finns ingen innebörd i current directory och inget nyckelord som +CHDIR att ändra det. +

+Var försiktig: du måste använda relativ sökväg endast för att komma åt +projektfiler, ty absoluta sökvägar fungerar inte längre, när du gör en körbar fil. + + +[GLOBAL] + +Det finns inga globala variabler i Gambas! +

+Ett sätt att kringgå detta är att placera dem i din huvud/main-modul +och deklarera dem som PUBLIC. +

+Om du inte har en huvud/main-modul i ditt projekt, men ett huvud/main- +formulär, deklarera dem som STATIC PUBLIC. +

+För att komma åt dessa variabler, måste du använda namnet på huvudmodulen +eller huvudformuläret: MinMainModul.MinGlobalaVariabel or +MinMainForm.MinGlobalaVariabel. + + +[EMPTY] + +

För att veta om en sträng är tom, är det inte nödvändigt att använda +Len()-funktionen. Du kan testa den direkt, eftersom en tom sträng +är FALSE och en icke-tom sträng är TRUE.

+ +

Till exempel, i stället för att göra:

+ +
IF Len(MyString) > 0 THEN ...
+IF Len(MyString) = 0 THEN ...
+ +

Bör du göra:

+ +
IF MyString THEN ...
+IF NOT MyString THEN ...
+ + +[TRANSLATE] + +

Gambastillämpningar är helt och hållet översättningsbara, förutsatt att du +talar om vilka strängar som skall översättas.

+

För att markera att en sträng är översättningsbar, så sätt den bara inom parantester:

+ +

PRINT ("Översätt mig")
+PRINT "Men inte mig!"
+ +[EVENT] + +

Varje kontroll och varje objekt, som kan ge avbrott, har en +avbrottshanterare och ett avbrotts-group name.

+ +

Avbrottshanteraren fångar varje avbrott åstadkommet av objektet och +avbrottsgruppnamnet är prefix för den procedur, som anropas för att hantera +avbrottet.

+ +

Som standard är denna avbrottshanterare det objekt där du har +skapat kontrollen och gruppnamnet är samma som kontrollens.

+ +

På detta sätt får ett formulär mottaga alla avbrott som åstadkommits +av de kontroller du skapade inuti.

+ +
' Gambas form
+DIM hButton AS Button
+
+PUBLIC SUB _new()
+  hButton = NEW Button(ME) AS "MyButton"
+END
+
+PUBLIC SUB MyButton_Click()
+  PRINT "You have clicked MyButton !"
+END
+
+ + +[FORM] + +

I Gambas är ett formulär sin egen avbrottshanterare, så att +du direkt kan hantera dess avbrott (som Resize, +Activate, ...) in till dess egen klasskod.

+ +

På detta sätt blir nybörjare, som kommer från Visual Basic inte +disorienterade :-).

+ + +[EMBED] + +

Du kan inbädda vilket formulär som helst i andra formulär med Gambas + !

+ +

För att åstadkomma en så kraftfull sak, bara instanciera formuläret genom att skicka +ett förälderbehållare (parent container) som sista argument hos konstruktorn (contructor).

+ +

Till exempel :

+

DIM hForm AS MyDialog
+DIM hSuperControl AS MyForm

+' Skapa en dialog
+hForm = NEW MyDialog
+' Tag in ett formulär i denna dialog
+' Notera att detta formulär tar två parametrar före behållaren (container)
+hSuperControl = NEW MyForm(Param1, Param2, MyDialog)
+' Flytta och justera storlek på formuläret
+hSuperControl.Move(8, 8, 128, 64)
+

+ +

Var uppmärksam: ett formulär inbäddat i ett annat är fortfarande ett formulär och +dessutom sin egen avbrottshanterare.

+ + +[GROUP] + +

Varje kontroll har en (Group)-egenskap. När denna egenskap +sätts, är prefixet för avbrottshanterarens namn, namnet på gruppen +och inte namnet på kontrollen.

+ +

Låt oss anta att vi har en Knapp kallad btnAction +med följande Click avbrottshanterare:

+ +
PUBLIC SUB btnAction_Click()
+ +

Om du sätter (Group)-egenskapen hos btnAction till +MyGroup, så kommer avbrotsshanteraren att mottaga avbrott från +knappen att se ut som:

+ +
PUBLIC SUB MyGroup_Click()
+ +

Denna egenskap låter dig hantera avbrott från skilda kontroller med +en enkel funktion och kontrollerna i samma grupp behöver inte ha samma typ!

+ +

Notera : Den gamle Visual Basic-veteranen kan kanske känna igen +konceptet i kontroll array, men i en kraftfullare implementering. :-)

+ + +[TAG] + +

Varje kontroll har en Tag-egenskap. Denna är till för +programmeraren och kan innehålla vilken VARIANT-data som du tycker är relevant.

+ +

Detta är mycket användbart, när du vill åtskilja kontroller i +samma grupp i en gemensam avbrottshanterare.

+ + + +[LAST] + +

Nyckelordet LAST returnerar den sista kontroll, som +har mottagit ett avbrott. Detta är mycket användbart om du vill skriva en +avbrottshanterare, som är oberoende av namn på kontroller.

+ +

Till exempel, låt oss anta du vill skriva ett kalkylatorprogram. +Du har definierat tio knappar, en för varje siffra, var och en i +samma group "Digit". Tag-en för varje kontroll sätts till +siffran ritad i knappen. Din avbrottshanterare skulle kunna se ut som:

+ +

PUBLIC SUB Digit_Click()

+  Display = Display & LAST.Tag
+  RefreshDisplay

+END

+ + +[LEFT] + +

De välkända BASIC rutinerna Left$, Right$ +och Mid$ har användbara uppträdande i Gambas

+ +

Andra parametern i Left$ och Right$ är +frivillig och sätts till ett som standard.

+ +

Left$("Gambas") returnerar "G"
+Right$("Gambas") returnerar "s"

+ +

Andra parametern kan vara negativ och betyder då antal +tecken som ej skall tas ut.

+ +

Left$("Gambas", -2) returnerar "Gamb"
+Right$("Gambas", -2) returnerar "mbas"

+ +

På samma sätt med tredje argumentet till Mid$ kan vara negativt och +ger då antal tecken från slutet på strängen som ej skall tas ut.

+ +

Mid$("Gambas", 2, -2) returnerar "amb" + +[OBSERVER] + +

Observer-klassen tillåter dig att fånga upp alla händelser skapade +av ett objekt innan de verkligen sänds.

+ +
MyTextBox = NEW TextBox(ME) AS "MyTextBox"
+MyObserver = NEW Observer(MyTextBox) AS "MyObserver"
+...
+PUBLIC SUB MyObserver_KeyPress()
+  DEBUG "Got it first"
+END
+
+PUBLIC SUB MyTextBox_KeyPress()
+  DEBUG "Got it next"
+END
+ +"Observatören" kan avbryta händelsen för att förhindra att objektet att åstadkommer den (händelsen). + + +[STRING] + +

Gambas använder UTF-8-teckensätt för att representera strängar i minnet.

+ +

Men alla Gambas standardsträngfunktioner hanterar ASCII: +Left, Mid, Right, UCase... + +

Om du vill manipulera UTF-8-strängar, måste du använda metoder hörande till +String-static klass, vilka har samma namn som deras motsvarande standard. + +

PRINT Len("bébé");; Left$("bébé", 3)
+6 bé
+PRINT String.Len("bébé");; String.Left("bébé", 3)
+4 béb
+ + +[ASSIGNMENT] + +

Gambas implementerar förenklad tilldelning, som C/C++ programmerare är vana vid. + +

MyVariable += 2 är samma sak som MyVariable = MyVariable + 2 + +

MyVariable &= "Great" är samma sak som MyVariable = MyVariable & "Great" + +

och så vidare... + + +[DEBUG] + +

Du kan använda DEBUG-instruktionen till att skriva ut avlusningsmeddelandem +till konsolen (nämligen standard error output). Den uppför sig precis som PRINT- +instruktionen. + +

Dessa meddelanden föregås av klassnamn, metodnamn och radnummer för +DEBUG-instruktionen. + +

Debugmeddelandena tas automatiskt bort när en exekverbar fil +utan avlusningsinformation görs. + + +[TRY] + +

Felhantering i Gambas görs med följande instruktioner: +TRY, ERROR, CATCH och FINALLY. + +

TRY försöker utföra en sats utan att åstadkomma ett fel. ERROR- +instruktionen används just för att ta reda på om satsen utfördes korrekt. + +

TRY MyFile = OPEN "/etc/password" FOR WRITE
+IF ERROR THEN PRINT "I cannot do what I want!"
+ + +[CATCH] + +

Felhantering i Gambas görs med följande instruktioner: +TRY, ERROR, CATCH och FINALLY. + +

CATCH utvisar början på felhanteringsdelen i en funktion eller procedur. +Den placeras i slutet på funktionskoden. + +

Catch-delen utförs när ett fel har åstadkommits mellan början på funktionen och dess slut. + + +

Om ett fel inträffar under utförande av catch-delen, fångas den. + +

SUB ProcessFile(FileName AS STRING)
+  ...
+  OPEN FileName FOR READ AS #hFile
+  ...
+  CLOSE #hFile
+CATCH ' Utförs endast om det finns ett fel
+  PRINT "Cannot process file "; FileName
+END
+ + +[FINALLY] + +

Felhantering i Gambas görs med följande instruktioner: +TRY, ERROR, CATCH och FINALLY. + +

FINALLY inleder den kod, som utförs vid slutet av funktionen, även om ett fel åstadkomms under funktionsutförandet. + +

Finally-delen är inte obligatorisk. Om det finns en catch-del, så måste finally-delen föregå den. + +

Om ett fel inträffar under utförande av finally-delen, fortsättes normalt. + +

SUB ProcessFile(FileName AS STRING)
+  ...
+  OPEN FileName FOR READ AS #hFile
+  ...
+FINALLY ' Utförs alltid, även om fel inträffat
+  CLOSE #hFile
+CATCH ' Utförs endast om fel inträffat
+  PRINT "Cannot print file "; FileName
+END
+ + + +[END] + +

Du har nu lästa alla Dagens Tips. Hoppas att du blivit +en Gambas-expert nu! :-)

+ +

Om du vill bidraga, sänd nya tips till följande +adress :

+

g4mba5@gmail.com

+ +

Tack på förhand!

+ + + diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.tr gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.tr --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.tr 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.tr 1970-01-01 00:00:00.000000000 +0000 @@ -1,278 +0,0 @@ -[WELCOME] - -

Gambas'a Hoş Geldiniz !

- -

Gambas gelişmiş bir Basic yorumlayıcısı -üzerine kurulu grafiksel bir geliştirme ortamıdır.

- -

Gambas sizin kolay ve hızlı bir şekilde -güçlü programlar yapabilmenizi amaçlar. Ama düzgün programlar -sizin kendi sorumluluğunuzda kalır...

- -

Eğlenmenize bakın !

- -

Benoît Minisini
-g4mba5@gmail.com

- - -[STARTUP] - -

Her proje bir başlangıç sınıfı içermelidir. Bu başlangıç -sınıfı, programınızın başlangıç yöntemi olarak davranacak, parametre -almayan Main adlı durağan (static) ve genel (public) bir -yöntem tanımlamalıdır.

- -

Proje ağacında sağ fare tuşuyla üzerine tıklayarak ve açılan -menüden Başlangıç sınıfı'nı seçerek başlangıç sınıfını -tanımlayabilirsiniz.

- -

Bir başlangıç formunda Main yöntemi tanımlamanıza gerek yoktur; -çünkü formlar zaten öntanımlı bir yönteme sahiptir.

- -

Bu öntanımlı başlangıç yöntemi formu örnekler ve gösterir. Aynı -Visual Basic™'de olduğu gibi.

- - -[OPEN] - -

Gambas'ın OPEN yönergesi Visual Basic'deki -gibi çalışmaz. Dosyayı bir tamsayı (integer) yerine File -nesnesi olarak döndürür.

- -

Yani, şu şekilde yazmak yerine :

- -
DIM handle AS Integer
-...
-OPEN "myfile" FOR READ AS #handle
- -

aşağıdaki gibi yazmalısınız :

- -
DIM handle AS File
-...
-handle = OPEN "myfile" FOR READ
- - -[CATDIR] - -

Dizin ve dosya adlarını &/ işleciyle -birleştirebileceğinizi biliyor muydunuz ? Bu işleç eğik -çizgilerle ilgilenir. Böylece sonuçta oluşacak yol adı -kusursuz olur.

- -

Örneğin:

PRINT "/home/gambas" &/ ".bashrc" -/home/gambas/.bashrc - -PRINT "/home/gambas/" &/ "/tmp" &/ "foo.bar" -/home/gambas/tmp/foo.bar - - -

Harika değil mi ?

- - -[EXEC] - -

Projenizin tümünden çalışabilir bir dosya oluşturabilirsiniz. -Bunun için Proje menüsünden Çalışabilir dosyayı oluştur -seçeneğini tıklayınız.

- -

Gambas çalışabilir bir dosya oluşturduğunda, sonucu doğrudan -projenizin dizinine koyar. Bu dosya projenizle aynı adı alır.

- - -[PATH] -

-Göreceli yol adlarının Gambas'da özel bir anlamı vardır. -Bu yollar her zaman projenizdeki dosyaları gösterir. -

-Geçerli dizin kavramı yoktur, ve değiştirmek için -CHDIR gibi anahtar bir sözcük de yoktur. -

-Dikkatli olun: göreceli yol adlarını sadece proje dosyalarına -erişmek için kullanın, çünkü çalışabilir dosya oluştuğunda tam yollar -çalışmayacaktır. - - -[GLOBAL] - -Gambas'da global değişkenler yoktur! -

-Mümkünse, bu değişkenleri ana modülünüze koyun ve onları -PUBLIC olarak bildirin. -

-Eğer projenizde bir ana modül değil de bir ana form varsa, -STATIC PUBLIC olarak bildirin. -

-Bu değişkenlere erişmek için, ana modülün veya formun adını -kullanmalısınız: MyMainModule.MyGlobalVariable veya -MyMainForm.MyGlobalVariable. - - -[EMPTY] - -

Bir dizgenin boş olup olmadığını öğrenmek için, Len() -işlevini kullanmak zorunda değilsiniz. Doğrudan boş bir dizge -FALSE ve dolu bir dizge TRUE olarak sınanabilir.

- -

Örneğin, şu şekilde yapmak yerine :

- -
IF Len(MyString) > 0 THEN ...
-IF Len(MyString) = 0 THEN ...
- -

Şöyle yapabilirsiniz :

- -
IF MyString THEN ...
-IF NOT MyString THEN ...
- - -[EVENT] - -

Olay meydana getiren her denetim ve nesnenin, bir -olay gözlemcisi ve bir olay grup adı vardır.

- -

Olay gözlemcisi oluşan her olayı yakalar. Olay grup adı ise -olayı yöneten yordamın önekidir.

- -

Öntanımlı olarak, bu olay gözlemcisi denetimi oluşturduğunuz -nesnedir ve grup adı da o denetimin adıdır.

- -

Böylece bir form, üzerinde oluşturulan denetimlerden -gelen tüm olayları alır.

- -
' Gambas form
-DIM hButton AS Button
-
-PUBLIC SUB _new()
-  hButton = NEW Button(ME) AS "MyButton"
-END
-
-PUBLIC SUB MyButton_Click()
-  PRINT "You have clicked MyButton !"
-END
-
- - -[FORM] - -

Gambas'da, bir form kendi olay gözlemcisidir. Böylece -tüm form olaylarını (Resize, Activate, vb...) kendi -sınıf kodundan yönetebilirsiniz.

- -

Bu sayede, Visual Basic'den gelen yeni kullanıcılar -yolunu şaşırmaz :-).

- - -[EMBED] - -

Gambas ile bir formu diğer formların içine gömebilirsiniz - !

- -

Böyle güçlü bir şey yapmak için, sadece yapıcı işlevin son argümanı -olarak bir sahip kap (container) vererek formu örnekleyin.

- -

Örneğin :

-

DIM hForm AS MyDialog
-DIM hSuperControl AS MyForm

-' Bir iletişim penceresi oluştur
-hForm = NEW MyDialog
-' Bu iletişim penceresine bir form yerleştir
-' Unutmayın, bu form kaptan önce iki parametre daha alır
-hSuperControl = NEW MyForm(Param1, Param2, MyDialog)
-' Formu taşır ve yeniden boyutlandırır
-hSuperControl.Move(8, 8, 128, 64)
-

- -

Dikkatli olun: başka bir form içine gömülen bir form hala formdur ve -bundan dolayı kendi olay gözlemcisine sahiptir.

- - -[GROUP] - -

Her denetim bir (Group) özelliğine sahiptir. Bu özellik -girildiğinde, olay yöneticisinin adı denetim adı yerine grup adını -önek olarak alır.

- -

Diyelim ki btnAction adında bir Button nesneniz var. -Bu nesneye ait Click olayının yöneticisi de aşağıdaki gibi olsun :

- -
PUBLIC SUB btnAction_Click()
- -

Eğer btnAction nesnesinin (Group) özelliğini -MyGroup olarak değiştirirseniz, bu butondan olayları alacak -olay yöneticisi şöyle olur :

- -
PUBLIC SUB MyGroup_Click()
- -

Bu özellik tek bir işlevde değişik denetimlerin olaylarını yönetmenize -olanak sağlar. Bu denetimlerin aynı türden olmaları da gerekmez !

- -

Not : Eski Visual Basic emektarları -denetim dizisi (control array) kavramını hatırlayabilir, -ancak bu daha güçlü bir uygulama. :-)

- - -[TAG] - -

Her denetim bir Tag özelliğine sahiptir. Bu özellik -programcı içindir ve ilgili bulduğunuz herhangi bir veriyi içerebilir.

- -

Bu yöntem, bir olay yöneticisinde aynı grupta yer alan denetimleri -ayırt etmek için çok kullanışlıdır.

- - - -[LAST] - -

LAST anahtar sözcüğü bir olay algılayan en son denetimi -döndürür. Bu, herhangi bir denetim adından bağımsız bir olay yöneticisi -yazmak istediğinizde çok kullanışlıdır.

- -

Örneğin, diyelim ki bir hesap makinesi programı yapmak istiyorsunuz. -Her rakam için bir tane olacak şekilde on tane tuş tanımladınız ve hepsi -"Digit" grubunda yer alsın. Her denetimin Tag özelliği -tuşta yer alan rakamı içersin. Olay yöneticiniz şunun gibi olacaktır :

- -

PUBLIC SUB Digit_Click()

-  Display = Display & LAST.Tag
-  RefreshDisplay

-END

- - -[LEFT] - -

Çok bilinen BASIC işlevleri Left$, Right$ ve -Mid$ Gambas'da çok kullanışlı davranışlar gösterir

- -

Left$ ve Right$ işlevlerinin ikinci parametreleri -seçimliktir ve biri öntanımlıdır.

- -

Left$("Gambas") --> "G" değerini,
-Right$("Gambas") --> "s" değerini döndürür.

- -

İkinci parametre negatif olabilir ve bu ayıklanmayan -karakterlerin sayısını verir.

- -

Left$("Gambas", -2) --> "Gamb"
-Right$("Gambas", -2) --> "mbas"

- -

Aynı şekilde, Mid$ işlevinin üçüncü parametresi negatif -olabilir ve bu değer dizge sonundan itibaren ayıklanmayan -karakter sayısını verir.

- -

Mid$("Gambas", 2, -2) --> "amb" - - -[END] - -

Tüm ipuçlarını okudunuz. Umarım şimdi bir Gambas uzmanı -olmuşsunuzdur ! :-)

- -

Eğer katkıda bulunmak istiyorsanız, aşağıdaki adrese yeni ipuçları -gönderin :

-

g4mba5@gmail.com

- -

Şimdiden teşekkürler !

- - - diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.tr.txt gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.tr.txt --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.tr.txt 1970-01-01 00:00:00.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.tr.txt 2021-09-14 19:01:29.000000000 +0000 @@ -0,0 +1,278 @@ +[WELCOME] + +

Gambas'a Hoş Geldiniz !

+ +

Gambas gelişmiş bir Basic yorumlayıcısı +üzerine kurulu grafiksel bir geliştirme ortamıdır.

+ +

Gambas sizin kolay ve hızlı bir şekilde +güçlü programlar yapabilmenizi amaçlar. Ama düzgün programlar +sizin kendi sorumluluğunuzda kalır...

+ +

Eğlenmenize bakın !

+ +

Benoît Minisini
+g4mba5@gmail.com

+ + +[STARTUP] + +

Her proje bir başlangıç sınıfı içermelidir. Bu başlangıç +sınıfı, programınızın başlangıç yöntemi olarak davranacak, parametre +almayan Main adlı durağan (static) ve genel (public) bir +yöntem tanımlamalıdır.

+ +

Proje ağacında sağ fare tuşuyla üzerine tıklayarak ve açılan +menüden Başlangıç sınıfı'nı seçerek başlangıç sınıfını +tanımlayabilirsiniz.

+ +

Bir başlangıç formunda Main yöntemi tanımlamanıza gerek yoktur; +çünkü formlar zaten öntanımlı bir yönteme sahiptir.

+ +

Bu öntanımlı başlangıç yöntemi formu örnekler ve gösterir. Aynı +Visual Basic™'de olduğu gibi.

+ + +[OPEN] + +

Gambas'ın OPEN yönergesi Visual Basic'deki +gibi çalışmaz. Dosyayı bir tamsayı (integer) yerine File +nesnesi olarak döndürür.

+ +

Yani, şu şekilde yazmak yerine :

+ +
DIM handle AS Integer
+...
+OPEN "myfile" FOR READ AS #handle
+ +

aşağıdaki gibi yazmalısınız :

+ +
DIM handle AS File
+...
+handle = OPEN "myfile" FOR READ
+ + +[CATDIR] + +

Dizin ve dosya adlarını &/ işleciyle +birleştirebileceğinizi biliyor muydunuz ? Bu işleç eğik +çizgilerle ilgilenir. Böylece sonuçta oluşacak yol adı +kusursuz olur.

+ +

Örneğin:

PRINT "/home/gambas" &/ ".bashrc" +/home/gambas/.bashrc + +PRINT "/home/gambas/" &/ "/tmp" &/ "foo.bar" +/home/gambas/tmp/foo.bar + + +

Harika değil mi ?

+ + +[EXEC] + +

Projenizin tümünden çalışabilir bir dosya oluşturabilirsiniz. +Bunun için Proje menüsünden Çalışabilir dosyayı oluştur +seçeneğini tıklayınız.

+ +

Gambas çalışabilir bir dosya oluşturduğunda, sonucu doğrudan +projenizin dizinine koyar. Bu dosya projenizle aynı adı alır.

+ + +[PATH] +

+Göreceli yol adlarının Gambas'da özel bir anlamı vardır. +Bu yollar her zaman projenizdeki dosyaları gösterir. +

+Geçerli dizin kavramı yoktur, ve değiştirmek için +CHDIR gibi anahtar bir sözcük de yoktur. +

+Dikkatli olun: göreceli yol adlarını sadece proje dosyalarına +erişmek için kullanın, çünkü çalışabilir dosya oluştuğunda tam yollar +çalışmayacaktır. + + +[GLOBAL] + +Gambas'da global değişkenler yoktur! +

+Mümkünse, bu değişkenleri ana modülünüze koyun ve onları +PUBLIC olarak bildirin. +

+Eğer projenizde bir ana modül değil de bir ana form varsa, +STATIC PUBLIC olarak bildirin. +

+Bu değişkenlere erişmek için, ana modülün veya formun adını +kullanmalısınız: MyMainModule.MyGlobalVariable veya +MyMainForm.MyGlobalVariable. + + +[EMPTY] + +

Bir dizgenin boş olup olmadığını öğrenmek için, Len() +işlevini kullanmak zorunda değilsiniz. Doğrudan boş bir dizge +FALSE ve dolu bir dizge TRUE olarak sınanabilir.

+ +

Örneğin, şu şekilde yapmak yerine :

+ +
IF Len(MyString) > 0 THEN ...
+IF Len(MyString) = 0 THEN ...
+ +

Şöyle yapabilirsiniz :

+ +
IF MyString THEN ...
+IF NOT MyString THEN ...
+ + +[EVENT] + +

Olay meydana getiren her denetim ve nesnenin, bir +olay gözlemcisi ve bir olay grup adı vardır.

+ +

Olay gözlemcisi oluşan her olayı yakalar. Olay grup adı ise +olayı yöneten yordamın önekidir.

+ +

Öntanımlı olarak, bu olay gözlemcisi denetimi oluşturduğunuz +nesnedir ve grup adı da o denetimin adıdır.

+ +

Böylece bir form, üzerinde oluşturulan denetimlerden +gelen tüm olayları alır.

+ +
' Gambas form
+DIM hButton AS Button
+
+PUBLIC SUB _new()
+  hButton = NEW Button(ME) AS "MyButton"
+END
+
+PUBLIC SUB MyButton_Click()
+  PRINT "You have clicked MyButton !"
+END
+
+ + +[FORM] + +

Gambas'da, bir form kendi olay gözlemcisidir. Böylece +tüm form olaylarını (Resize, Activate, vb...) kendi +sınıf kodundan yönetebilirsiniz.

+ +

Bu sayede, Visual Basic'den gelen yeni kullanıcılar +yolunu şaşırmaz :-).

+ + +[EMBED] + +

Gambas ile bir formu diğer formların içine gömebilirsiniz + !

+ +

Böyle güçlü bir şey yapmak için, sadece yapıcı işlevin son argümanı +olarak bir sahip kap (container) vererek formu örnekleyin.

+ +

Örneğin :

+

DIM hForm AS MyDialog
+DIM hSuperControl AS MyForm

+' Bir iletişim penceresi oluştur
+hForm = NEW MyDialog
+' Bu iletişim penceresine bir form yerleştir
+' Unutmayın, bu form kaptan önce iki parametre daha alır
+hSuperControl = NEW MyForm(Param1, Param2, MyDialog)
+' Formu taşır ve yeniden boyutlandırır
+hSuperControl.Move(8, 8, 128, 64)
+

+ +

Dikkatli olun: başka bir form içine gömülen bir form hala formdur ve +bundan dolayı kendi olay gözlemcisine sahiptir.

+ + +[GROUP] + +

Her denetim bir (Group) özelliğine sahiptir. Bu özellik +girildiğinde, olay yöneticisinin adı denetim adı yerine grup adını +önek olarak alır.

+ +

Diyelim ki btnAction adında bir Button nesneniz var. +Bu nesneye ait Click olayının yöneticisi de aşağıdaki gibi olsun :

+ +
PUBLIC SUB btnAction_Click()
+ +

Eğer btnAction nesnesinin (Group) özelliğini +MyGroup olarak değiştirirseniz, bu butondan olayları alacak +olay yöneticisi şöyle olur :

+ +
PUBLIC SUB MyGroup_Click()
+ +

Bu özellik tek bir işlevde değişik denetimlerin olaylarını yönetmenize +olanak sağlar. Bu denetimlerin aynı türden olmaları da gerekmez !

+ +

Not : Eski Visual Basic emektarları +denetim dizisi (control array) kavramını hatırlayabilir, +ancak bu daha güçlü bir uygulama. :-)

+ + +[TAG] + +

Her denetim bir Tag özelliğine sahiptir. Bu özellik +programcı içindir ve ilgili bulduğunuz herhangi bir veriyi içerebilir.

+ +

Bu yöntem, bir olay yöneticisinde aynı grupta yer alan denetimleri +ayırt etmek için çok kullanışlıdır.

+ + + +[LAST] + +

LAST anahtar sözcüğü bir olay algılayan en son denetimi +döndürür. Bu, herhangi bir denetim adından bağımsız bir olay yöneticisi +yazmak istediğinizde çok kullanışlıdır.

+ +

Örneğin, diyelim ki bir hesap makinesi programı yapmak istiyorsunuz. +Her rakam için bir tane olacak şekilde on tane tuş tanımladınız ve hepsi +"Digit" grubunda yer alsın. Her denetimin Tag özelliği +tuşta yer alan rakamı içersin. Olay yöneticiniz şunun gibi olacaktır :

+ +

PUBLIC SUB Digit_Click()

+  Display = Display & LAST.Tag
+  RefreshDisplay

+END

+ + +[LEFT] + +

Çok bilinen BASIC işlevleri Left$, Right$ ve +Mid$ Gambas'da çok kullanışlı davranışlar gösterir

+ +

Left$ ve Right$ işlevlerinin ikinci parametreleri +seçimliktir ve biri öntanımlıdır.

+ +

Left$("Gambas") --> "G" değerini,
+Right$("Gambas") --> "s" değerini döndürür.

+ +

İkinci parametre negatif olabilir ve bu ayıklanmayan +karakterlerin sayısını verir.

+ +

Left$("Gambas", -2) --> "Gamb"
+Right$("Gambas", -2) --> "mbas"

+ +

Aynı şekilde, Mid$ işlevinin üçüncü parametresi negatif +olabilir ve bu değer dizge sonundan itibaren ayıklanmayan +karakter sayısını verir.

+ +

Mid$("Gambas", 2, -2) --> "amb" + + +[END] + +

Tüm ipuçlarını okudunuz. Umarım şimdi bir Gambas uzmanı +olmuşsunuzdur ! :-)

+ +

Eğer katkıda bulunmak istiyorsanız, aşağıdaki adrese yeni ipuçları +gönderin :

+

g4mba5@gmail.com

+ +

Şimdiden teşekkürler !

+ + + diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.zh gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.zh --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.zh 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.zh 1970-01-01 00:00:00.000000000 +0000 @@ -1,341 +0,0 @@ -[WELCOME] - -

欢迎使用Gambas

- -

Gambas是一个基于高级Basic语言解释器的图形界面的开发环境。

- -

Gambas的目标是使你能轻易而快速地开发出功能强大的程序。但是高效而简洁的程序还得靠你自己的努力...

- -

希望你能喜欢!

- -

Benoît Minisini
-English:g4mba5@gmail.com
-中文:yizhou.he@gmail.com

- -[STARTUP] - -

每一个工程都需要有一个启动类,这个启动类必须定义一个名为Main的无参数的静态公用方法,它将成为你的程序的启动方法。

- -

定义启动类的方法是,用鼠标右键点击工程目录树中要设为启动类的类,并在弹出的右键菜单中选中启动类

- -

你不需要在启动窗体中定义一个Main方法,因为Gambas己经预定义好了。

- -

这个预定义的启动方法创建并显示窗体就像Visual Basic™一样。

- - -[OPEN] - -

GambasOPEN函数和Visual Basic的不太一样,它并不返回一个整型变量,而是返回一个文件对象。

- -

所以,不要使用:

- -
DIM handle AS Integer
-...
-OPEN "myfile" FOR READ AS #handle
- -

而应该使用:

- -
DIM handle AS File
-...
-handle = OPEN "myfile" FOR READ
- - -[CATDIR] - -

你知道吗?你可以使用&/操作符连结文件路径中的目录和文件,此操作符处理路径尾的斜杠以免重复。

- -

例如:

- -
PRINT "/home/gambas" &/ ".bashrc"
-/home/gambas/.bashrc
-
-PRINT "/home/gambas/" &/ "/tmp" &/ "foo.bar"
-/home/gambas/tmp/foo.bar
-
- -

怎么样?好用吧!

- - -[EXEC] - -

可以将你的整个工程生成一个可执行文件,在工程菜单中选择生成可执行文件

- -

Gambas生成可执行文件时,默认将产生的可执行文件放到你的工程目录下,可执行文件名和你的工程名相同。

- - -[PATH] -

- 相对路径在Gambas中有特殊含义,它们总是指向你工程内的文件。 -

-这里没有当前目录的概念,没有CHDIR之类的关键字来改变它。 -

-注意:只能使用相对路径访问你的工程文件,因为绝对路径在你生成可执行文件后就不再可靠了。 - - -[GLOBAL] - - Gambas里不再有全局变量了! -

-相应的,在你的主模块中声明它们为PUBLIC(公用类型)。 -

-如果你的工程中没有主模块,只有主窗体,那么声明它们为STATIC PUBLIC(静态公用类型)。 -

-要访问这些变量,你必须使用主模块名或主窗体名:MyMainModule.MyGlobalVariable或 -MyMainForm.MyGlobalVariable。 - - -[EMPTY] - -

要知道一个字符串是否为空,没必要使用Len()函数,你可以直接测试它,因为空字符串为FALSE非空字符串为TRUE

- -

例如,你不用写:

- -
IF Len(MyString) > 0 THEN ...
-IF Len(MyString) = 0 THEN ...
- -

你只需写:

- -
IF MyString THEN ...
-IF NOT MyString THEN ...
- -[TRANSLATE] - -

Gambas应用程序是可完全翻译的,条件是你应声明哪些字符串是必须要翻译的,哪些不必翻译。

-

用括号括起来就表明该字符串是可以被翻译的。

- -

PRINT ("我可以被翻译!")
-PRINT "我不能被翻译!"
- -[EVENT] - -

每个控件和每个对象都可以产生事件,都有一个event observer(事件观察器)和一个事件 group name(组名)。

- -

事件观察器捕捉对象产生的每一个事件,事件组名将是你用来处理事件的类名的前缀。

- -

默认的事件观察器是你创建的控件的容器对象,事件组名是控件名。

- -

这梓,一个窗体接收你在它上面创建的所有控件发生的事件。

- -
' Gambas form
-DIM hButton AS Button
-
-PUBLIC SUB _new()
-  hButton = NEW Button(ME) AS "MyButton"
-END
-
-PUBLIC SUB MyButton_Click()
-  PRINT "You have clicked MyButton !"
-END
-
- - -[FORM] - -

Gambas中,一个窗体是它自己的事件观察器,所以你可以直接在它自己的类代码中管理它的事件(像Resize, -Activate, ...)。

- -

这样,从Visual Basic转来的新手们就不会迷失方向:-)。

- - -[EMBED] - -

Gambas中,你可以在窗体中嵌入窗体!

- -

要实现如此强大的功能,只要在初始化窗体对象时将父容器做为最后一个参数传给窗体构建函数。

- -

例如:

-

DIM hForm AS MyDialog
-DIM hSuperControl AS MyForm

-' 创建一个对话框
-hForm = NEW MyDialog
-' 在此对话框中插入一个窗体
-' 注意此窗体需要三个参数,最后一个参数是容器对象
-hSuperControl = NEW MyForm(Param1, Param2, MyDialog)
-' 移动并改变窗体的大小
-hSuperControl.Move(8, 8, 128, 64)
-

- -

小心:嵌入后的窗体还是个窗体,它还是它自己的事件观察器。

- - -[GROUP] - -

每个控件都有一个Group(组)属性,当此属性被设置,事件处理名称的前缀就将是组名而不是控件名。

- -

假定你有一个Button(按钮)名叫btnAction -有一个Click事件处理:

- -
PUBLIC SUB btnAction_Click()
- -

如果你将btnAction(Group)属性设为MyGroup,那么事件处理从按钮收到的事件将是:

- -
PUBLIC SUB MyGroup_Click()
- -

此属性让你在一个函数中处理不同的控件的事件,同组中的控件不需要有相同的类型!

- -

注释: Visual Basic老手可以认为是控件数组,但有更为强大的用法。:-)

- - -[TAG] - -

每一个控件都有Tag属性,此属性是为编程者设计的,可以是任何你想要的VARIANT(变体类型)数据。

- -

这在使用同组的公用事件处理中区别控件时非常有用。

- - - -[LAST] - -

LAST关键字返回发生事件的最近控件,当你要写一个独立于控件名的事件处理类就非常有用。

- -

例如,假设你要写一个计算器程序。 -你定义了十个按钮,每个数字一个,它们都在一个名叫"Digit"的,每个控件的Tag属性都被设为相应的数字。 -你的处理程序将会是:

- -

PUBLIC SUB Digit_Click()

-  Display = Display & LAST.Tag
-  RefreshDisplay

-END

- - -[LEFT] - -

大名鼎鼎的BASIC函数Left$Right$ -和Mid$Gambas中有了新功能。

- -

Left$Right$的第二个参数是可选的,默认值为1。

- -

Left$("Gambas") 返回"G"
-Right$("Gambas") 返回"s"

- -

第二个参数可以是负数,它将指定反方向上将被切掉的字符个数。

- -

Left$("Gambas", -2) 返回"Gamb"
-Right$("Gambas", -2) 返回"mbas"

- -

相同的,Mid$的第三个参数也可以是负数,指定字符串末端将被切掉的字符的个数。

- -

Mid$("Gambas", 2, -2) 返回"amb" - -[OBSERVER] - -

Observer类允许你将对象发生的所有事件在被发送之前截获。

- -
MyTextBox = NEW TextBox(ME) AS "MyTextBox"
-MyObserver = NEW Observer(MyTextBox) AS "MyObserver"
-...
-PUBLIC SUB MyObserver_KeyPress()
-  DEBUG "Got it first"
-END
-
-PUBLIC SUB MyTextBox_KeyPress()
-  DEBUG "Got it next"
-END
- - Observer能取消事件防止对象有效的发出它。 - - -[STRING] - -

Gambas使用UTF-8字符编码在内存中描述字符串。

- -

但是所有的标准Gambas字符串函数处理ASCII码: -LeftMidRightUCase... - -

如果想处理UTF-8编码的字符串,必须使用String静态类的方法,它们有和标准字符串处理函数相同的名字。 - -

PRINT Len("bébé");; Left$("bébé", 3)
-6 bé
-PRINT String.Len("bébé");; String.Left("bébé", 3)
-4 béb
- - -[ASSIGNMENT] - -

Gambas实现了C/C++程序员常用的快捷赋值。 - -

MyVariable += 2 等价于 MyVariable = MyVariable + 2 - -

MyVariable &= "Great" 等价于 MyVariable = MyVariable & "Great" - -

诸如此类... - - -[DEBUG] - -

可以使用DEBUG语句打印调试信息到控制台(也就是标准错误输出),用法和PRINT语句完全一样。 - -

调试信息前缀有类名,方法名和DEBUG语句所在行号。 - -

调试信息在生成不包含调试信息的可执行文件时被自动删除。 - - -[TRY] - -

Gambas使用下面的语句实现错误管理: -TRYERRORCATCHFINALLY。 - -

TRY尝试执行一个语句而不引发错误,随后使用ERROR语句检测语句执行中是否发生错误。 - -

TRY MyFile = OPEN "/etc/password" FOR WRITE
-IF ERROR THEN PRINT "I cannot do what I want!"
- - -[CATCH] - -

Gambas使用下面的语句实现错误管理: -TRYERRORCATCHFINALLY。 - -

CATCH标明函数或者过程中错误管理部分(错误陷阱)的代码起始。 - -

当错误发生于函数执行的起始到终止之间,执行错误陷阱部分。 - -

如果错误发生于执行错误陷阱代码期间,会正常传送。错误陷阱不保护自己! - -

SUB ProcessFile(FileName AS STRING)
-  ...
-  OPEN FileName FOR READ AS #hFile
-  ...
-  CLOSE #hFile
-CATCH ' 仅仅发生错误时执行
-  PRINT "Cannot process file "; FileName
-END
- - -[FINALLY] - -

Gambas使用下面的语句实现错误管理: -TRYERRORCATCHFINALLY。 - -

在函数的尾部,FINALLY语句引领的代码被执行,即使在其执行期间有错误发生。 - -FINALLY部分是非托管的。如果函数中有错误陷阱,FINALLY部分必须位于陷阱之前。 - - -

FINALLY部分是非托管的。如果函数中有错误陷阱,FINALLY部分必须位于陷阱之前。 - -

如果错误发生于FINALLY部分执行期间,错误会正常传送。 - -

SUB ProcessFile(FileName AS STRING)
-  ...
-  OPEN FileName FOR READ AS #hFile
-  ...
-FINALLY '总是执行,即使有错误发生
-  CLOSE #hFile
-CATCH ' 仅当错误发生时执行
-  PRINT "Cannot print file "; FileName
-END
- - -[END] - -

你己读完所有今日提示。我希望你己经是一个Gambas的专家了!:-)

- -

如果你想为Gambas贡献一份力量,用电子邮件发送新提示到:

-英文:

g4mba5@gmail.com

-中文:

yizhou.he@gmail.com

- -

预先感谢!

- - - diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.zh_TW gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.zh_TW --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.zh_TW 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.zh_TW 1970-01-01 00:00:00.000000000 +0000 @@ -1,442 +0,0 @@ -[WELCOME] - -

歡迎使用Gambas

- -

Gambas是一個基於高級Basic語言直譯器的圖形界面的開發環境。

- -

Gambas的目標是使您能輕易而快速地開發出功能強大的程式。但是高效而簡潔的程式還得靠您自己的努力...

- -

希望您會喜歡!

- -

Benoît Minisini
-English:g4mba5@gmail.com
-中文:yizhou.he@gmail.com

- -[STARTUP] - -

每一個專案都需要有一個啟動類別,這個啟動類別必須定義一個名爲Main的無參數靜態公用方法,它將成爲您的程式的進入點。

- -

定義啟動類別的方法是,用鼠標右鍵點擊工程目錄樹中要設爲啟動類別的類別,並在彈出的右鍵菜單中選中啟動類別

- -

您不需要在啟動視窗中定義一個Main方法,因爲Gambas己經預定義好了。

- -

這個預定義的啟動方法創建並顯示視窗, 就像Visual Basic™一樣。

- - -[OPEN] - -

GambasOPEN函數和Visual Basic的不太一樣,它並不回傳整數,而是回傳一個檔案物件。

- -

所以,不要使用:

- -
DIM handle AS Integer
-...
-OPEN "myfile" FOR READ AS #handle
- -

而應該使用:

- -
DIM handle AS File
-...
-handle = OPEN "myfile" FOR READ
- - -[CATDIR] - -

您知道嗎?您可以使用&/來連接資料夾和檔案名稱,這個運算子會自動處理路徑結尾的/以免重複。

- -

例如:

- -
PRINT "/home/gambas" &/ ".bashrc"
-/home/gambas/.bashrc
-
-PRINT "/home/gambas/" &/ "/tmp" &/ "foo.bar"
-/home/gambas/tmp/foo.bar
-
- -

怎麼樣?好用吧!

- - -[EXEC] - -

可以將您的整個專案生成一個可執行檔,在專案選單中選擇生成可執行檔

- -

Gambas生成可執行檔時,預設會將產生的可執行檔放到您的專案目錄下,可執行檔名和您的專案名稱相同。

- - -[PATH] -

- 相對路徑在Gambas中有特殊含義,它們總是指向您專案內的文件。 -

-這裏沒有當前目錄的概念,沒有CHDIR之類的關鍵字來改變它。 -

-注意:您只能用相對路徑存取專案中的檔案,因爲絕對路徑在您生成可執行檔後就不再可靠了。 - - -[GLOBAL] - - Gambas裏不再有全域變數了! -

-新的處理方法是,在您的主模組中宣告它們爲PUBLIC(公用類型)。 -

-如果您的專案中沒有主模組,只有主視窗,那麼宣告它們爲STATIC PUBLIC(靜態公用類型)。 -

-要存取這些變數,您必須使用主模組名或主視窗名:MyMainModule.MyGlobalVariable或 -MyMainForm.MyGlobalVariable。 - - -[EMPTY] - -

要知道一個字串是否爲空,並不需要使用Len()函數,您可以直接測試它,因爲空字串爲FALSE非空字串爲TRUE

- -

例如,您不需要寫:

- -
IF Len(MyString) > 0 THEN ...
-IF Len(MyString) = 0 THEN ...
- -

您只需寫:

- -
IF MyString THEN ...
-IF NOT MyString THEN ...
- -[TRANSLATE] - -

Gambas應用程式是可完全翻譯的,條件是您應指定哪些字串是必須要翻譯的。

-

用括號將字串括起來就表示該字串是可以被翻譯的。

- -

PRINT ("我可以被翻譯!")
-PRINT "我不能被翻譯!"
- -[EVENT] - -

每個控制項和每個物件都可以產生事件,都有一個event observer(事件觀察器)和一個事件 group name(組名)。

- -

事件觀察器捕捉物件產生的每一個事件,事件組名將是您用來處理事件的類別名稱的前綴。

- -

預設的事件觀察器是您創建的控制項的容器物件,事件組名是控制項名。

- -

在這種狀況下,一個視窗會接收您在它上面創建的所有控制項發生的事件。

- -
' Gambas form
-DIM hButton AS Button
-
-PUBLIC SUB _new()
-  hButton = NEW Button(ME) AS "MyButton"
-END
-
-PUBLIC SUB MyButton_Click()
-  PRINT "You have clicked MyButton !"
-END
-
- - -[FORM] - -

Gambas中,一個視窗是它自己的事件觀察器,所以您可以直接在它自己的類代碼中管理它的事件(像Resize, -Activate, ...)。

- -

這樣,從Visual Basic轉來的新手們就不會迷失方向:-)。

- - -[EMBED] - -

Gambas中,您可以在視窗中嵌入視窗!

- -

要實現如此強大的功能,只要在初始化視窗物件時將父容器做爲最後一個參數傳給視窗構建函數。

- -

例如:

-

DIM hForm AS MyDialog
-DIM hSuperControl AS MyForm

-' 創建一個對話框
-hForm = NEW MyDialog
-' 在此對話框中插入一個視窗
-' 注意此視窗需要三個參數,最後一個參數是容器物件
-hSuperControl = NEW MyForm(Param1, Param2, MyDialog)
-' 移動並改變視窗的大小
-hSuperControl.Move(8, 8, 128, 64)
-

- -

小心:嵌入後的視窗還是個視窗,它還是它自己的事件觀察器。

- - -[GROUP] - -

每個控制項都有一個Group(組)屬性,當此屬性被設置,事件處理名稱的前綴就將是組名而不是控制項名。

- -

假定您有一個Button(按鈕)名叫btnAction -有一個Click事件處理:

- -
PUBLIC SUB btnAction_Click()
- -

如果您將btnAction(Group)屬性設爲MyGroup,那麼事件處理從按鈕收到的事件將是:

- -
PUBLIC SUB MyGroup_Click()
- -

此屬性讓您在一個函數中處理不同的控制項的事件,同組中的控制項不需要有相同的類型!

- -

註釋: Visual Basic老手可能會認為這個屬性和VB中的控制項陣列相似,但更為強大。:-)

- - -[TAG] - -

每一個控制項都有Tag屬性,此屬性是爲編程者設計的,可以是任何您想要的VARIANT(可變類型)數據。

- -

這在使用同組的公用事件處理中區別控制項時非常有用。

- - - -[LAST] - -

LAST關鍵字回傳最近一次發生事件的控制項,當您要寫一個獨立於控制項名的事件處理函式就非常有用。

- -

例如,假設您要寫一個計算器程式。 -您定義了十個按鈕,每個數字一個,它們都在一個名叫"Digit"的群組,每個控制項的Tag屬性都被設爲相應的數字。 -您的處理程序將會是:

- -

PUBLIC SUB Digit_Click()

-  Display = Display & LAST.Tag
-  RefreshDisplay

-END

- - -[LEFT] - -

大名鼎鼎的BASIC函數Left$Right$ -和Mid$Gambas中有了新功能。

- -

Left$Right$的第二個參數是可選的,預設值爲1。

- -

Left$("Gambas") 回傳"G"
-Right$("Gambas") 回傳"s"

- -

第二個參數可以是負數,它的用途是指定反方向上將被切掉的字元個數。

- -

Left$("Gambas", -2) 回傳"Gamb"
-Right$("Gambas", -2) 回傳"mbas"

- -

相同的,Mid$的第三個參數也可以是負數,指定字串末端將被切掉的字元的個數。

- -

Mid$("Gambas", 2, -2) 回傳"amb" - -[OBSERVER] - -

Observer類別允許您在物件發出事件之前先攔截它。

- -
MyTextBox = NEW TextBox(ME) AS "MyTextBox"
-MyObserver = NEW Observer(MyTextBox) AS "MyObserver"
-...
-PUBLIC SUB MyObserver_KeyPress()
-  DEBUG "Got it first"
-END
-
-PUBLIC SUB MyTextBox_KeyPress()
-  DEBUG "Got it next"
-END
- - Observer能取消事件,防止物件對外發出事件。 - - -[STRING] - -

Gambas使用UTF-8字元編碼在記憶體中描述字串。

- -

但是所有的標準Gambas字串函數只處理ASCII碼: -LeftMidRightUCase... - -

如果想處理UTF-8編碼的字串,必須使用String靜態類別的方法,它們的名字和標準字串處理函數完全相同。 - -

PRINT Len("bébé");; Left$("bébé", 3)
-6 bé
-PRINT String.Len("bébé");; String.Left("bébé", 3)
-4 béb
- - -[ASSIGNMENT] - -

Gambas實現了C/C++程序員常用的快捷賦值。 - -

MyVariable += 2 等價於 MyVariable = MyVariable + 2 - -

MyVariable &= "Great" 等價於 MyVariable = MyVariable & "Great" - -

諸如此類... - - -[DEBUG] - -

可以使用DEBUG語句列印除錯信息到控制台(也就是stderr),用法和PRINT語句完全一樣。 - -

除錯信息前綴有類別名稱,方法名稱和DEBUG語句所在的行號。 - -

除錯信息在生成不包含除錯信息的可執行檔時會被自動刪除。 - - -[TRY] - -

Gambas使用下面的語句實現錯誤管理: -TRYERRORCATCHFINALLY。 - -

TRY嘗試執行一個語句而不引發錯誤,隨後使用ERROR語句檢測語句執行中是否發生錯誤。 - -

TRY MyFile = OPEN "/etc/password" FOR WRITE
-IF ERROR THEN PRINT "I cannot do what I want!"
- - -[CATCH] - -

Gambas使用下面的語句實現錯誤管理: -TRYERRORCATCHFINALLY。 - -

CATCH標明函數或者過程中錯誤管理部分(錯誤處理常式)的程式碼的開頭。 - -

當錯誤發生於函數執行的起始到終止之間時,會跳去執行錯誤處理常式的部分。 - -

如果錯誤發生於執行錯誤處理常式期間,會繼續向下一層傳送。錯誤處理常式不保護自己! - -

SUB ProcessFile(FileName AS STRING)
-  ...
-  OPEN FileName FOR READ AS #hFile
-  ...
-  CLOSE #hFile
-CATCH ' 只在發生錯誤時執行
-  PRINT "Cannot process file "; FileName
-END
- - -[FINALLY] - -

Gambas使用下面的語句實現錯誤管理: -TRYERRORCATCHFINALLY。 - -

在函數的尾部,FINALLY語句引領的代碼被執行,即使在其執行期間有錯誤發生。 - -FINALLY部分是非必要的。如果函數中有錯誤處理常式,FINALLY部分必須位於處理常式之前。 - - -

FINALLY部分是非必要的。如果函數中有錯誤處理常式,FINALLY部分必須位於處理常式之前。 - -

如果錯誤發生於FINALLY部分執行期間,錯誤會正常傳送。 - -

SUB ProcessFile(FileName AS STRING)
-  ...
-  OPEN FileName FOR READ AS #hFile
-  ...
-FINALLY ' 即使有錯誤發生也會被執行
-  CLOSE #hFile
-CATCH ' 只在錯誤發生時執行
-  PRINT "Cannot print file "; FileName
-END
- - -[OPTIONAL] - -

Optional

- -

Gambas裡面,函數和程序的參數可以含有選擇性的參數。

- -

定義選擇性參數的方法是在參數名稱面加上 Optional 關鍵字。

- -

您也可以在選擇性參數後面加上預設值,例如:

- -
Private Sub MyFunction(Param AS String, Optional Optim AS String = "Default")
-  ...
-  Print "Required: "; param; ", Optional: "; optim
-  ...
-End
- - -[ARRAY] - -

For Each

- -

Gambas 裡面,您可以輕易地用迴圈跑過陣列、集合以及其他支援 For Each 的可列舉類別。

- -

例如:

- -
Dim Xml As New XmlDocument
-Dim Node As XmlNode
-Dim I As Integer
-
-' Open XML file
-Xml.Open("pokus.xml")
-' Children is indexed via [i], since it's an array
-For I = 0 To Xml.Root.Children.Count - 1
-  'Attributes are looped via For Each, since it's a collection
-  For Each Node In Xml.Root.Children[i].Attributes
-    Print Node.Name;; Node.Value
-  Next
-Next
- - -[ICON] - -

預設圖示

- -

您可以使用內建的圖示來建構更美觀的圖形程式。這些內建圖示提供多種大小 ("small", "medium", "large",...),您也可以使用絕對大小 (從 16x16 到 256x256)。

- -

例如: - -

Image1.Picture = Picture["icon:/32/warning"]
-Image2.Picture = Picture["icon:/small/error"]
-
- -

警告: 這個功能需要 gb.form 元件. - - -[SETTINGS] - -

設定

- -

如果您需要在程式中儲存一些設定值 (如視窗位置、大小),您很幸運,在 Gambas -中做到這個是易如反掌。 :-) - -

儲存視窗位置: -

Settings.Write(TheForm)
- -

回復視窗位置: -

Settings.Read(TheForm)
- -儲存設定的方法: -
Settings["Slot/Key"] = Value
- -讀取設定的方法: -
Value = Settings["Slot/Key", DefaultValue]
- -這些設定將被儲存在 ~/.config/gambas3/<MyApplication>.conf 中, -<MyApplication> 是您的專案名稱。 - -

警告: 這個功能需要 gb.settings 元件。 - - -[EDITOR] - -

來點編輯器的提示...

- -

兩種註解類型

- -
' 普通註解
-
'' 粗體註解
- -

粗體註解可以用來替程式碼撰寫文件.

- -

如何使用程式碼片段

- -

輸入 main 然後按下 TAB 鍵. 編輯器將自動插入 static public Main -到程式碼中. - -

輸入 ds 然後按下 TAB 鍵. 編輯器將自動插入區域字串變數的宣告, 之後可以立即輸入變數名稱. - -

程式碼片段可以在開發環境的選項中設定. - - -[END] - -

您己讀完所有的每日提示提示。我希望您己經是 Gambas 的專家了!:-)

- -

如果您想爲Gambas貢獻一份力量,請用電子郵件發送新提示到:

-英文:

g4mba5@gmail.com

-中文:

yizhou.he@gmail.com

- -

預先感謝!

- - - diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.zh_TW.txt gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.zh_TW.txt --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.zh_TW.txt 1970-01-01 00:00:00.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.zh_TW.txt 2021-09-14 19:01:29.000000000 +0000 @@ -0,0 +1,442 @@ +[WELCOME] + +

歡迎使用Gambas

+ +

Gambas是一個基於高級Basic語言直譯器的圖形界面的開發環境。

+ +

Gambas的目標是使您能輕易而快速地開發出功能強大的程式。但是高效而簡潔的程式還得靠您自己的努力...

+ +

希望您會喜歡!

+ +

Benoît Minisini
+English:g4mba5@gmail.com
+中文:yizhou.he@gmail.com

+ +[STARTUP] + +

每一個專案都需要有一個啟動類別,這個啟動類別必須定義一個名爲Main的無參數靜態公用方法,它將成爲您的程式的進入點。

+ +

定義啟動類別的方法是,用鼠標右鍵點擊工程目錄樹中要設爲啟動類別的類別,並在彈出的右鍵菜單中選中啟動類別

+ +

您不需要在啟動視窗中定義一個Main方法,因爲Gambas己經預定義好了。

+ +

這個預定義的啟動方法創建並顯示視窗, 就像Visual Basic™一樣。

+ + +[OPEN] + +

GambasOPEN函數和Visual Basic的不太一樣,它並不回傳整數,而是回傳一個檔案物件。

+ +

所以,不要使用:

+ +
DIM handle AS Integer
+...
+OPEN "myfile" FOR READ AS #handle
+ +

而應該使用:

+ +
DIM handle AS File
+...
+handle = OPEN "myfile" FOR READ
+ + +[CATDIR] + +

您知道嗎?您可以使用&/來連接資料夾和檔案名稱,這個運算子會自動處理路徑結尾的/以免重複。

+ +

例如:

+ +
PRINT "/home/gambas" &/ ".bashrc"
+/home/gambas/.bashrc
+
+PRINT "/home/gambas/" &/ "/tmp" &/ "foo.bar"
+/home/gambas/tmp/foo.bar
+
+ +

怎麼樣?好用吧!

+ + +[EXEC] + +

可以將您的整個專案生成一個可執行檔,在專案選單中選擇生成可執行檔

+ +

Gambas生成可執行檔時,預設會將產生的可執行檔放到您的專案目錄下,可執行檔名和您的專案名稱相同。

+ + +[PATH] +

+ 相對路徑在Gambas中有特殊含義,它們總是指向您專案內的文件。 +

+這裏沒有當前目錄的概念,沒有CHDIR之類的關鍵字來改變它。 +

+注意:您只能用相對路徑存取專案中的檔案,因爲絕對路徑在您生成可執行檔後就不再可靠了。 + + +[GLOBAL] + + Gambas裏不再有全域變數了! +

+新的處理方法是,在您的主模組中宣告它們爲PUBLIC(公用類型)。 +

+如果您的專案中沒有主模組,只有主視窗,那麼宣告它們爲STATIC PUBLIC(靜態公用類型)。 +

+要存取這些變數,您必須使用主模組名或主視窗名:MyMainModule.MyGlobalVariable或 +MyMainForm.MyGlobalVariable。 + + +[EMPTY] + +

要知道一個字串是否爲空,並不需要使用Len()函數,您可以直接測試它,因爲空字串爲FALSE非空字串爲TRUE

+ +

例如,您不需要寫:

+ +
IF Len(MyString) > 0 THEN ...
+IF Len(MyString) = 0 THEN ...
+ +

您只需寫:

+ +
IF MyString THEN ...
+IF NOT MyString THEN ...
+ +[TRANSLATE] + +

Gambas應用程式是可完全翻譯的,條件是您應指定哪些字串是必須要翻譯的。

+

用括號將字串括起來就表示該字串是可以被翻譯的。

+ +

PRINT ("我可以被翻譯!")
+PRINT "我不能被翻譯!"
+ +[EVENT] + +

每個控制項和每個物件都可以產生事件,都有一個event observer(事件觀察器)和一個事件 group name(組名)。

+ +

事件觀察器捕捉物件產生的每一個事件,事件組名將是您用來處理事件的類別名稱的前綴。

+ +

預設的事件觀察器是您創建的控制項的容器物件,事件組名是控制項名。

+ +

在這種狀況下,一個視窗會接收您在它上面創建的所有控制項發生的事件。

+ +
' Gambas form
+DIM hButton AS Button
+
+PUBLIC SUB _new()
+  hButton = NEW Button(ME) AS "MyButton"
+END
+
+PUBLIC SUB MyButton_Click()
+  PRINT "You have clicked MyButton !"
+END
+
+ + +[FORM] + +

Gambas中,一個視窗是它自己的事件觀察器,所以您可以直接在它自己的類代碼中管理它的事件(像Resize, +Activate, ...)。

+ +

這樣,從Visual Basic轉來的新手們就不會迷失方向:-)。

+ + +[EMBED] + +

Gambas中,您可以在視窗中嵌入視窗!

+ +

要實現如此強大的功能,只要在初始化視窗物件時將父容器做爲最後一個參數傳給視窗構建函數。

+ +

例如:

+

DIM hForm AS MyDialog
+DIM hSuperControl AS MyForm

+' 創建一個對話框
+hForm = NEW MyDialog
+' 在此對話框中插入一個視窗
+' 注意此視窗需要三個參數,最後一個參數是容器物件
+hSuperControl = NEW MyForm(Param1, Param2, MyDialog)
+' 移動並改變視窗的大小
+hSuperControl.Move(8, 8, 128, 64)
+

+ +

小心:嵌入後的視窗還是個視窗,它還是它自己的事件觀察器。

+ + +[GROUP] + +

每個控制項都有一個Group(組)屬性,當此屬性被設置,事件處理名稱的前綴就將是組名而不是控制項名。

+ +

假定您有一個Button(按鈕)名叫btnAction +有一個Click事件處理:

+ +
PUBLIC SUB btnAction_Click()
+ +

如果您將btnAction(Group)屬性設爲MyGroup,那麼事件處理從按鈕收到的事件將是:

+ +
PUBLIC SUB MyGroup_Click()
+ +

此屬性讓您在一個函數中處理不同的控制項的事件,同組中的控制項不需要有相同的類型!

+ +

註釋: Visual Basic老手可能會認為這個屬性和VB中的控制項陣列相似,但更為強大。:-)

+ + +[TAG] + +

每一個控制項都有Tag屬性,此屬性是爲編程者設計的,可以是任何您想要的VARIANT(可變類型)數據。

+ +

這在使用同組的公用事件處理中區別控制項時非常有用。

+ + + +[LAST] + +

LAST關鍵字回傳最近一次發生事件的控制項,當您要寫一個獨立於控制項名的事件處理函式就非常有用。

+ +

例如,假設您要寫一個計算器程式。 +您定義了十個按鈕,每個數字一個,它們都在一個名叫"Digit"的群組,每個控制項的Tag屬性都被設爲相應的數字。 +您的處理程序將會是:

+ +

PUBLIC SUB Digit_Click()

+  Display = Display & LAST.Tag
+  RefreshDisplay

+END

+ + +[LEFT] + +

大名鼎鼎的BASIC函數Left$Right$ +和Mid$Gambas中有了新功能。

+ +

Left$Right$的第二個參數是可選的,預設值爲1。

+ +

Left$("Gambas") 回傳"G"
+Right$("Gambas") 回傳"s"

+ +

第二個參數可以是負數,它的用途是指定反方向上將被切掉的字元個數。

+ +

Left$("Gambas", -2) 回傳"Gamb"
+Right$("Gambas", -2) 回傳"mbas"

+ +

相同的,Mid$的第三個參數也可以是負數,指定字串末端將被切掉的字元的個數。

+ +

Mid$("Gambas", 2, -2) 回傳"amb" + +[OBSERVER] + +

Observer類別允許您在物件發出事件之前先攔截它。

+ +
MyTextBox = NEW TextBox(ME) AS "MyTextBox"
+MyObserver = NEW Observer(MyTextBox) AS "MyObserver"
+...
+PUBLIC SUB MyObserver_KeyPress()
+  DEBUG "Got it first"
+END
+
+PUBLIC SUB MyTextBox_KeyPress()
+  DEBUG "Got it next"
+END
+ + Observer能取消事件,防止物件對外發出事件。 + + +[STRING] + +

Gambas使用UTF-8字元編碼在記憶體中描述字串。

+ +

但是所有的標準Gambas字串函數只處理ASCII碼: +LeftMidRightUCase... + +

如果想處理UTF-8編碼的字串,必須使用String靜態類別的方法,它們的名字和標準字串處理函數完全相同。 + +

PRINT Len("bébé");; Left$("bébé", 3)
+6 bé
+PRINT String.Len("bébé");; String.Left("bébé", 3)
+4 béb
+ + +[ASSIGNMENT] + +

Gambas實現了C/C++程序員常用的快捷賦值。 + +

MyVariable += 2 等價於 MyVariable = MyVariable + 2 + +

MyVariable &= "Great" 等價於 MyVariable = MyVariable & "Great" + +

諸如此類... + + +[DEBUG] + +

可以使用DEBUG語句列印除錯信息到控制台(也就是stderr),用法和PRINT語句完全一樣。 + +

除錯信息前綴有類別名稱,方法名稱和DEBUG語句所在的行號。 + +

除錯信息在生成不包含除錯信息的可執行檔時會被自動刪除。 + + +[TRY] + +

Gambas使用下面的語句實現錯誤管理: +TRYERRORCATCHFINALLY。 + +

TRY嘗試執行一個語句而不引發錯誤,隨後使用ERROR語句檢測語句執行中是否發生錯誤。 + +

TRY MyFile = OPEN "/etc/password" FOR WRITE
+IF ERROR THEN PRINT "I cannot do what I want!"
+ + +[CATCH] + +

Gambas使用下面的語句實現錯誤管理: +TRYERRORCATCHFINALLY。 + +

CATCH標明函數或者過程中錯誤管理部分(錯誤處理常式)的程式碼的開頭。 + +

當錯誤發生於函數執行的起始到終止之間時,會跳去執行錯誤處理常式的部分。 + +

如果錯誤發生於執行錯誤處理常式期間,會繼續向下一層傳送。錯誤處理常式不保護自己! + +

SUB ProcessFile(FileName AS STRING)
+  ...
+  OPEN FileName FOR READ AS #hFile
+  ...
+  CLOSE #hFile
+CATCH ' 只在發生錯誤時執行
+  PRINT "Cannot process file "; FileName
+END
+ + +[FINALLY] + +

Gambas使用下面的語句實現錯誤管理: +TRYERRORCATCHFINALLY。 + +

在函數的尾部,FINALLY語句引領的代碼被執行,即使在其執行期間有錯誤發生。 + +FINALLY部分是非必要的。如果函數中有錯誤處理常式,FINALLY部分必須位於處理常式之前。 + + +

FINALLY部分是非必要的。如果函數中有錯誤處理常式,FINALLY部分必須位於處理常式之前。 + +

如果錯誤發生於FINALLY部分執行期間,錯誤會正常傳送。 + +

SUB ProcessFile(FileName AS STRING)
+  ...
+  OPEN FileName FOR READ AS #hFile
+  ...
+FINALLY ' 即使有錯誤發生也會被執行
+  CLOSE #hFile
+CATCH ' 只在錯誤發生時執行
+  PRINT "Cannot print file "; FileName
+END
+ + +[OPTIONAL] + +

Optional

+ +

Gambas裡面,函數和程序的參數可以含有選擇性的參數。

+ +

定義選擇性參數的方法是在參數名稱面加上 Optional 關鍵字。

+ +

您也可以在選擇性參數後面加上預設值,例如:

+ +
Private Sub MyFunction(Param AS String, Optional Optim AS String = "Default")
+  ...
+  Print "Required: "; param; ", Optional: "; optim
+  ...
+End
+ + +[ARRAY] + +

For Each

+ +

Gambas 裡面,您可以輕易地用迴圈跑過陣列、集合以及其他支援 For Each 的可列舉類別。

+ +

例如:

+ +
Dim Xml As New XmlDocument
+Dim Node As XmlNode
+Dim I As Integer
+
+' Open XML file
+Xml.Open("pokus.xml")
+' Children is indexed via [i], since it's an array
+For I = 0 To Xml.Root.Children.Count - 1
+  'Attributes are looped via For Each, since it's a collection
+  For Each Node In Xml.Root.Children[i].Attributes
+    Print Node.Name;; Node.Value
+  Next
+Next
+ + +[ICON] + +

預設圖示

+ +

您可以使用內建的圖示來建構更美觀的圖形程式。這些內建圖示提供多種大小 ("small", "medium", "large",...),您也可以使用絕對大小 (從 16x16 到 256x256)。

+ +

例如: + +

Image1.Picture = Picture["icon:/32/warning"]
+Image2.Picture = Picture["icon:/small/error"]
+
+ +

警告: 這個功能需要 gb.form 元件. + + +[SETTINGS] + +

設定

+ +

如果您需要在程式中儲存一些設定值 (如視窗位置、大小),您很幸運,在 Gambas +中做到這個是易如反掌。 :-) + +

儲存視窗位置: +

Settings.Write(TheForm)
+ +

回復視窗位置: +

Settings.Read(TheForm)
+ +儲存設定的方法: +
Settings["Slot/Key"] = Value
+ +讀取設定的方法: +
Value = Settings["Slot/Key", DefaultValue]
+ +這些設定將被儲存在 ~/.config/gambas3/<MyApplication>.conf 中, +<MyApplication> 是您的專案名稱。 + +

警告: 這個功能需要 gb.settings 元件。 + + +[EDITOR] + +

來點編輯器的提示...

+ +

兩種註解類型

+ +
' 普通註解
+
'' 粗體註解
+ +

粗體註解可以用來替程式碼撰寫文件.

+ +

如何使用程式碼片段

+ +

輸入 main 然後按下 TAB 鍵. 編輯器將自動插入 static public Main +到程式碼中. + +

輸入 ds 然後按下 TAB 鍵. 編輯器將自動插入區域字串變數的宣告, 之後可以立即輸入變數名稱. + +

程式碼片段可以在開發環境的選項中設定. + + +[END] + +

您己讀完所有的每日提示提示。我希望您己經是 Gambas 的專家了!:-)

+ +

如果您想爲Gambas貢獻一份力量,請用電子郵件發送新提示到:

+英文:

g4mba5@gmail.com

+中文:

yizhou.he@gmail.com

+ +

預先感謝!

+ + + diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.zh.txt gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.zh.txt --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.zh.txt 1970-01-01 00:00:00.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas3/tips/tips.zh.txt 2021-09-14 19:01:29.000000000 +0000 @@ -0,0 +1,341 @@ +[WELCOME] + +

欢迎使用Gambas

+ +

Gambas是一个基于高级Basic语言解释器的图形界面的开发环境。

+ +

Gambas的目标是使你能轻易而快速地开发出功能强大的程序。但是高效而简洁的程序还得靠你自己的努力...

+ +

希望你能喜欢!

+ +

Benoît Minisini
+English:g4mba5@gmail.com
+中文:yizhou.he@gmail.com

+ +[STARTUP] + +

每一个工程都需要有一个启动类,这个启动类必须定义一个名为Main的无参数的静态公用方法,它将成为你的程序的启动方法。

+ +

定义启动类的方法是,用鼠标右键点击工程目录树中要设为启动类的类,并在弹出的右键菜单中选中启动类

+ +

你不需要在启动窗体中定义一个Main方法,因为Gambas己经预定义好了。

+ +

这个预定义的启动方法创建并显示窗体就像Visual Basic™一样。

+ + +[OPEN] + +

GambasOPEN函数和Visual Basic的不太一样,它并不返回一个整型变量,而是返回一个文件对象。

+ +

所以,不要使用:

+ +
DIM handle AS Integer
+...
+OPEN "myfile" FOR READ AS #handle
+ +

而应该使用:

+ +
DIM handle AS File
+...
+handle = OPEN "myfile" FOR READ
+ + +[CATDIR] + +

你知道吗?你可以使用&/操作符连结文件路径中的目录和文件,此操作符处理路径尾的斜杠以免重复。

+ +

例如:

+ +
PRINT "/home/gambas" &/ ".bashrc"
+/home/gambas/.bashrc
+
+PRINT "/home/gambas/" &/ "/tmp" &/ "foo.bar"
+/home/gambas/tmp/foo.bar
+
+ +

怎么样?好用吧!

+ + +[EXEC] + +

可以将你的整个工程生成一个可执行文件,在工程菜单中选择生成可执行文件

+ +

Gambas生成可执行文件时,默认将产生的可执行文件放到你的工程目录下,可执行文件名和你的工程名相同。

+ + +[PATH] +

+ 相对路径在Gambas中有特殊含义,它们总是指向你工程内的文件。 +

+这里没有当前目录的概念,没有CHDIR之类的关键字来改变它。 +

+注意:只能使用相对路径访问你的工程文件,因为绝对路径在你生成可执行文件后就不再可靠了。 + + +[GLOBAL] + + Gambas里不再有全局变量了! +

+相应的,在你的主模块中声明它们为PUBLIC(公用类型)。 +

+如果你的工程中没有主模块,只有主窗体,那么声明它们为STATIC PUBLIC(静态公用类型)。 +

+要访问这些变量,你必须使用主模块名或主窗体名:MyMainModule.MyGlobalVariable或 +MyMainForm.MyGlobalVariable。 + + +[EMPTY] + +

要知道一个字符串是否为空,没必要使用Len()函数,你可以直接测试它,因为空字符串为FALSE非空字符串为TRUE

+ +

例如,你不用写:

+ +
IF Len(MyString) > 0 THEN ...
+IF Len(MyString) = 0 THEN ...
+ +

你只需写:

+ +
IF MyString THEN ...
+IF NOT MyString THEN ...
+ +[TRANSLATE] + +

Gambas应用程序是可完全翻译的,条件是你应声明哪些字符串是必须要翻译的,哪些不必翻译。

+

用括号括起来就表明该字符串是可以被翻译的。

+ +

PRINT ("我可以被翻译!")
+PRINT "我不能被翻译!"
+ +[EVENT] + +

每个控件和每个对象都可以产生事件,都有一个event observer(事件观察器)和一个事件 group name(组名)。

+ +

事件观察器捕捉对象产生的每一个事件,事件组名将是你用来处理事件的类名的前缀。

+ +

默认的事件观察器是你创建的控件的容器对象,事件组名是控件名。

+ +

这梓,一个窗体接收你在它上面创建的所有控件发生的事件。

+ +
' Gambas form
+DIM hButton AS Button
+
+PUBLIC SUB _new()
+  hButton = NEW Button(ME) AS "MyButton"
+END
+
+PUBLIC SUB MyButton_Click()
+  PRINT "You have clicked MyButton !"
+END
+
+ + +[FORM] + +

Gambas中,一个窗体是它自己的事件观察器,所以你可以直接在它自己的类代码中管理它的事件(像Resize, +Activate, ...)。

+ +

这样,从Visual Basic转来的新手们就不会迷失方向:-)。

+ + +[EMBED] + +

Gambas中,你可以在窗体中嵌入窗体!

+ +

要实现如此强大的功能,只要在初始化窗体对象时将父容器做为最后一个参数传给窗体构建函数。

+ +

例如:

+

DIM hForm AS MyDialog
+DIM hSuperControl AS MyForm

+' 创建一个对话框
+hForm = NEW MyDialog
+' 在此对话框中插入一个窗体
+' 注意此窗体需要三个参数,最后一个参数是容器对象
+hSuperControl = NEW MyForm(Param1, Param2, MyDialog)
+' 移动并改变窗体的大小
+hSuperControl.Move(8, 8, 128, 64)
+

+ +

小心:嵌入后的窗体还是个窗体,它还是它自己的事件观察器。

+ + +[GROUP] + +

每个控件都有一个Group(组)属性,当此属性被设置,事件处理名称的前缀就将是组名而不是控件名。

+ +

假定你有一个Button(按钮)名叫btnAction +有一个Click事件处理:

+ +
PUBLIC SUB btnAction_Click()
+ +

如果你将btnAction(Group)属性设为MyGroup,那么事件处理从按钮收到的事件将是:

+ +
PUBLIC SUB MyGroup_Click()
+ +

此属性让你在一个函数中处理不同的控件的事件,同组中的控件不需要有相同的类型!

+ +

注释: Visual Basic老手可以认为是控件数组,但有更为强大的用法。:-)

+ + +[TAG] + +

每一个控件都有Tag属性,此属性是为编程者设计的,可以是任何你想要的VARIANT(变体类型)数据。

+ +

这在使用同组的公用事件处理中区别控件时非常有用。

+ + + +[LAST] + +

LAST关键字返回发生事件的最近控件,当你要写一个独立于控件名的事件处理类就非常有用。

+ +

例如,假设你要写一个计算器程序。 +你定义了十个按钮,每个数字一个,它们都在一个名叫"Digit"的,每个控件的Tag属性都被设为相应的数字。 +你的处理程序将会是:

+ +

PUBLIC SUB Digit_Click()

+  Display = Display & LAST.Tag
+  RefreshDisplay

+END

+ + +[LEFT] + +

大名鼎鼎的BASIC函数Left$Right$ +和Mid$Gambas中有了新功能。

+ +

Left$Right$的第二个参数是可选的,默认值为1。

+ +

Left$("Gambas") 返回"G"
+Right$("Gambas") 返回"s"

+ +

第二个参数可以是负数,它将指定反方向上将被切掉的字符个数。

+ +

Left$("Gambas", -2) 返回"Gamb"
+Right$("Gambas", -2) 返回"mbas"

+ +

相同的,Mid$的第三个参数也可以是负数,指定字符串末端将被切掉的字符的个数。

+ +

Mid$("Gambas", 2, -2) 返回"amb" + +[OBSERVER] + +

Observer类允许你将对象发生的所有事件在被发送之前截获。

+ +
MyTextBox = NEW TextBox(ME) AS "MyTextBox"
+MyObserver = NEW Observer(MyTextBox) AS "MyObserver"
+...
+PUBLIC SUB MyObserver_KeyPress()
+  DEBUG "Got it first"
+END
+
+PUBLIC SUB MyTextBox_KeyPress()
+  DEBUG "Got it next"
+END
+ + Observer能取消事件防止对象有效的发出它。 + + +[STRING] + +

Gambas使用UTF-8字符编码在内存中描述字符串。

+ +

但是所有的标准Gambas字符串函数处理ASCII码: +LeftMidRightUCase... + +

如果想处理UTF-8编码的字符串,必须使用String静态类的方法,它们有和标准字符串处理函数相同的名字。 + +

PRINT Len("bébé");; Left$("bébé", 3)
+6 bé
+PRINT String.Len("bébé");; String.Left("bébé", 3)
+4 béb
+ + +[ASSIGNMENT] + +

Gambas实现了C/C++程序员常用的快捷赋值。 + +

MyVariable += 2 等价于 MyVariable = MyVariable + 2 + +

MyVariable &= "Great" 等价于 MyVariable = MyVariable & "Great" + +

诸如此类... + + +[DEBUG] + +

可以使用DEBUG语句打印调试信息到控制台(也就是标准错误输出),用法和PRINT语句完全一样。 + +

调试信息前缀有类名,方法名和DEBUG语句所在行号。 + +

调试信息在生成不包含调试信息的可执行文件时被自动删除。 + + +[TRY] + +

Gambas使用下面的语句实现错误管理: +TRYERRORCATCHFINALLY。 + +

TRY尝试执行一个语句而不引发错误,随后使用ERROR语句检测语句执行中是否发生错误。 + +

TRY MyFile = OPEN "/etc/password" FOR WRITE
+IF ERROR THEN PRINT "I cannot do what I want!"
+ + +[CATCH] + +

Gambas使用下面的语句实现错误管理: +TRYERRORCATCHFINALLY。 + +

CATCH标明函数或者过程中错误管理部分(错误陷阱)的代码起始。 + +

当错误发生于函数执行的起始到终止之间,执行错误陷阱部分。 + +

如果错误发生于执行错误陷阱代码期间,会正常传送。错误陷阱不保护自己! + +

SUB ProcessFile(FileName AS STRING)
+  ...
+  OPEN FileName FOR READ AS #hFile
+  ...
+  CLOSE #hFile
+CATCH ' 仅仅发生错误时执行
+  PRINT "Cannot process file "; FileName
+END
+ + +[FINALLY] + +

Gambas使用下面的语句实现错误管理: +TRYERRORCATCHFINALLY。 + +

在函数的尾部,FINALLY语句引领的代码被执行,即使在其执行期间有错误发生。 + +FINALLY部分是非托管的。如果函数中有错误陷阱,FINALLY部分必须位于陷阱之前。 + + +

FINALLY部分是非托管的。如果函数中有错误陷阱,FINALLY部分必须位于陷阱之前。 + +

如果错误发生于FINALLY部分执行期间,错误会正常传送。 + +

SUB ProcessFile(FileName AS STRING)
+  ...
+  OPEN FileName FOR READ AS #hFile
+  ...
+FINALLY '总是执行,即使有错误发生
+  CLOSE #hFile
+CATCH ' 仅当错误发生时执行
+  PRINT "Cannot print file "; FileName
+END
+ + +[END] + +

你己读完所有今日提示。我希望你己经是一个Gambas的专家了!:-)

+ +

如果你想为Gambas贡献一份力量,用电子邮件发送新提示到:

+英文:

g4mba5@gmail.com

+中文:

yizhou.he@gmail.com

+ +

预先感谢!

+ + + diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas-wiki/gambas3-ide.project gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas-wiki/gambas3-ide.project --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/app/src/gambas-wiki/gambas3-ide.project 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/app/src/gambas-wiki/gambas3-ide.project 2021-09-14 19:01:29.000000000 +0000 @@ -31,7 +31,7 @@ Description="Integrated Development Environment for Gambas" Authors="Benoît Minisini\nFabien Bodard\nCharlie Reinl\nJosé Luis Redrejo\nRobert Rowe\nTobias Boege" Arguments=[["-L"],["-t","/home/benoit/gambas/git/master/app/src/gambas3"],["--help"]] -Environment="GB_GUI=gb.gtk3\n GTK_DEBUG=interactive" +Environment="GB_GUI=gb.gtk3\n GTK_DEBUG=interactive\nGB_NO_JIT=1" TabSize=2 Translate=1 Language=en diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.dbus.trayicon/.src/TrayIcon.class gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.dbus.trayicon/.src/TrayIcon.class --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.dbus.trayicon/.src/TrayIcon.class 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.dbus.trayicon/.src/TrayIcon.class 2021-09-14 19:01:29.000000000 +0000 @@ -32,7 +32,7 @@ Private $hIcon As Picture Private $sMenu As String Private $sText As String -Private $bIconDirty As Boolean +Private $iIconId As Integer Private $vTag As Variant Public Sub _new() @@ -177,17 +177,24 @@ Private Sub Picture_Write(Value As Picture) + If $hIcon = Value Then Return + $hIcon = Value If $bAppIndicator Then - $bIconDirty = True + + Try Kill _GetIconThemePath() &/ GetIconFile() + Inc $iIconId If $bVisible Then Hide Show Endif Endif - If $bVisible Or If $bAppIndicator Then DBus[GetServiceName()].Raise($hObject, "org.kde.StatusNotifierItem.NewIcon") + If $bVisible Or If $bAppIndicator Then + DBus[GetServiceName()].Raise($hObject, "org.kde.StatusNotifierItem.NewIcon") + 'DBus[GetServiceName()].Raise($hObject, "org.freedesktop.DBus.Properties.PropertiesChanged", ["org.kde.StatusNotifierItem", Object.New("Collection"), ["IconPixmap"]]) + Endif End @@ -254,6 +261,13 @@ End +Private Sub GetIconFile() As String + + Return "icon-" & CStr($iId) & ":" & CStr($iIconId) & ".png" + +End + + Public Sub _GetIconName() As String Dim hPict As Picture @@ -263,13 +277,12 @@ If $bAppIndicator Then sPath = _GetIconThemePath() - sName = "icon-" & CStr($iId) & ".png" + sName = GetIconFile() - If Not Exist(sPath &/ sName) Or If $bIconDirty Then + If Not Exist(sPath &/ sName) Then hPict = $hIcon If Not hPict Then hPict = Picture["default.png"] hPict.Save(sPath &/ sName) - $bIconDirty = False Endif Return File.BaseName(sName) diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.desktop/.src/Main.module gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.desktop/.src/Main.module --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.desktop/.src/Main.module 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.desktop/.src/Main.module 2021-09-14 19:01:29.000000000 +0000 @@ -101,6 +101,10 @@ Dim hFile As File Dim sLine As String Dim aLine As String[] + Dim sAltDirectory As String + Dim bFullPath As Boolean + + sAltDirectory = "XDG_" & sDirectory & "_DIR" hFile = Open sFileConfig For Input While Not Eof(hFile) @@ -108,6 +112,11 @@ sLine = Trim(sLine) If Not sLine Then Continue If Left(sLine) = "#" Then Continue + If sLine Begins sAltDirectory Then + sDirectory = sAltDirectory + bFullPath = True + Break + Endif If sLine Begins sDirectory Then Break sLine = "" Wend @@ -117,6 +126,7 @@ sLine = aLine[0] If Left(sLine) = Chr$(34) Then sLine = Mid$(sLine, 2, -1) If sLine Begins "$HOME/" Then sLine = Replace(sLine, "$HOME", System.User.Home) + If Not bFullPath Then sLine = User.Home &/ sLine Return sLine Endif @@ -190,7 +200,7 @@ sFileConfig = SearchPathConfig(sXdgConfigHome, sXdgConfigDirs) If sFileConfig Then - sDir = SearchPathVariable(sFileConfig, "XDG_" & UCase(sType) & "_DIR") + sDir = SearchPathVariable(sFileConfig, UCase(sType)) Else sDir = System.User.Home &/ "Desktop" Endif @@ -223,9 +233,7 @@ ' hMime = DesktopMime.FromFile("/bin/ls") ' Print hMime.Type - Print Desktop.Count - Print Desktop.Showing - Desktop.Showing = True + Print Desktop.Path End diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.form/.project gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.form/.project --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.form/.project 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.form/.project 2021-09-14 19:01:29.000000000 +0000 @@ -1,6 +1,6 @@ # Gambas Project File 3.0 Title=More controls for graphical components -Startup=FTestMaskBox +Startup=FTestDateChooser Icon=.hidden/icon.png Version=3.16.90 VersionFile=1 @@ -10,7 +10,7 @@ Component=gb.settings Component=gb.form.stock Authors="Benoît Minisini" -Environment="GB_GUI=gb.gtk3\n GB_STOCK_DEBUG=1\n LANG=zh_CN.UTF-8\n LC_ALL=en_US.UTF-8\n LC_ALL=zh_CN.UTF-8\n GTK_DEBUG=interactive" +Environment="GB_GUI=gb.qt5\n GB_STOCK_DEBUG=1\n LANG=zh_CN.UTF-8\n LC_ALL=en_US.UTF-8\n LC_ALL=zh_CN.UTF-8\n GTK_DEBUG=interactive" TabSize=2 Translate=1 Language=en diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.form/.src/Button/ButtonBox.class gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.form/.src/Button/ButtonBox.class --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.form/.src/Button/ButtonBox.class 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.form/.src/Button/ButtonBox.class 2021-09-14 19:01:29.000000000 +0000 @@ -14,6 +14,7 @@ Event Activate Event Clear Event Filter +Event Validate Property Picture As Picture Property Text As String @@ -211,6 +212,16 @@ End +Public Sub TextBox_Validate() + + Dim bStop As Boolean + + bStop = Raise Validate + If bStop Then Stop Event + +End + + Public Sub TextBox_Change() If $bFilter Then $hTimer.Start diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.form/.src/File/DirBox.class gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.form/.src/File/DirBox.class --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.form/.src/File/DirBox.class 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.form/.src/File/DirBox.class 2021-09-14 19:01:29.000000000 +0000 @@ -57,9 +57,13 @@ If Dialog.SelectDirectory() Then Return $hButtonBox.Text = Dialog.Path - '$hButtonBox.Foreground = Color.Foreground - Raise Click + +End + +Public Sub Button_Change() + Raise Change End + diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.form/.src/MaskBox2.class gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.form/.src/MaskBox2.class --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.form/.src/MaskBox2.class 1970-01-01 00:00:00.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.form/.src/MaskBox2.class 2021-09-14 19:01:29.000000000 +0000 @@ -0,0 +1,62 @@ +' Gambas class file + +'Export + +Inherits UserControl + +Public Const _Properties As String = "*,-Password,-MaxLength,Action,Filter,Mask,ShowDefault,Prompt{MaskBox.*}" +'Public Const _DefaultEvent As String = "Click" +'Public Const _DefaultSize As String = "24,4" +Public Const _Similar As String = "TextBox" +Public Const _DrawWith As String = "TextBox" + +Public Enum Space, Underscore, Bracket, Dash, Square, Circle + +Event Filter(Char As String) +Event Validate + +Property Mask As String + +Private $sMask As String +'Property Filter As String +'Property ShowDefault As Boolean +'Property Text As String +'Property Prompt As Integer + +Public Sub _new() + + UpdateMask + +End + +Private Function Mask_Read() As String + + Return $sMask + +End + +Private Sub Mask_Write(Value As String) + + If Value = $sMask Then Return + $sMask = Value + UpdateMask + +End + +Private Sub UpdateMask() + + Dim hChild As Control + Dim hTextBox As TextBox + + For Each hChild In Me.Children + hChild.Delete + Next + + If Not $sMask Then + + hTextBox = New TextBox(Me) + Me.Proxy = hTextBox + + Endif + +End \ No newline at end of file diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.form/.src/MaskBox.class gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.form/.src/MaskBox.class --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.form/.src/MaskBox.class 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.form/.src/MaskBox.class 2021-09-14 19:01:29.000000000 +0000 @@ -78,15 +78,17 @@ End -Private Sub GetFirstCharacterPos() As Integer +Private Sub GetFirstCharacterPos(Optional iPos As Integer) As Integer - Dim iPos As Integer Dim sText As String Dim sCar As String + Dim I As Integer - For iPos = 0 To $aMask.Max - If $aMask[iPos] Then Break + For I = iPos To $aMask.Max + If $aMask[I] Then Break Next + + iPos = I If IsRightAlign(iPos) Then sText = UnmaskText(Super.Text) @@ -101,19 +103,23 @@ End -Private Sub GetLastCharacterPos() As Integer +Private Sub GetLastCharacterPos(Optional iPos As Integer) As Integer - Dim iPos As Integer Dim sText As String Dim sCar As String + Dim I As Integer - For iPos = $aMask.Max DownTo 0 - If $aMask[iPos] Then - Inc iPos + If IsMissing(iPos) Then iPos = $aMask.Max + + For I = iPos DownTo 0 + If $aMask[I] Then + Inc I Break Endif Next + iPos = I + If Not IsRightAlign(iPos) Then sText = UnmaskText(Super.Text) While iPos > 0 @@ -194,7 +200,12 @@ $sSeparator = sSeparator $sAlign = sAlign $sDefault = sDefault - $iPosFocus = iPosFocus + + If iPosFocus < 0 Then + $iPosFocus = GetFirstCharacterPos() + Else + $iPosFocus = iPosFocus + Endif 'If $sMaskChar Then $sDefault = Replace($sDefault, "_", $sMaskChar) End @@ -212,8 +223,6 @@ Clear() Endif - Me.Pos = GetFirstCharacterPos() - End ' Private Sub IsMaskCharacter(sCar As String) As Boolean @@ -283,6 +292,48 @@ End +Private Sub IsFull(sText As String, iPos As Integer) As Boolean + + Dim iStart As Integer + Dim iEnd As Integer + Dim I As Integer + + iStart = GetPreviousSeparator(iPos) + iEnd = GetNextSeparator(iPos) + + For I = iStart + 1 To iEnd - 1 + If String.Mid$(sText, I + 1, 1) = UNMASKED_CHAR Then Return + Next + + Return True + +End + +Private Sub IsSeparator(iPos As Integer) As Boolean + + If iPos < 0 Or If iPos >= $aMask.Count Then Return True + If Not $aMask[iPos] Then Return True + +End + + +Private Sub IsVoid(sText As String, iPos As Integer) As Boolean + + Dim iStart As Integer + Dim iEnd As Integer + Dim I As Integer + + iStart = GetPreviousSeparator(iPos) + iEnd = GetNextSeparator(iPos) + + For I = iStart + 1 To iEnd - 1 + If String.Mid$(sText, I + 1, 1) <> UNMASKED_CHAR Then Return + Next + + Return True + +End + Private Sub UnmaskText(sText As String) As String Dim iPos As Integer @@ -317,7 +368,7 @@ bNumber = False - Else If sMask = "[0-9]" Then + Else If sMask = "[0-9]" And If IsRightAlign(iPos) Then If sCar = UNMASKED_CHAR And If bNumber Then sCar = "0" @@ -478,9 +529,13 @@ Endif If sInsert Then + If Not bBefore Then + sText = String.Left(sText, iPos) & sInsert & String.Mid$(sText, iPos + 2) + Else + iPosNext = iPos While iPos > 0 If Not $aMask[iPos - 1] Then Break @@ -490,47 +545,42 @@ sText = String.Left(sText, iPos) & String.Mid$(sText, iPos + 2, iPosNext - iPos - 1) & sInsert & String.Mid$(sText, iPosNext + 1) Endif iPos = iPosNext + Endif + Endif iPos += iMove - If iMove Then + If sInsert And If IsFull(sText, iPos - 1) And If IsSeparator(iPos) Then - ' iOldPos = iPos - ' Do - ' iPos += iMove - ' If iPos < 0 Then - ' iPos = GetFirstCharacterPos() - ' Break - ' Endif - ' If iPos >= Me.Length Then - ' iPos = GetLastCharacterPos() - ' Break - ' Endif - ' If iMove > 0 Or If bDelete Then - ' If $aMask[iPos] Then Break - ' Endif - ' If iMove < 0 And If iPos > 0 And If $aMask[iPos - 1] Then Break - ' Loop - - ' If IsRightAlign(iPos) Then - ' Do - ' If (iPos + iMove) < 0 Then Break - ' If (iPos + iMove) > Me.Length Then Break - ' ' sCar = String.Mid$(sText, iPos + 1, 1) - ' ' If iMove > 0 Then - ' ' If sCar <> UNMASKED_CHAR Then Break - ' ' Else - ' ' If sCar <> "0" Then Break - ' ' Endif - ' iPos += iMove - ' Break - ' Loop - ' Endif + iPos = GetNextSeparator(iPos) + + While iPos < $aMask.Count + If $aMask[iPos] Then Break + Inc iPos + Wend + + iPos = GetFirstCharacterPos(iPos) + + Else If Key.Code = Key.BackSpace And If IsVoid(sText, iPos) Then + + iPos = GetPreviousSeparator(iPos) + + While iPos >= 0 + If $aMask[iPos] Then Break + Dec iPos + Wend + + iPos = GetLastCharacterPos(iPos) + + If iPos < 0 Then + Stop Event + Return + Endif Endif - + If bDelete Then iPosNext = GetNextSeparator(iPos) If iPosNext > iPos Then @@ -618,8 +668,8 @@ Public Sub TextBox_LostFocus() If Not $sMaskOrg Then Return + $iPosFocus = Me.Pos TextBox_Change - GotoCursor($iPosFocus) End @@ -765,6 +815,7 @@ If sMask Then If sCar <> GetDefaultCharacter(I - 1) And If sCar Not Like sMask Then Return False Else + If sCar = $sPrompt Then sCar = " " If sCar <> String.Mid$($sSeparator, I, 1) Then Return False Endif diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.form/.src/SliderBox.class gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.form/.src/SliderBox.class --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.form/.src/SliderBox.class 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.form/.src/SliderBox.class 2021-09-14 19:01:29.000000000 +0000 @@ -49,6 +49,7 @@ Private Sub Value_Write(Value As Integer) $hSlider.Value = Value + $hSpinBox.Value = Value End diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.form/.src/Test/FTestDateChooser.class gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.form/.src/Test/FTestDateChooser.class --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.form/.src/Test/FTestDateChooser.class 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.form/.src/Test/FTestDateChooser.class 2021-09-14 19:01:29.000000000 +0000 @@ -1,5 +1,13 @@ ' Gambas class file +Public Sub _new() + + DateBox2.Value = Date(Now) + DateBox2.SetFocus + +End + + Public Sub DateBox1_Change() Debug DateBox1.Value diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.form/.src/Test/FTestMaskBox.class gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.form/.src/Test/FTestMaskBox.class --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.form/.src/Test/FTestMaskBox.class 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.form/.src/Test/FTestMaskBox.class 2021-09-14 19:01:29.000000000 +0000 @@ -41,8 +41,6 @@ Public Sub Form_Open() - MaskBox1.Text = 30 - End Public Sub TextBox1_KeyPress() diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.form/.src/Test/FTestMaskBox.form gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.form/.src/Test/FTestMaskBox.form --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.form/.src/Test/FTestMaskBox.form 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.form/.src/Test/FTestMaskBox.form 2021-09-14 19:01:29.000000000 +0000 @@ -4,6 +4,6 @@ MoveScaled(0,0,64,64) { MaskBox1 MaskBox MoveScaled(13,34,24,4) - Mask = "####0= 0 Then Return hPrev = GetWorkspace(hWin) - If hPrev Then RemoveWindow(hWin) + If hPrev Then hPrev.Remove(hWin) If bResize Then hWin.Reparent(dwgBorder) @@ -424,6 +424,7 @@ If hWindow Then iInd = GetIndex(hWindow) + If iInd < 0 Then Return If Not $aWindow[iInd].Detached Then Try tabWorkspace.Index = iInd Return diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.gui.base/.project gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.gui.base/.project --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.gui.base/.project 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.gui.base/.project 2021-09-14 19:01:29.000000000 +0000 @@ -1,6 +1,6 @@ # Gambas Project File 3.0 Title=Common controls and classes for GUI components -Startup=TestMessage +Startup=FTestSplit Icon=.hidden/window.png Version=3.16.90 VersionFile=1 @@ -8,7 +8,7 @@ Component=gb.gui Component=gb.settings Arguments=[["-style=oxygen"],["-style=qtcurve"]] -Environment="GB_JIT_DEBUG=1\nGB_GUI=gb.qt5\nLIBOVERLAY_SCROLLBAR=0\n GTK_DEBUG=interactive" +Environment="GB_JIT_DEBUG=1\nGB_GUI=gb.gtk3\nLIBOVERLAY_SCROLLBAR=0\n GTK_DEBUG=interactive" TabSize=2 Translate=1 Language=en diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.gui.base/.src/Message/FMessage.class gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.gui.base/.src/Message/FMessage.class --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.gui.base/.src/Message/FMessage.class 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.gui.base/.src/Message/FMessage.class 2021-09-14 19:01:29.000000000 +0000 @@ -44,6 +44,7 @@ Default lblTitle.Hide + Me.Title = sTitle End Select diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.gui.base/.src/Split/Splitter.class gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.gui.base/.src/Split/Splitter.class --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/comp/src/gb.gui.base/.src/Split/Splitter.class 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/comp/src/gb.gui.base/.src/Split/Splitter.class 2021-09-14 19:01:29.000000000 +0000 @@ -385,7 +385,7 @@ If $bVertical Then - X = Min(Max(Mouse.ScreenY, $XMin + $iMinSize), $XMax - $iMinSize) + X = Min(Max(Mouse.ScreenY + SW - Mouse.StartY, $XMin + $iMinSize), $XMax - $iMinSize) aChildren[I].H = X - $XMin - SW aChildren[I + 1].Move(0, X - Me.ScreenY, Me.W, $XMax - X - SW) @@ -400,7 +400,7 @@ Else - X = Min(Max(Mouse.ScreenX, $XMin + $iMinSize), $XMax - $iMinSize) + X = Min(Max(Mouse.ScreenX + SW - Mouse.StartX, $XMin + $iMinSize), $XMax - $iMinSize) If System.RightToLeft Then I2 = I diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/debian/changelog gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/debian/changelog --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/debian/changelog 2021-07-14 12:29:51.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/debian/changelog 2021-09-14 19:01:33.000000000 +0000 @@ -1,8 +1,8 @@ -gambas3 (3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1) trusty; urgency=low +gambas3 (3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1) trusty; urgency=low * Auto build. - -- Benoit Minisini Wed, 14 Jul 2021 12:29:51 +0000 + -- Benoit Minisini Tue, 14 Sep 2021 19:01:33 +0000 gambas3 (3.15.90) saucy; urgency=low diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/debian/git-build-recipe.manifest gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/debian/git-build-recipe.manifest --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/debian/git-build-recipe.manifest 2021-07-14 12:29:51.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/debian/git-build-recipe.manifest 2021-09-14 19:01:33.000000000 +0000 @@ -1,4 +1,4 @@ -# git-build-recipe format 0.4 deb-version 3.16.2+git202107140302.20e5fc014+build17 -lp:~gambas-team/+git/gambas git-commit:20e5fc01472f7f9bad8bcb8833f7db1f444f3bc7 +# git-build-recipe format 0.4 deb-version 3.16.3+git202109141524.185a3d4a3+build17 +lp:~gambas-team/+git/gambas git-commit:185a3d4a3d3278919afbf53810105c3ee5fa4b39 nest debian-common lp:~gambas-team/+git/gambas3-stable-common debian git-commit:70a20910168cece27bae3da978471a96b0429f28 merge debian lp:~gambas-team/+git/gambas3-stable-trusty git-commit:227a81736ef0f0a06b1963d79652836f72eba65f diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.compress.zlib/src/main.c gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.compress.zlib/src/main.c --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.compress.zlib/src/main.c 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.compress.zlib/src/main.c 2021-09-14 19:01:29.000000000 +0000 @@ -188,9 +188,10 @@ .avail_in = len, .next_in = (Bytef *) source, }; - unsigned long pos = 0; + + size_t pos = 0; - *lent = 2 * len; + *lent = 2; // * len; GB.Alloc((void **) target, *lent); stream.avail_out = *lent; @@ -204,6 +205,8 @@ break; case Z_BUF_ERROR: pos = (unsigned long) (stream.next_out - (unsigned long) *target); + if (stream.avail_in == 0) // BM: No idea why zlib returns Z_BUF_ERROR and not Z_STREAM_END in that case. + goto out; *lent += *lent / 2; GB.Realloc((void **) target, *lent); stream.avail_out = *lent - pos; diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.db.mysql/src/main.c gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.db.mysql/src/main.c --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.db.mysql/src/main.c 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.db.mysql/src/main.c 2021-09-14 19:01:29.000000000 +0000 @@ -727,7 +727,10 @@ if (search_result(res, "character_set_client", &row)) return; - db->charset = GB.NewZeroString(row[1]); + if (strncasecmp(row[1], "utf8", 4) == 0) + db->charset = GB.NewString("utf8", 4); + else + db->charset = GB.NewZeroString(row[1]); //fprintf(stderr, "charset is '%s'\n", db->charset); mysql_free_result(res); } @@ -1798,7 +1801,7 @@ if (fp->def.type != GB_T_NULL) { - DB.Query.Add(" NOT NULL DEFAULT"); + DB.Query.Add(" NOT NULL DEFAULT "); DB.FormatVariant(&_driver, &fp->def, DB.Query.AddLength); } else if (DB.StringArray.Find(primary, fp->name) >= 0) diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.db.odbc/src/main.c gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.db.odbc/src/main.c --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.db.odbc/src/main.c 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.db.odbc/src/main.c 2021-09-14 19:01:29.000000000 +0000 @@ -121,12 +121,8 @@ * Adapted to obey Gambas' DB.IsDebug(). * Mostly from http://www.easysoft.com/developer/interfaces/odbc/diagnostics_error_status_codes.html */ -void reportODBCError(const char *fn, - SQLHANDLE handle, - SQLSMALLINT type - ) +static void reportODBCError(const char *fn, SQLHANDLE handle, SQLSMALLINT type) { - SQLINTEGER i = 0; SQLINTEGER native; SQLTCHAR state[7]; @@ -136,7 +132,7 @@ if (DB.IsDebug()) { - DB.Debug("gb.db.odbc", fn); + DB.Debug("gb.db.odbc","ERROR: %s", fn); do { ret = SQLGetDiagRec(type, handle, ++i, state, &native, text, sizeof(text), &len); @@ -210,7 +206,7 @@ int GetRecordCount(SQLHANDLE stmtHandle, SQLINTEGER cursorScrollable) { SQLRETURN retcode; //ODBC call return values - int formerRecIdx = 0; //Where we were when this all started. + int formerRecIdx = -1; //Where we were when this all started. SQLINTEGER myRecCnt = -1; //Default for when there's no cursor. SQLINTEGER firstRecNo = 0; //20161111 holder for 1st recno. SQLINTEGER lastRecNo = 0; //20161111 holder for last recno. @@ -246,7 +242,7 @@ if (formerRecIdx < 0) { DB.Debug("gb.db.odbc", "GetRecordCount: Current record returned %d, returning -1 as count", formerRecIdx); - return ((int) myRecCnt); + goto __RETURN_COUNT; } //Try to get (back?) to the first record, abort if not possible. @@ -301,6 +297,11 @@ reportODBCError("SQLFetchScroll SQL_FETCH_LAST", stmtHandle, SQL_HANDLE_STMT); } + myRecCnt = (lastRecNo - firstRecNo + 1); + DB.Debug("gb.db.odbc", "GetRecordCount: Record count=%d", (int) myRecCnt); + +__RETURN_COUNT: + //Tell ODBC we will be reading data now. //SQL_ATTR_RETRIEVE_DATA = [SQL_RD_ON] | SQL_RD_OFF retcode = SQLSetStmtAttr(stmtHandle, SQL_ATTR_RETRIEVE_DATA, (SQLPOINTER) SQL_RD_ON, 0); @@ -309,9 +310,6 @@ reportODBCError("SQLSetStmtAttr SQL_ATTR_RETRIEVE_DATA", stmtHandle, SQL_HANDLE_STMT); } - myRecCnt = (lastRecNo - firstRecNo + 1); - DB.Debug("gb.db.odbc", "GetRecordCount: Record count=%d", (int) myRecCnt); - return ((int) myRecCnt); } @@ -1159,7 +1157,7 @@ if (res->Function_exist == SQL_TRUE) //Does driver support SQLFetchScroll? { - if (res->Cursor_Scrollable == SQL_TRUE) //Does the query support scrolling? + if (res->Cursor_Scrollable == SQL_TRUE && !next) //Does the query support scrolling? { retcode2 = SQLFetchScroll( res->odbcStatHandle, @@ -1315,14 +1313,8 @@ *field->data = 0; // If SQLGetData returns nothing len_read = 0; - SQLGetData( - res->odbcStatHandle, - i + 1, - SQL_C_CHAR, - field->data, - field->len, - &len_read - ); + if (!SQL_SUCCEEDED(SQLGetData(res->odbcStatHandle, i + 1, SQL_C_CHAR, field->data, field->len, &len_read))) + reportODBCError("SQLGetData", res->odbcStatHandle, SQL_HANDLE_STMT); DB.Debug("gb.db.odbc", "query_fill: %s (%d) = %.*s", field->name, field->type, (int)len_read, field->data); @@ -1572,9 +1564,9 @@ } retcode = SQLSetStmtAttr(odbcres->odbcStatHandle, SQL_ATTR_CURSOR_SCROLLABLE, (SQLPOINTER) SQL_SCROLLABLE, 0); - //DB.Debug("gb.db.odbc", "do_query() SQLSetStmtAttr(SQL_ATTR_CURSOR_SCROLLABLE)=%d", odbcres->Cursor_Scrollable); odbcres->Cursor_Scrollable = ((retcode != SQL_SUCCESS) && (retcode != SQL_SUCCESS_WITH_INFO)) ? SQL_FALSE : SQL_TRUE; odbcres->Function_exist = handle->drvrCanFetchScroll; + DB.Debug("gb.db.odbc", "do_query() Cursor_Scrollable = %d, drvrCanFetchScroll %d", odbcres->Cursor_Scrollable, handle->drvrCanFetchScroll); /* Execute the query */ retcode = SQLExecDirect(odbcres->odbcStatHandle, (SQLCHAR *) query, SQL_NTS); diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk/src/cpaint_impl.cpp gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk/src/cpaint_impl.cpp --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk/src/cpaint_impl.cpp 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk/src/cpaint_impl.cpp 2021-09-14 19:01:29.000000000 +0000 @@ -1119,18 +1119,24 @@ if (rich) { - html = gt_html_to_pango_string(text, len, false); + pango_layout_set_text(layout, "", 0); pango_layout_set_wrap(layout, PANGO_WRAP_WORD_CHAR); + html = gt_html_to_pango_string(text, len, false); pango_layout_set_markup(layout, html, -1); } else + { + pango_layout_set_markup(layout, "", 0); pango_layout_set_text(layout, text, len); - - update_layout(d); - //gt_add_layout_from_font(layout, dx->font, d->resolutionY); + } if (width > 0) pango_layout_set_width(layout, width * PANGO_SCALE); + else + pango_layout_set_width(layout, -1); + + update_layout(d); + //gt_add_layout_from_font(layout, dx->font, d->resolutionY); pango_layout_get_extents(layout, &rect, NULL); diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk/src/gapplication.cpp gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk/src/gapplication.cpp --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk/src/gapplication.cpp 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk/src/gapplication.cpp 2021-09-14 19:01:29.000000000 +0000 @@ -555,7 +555,11 @@ control = save_control; - bool menu = false; +#if GTK_CHECK_VERSION(3, 4, 0) + bool menu = gdk_event_triggers_context_menu(event); +#else + bool menu = (event->button.button == 3) && (event->type == GDK_BUTTON_PRESS); +#endif if (event->type != GDK_BUTTON_RELEASE) { @@ -573,74 +577,52 @@ __BUTTON_TRY_PROXY: - if (!control->isDesign() && !control->isEnabled()) - goto __HANDLE_EVENT; - cancel = false; - if (control->onMouseEvent) + if (control->isDesign() || control->isEnabled()) { - if (event->type == GDK_BUTTON_PRESS || control->canRaise(control, type)) + if (control->onMouseEvent) { - control->getScreenPos(&xc, &yc); - xs = (int)event->button.x_root; - ys = (int)event->button.y_root; - x = xs - xc; - y = ys - yc; - - gMouse::validate(); - gMouse::setEvent(event); - //gMouse::setValid(1,(int)event->x,(int)event->y,event->button,event->state,data->screenX(),data->screenY()); - gMouse::setMouse(x, y, xs, ys, event->button.button, event->button.state); - switch ((int)event->type) + if (event->type == GDK_BUTTON_PRESS || control->canRaise(control, type)) { - case GDK_BUTTON_PRESS: - gMouse::setControl(control); - gMouse::setStart(x, y); - cancel = control->onMouseEvent(control, gEvent_MousePress); - break; - - case GDK_2BUTTON_PRESS: - cancel = control->onMouseEvent(control, gEvent_MouseDblClick); - break; - - case GDK_BUTTON_RELEASE: - gMouse::setControl(NULL); - cancel = control->onMouseEvent(control, gEvent_MouseRelease); - break; - } + control->getScreenPos(&xc, &yc); + xs = (int)event->button.x_root; + ys = (int)event->button.y_root; + x = xs - xc; + y = ys - yc; + + gMouse::validate(); + gMouse::setEvent(event); + //gMouse::setValid(1,(int)event->x,(int)event->y,event->button,event->state,data->screenX(),data->screenY()); + gMouse::setMouse(x, y, xs, ys, event->button.button, event->button.state); + switch ((int)event->type) + { + case GDK_BUTTON_PRESS: + gMouse::setControl(control); + gMouse::setStart(x, y); + cancel = control->onMouseEvent(control, gEvent_MousePress); + break; + + case GDK_2BUTTON_PRESS: + cancel = control->onMouseEvent(control, gEvent_MouseDblClick); + break; + + case GDK_BUTTON_RELEASE: + gMouse::setControl(NULL); + cancel = control->onMouseEvent(control, gEvent_MouseRelease); + break; + } - gMouse::invalidate(); + gMouse::invalidate(); + } } } - /*if (type == gEvent_MousePress && control->isTopLevel()) - { - gMainWindow *win = ((gMainWindow *)control); - if (win->isPopup()) - { - control->getScreenPos(&xc, &yc); - xs = (int)event->button.x_root; - ys = (int)event->button.y_root; - x = xs - xc; - y = ys - yc; - - if (x < 0 || y < 0 || x >= win->width() || y >= win->height()) - win->close(); - } - } - else*/ if (type == gEvent_MouseRelease && control->_grab) + if (type == gEvent_MouseRelease && control->_grab) { gApplication::exitLoop(control); } -#if GTK_CHECK_VERSION(3, 4, 0) - if (gdk_event_triggers_context_menu(event)) -#else - if (event->button.button == 3 && event->type == GDK_BUTTON_PRESS) -#endif - menu = true; - if (!cancel) { if (control->_proxy_for) @@ -1022,8 +1004,6 @@ appEvents = 0; - gtk_init(argc, argv); - #ifdef GTK3 _app = gtk_application_new(NULL, G_APPLICATION_FLAGS_NONE); g_object_set(G_OBJECT(_app), "register-session", TRUE, NULL); diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk/src/gcontrol.cpp gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk/src/gcontrol.cpp --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk/src/gcontrol.cpp 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk/src/gcontrol.cpp 2021-09-14 19:01:29.000000000 +0000 @@ -644,7 +644,7 @@ return pr->screenY() + y() + pr->clientY() - pr->scrollY(); } -static void send_configure (gControl *control) +static void send_configure(gControl *control) { GtkWidget *widget; GdkEvent *event; @@ -1035,18 +1035,11 @@ { if (GDK_IS_WINDOW(gtk_widget_get_window(border)) && _inside) { - #if DEBUG_ENTER_LEAVE - fprintf(stderr, "updateCursor: %s %p\n", name(), cursor); - #endif - if (!cursor && parent() && gtk_widget_get_window(parent()->border) == gtk_widget_get_window(border)) - parent()->updateCursor(parent()->getGdkCursor()); - else - { - #if DEBUG_ENTER_LEAVE - fprintf(stderr, "updateCursor: gdk_window_set_cursor: window = %p\n", gtk_widget_get_window(border)); - #endif + if (cursor || isWindow()) gdk_window_set_cursor(gtk_widget_get_window(border), cursor); - } + + if (!cursor && parent()) + parent()->updateCursor(parent()->getGdkCursor()); } } diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk/src/gcontrol.h gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk/src/gcontrol.h --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk/src/gcontrol.h 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk/src/gcontrol.h 2021-09-14 19:01:29.000000000 +0000 @@ -324,7 +324,7 @@ void realizeScrolledWindow(GtkWidget *wid, bool doNotRealize = false); void registerControl(); void updateGeometry(bool force = false); - bool mustUpdateCursor() { return mouse() != -1 || have_cursor; } + bool mustUpdateCursor() { return mouse() != -1 || have_cursor || !parent(); } bool hasInputMethod() { return _has_input_method; } virtual GtkIMContext *getInputMethod(); diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk/src/gfont.cpp gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk/src/gfont.cpp --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk/src/gfont.cpp 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk/src/gfont.cpp 2021-09-14 19:01:29.000000000 +0000 @@ -782,7 +782,7 @@ } html = gt_html_to_pango_string(text, len, false); pango_layout_set_markup(ly, html, -1); - gt_set_layout_from_font(ly, this); + gt_add_layout_from_font(ly, this); pango_layout_get_extents(ly, &ink_rect, &rect); g_free(html); g_object_unref(ly); diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk/src/gmainwindow.cpp gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk/src/gmainwindow.cpp --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk/src/gmainwindow.cpp 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk/src/gmainwindow.cpp 2021-09-14 19:01:29.000000000 +0000 @@ -235,6 +235,10 @@ data->bufW = event->width - data->_csd_w; data->bufH = event->height - data->_csd_h; + + #ifdef DEBUG_RESIZE + fprintf(stderr, "-> %d %d\n", data->bufW, data->bufH); + #endif data->emitResize(); @@ -994,18 +998,19 @@ { if (!isTopLevel()) return; - GdkRectangle rect; - int x, y; - - if (!isTopLevel()) return; +#ifdef GTK3 - #ifdef GTK3 if (MAIN_platform_is_wayland) gtk_window_set_position(GTK_WINDOW(border), GTK_WIN_POS_CENTER_ON_PARENT); - #endif + +#endif + GdkRectangle rect; + int x, y; + + gtk_widget_realize(border); gDesktop::availableGeometry(screen(), &rect); - + x = rect.x + (rect.width - width()) / 2; y = rect.y + (rect.height - height()) / 2; @@ -1037,8 +1042,8 @@ save = _current; _current = this; + center(); show(); - center(); gtk_grab_add(border); gApplication::enterLoop(this); @@ -2054,17 +2059,18 @@ } gtk_widget_get_allocation(border, &ba); - gtk_widget_get_allocation(frame, &wa); - - if (wa.width == 1 && wa.height == 1) + if (ba.width <= 1 && ba.height <= 1) return; - //fprintf(stderr, "border: %d %d layout: %d %d\n", ba.width, ba.height, wa.width, wa.height); + gtk_widget_get_allocation(frame, &wa); + if (wa.width <= 1 && wa.height <= 1) + return; _csd_w = ba.width - wa.width; _csd_h = ba.height - wa.height; #ifdef DEBUG_RESIZE - fprintf(stderr, "calcCsdSize: %s: csd = %d %d\n", name(), _csd_w, _csd_h); + fprintf(stderr, "calcCsdSize: border: %d %d layout: %d %d\n", ba.width, ba.height, wa.width, wa.height); + fprintf(stderr, "calcCsdSize: --> %s: csd = %d %d\n", name(), _csd_w, _csd_h); #endif if (!isResizable()) diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk/src/gmenu.cpp gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk/src/gmenu.cpp --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk/src/gmenu.cpp 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk/src/gmenu.cpp 2021-09-14 19:01:29.000000000 +0000 @@ -861,13 +861,25 @@ GdkWindow *win; GdkRectangle rect; GdkEvent *event; + GdkEvent *last_event; gt_disable_warnings(true); event = gdk_event_new(GDK_BUTTON_PRESS); event->button.time = gApplication::lastEventTime(); //GDK_CURRENT_TIME; - event->button.button = 1; - event->button.window = gtk_widget_get_window(window()->border); + + last_event = gApplication::lastEvent(); + if (last_event && last_event->type == GDK_BUTTON_PRESS) + { + event->button.button = last_event->button.button; + event->button.window = last_event->button.window; + } + else + { + event->button.button = 1; + event->button.window = gtk_widget_get_window(window()->border); + } + gdk_event_set_device(event, gMouse::getPointer()); if (move) diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk/src/gtools.cpp gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk/src/gtools.cpp --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk/src/gtools.cpp 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk/src/gtools.cpp 2021-09-14 19:01:29.000000000 +0000 @@ -821,6 +821,43 @@ g_string_append_c(str, ' '); } +static void add_paragraph_break(GString *str) +{ + int i; + char c; + bool markup = false; + int nl = 0; + + for (i = str->len - 1; i >= 0; i--) + { + c = str->str[i]; + if (markup) + { + if (c == '<') + markup = false; + continue; + } + if (c == '>') + { + markup = true; + continue; + } + if (c != '\n') + break; + nl++; + if (nl >= 2) + break; + } + + if (nl == 2 || i < 0) + return; + + while (nl < 2) + { + g_string_append_c(str, '\n'); + nl++; + } +} static void add_attr(GString *pango, const char *attr, const char *value) { @@ -868,9 +905,8 @@ int size = 3; // medium char size_stack[size_stack_len]; int size_stack_ptr = 0; - bool newline = true; - bool inside_par = false; int i; + int mode_pre = 0; //fprintf(stderr, "gt_html_to_pango_string: %.*s\n", len_html, html); @@ -915,7 +951,6 @@ if (!p_markup) { g_string_append(pango, ">"); - newline = false; continue; } @@ -961,12 +996,15 @@ if (!strcasecmp(*pt, token)) { if (start_token && !end_token) + { + add_paragraph_break(pango); g_string_append_printf(pango, "", pt[1]); + } else if (end_token && !start_token) { - g_string_append_printf(pango, "\n"); - g_string_append(pango, "\n"); - newline = true; + g_string_append_printf(pango, "
"); + add_paragraph_break(pango); + //g_string_append(pango, "\n"); } goto __FOUND_TOKEN; } @@ -987,19 +1025,13 @@ if (start_token) { g_string_append_c(pango, '\n'); - newline = true; } goto __FOUND_TOKEN; } if (!strcasecmp(token, "p")) { - if ((end_token || inside_par) && p[1]) - { - g_string_append_c(pango, '\n'); - newline = true; - } - inside_par = start_token; + add_paragraph_break(pango); goto __FOUND_TOKEN; } @@ -1087,6 +1119,23 @@ goto __FOUND_TOKEN; } + if (!strcasecmp(token, "pre")) + { + if (start_token && !end_token) + { + add_paragraph_break(pango); + g_string_append(pango, ""); + mode_pre++; + } + else if (end_token && !start_token) + { + mode_pre--; + g_string_append(pango, ""); + add_paragraph_break(pango); + } + goto __FOUND_TOKEN; + } + g_string_append(pango, "<"); if (end_token) g_string_append(pango, "/"); while (p_markup < p) @@ -1095,7 +1144,6 @@ p_markup++; } g_string_append(pango, ">"); - newline = false; __FOUND_TOKEN: @@ -1104,19 +1152,6 @@ continue; } - if (c == '\n' && !newline_are_break) - { - if (!newline) - add_space(pango); - continue; - } - - if (c == '\r') - { - add_space(pango); - continue; - } - if (c == '&') { const char *entity_start = ++p; @@ -1183,21 +1218,33 @@ g_string_append(pango, "&"); p = entity_start - 1; - newline = false; continue; } if (!p_markup) { + if (c == '\n' && !newline_are_break && mode_pre == 0) + { + add_space(pango); + continue; + } + + if (c == '\r') + { + add_space(pango); + continue; + } + if (c == ' ') { - if (!newline) + if (mode_pre) + g_string_append_unichar(pango, 160); + else add_space(pango); continue; } g_string_append(pango, html_entity(*p)); - newline = false; } } diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk/src/main.cpp gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk/src/main.cpp --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk/src/main.cpp 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk/src/main.cpp 2021-09-14 19:01:29.000000000 +0000 @@ -441,9 +441,10 @@ return; env = getenv("GB_X11_INIT_THREADS"); - if (env && atoi(env)) - XInitThreads(); + if (env && atoi(env)) + XInitThreads(); + gtk_init(argc, argv); gApplication::init(argc, argv); gApplication::setDefaultTitle(GB.Application.Title()); gDesktop::init(); diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk3/src/cpaint_impl.cpp gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk3/src/cpaint_impl.cpp --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk3/src/cpaint_impl.cpp 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk3/src/cpaint_impl.cpp 2021-09-14 19:01:29.000000000 +0000 @@ -1119,18 +1119,24 @@ if (rich) { - html = gt_html_to_pango_string(text, len, false); + pango_layout_set_text(layout, "", 0); pango_layout_set_wrap(layout, PANGO_WRAP_WORD_CHAR); + html = gt_html_to_pango_string(text, len, false); pango_layout_set_markup(layout, html, -1); } else + { + pango_layout_set_markup(layout, "", 0); pango_layout_set_text(layout, text, len); - - update_layout(d); - //gt_add_layout_from_font(layout, dx->font, d->resolutionY); + } if (width > 0) pango_layout_set_width(layout, width * PANGO_SCALE); + else + pango_layout_set_width(layout, -1); + + update_layout(d); + //gt_add_layout_from_font(layout, dx->font, d->resolutionY); pango_layout_get_extents(layout, &rect, NULL); diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk3/src/gapplication.cpp gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk3/src/gapplication.cpp --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk3/src/gapplication.cpp 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk3/src/gapplication.cpp 2021-09-14 19:01:29.000000000 +0000 @@ -555,7 +555,11 @@ control = save_control; - bool menu = false; +#if GTK_CHECK_VERSION(3, 4, 0) + bool menu = gdk_event_triggers_context_menu(event); +#else + bool menu = (event->button.button == 3) && (event->type == GDK_BUTTON_PRESS); +#endif if (event->type != GDK_BUTTON_RELEASE) { @@ -573,74 +577,52 @@ __BUTTON_TRY_PROXY: - if (!control->isDesign() && !control->isEnabled()) - goto __HANDLE_EVENT; - cancel = false; - if (control->onMouseEvent) + if (control->isDesign() || control->isEnabled()) { - if (event->type == GDK_BUTTON_PRESS || control->canRaise(control, type)) + if (control->onMouseEvent) { - control->getScreenPos(&xc, &yc); - xs = (int)event->button.x_root; - ys = (int)event->button.y_root; - x = xs - xc; - y = ys - yc; - - gMouse::validate(); - gMouse::setEvent(event); - //gMouse::setValid(1,(int)event->x,(int)event->y,event->button,event->state,data->screenX(),data->screenY()); - gMouse::setMouse(x, y, xs, ys, event->button.button, event->button.state); - switch ((int)event->type) + if (event->type == GDK_BUTTON_PRESS || control->canRaise(control, type)) { - case GDK_BUTTON_PRESS: - gMouse::setControl(control); - gMouse::setStart(x, y); - cancel = control->onMouseEvent(control, gEvent_MousePress); - break; - - case GDK_2BUTTON_PRESS: - cancel = control->onMouseEvent(control, gEvent_MouseDblClick); - break; - - case GDK_BUTTON_RELEASE: - gMouse::setControl(NULL); - cancel = control->onMouseEvent(control, gEvent_MouseRelease); - break; - } + control->getScreenPos(&xc, &yc); + xs = (int)event->button.x_root; + ys = (int)event->button.y_root; + x = xs - xc; + y = ys - yc; + + gMouse::validate(); + gMouse::setEvent(event); + //gMouse::setValid(1,(int)event->x,(int)event->y,event->button,event->state,data->screenX(),data->screenY()); + gMouse::setMouse(x, y, xs, ys, event->button.button, event->button.state); + switch ((int)event->type) + { + case GDK_BUTTON_PRESS: + gMouse::setControl(control); + gMouse::setStart(x, y); + cancel = control->onMouseEvent(control, gEvent_MousePress); + break; + + case GDK_2BUTTON_PRESS: + cancel = control->onMouseEvent(control, gEvent_MouseDblClick); + break; + + case GDK_BUTTON_RELEASE: + gMouse::setControl(NULL); + cancel = control->onMouseEvent(control, gEvent_MouseRelease); + break; + } - gMouse::invalidate(); + gMouse::invalidate(); + } } } - /*if (type == gEvent_MousePress && control->isTopLevel()) - { - gMainWindow *win = ((gMainWindow *)control); - if (win->isPopup()) - { - control->getScreenPos(&xc, &yc); - xs = (int)event->button.x_root; - ys = (int)event->button.y_root; - x = xs - xc; - y = ys - yc; - - if (x < 0 || y < 0 || x >= win->width() || y >= win->height()) - win->close(); - } - } - else*/ if (type == gEvent_MouseRelease && control->_grab) + if (type == gEvent_MouseRelease && control->_grab) { gApplication::exitLoop(control); } -#if GTK_CHECK_VERSION(3, 4, 0) - if (gdk_event_triggers_context_menu(event)) -#else - if (event->button.button == 3 && event->type == GDK_BUTTON_PRESS) -#endif - menu = true; - if (!cancel) { if (control->_proxy_for) @@ -1022,8 +1004,6 @@ appEvents = 0; - gtk_init(argc, argv); - #ifdef GTK3 _app = gtk_application_new(NULL, G_APPLICATION_FLAGS_NONE); g_object_set(G_OBJECT(_app), "register-session", TRUE, NULL); diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk3/src/gcontrol.cpp gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk3/src/gcontrol.cpp --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk3/src/gcontrol.cpp 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk3/src/gcontrol.cpp 2021-09-14 19:01:29.000000000 +0000 @@ -644,7 +644,7 @@ return pr->screenY() + y() + pr->clientY() - pr->scrollY(); } -static void send_configure (gControl *control) +static void send_configure(gControl *control) { GtkWidget *widget; GdkEvent *event; @@ -1035,18 +1035,11 @@ { if (GDK_IS_WINDOW(gtk_widget_get_window(border)) && _inside) { - #if DEBUG_ENTER_LEAVE - fprintf(stderr, "updateCursor: %s %p\n", name(), cursor); - #endif - if (!cursor && parent() && gtk_widget_get_window(parent()->border) == gtk_widget_get_window(border)) - parent()->updateCursor(parent()->getGdkCursor()); - else - { - #if DEBUG_ENTER_LEAVE - fprintf(stderr, "updateCursor: gdk_window_set_cursor: window = %p\n", gtk_widget_get_window(border)); - #endif + if (cursor || isWindow()) gdk_window_set_cursor(gtk_widget_get_window(border), cursor); - } + + if (!cursor && parent()) + parent()->updateCursor(parent()->getGdkCursor()); } } diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk3/src/gcontrol.h gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk3/src/gcontrol.h --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk3/src/gcontrol.h 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk3/src/gcontrol.h 2021-09-14 19:01:29.000000000 +0000 @@ -324,7 +324,7 @@ void realizeScrolledWindow(GtkWidget *wid, bool doNotRealize = false); void registerControl(); void updateGeometry(bool force = false); - bool mustUpdateCursor() { return mouse() != -1 || have_cursor; } + bool mustUpdateCursor() { return mouse() != -1 || have_cursor || !parent(); } bool hasInputMethod() { return _has_input_method; } virtual GtkIMContext *getInputMethod(); diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk3/src/gfont.cpp gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk3/src/gfont.cpp --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk3/src/gfont.cpp 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk3/src/gfont.cpp 2021-09-14 19:01:29.000000000 +0000 @@ -782,7 +782,7 @@ } html = gt_html_to_pango_string(text, len, false); pango_layout_set_markup(ly, html, -1); - gt_set_layout_from_font(ly, this); + gt_add_layout_from_font(ly, this); pango_layout_get_extents(ly, &ink_rect, &rect); g_free(html); g_object_unref(ly); diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk3/src/gmainwindow.cpp gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk3/src/gmainwindow.cpp --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk3/src/gmainwindow.cpp 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk3/src/gmainwindow.cpp 2021-09-14 19:01:29.000000000 +0000 @@ -235,6 +235,10 @@ data->bufW = event->width - data->_csd_w; data->bufH = event->height - data->_csd_h; + + #ifdef DEBUG_RESIZE + fprintf(stderr, "-> %d %d\n", data->bufW, data->bufH); + #endif data->emitResize(); @@ -994,18 +998,19 @@ { if (!isTopLevel()) return; - GdkRectangle rect; - int x, y; - - if (!isTopLevel()) return; +#ifdef GTK3 - #ifdef GTK3 if (MAIN_platform_is_wayland) gtk_window_set_position(GTK_WINDOW(border), GTK_WIN_POS_CENTER_ON_PARENT); - #endif + +#endif + GdkRectangle rect; + int x, y; + + gtk_widget_realize(border); gDesktop::availableGeometry(screen(), &rect); - + x = rect.x + (rect.width - width()) / 2; y = rect.y + (rect.height - height()) / 2; @@ -1037,8 +1042,8 @@ save = _current; _current = this; + center(); show(); - center(); gtk_grab_add(border); gApplication::enterLoop(this); @@ -2054,17 +2059,18 @@ } gtk_widget_get_allocation(border, &ba); - gtk_widget_get_allocation(frame, &wa); - - if (wa.width == 1 && wa.height == 1) + if (ba.width <= 1 && ba.height <= 1) return; - //fprintf(stderr, "border: %d %d layout: %d %d\n", ba.width, ba.height, wa.width, wa.height); + gtk_widget_get_allocation(frame, &wa); + if (wa.width <= 1 && wa.height <= 1) + return; _csd_w = ba.width - wa.width; _csd_h = ba.height - wa.height; #ifdef DEBUG_RESIZE - fprintf(stderr, "calcCsdSize: %s: csd = %d %d\n", name(), _csd_w, _csd_h); + fprintf(stderr, "calcCsdSize: border: %d %d layout: %d %d\n", ba.width, ba.height, wa.width, wa.height); + fprintf(stderr, "calcCsdSize: --> %s: csd = %d %d\n", name(), _csd_w, _csd_h); #endif if (!isResizable()) diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk3/src/gmenu.cpp gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk3/src/gmenu.cpp --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk3/src/gmenu.cpp 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk3/src/gmenu.cpp 2021-09-14 19:01:29.000000000 +0000 @@ -861,13 +861,25 @@ GdkWindow *win; GdkRectangle rect; GdkEvent *event; + GdkEvent *last_event; gt_disable_warnings(true); event = gdk_event_new(GDK_BUTTON_PRESS); event->button.time = gApplication::lastEventTime(); //GDK_CURRENT_TIME; - event->button.button = 1; - event->button.window = gtk_widget_get_window(window()->border); + + last_event = gApplication::lastEvent(); + if (last_event && last_event->type == GDK_BUTTON_PRESS) + { + event->button.button = last_event->button.button; + event->button.window = last_event->button.window; + } + else + { + event->button.button = 1; + event->button.window = gtk_widget_get_window(window()->border); + } + gdk_event_set_device(event, gMouse::getPointer()); if (move) diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk3/src/gtools.cpp gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk3/src/gtools.cpp --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk3/src/gtools.cpp 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk3/src/gtools.cpp 2021-09-14 19:01:29.000000000 +0000 @@ -821,6 +821,43 @@ g_string_append_c(str, ' '); } +static void add_paragraph_break(GString *str) +{ + int i; + char c; + bool markup = false; + int nl = 0; + + for (i = str->len - 1; i >= 0; i--) + { + c = str->str[i]; + if (markup) + { + if (c == '<') + markup = false; + continue; + } + if (c == '>') + { + markup = true; + continue; + } + if (c != '\n') + break; + nl++; + if (nl >= 2) + break; + } + + if (nl == 2 || i < 0) + return; + + while (nl < 2) + { + g_string_append_c(str, '\n'); + nl++; + } +} static void add_attr(GString *pango, const char *attr, const char *value) { @@ -868,9 +905,8 @@ int size = 3; // medium char size_stack[size_stack_len]; int size_stack_ptr = 0; - bool newline = true; - bool inside_par = false; int i; + int mode_pre = 0; //fprintf(stderr, "gt_html_to_pango_string: %.*s\n", len_html, html); @@ -915,7 +951,6 @@ if (!p_markup) { g_string_append(pango, ">"); - newline = false; continue; } @@ -961,12 +996,15 @@ if (!strcasecmp(*pt, token)) { if (start_token && !end_token) + { + add_paragraph_break(pango); g_string_append_printf(pango, "", pt[1]); + } else if (end_token && !start_token) { - g_string_append_printf(pango, "\n"); - g_string_append(pango, "\n"); - newline = true; + g_string_append_printf(pango, "
"); + add_paragraph_break(pango); + //g_string_append(pango, "\n"); } goto __FOUND_TOKEN; } @@ -987,19 +1025,13 @@ if (start_token) { g_string_append_c(pango, '\n'); - newline = true; } goto __FOUND_TOKEN; } if (!strcasecmp(token, "p")) { - if ((end_token || inside_par) && p[1]) - { - g_string_append_c(pango, '\n'); - newline = true; - } - inside_par = start_token; + add_paragraph_break(pango); goto __FOUND_TOKEN; } @@ -1087,6 +1119,23 @@ goto __FOUND_TOKEN; } + if (!strcasecmp(token, "pre")) + { + if (start_token && !end_token) + { + add_paragraph_break(pango); + g_string_append(pango, ""); + mode_pre++; + } + else if (end_token && !start_token) + { + mode_pre--; + g_string_append(pango, ""); + add_paragraph_break(pango); + } + goto __FOUND_TOKEN; + } + g_string_append(pango, "<"); if (end_token) g_string_append(pango, "/"); while (p_markup < p) @@ -1095,7 +1144,6 @@ p_markup++; } g_string_append(pango, ">"); - newline = false; __FOUND_TOKEN: @@ -1104,19 +1152,6 @@ continue; } - if (c == '\n' && !newline_are_break) - { - if (!newline) - add_space(pango); - continue; - } - - if (c == '\r') - { - add_space(pango); - continue; - } - if (c == '&') { const char *entity_start = ++p; @@ -1183,21 +1218,33 @@ g_string_append(pango, "&"); p = entity_start - 1; - newline = false; continue; } if (!p_markup) { + if (c == '\n' && !newline_are_break && mode_pre == 0) + { + add_space(pango); + continue; + } + + if (c == '\r') + { + add_space(pango); + continue; + } + if (c == ' ') { - if (!newline) + if (mode_pre) + g_string_append_unichar(pango, 160); + else add_space(pango); continue; } g_string_append(pango, html_entity(*p)); - newline = false; } } diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk3/src/main.cpp gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk3/src/main.cpp --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/gb.gtk3/src/main.cpp 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/gb.gtk3/src/main.cpp 2021-09-14 19:01:29.000000000 +0000 @@ -473,11 +473,13 @@ fprintf(stderr, "gb.gtk3: warning: unknown platform: %s\n", env); } - gApplication::init(argc, argv); + gtk_init(argc, argv); load_platform(); PLATFORM.Init(); + gApplication::init(argc, argv); + gApplication::setDefaultTitle(GB.Application.Title()); gDesktop::init(); diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/.gitlab-ci.yml gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/.gitlab-ci.yml --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/.gitlab-ci.yml 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/.gitlab-ci.yml 2021-09-14 19:01:29.000000000 +0000 @@ -48,23 +48,23 @@ - > apt-get update && apt-get install -y build-essential g++ automake autoconf libbz2-dev libzstd-dev default-libmysqlclient-dev unixodbc-dev libpq-dev - postgresql-server-dev-9.6 libsqlite0-dev libsqlite3-dev libglib2.0-dev + postgresql-server-dev-11 libsqlite0-dev libsqlite3-dev libglib2.0-dev libgtk2.0-dev libcurl4-gnutls-dev libgtkglext1-dev libpcre3-dev libsdl-sound1.2-dev libsdl-mixer1.2-dev libsdl-image1.2-dev libxml2-dev - libxslt1-dev librsvg2-dev libpoppler-private-dev libpoppler-dev libpoppler-glib-dev - libpoppler-cpp-dev libasound2-dev libesd0-dev libdirectfb-dev - libxtst-dev libffi-dev libqt4-dev libqtwebkit-dev libqt4-opengl-dev - libglew-dev libimlib2-dev libv4l-dev libsdl-ttf2.0-dev - libgnome-keyring-dev libgdk-pixbuf2.0-dev linux-libc-dev - libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev libcairo2-dev - libgsl-dev libncurses5-dev libgmime-2.6-dev libalure-dev libgmp-dev - libgtk-3-dev libsdl2-dev libsdl2-mixer-dev libsdl2-ttf-dev + libxslt1-dev librsvg2-dev libpoppler-dev libpoppler-glib-dev + libpoppler-private-dev libpoppler-cpp-dev libasound2-dev libdirectfb-dev libxtst-dev + libffi-dev libqt4-dev libqtwebkit-dev libqt4-opengl-dev libglew-dev + libimlib2-dev libv4l-dev libsdl-ttf2.0-dev libgdk-pixbuf2.0-dev + linux-libc-dev libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev + libcairo2-dev libgsl-dev libncurses5-dev libgmime-2.6-dev libalure-dev + libgmp-dev libgtk-3-dev libsdl2-dev libsdl2-mixer-dev libsdl2-ttf-dev libsdl2-image-dev sane-utils libdumb1-dev libqt5opengl5-dev libqt5svg5-dev libqt5webkit5-dev libqt5x11extras5-dev qtbase5-dev - qtwebengine5-dev libwebkit2gtk-4.0-dev git libssl-dev + qtwebengine5-dev libwebkit2gtk-4.0-dev git + libssl-dev script: - ./reconf-all - - GAMBAS_CONFIG_FAILURE=1 ./configure -C --disable-gtk3webview --disable-zstd + - GAMBAS_CONFIG_FAILURE=1 ./configure -C --disable-keyring - make -j$(nproc) - make install @@ -74,23 +74,22 @@ - > apt-get update && apt-get install -y build-essential g++ automake autoconf libbz2-dev libzstd-dev default-libmysqlclient-dev unixodbc-dev libpq-dev - postgresql-server-dev-11 libsqlite0-dev libsqlite3-dev libglib2.0-dev + postgresql-server-dev-13 libsqlite3-dev libglib2.0-dev libgtk2.0-dev libcurl4-gnutls-dev libgtkglext1-dev libpcre3-dev libsdl-sound1.2-dev libsdl-mixer1.2-dev libsdl-image1.2-dev libxml2-dev libxslt1-dev librsvg2-dev libpoppler-dev libpoppler-glib-dev libpoppler-private-dev libpoppler-cpp-dev libasound2-dev libdirectfb-dev libxtst-dev - libffi-dev libqt4-dev libqtwebkit-dev libqt4-opengl-dev libglew-dev + libffi-dev libglew-dev libimlib2-dev libv4l-dev libsdl-ttf2.0-dev libgdk-pixbuf2.0-dev linux-libc-dev libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev - libcairo2-dev libgsl-dev libncurses5-dev libgmime-2.6-dev libalure-dev + libcairo2-dev libgsl-dev libncurses5-dev libgmime-3.0-dev libalure-dev libgmp-dev libgtk-3-dev libsdl2-dev libsdl2-mixer-dev libsdl2-ttf-dev libsdl2-image-dev sane-utils libdumb1-dev libqt5opengl5-dev libqt5svg5-dev libqt5webkit5-dev libqt5x11extras5-dev qtbase5-dev - qtwebengine5-dev libwebkit2gtk-4.0-dev git - libssl-dev + qtwebengine5-dev libwebkit2gtk-4.0-dev git libssl-dev script: - ./reconf-all - - GAMBAS_CONFIG_FAILURE=1 ./configure -C --disable-keyring + - GAMBAS_CONFIG_FAILURE=1 ./configure -C --disable-keyring --disable-sqlite2 --disable-qt4 --disable-qtwebkit - make -j$(nproc) - make install diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/VERSION gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/VERSION --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/VERSION 2021-07-14 12:29:43.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/VERSION 2021-09-14 19:01:29.000000000 +0000 @@ -1 +1 @@ -3.16.2 +3.16.3 diff -Nru gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/version.m4 gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/version.m4 --- gambas3-3.16.2+git202107140302.20e5fc014+build17~ubuntu14.04.1/version.m4 2021-07-14 12:29:44.000000000 +0000 +++ gambas3-3.16.3+git202109141524.185a3d4a3+build17~ubuntu14.04.1/version.m4 2021-09-14 19:01:29.000000000 +0000 @@ -1,13 +1,13 @@ ## Package version and e-mail for bugs are defined here -m4_define([GB_VERSION], [3.16.2]) +m4_define([GB_VERSION], [3.16.3]) m4_define([GB_MAIL], [g4mba5@gmail.com]) m4_define([GB_URL], [http://gambas.sourceforge.net]) m4_define([GB_VERSION_MAJOR], [3]) m4_define([GB_VERSION_MINOR], [16]) -m4_define([GB_VERSION_RELEASE], [2]) +m4_define([GB_VERSION_RELEASE], [3]) -m4_define([GB_VERSION_FULL], [0x03160002]) +m4_define([GB_VERSION_FULL], [0x03160003]) m4_define([GB_PCODE_VERSION], [0x03150000]) m4_define([GB_PCODE_VERSION_MIN],[0x03000000])