builtin2.go 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125
  1. package builtin
  2. import (
  3. "os"
  4. "io"
  5. "fmt"
  6. "math"
  7. "time"
  8. "regexp"
  9. "errors"
  10. "strconv"
  11. "strings"
  12. "unicode"
  13. "reflect"
  14. "runtime"
  15. "net/url"
  16. "math/big"
  17. "math/rand"
  18. "unicode/utf8"
  19. "path/filepath"
  20. "kumachan/standalone/qt"
  21. "kumachan/standalone/ctn"
  22. "kumachan/standalone/util"
  23. "kumachan/standalone/util/pseudounion"
  24. "kumachan/interpreter/core"
  25. )
  26. var functionList = [] interface{} {
  27. // Reflection
  28. ReflectType,
  29. DebugInspect, DebugExpose, DebugTrace, DebugWatch,
  30. Serialize, Deserialize,
  31. ObjectPairEqualities,
  32. // Null, Error, undefined (panic)
  33. Null, Error, ErrorMessage, ErrorIsCancel, ErrorWrap, Undefined,
  34. // Bool
  35. BoolNo, BoolYes, BoolNot, BoolAnd, BoolOr, BoolEqual, BoolAssert,
  36. // Int
  37. IntPlus, IntMinus, IntTimes, IntQuo, IntRem, IntPow,
  38. IntEqual, IntLessThan, IntCompare,
  39. // Float
  40. FloatPlus, FloatMinus, FloatTimes, FloatQuo, FloatRem, FloatPow,
  41. FloatEqual, FloatLessThan,
  42. FloatInt, IntFloat, FloatNormal, FloatNaN, FloatInfinite,
  43. math.Floor, math.Ceil, math.Round,
  44. math.Sqrt, math.Cbrt, math.Exp, math.Log,
  45. math.Sin, math.Cos, math.Tan, math.Asin, math.Acos, math.Atan, math.Atan2,
  46. // Char
  47. Char,
  48. CharInt, CharUtf8Size,
  49. CharEqual, CharLessThan, CharCompare,
  50. // String
  51. String, StringFromChars, Quote, Unquote,
  52. StringEmpty,
  53. StringChars, StringFirstChar, StringNumberOfChars,
  54. StringUtf8Size,
  55. StringEqual, StringLessThan, StringCompare,
  56. StringShift, StringReverse,
  57. ListStringJoin, StringSplit, StringCut,
  58. StringHasPrefix, StringHasSuffix,
  59. StringTrimPrefix, StringTrimSuffix,
  60. StringTrim, StringTrimLeft, StringTrimRight,
  61. // RegExp
  62. RegExpString,
  63. StringAdvance, StringSatisfy, StringReplace,
  64. // To String
  65. BoolString, OrderingString, IntString, FloatString, CharString,
  66. // From String
  67. ParseInt, ParseFloat,
  68. // List
  69. ListConcat,
  70. core.Cons, core.Count, ListEmpty, ListFirst, ListLength, ListSeq,
  71. ListShift, ListReverse,
  72. ListSort, ListTake,
  73. ListWithIndex,
  74. ListMap, ListDeflateMap, ListFlatMap, ListFilter, ListScan, ListFold,
  75. // Seq
  76. SeqEmpty, SeqLast, SeqLength, SeqList,
  77. SeqAppend, SeqDeflateAppend, SeqFlatAppend, SeqSort, SeqFilter,
  78. // Queue
  79. Queue,
  80. QueueEmpty, QueueSize, QueueFirst, QueueList,
  81. QueueShift, QueueAppend,
  82. // Heap
  83. Heap,
  84. HeapEmpty, HeapSize, HeapFirst, HeapList,
  85. HeapShift, HeapInsert,
  86. // Set
  87. Set,
  88. SetEmpty, SetSize, SetList,
  89. SetHas, SetDelete, SetInsert,
  90. // Map
  91. Map,
  92. MapEmpty, MapSize, MapKeys, MapValues, MapEntries,
  93. MapHas, MapLookup, MapDelete, MapInsert,
  94. // Observable
  95. Observable,
  96. Go,
  97. core.WithChildContext, core.WithCancelTrigger, core.WithCancelTimeout,
  98. core.SetTimeout, core.SetInterval,
  99. Throw, Crash,
  100. ObservableCatch, ObservableRetry, ObservableLogError,
  101. ObservableDistinctUntilChanged,
  102. ObservableWithLatestFrom, ObservableMapToLatestFrom,
  103. ObservableWithCycle, ObservableWithIndex, ObservableWithTime,
  104. ObservableDelaySubscription, ObservableDelayValues,
  105. ObservableStartWith, ObservableEndWith,
  106. ObservableThrottle, ObservableDebounce,
  107. ObservableThrottleTime, ObservableDebounceTime,
  108. ObservableCompleteOnEmit,
  109. ObservableSkip,
  110. ObservableTake,
  111. ObservableTakeLast, ObservableTakeLastAsMaybe,
  112. ObservableTakeWhile, ObservableTakeWhileMaybeOK,
  113. ObservableTakeUntil,
  114. ObservableCount, ObservableCollect,
  115. ObservableBufferTime,
  116. ObservablePairwise, ObservableBufferCount,
  117. ObservableMap, ObservableMapTo,
  118. ObservableFilter,
  119. ObservableScan, ObservableReduce,
  120. ObservableCombineLatest, ListObservableCombineLatest,
  121. ObservableAwait, ObservableAwaitNoexcept,
  122. ObservableThen,
  123. ObservableWith, ObservableAnd,
  124. ObservableAutoMap,
  125. ListObservableMerge, ObservableMerge, ObservableMergeMap,
  126. ListObservableConcat, ObservableConcat, ObservableConcatMap,
  127. ObservableSwitchMap, ObservableExhaustMap,
  128. NumCPU,
  129. ListObservableConcurrent, ObservableConcurrentMap,
  130. ListObservableForkJoin, ObservableForkJoin,
  131. UUID,
  132. Random,
  133. Shuffle,
  134. // Subject
  135. CreateSubject,
  136. SubjectValues, SubjectPlug,
  137. core.Multicast, core.Loopback, core.SkipSync,
  138. // Time
  139. TimeString, TimeSubtractMillisecond, core.Now,
  140. // Request
  141. Get, Post, Put, Delete, Subscribe,
  142. // File
  143. FileString, FileEqual,
  144. ReadTextFile, WriteTextFile,
  145. // Config
  146. ReadConfig,
  147. WriteConfig,
  148. // Process
  149. Arguments,
  150. Environment,
  151. // GUI
  152. // general
  153. FontSize,
  154. // standard dialogs
  155. ShowInfo, ShowWarning, ShowCritical,
  156. ShowYesNo, ShowAbortRetryIgnore, ShowSaveDiscardCancel,
  157. GetChoice, GetLine, GetText, GetInt, GetFloat,
  158. GetFileListToOpen, GetFileToOpen, GetFileToSave,
  159. // action, context menu
  160. Action, ActionTriggers,
  161. ActionCheckBox, ActionComboBox,
  162. BindContextMenu,
  163. // widget
  164. ShowAndActivate,
  165. BindInlineStyleSheet,
  166. ComboBoxSelectedItem,
  167. core.CreateDynamicWidget,
  168. CreateWidget,
  169. CreateScrollArea,
  170. CreateGroupBox,
  171. CreateSplitter,
  172. CreateMainWindow,
  173. CreateDialog,
  174. CreateLabel,
  175. CreateIconLabel,
  176. CreateElidedLabel,
  177. CreateTextView,
  178. CreateCheckBox,
  179. CreateComboBox,
  180. CreatePushButton,
  181. CreateLineEdit,
  182. CreatePlainTextEdit,
  183. CreateSlider,
  184. CreateProgressBar,
  185. // signal and events
  186. Connect, Listen,
  187. SignalToggled,
  188. SignalClicked,
  189. SignalTextChanged0,
  190. SignalTextChanged1,
  191. SignalReturnPressed,
  192. SignalValueChanged,
  193. EventsShow,
  194. EventsClose,
  195. // prop
  196. Read,
  197. Bind,
  198. ClearTextLater,
  199. PropEnabled,
  200. PropWindowTitle,
  201. PropText,
  202. PropChecked,
  203. PropPlainText,
  204. PropValue,
  205. // list
  206. ListView,
  207. ListEditView,
  208. }
  209. var functionMap = (func() (map[string] core.NativeFunction) {
  210. var m = make(map[string] core.NativeFunction)
  211. for _, item := range functionList {
  212. var rv = reflect.ValueOf(item)
  213. var name = strings.Split(runtime.FuncForPC(rv.Pointer()).Name(), ".")[1]
  214. var obj = core.MakeNativeFunction(item)
  215. if _, duplicate := m[name]; duplicate {
  216. panic("duplicate native function: " + name)
  217. }
  218. m[name] = obj
  219. }
  220. return m
  221. })()
  222. func LookupFunction(id string) (core.NativeFunction, bool) {
  223. var f, ok = functionMap[id]
  224. return f, ok
  225. }
  226. func ReflectType() core.Object {
  227. // DummyReflectType
  228. return nil
  229. }
  230. func DebugInspect(hint string, rv core.ReflectValue, h core.RuntimeHandle) core.Object {
  231. var lg = core.MakeLogger(h)
  232. lg.Inspect(rv.Value(), rv.Type().CertainType(), hint)
  233. return rv.Value()
  234. }
  235. func DebugExpose(name string, rv core.ReflectValue, h core.RuntimeHandle) core.Observable {
  236. var lg = core.MakeLogger(h)
  237. return lg.Expose(name, rv.Value(), rv.Type().CertainType())
  238. }
  239. func DebugTrace(hint string, rv core.ReflectValue, h core.RuntimeHandle) core.Observable {
  240. var lg = core.MakeLogger(h)
  241. var ro = rv.CastToReflectObservable()
  242. return lg.Trace(ro.ObservableValue(), ro.InnerType().CertainType(), hint)
  243. }
  244. func DebugWatch(hint string, rv core.ReflectValue, h core.RuntimeHandle) core.Observable {
  245. var lg = core.MakeLogger(h)
  246. var ro = rv.CastToReflectObservable()
  247. return lg.Watch(ro.ObservableValue(), ro.InnerType().CertainType(), hint)
  248. }
  249. func Serialize(rv core.ReflectValue, h core.RuntimeHandle) core.Observable {
  250. var ctx = h.SerializationContext()
  251. return core.Observable(func(pub core.DataPublisher) {
  252. go (func() {
  253. var b, err = core.Marshal(rv, ctx)
  254. if err != nil { pub.AsyncThrow(err); return }
  255. var s = util.WellBehavedDecodeUtf8(b)
  256. pub.AsyncReturn(core.ObjString(s))
  257. })()
  258. })
  259. }
  260. func Deserialize(s string, rt core.ReflectType, h core.RuntimeHandle) core.Observable {
  261. var ctx = h.SerializationContext()
  262. return core.Observable(func(pub core.DataPublisher) {
  263. go (func() {
  264. var b = ([] byte)(s)
  265. var obj, err = core.Unmarshal(b, rt, ctx)
  266. if err != nil { pub.AsyncThrow(err); return }
  267. pub.AsyncReturn(obj)
  268. })()
  269. })
  270. }
  271. func marshal(rv core.ReflectValue, h core.RuntimeHandle) core.Observable {
  272. var ctx = h.SerializationContext()
  273. return core.Observable(func(pub core.DataPublisher) {
  274. go (func() {
  275. var b, err = core.Marshal(rv, ctx)
  276. if err != nil { pub.AsyncThrow(err); return }
  277. pub.AsyncReturn(core.ObjBytes(b))
  278. })()
  279. })
  280. }
  281. func unmarshal(b ([] byte), rt core.ReflectType, h core.RuntimeHandle) core.Observable {
  282. var ctx = h.SerializationContext()
  283. return core.Observable(func(pub core.DataPublisher) {
  284. go (func() {
  285. var obj, err = core.Unmarshal(b, rt, ctx)
  286. if err != nil { pub.AsyncThrow(err); return }
  287. pub.AsyncReturn(obj)
  288. })()
  289. })
  290. }
  291. func ObjectPairEqualities(o core.Observable) core.Observable {
  292. return o.ObjectPairEqualities()
  293. }
  294. func Null() core.Object {
  295. return nil
  296. }
  297. func Error(msg string) error {
  298. return errors.New(msg)
  299. }
  300. func ErrorMessage(err error) string {
  301. return err.Error()
  302. }
  303. func ErrorIsCancel(err error) bool {
  304. var _, is_cancel = err.(core.CancelError)
  305. return is_cancel
  306. }
  307. func ErrorWrap(err error, msg string) error {
  308. return fmt.Errorf("%s: %w", msg, err)
  309. }
  310. func Undefined(msg string, h core.RuntimeHandle) core.Object {
  311. return core.Crash1[core.Object] (
  312. h, core.ValueUndefined,
  313. strconv.Quote(msg),
  314. )
  315. }
  316. func BoolNo() bool {
  317. return false
  318. }
  319. func BoolYes() bool {
  320. return true
  321. }
  322. func BoolNot(p bool) bool {
  323. return !(p)
  324. }
  325. func BoolAnd(p bool, q bool) bool {
  326. return (p && q)
  327. }
  328. func BoolOr(p bool, q bool) bool {
  329. return (p || q)
  330. }
  331. func BoolEqual(p bool, q bool) bool {
  332. return (p == q)
  333. }
  334. func BoolAssert(ok bool, k func()(core.Object), h core.RuntimeHandle) core.Object {
  335. if ok {
  336. return k()
  337. } else {
  338. return core.Crash1[core.Object] (
  339. h, core.AssertionFailed,
  340. "given boolean value is false",
  341. )
  342. }
  343. }
  344. type CompareWithOperator func(core.Object,core.Object)(ctn.Ordering)
  345. type EqualToOperator func(core.Object,core.Object)(bool)
  346. type LessThanOperator func(core.Object,core.Object)(bool)
  347. func IntPlus(a *big.Int, b *big.Int) *big.Int {
  348. var c big.Int
  349. return c.Add(a, b)
  350. }
  351. func IntMinus(a *big.Int, b *big.Int) *big.Int {
  352. var c big.Int
  353. return c.Sub(a, b)
  354. }
  355. func IntTimes(a *big.Int, b *big.Int) *big.Int {
  356. var c big.Int
  357. return c.Mul(a, b)
  358. }
  359. func IntQuo(a *big.Int, b *big.Int, h core.RuntimeHandle) *big.Int {
  360. if b.Sign() == 0 {
  361. core.Crash(h, core.InvalidArgument, "division by zero")
  362. }
  363. var c big.Int
  364. return c.Quo(a, b)
  365. }
  366. func IntRem(a *big.Int, b *big.Int, h core.RuntimeHandle) *big.Int {
  367. if b.Sign() == 0 {
  368. core.Crash(h, core.InvalidArgument, "division by zero")
  369. }
  370. var c big.Int
  371. return c.Rem(a, b)
  372. }
  373. func IntPow(a *big.Int, b *big.Int, h core.RuntimeHandle) *big.Int {
  374. var c big.Int
  375. if b.Sign() < 0 {
  376. core.Crash(h, core.InvalidArgument, "negative integer power")
  377. }
  378. return c.Exp(a, b, nil)
  379. }
  380. func IntEqual(a *big.Int, b *big.Int) bool {
  381. return (a.Cmp(b) == 0)
  382. }
  383. func IntLessThan(a *big.Int, b *big.Int) bool {
  384. return (a.Cmp(b) < 0)
  385. }
  386. func IntCompare(a *big.Int, b *big.Int) ctn.Ordering {
  387. var result = a.Cmp(b)
  388. if result < 0 {
  389. return ctn.Smaller
  390. } else if result > 0 {
  391. return ctn.Bigger
  392. } else {
  393. return ctn.Equal
  394. }
  395. }
  396. func FloatPlus(x float64, y float64) float64 {
  397. return (x + y)
  398. }
  399. func FloatMinus(x float64, y float64) float64 {
  400. return (x - y)
  401. }
  402. func FloatTimes(x float64, y float64) float64 {
  403. return (x * y)
  404. }
  405. func FloatQuo(x float64, y float64) float64 {
  406. return (x / y)
  407. }
  408. func FloatRem(x float64, y float64) float64 {
  409. return math.Mod(x, y)
  410. }
  411. func FloatPow(x float64, y float64) float64 {
  412. return math.Pow(x, y)
  413. }
  414. func FloatEqual(x float64, y float64) bool {
  415. return (x == y)
  416. }
  417. func FloatLessThan(x float64, y float64) bool {
  418. return (x < y)
  419. }
  420. func FloatInt(x float64, h core.RuntimeHandle) *big.Int {
  421. var a, ok = util.DoubleToInteger(x)
  422. if !(ok) {
  423. core.Crash(h, core.InvalidArgument,
  424. "cannot convert abnormal float to integer")
  425. }
  426. return a
  427. }
  428. func IntFloat(a *big.Int, h core.RuntimeHandle) float64 {
  429. var x, ok = util.IntegerToDouble(a)
  430. if !(ok) {
  431. core.Crash(h, core.InvalidArgument,
  432. "cannot convert large integer to float")
  433. }
  434. return x
  435. }
  436. func FloatNormal(x float64) bool {
  437. return util.IsNormalFloat(x)
  438. }
  439. func FloatNaN(x float64) bool {
  440. return (x != x)
  441. }
  442. func FloatInfinite(x float64) bool {
  443. return math.IsInf(x, 0)
  444. }
  445. func Char(n *big.Int) rune {
  446. if n.IsInt64() {
  447. n := n.Int64()
  448. if (0 <= n && n <= 0x10FFFF) && !(0xD800 <= n && n <= 0xDFFF) {
  449. return rune(n)
  450. }
  451. }
  452. return unicode.ReplacementChar
  453. }
  454. func CharInt(c rune) int {
  455. return int(c)
  456. }
  457. func CharUtf8Size(c rune) int {
  458. return utf8.RuneLen(c)
  459. }
  460. func CharEqual(c rune, d rune) bool {
  461. return (c == d)
  462. }
  463. func CharLessThan(c rune, d rune) bool {
  464. return (c < d)
  465. }
  466. func CharCompare(c rune, d rune) ctn.Ordering {
  467. return ctn.DefaultCompare[rune](c, d)
  468. }
  469. func String(fragments ([] ToString)) string {
  470. var buf strings.Builder
  471. for _, f := range fragments {
  472. buf.WriteString(f())
  473. }
  474. return buf.String()
  475. }
  476. func StringFromChars(chars ([] rune)) string {
  477. return string(chars)
  478. }
  479. func Quote(s string) string {
  480. return strconv.Quote(s)
  481. }
  482. func Unquote(s string) ctn.Maybe[string] {
  483. var unquoted, err = strconv.Unquote(s)
  484. if err == nil {
  485. return ctn.Just(unquoted)
  486. } else {
  487. return nil
  488. }
  489. }
  490. func StringEmpty(s string) bool {
  491. return (s == "")
  492. }
  493. func StringChars(s string) ([] rune) {
  494. return ([] rune)(s)
  495. }
  496. func StringFirstChar(s string) ctn.Maybe[rune] {
  497. for _, char := range s {
  498. return ctn.Just(char)
  499. }
  500. return nil
  501. }
  502. func StringNumberOfChars(s string) int {
  503. var n = 0
  504. for range s {
  505. n++
  506. }
  507. return n
  508. }
  509. func StringUtf8Size(s string) int {
  510. return len(s)
  511. }
  512. func StringEqual(a string, b string) bool {
  513. return (a == b)
  514. }
  515. func StringLessThan(a string, b string) bool {
  516. return (a < b)
  517. }
  518. func StringCompare(a string, b string) ctn.Ordering {
  519. return ctn.StringCompare(a, b)
  520. }
  521. func StringShift(s string) ctn.Maybe[ctn.Pair[rune,string]] {
  522. for _, char := range s {
  523. var rest = s[utf8.RuneLen(char):]
  524. return ctn.Just(ctn.MakePair(char, rest))
  525. }
  526. return nil
  527. }
  528. func StringReverse(s string) string {
  529. var chars = ([] rune)(s)
  530. var L = len(chars)
  531. var buf strings.Builder
  532. for i := (L-1); i >= 0; i -= 1 {
  533. buf.WriteRune(chars[i])
  534. }
  535. return buf.String()
  536. }
  537. func ListStringJoin(l core.List, sep string) string {
  538. var values = make([] string, 0)
  539. l.ForEach(func(item core.Object) {
  540. var value = core.GetString(item)
  541. values = append(values, value)
  542. })
  543. return strings.Join(values, sep)
  544. }
  545. func StringSplit(s string, sep string) core.List {
  546. return core.ToObjectList(strings.Split(s, sep))
  547. }
  548. func StringCut(s string, sep string) ctn.Maybe[ctn.Pair[string,string]] {
  549. if a, b, ok := strings.Cut(s, sep); ok {
  550. return ctn.Just(ctn.MakePair(a, b))
  551. } else {
  552. return nil
  553. }
  554. }
  555. func StringHasPrefix(s string, prefix string) bool {
  556. return strings.HasPrefix(s, prefix)
  557. }
  558. func StringHasSuffix(s string, suffix string) bool {
  559. return strings.HasSuffix(s, suffix)
  560. }
  561. func StringTrimPrefix(s string, prefix string) string {
  562. return strings.TrimPrefix(s, prefix)
  563. }
  564. func StringTrimSuffix(s string, suffix string) string {
  565. return strings.TrimSuffix(s, suffix)
  566. }
  567. func StringTrim(s string, chars ([] rune)) string {
  568. return strings.Trim(s, string(chars))
  569. }
  570. func StringTrimLeft(s string, chars ([] rune)) string {
  571. return strings.TrimLeft(s, string(chars))
  572. }
  573. func StringTrimRight(s string, chars ([] rune)) string {
  574. return strings.TrimRight(s, string(chars))
  575. }
  576. func RegExpString(r *regexp.Regexp) string {
  577. return r.String()
  578. }
  579. func StringAdvance(s string, pattern *regexp.Regexp) ctn.Maybe[ctn.Pair[string,string]] {
  580. var header_pattern = ("^(?:" + pattern.String() + ")")
  581. var r = assumeValidRegexp(header_pattern)
  582. if result := r.FindStringIndex(s); (result != nil) {
  583. if result[0] != 0 { panic("something went wrong") }
  584. var pos = result[1]
  585. var match = s[:pos]
  586. var rest = s[pos:]
  587. return ctn.Just(ctn.MakePair(match, rest))
  588. } else {
  589. return nil
  590. }
  591. }
  592. func StringSatisfy(s string, pattern *regexp.Regexp) bool {
  593. var full_pattern = ("^(?:" + pattern.String() + ")$")
  594. var r = assumeValidRegexp(full_pattern)
  595. if result := r.FindStringIndex(s); (result != nil) {
  596. if result[0] != 0 { panic("something went wrong") }
  597. if result[1] != len(s) { panic("something went wrong") }
  598. return true
  599. } else {
  600. return false
  601. }
  602. }
  603. func StringReplace(s string, pattern *regexp.Regexp, f func(string)(string)) string {
  604. return pattern.ReplaceAllStringFunc(s, f)
  605. }
  606. type ToString func()(string)
  607. func BoolString(p bool) string {
  608. if p {
  609. return "Yes"
  610. } else {
  611. return "No"
  612. }
  613. }
  614. func OrderingString(o ctn.Ordering) string {
  615. return o.String()
  616. }
  617. func IntString(a *big.Int) string {
  618. return a.String()
  619. }
  620. func FloatString(x float64) string {
  621. return strconv.FormatFloat(x, 'g', -1, 64)
  622. }
  623. func CharString(c rune) string {
  624. return string([] rune { c })
  625. }
  626. func ParseInt(s string) ctn.Maybe[*big.Int] {
  627. var n = new(big.Int)
  628. if _, ok := n.SetString(s, 10); ok {
  629. return ctn.Just(n)
  630. } else {
  631. return nil
  632. }
  633. }
  634. func ParseFloat(s string) ctn.Maybe[float64] {
  635. var x, err = strconv.ParseFloat(s, 64)
  636. if err == nil {
  637. return ctn.Just(x)
  638. } else {
  639. return nil
  640. }
  641. }
  642. func ListConcat(l core.List) core.List {
  643. var buf core.ListBuilder
  644. l.ForEach(func(item core.Object) {
  645. core.GetList(item).ForEach(func(item core.Object) {
  646. buf.Append(item)
  647. })
  648. })
  649. return buf.Collect()
  650. }
  651. func ListEmpty(l core.List) bool {
  652. return l.Empty()
  653. }
  654. func ListFirst(l core.List) ctn.Maybe[core.Object] {
  655. return ctn.MakeMaybe(l.First())
  656. }
  657. func ListLength(l core.List) int {
  658. return l.Length()
  659. }
  660. func ListSeq(l core.List) core.Seq {
  661. return l.ToSeq()
  662. }
  663. func ListShift(l core.List) ctn.Maybe[ctn.Pair[core.Object,core.List]] {
  664. var head, tail, ok = l.Shifted()
  665. return ctn.MakeMaybe(ctn.MakePair(head, tail), ok)
  666. }
  667. func ListReverse(l core.List) core.List {
  668. return l.Reversed()
  669. }
  670. func ListSort(l core.List, lt LessThanOperator) core.List {
  671. return l.Sorted(ctn.Less[core.Object](lt))
  672. }
  673. func ListTake(l core.List, n int) core.List {
  674. return l.Take(n)
  675. }
  676. func ListWithIndex(l core.List) core.List {
  677. return l.WithIndex()
  678. }
  679. func ListMap(l core.List, f func(core.Object)(core.Object)) core.List {
  680. return l.Map(f)
  681. }
  682. func ListDeflateMap(l core.List, f func(core.Object)(ctn.Maybe[core.Object])) core.List {
  683. return l.DeflateMap(f)
  684. }
  685. func ListFlatMap(l core.List, f func(core.Object)(core.List)) core.List {
  686. return l.FlatMap(f)
  687. }
  688. func ListFilter(l core.List, f func(core.Object)(bool)) core.List {
  689. return l.Filter(f)
  690. }
  691. func ListScan(l core.List, b core.Object, f func(core.Object,core.Object)(core.Object)) core.List {
  692. return l.Scan(b, f)
  693. }
  694. func ListFold(l core.List, b core.Object, f func(core.Object,core.Object)(core.Object)) core.Object {
  695. return l.Fold(b, f)
  696. }
  697. func SeqEmpty(s core.Seq) bool {
  698. return s.Empty()
  699. }
  700. func SeqLast(s core.Seq) ctn.Maybe[core.Object] {
  701. return ctn.MakeMaybe(s.Last())
  702. }
  703. func SeqLength(s core.Seq) int {
  704. return s.Length()
  705. }
  706. func SeqList(s core.Seq) core.List {
  707. return s.ToList()
  708. }
  709. func SeqAppend(s core.Seq, item core.Object) core.Seq {
  710. return s.Appended(item)
  711. }
  712. func SeqDeflateAppend(s core.Seq, item ctn.Maybe[core.Object]) core.Seq {
  713. if item, ok := item.Value(); ok {
  714. return s.Appended(item)
  715. } else {
  716. return s
  717. }
  718. }
  719. func SeqFlatAppend(s core.Seq, items core.List) core.Seq {
  720. var draft = s
  721. items.ForEach(func(item core.Object) {
  722. draft = draft.Appended(item)
  723. })
  724. return draft
  725. }
  726. func SeqSort(s core.Seq, lt LessThanOperator) core.Seq {
  727. return s.Sorted(ctn.Less[core.Object](lt))
  728. }
  729. func SeqFilter(s core.Seq, f func(core.Object)(bool)) core.Seq {
  730. return s.Filter(f)
  731. }
  732. func Queue(items core.List) core.Queue {
  733. var queue = ctn.MakeQueue[core.Object]()
  734. items.ForEach(func(item core.Object) {
  735. queue = queue.Appended(item)
  736. })
  737. return core.Queue(queue)
  738. }
  739. func QueueEmpty(q core.Queue) bool {
  740. var queue = ctn.Queue[core.Object](q)
  741. return queue.IsEmpty()
  742. }
  743. func QueueSize(q core.Queue) int {
  744. var queue = ctn.Queue[core.Object](q)
  745. return queue.Size()
  746. }
  747. func QueueFirst(q core.Queue) ctn.Maybe[core.Object] {
  748. var queue = ctn.Queue[core.Object](q)
  749. return ctn.MakeMaybe(queue.First())
  750. }
  751. func QueueList(q core.Queue) core.List {
  752. var queue = ctn.Queue[core.Object](q)
  753. var buf core.ListBuilder
  754. queue.ForEach(func(item core.Object) {
  755. buf.Append(item)
  756. })
  757. return buf.Collect()
  758. }
  759. func QueueShift(q core.Queue) ctn.Maybe[ctn.Pair[core.Object,core.Queue]] {
  760. var queue = ctn.Queue[core.Object](q)
  761. var v, rest, ok = queue.Shifted()
  762. return ctn.MakeMaybe(ctn.MakePair(v, core.Queue(rest)), ok)
  763. }
  764. func QueueAppend(q core.Queue, item core.Object) core.Queue {
  765. var queue = ctn.Queue[core.Object](q)
  766. return core.Queue(queue.Appended(item))
  767. }
  768. func Heap(items core.List, lt LessThanOperator) core.Heap {
  769. var heap = ctn.MakeHeap(ctn.Less[core.Object](lt))
  770. items.ForEach(func(item core.Object) {
  771. heap = heap.Inserted(item)
  772. })
  773. return core.Heap(heap)
  774. }
  775. func HeapEmpty(h core.Heap) bool {
  776. var heap = ctn.Heap[core.Object](h)
  777. return heap.IsEmpty()
  778. }
  779. func HeapSize(h core.Heap) int {
  780. var heap = ctn.Heap[core.Object](h)
  781. return heap.Size()
  782. }
  783. func HeapFirst(h core.Heap) ctn.Maybe[core.Object] {
  784. var heap = ctn.Heap[core.Object](h)
  785. return ctn.MakeMaybe(heap.First())
  786. }
  787. func HeapList(h core.Heap) core.List {
  788. var heap = ctn.Heap[core.Object](h)
  789. var buf core.ListBuilder
  790. heap.ForEach(func(item core.Object) {
  791. buf.Append(item)
  792. })
  793. return buf.Collect()
  794. }
  795. func HeapShift(h core.Heap) ctn.Maybe[ctn.Pair[core.Object,core.Heap]] {
  796. var heap = ctn.Heap[core.Object](h)
  797. var v, rest, ok = heap.Shifted()
  798. return ctn.MakeMaybe(ctn.MakePair(v, core.Heap(rest)), ok)
  799. }
  800. func HeapInsert(h core.Heap, item core.Object) core.Heap {
  801. var heap = ctn.Heap[core.Object](h)
  802. return core.Heap(heap.Inserted(item))
  803. }
  804. func Set(items core.List, cmp CompareWithOperator) core.Set {
  805. var set = ctn.MakeSet(ctn.Compare[core.Object](cmp))
  806. items.ForEach(func(item core.Object) {
  807. set = set.Inserted(item)
  808. })
  809. return core.Set(set)
  810. }
  811. func SetEmpty(s core.Set) bool {
  812. var set = ctn.Set[core.Object](s)
  813. return set.IsEmpty()
  814. }
  815. func SetSize(s core.Set) int {
  816. var set = ctn.Set[core.Object](s)
  817. return set.Size()
  818. }
  819. func SetList(s core.Set) core.List {
  820. var set = ctn.Set[core.Object](s)
  821. var buf core.ListBuilder
  822. set.ForEach(func(item core.Object) {
  823. buf.Append(item)
  824. })
  825. return buf.Collect()
  826. }
  827. func SetHas(s core.Set, item core.Object) bool {
  828. var set = ctn.Set[core.Object](s)
  829. return set.Has(item)
  830. }
  831. func SetDelete(s core.Set, item core.Object) core.Set {
  832. var set = ctn.Set[core.Object](s)
  833. var new_set, _ = set.Deleted(item)
  834. return core.Set(new_set)
  835. }
  836. func SetInsert(s core.Set, item core.Object) core.Set {
  837. var set = ctn.Set[core.Object](s)
  838. return core.Set(set.Inserted(item))
  839. }
  840. func Map(entries core.List, cmp CompareWithOperator) core.Map {
  841. var map_ = ctn.MakeMap[core.Object,core.Object](ctn.Compare[core.Object](cmp))
  842. entries.ForEach(func(entry core.Object) {
  843. var pair = core.FromObject[ctn.Pair[core.Object,core.Object]](entry)
  844. map_ = map_.Inserted(pair.Key(), pair.Value())
  845. })
  846. return core.Map(map_)
  847. }
  848. func MapEmpty(m core.Map) bool {
  849. var map_ = ctn.Map[core.Object,core.Object](m)
  850. return map_.IsEmpty()
  851. }
  852. func MapSize(m core.Map) int {
  853. var map_ = ctn.Map[core.Object,core.Object](m)
  854. return map_.Size()
  855. }
  856. func MapKeys(m core.Map) core.List {
  857. var map_ = ctn.Map[core.Object,core.Object](m)
  858. var buf core.ListBuilder
  859. map_.ForEach(func(k core.Object, _ core.Object) {
  860. buf.Append(k)
  861. })
  862. return buf.Collect()
  863. }
  864. func MapValues(m core.Map) core.List {
  865. var map_ = ctn.Map[core.Object,core.Object](m)
  866. var buf core.ListBuilder
  867. map_.ForEach(func(_ core.Object, v core.Object) {
  868. buf.Append(v)
  869. })
  870. return buf.Collect()
  871. }
  872. func MapEntries(m core.Map) core.List {
  873. var map_ = ctn.Map[core.Object,core.Object](m)
  874. var buf core.ListBuilder
  875. map_.ForEach(func(k core.Object, v core.Object) {
  876. buf.Append(core.ToObject(ctn.MakePair(k, v)))
  877. })
  878. return buf.Collect()
  879. }
  880. func MapHas(m core.Map, key core.Object) bool {
  881. var map_ = ctn.Map[core.Object,core.Object](m)
  882. return map_.Has(key)
  883. }
  884. func MapLookup(m core.Map, key core.Object) ctn.Maybe[core.Object] {
  885. var map_ = ctn.Map[core.Object,core.Object](m)
  886. return ctn.MakeMaybe(map_.Lookup(key))
  887. }
  888. func MapDelete(m core.Map, key core.Object) core.Map {
  889. var map_ = ctn.Map[core.Object,core.Object](m)
  890. var _, new_map, _ = map_.Deleted(key)
  891. return core.Map(new_map)
  892. }
  893. func MapInsert(m core.Map, entry ctn.Pair[core.Object,core.Object]) core.Map {
  894. var map_ = ctn.Map[core.Object,core.Object](m)
  895. return core.Map(map_.Inserted(entry.Key(), entry.Value()))
  896. }
  897. func Observable(l core.List) core.Observable {
  898. return core.Observable(func(pub core.DataPublisher) {
  899. pub.SyncGenerate(func(yield func(core.Object)) error {
  900. l.ForEach(yield)
  901. return nil
  902. })
  903. })
  904. }
  905. func Go(k func()(core.Object)) core.Observable {
  906. return core.Observable(func(pub core.DataPublisher) {
  907. go (func() {
  908. var v = k()
  909. pub.AsyncReturn(v)
  910. })()
  911. })
  912. }
  913. func Throw(e error) core.Observable {
  914. return core.Observable(func(pub core.DataPublisher) {
  915. pub.SyncReturn(func() (core.Object, error) {
  916. return nil, e
  917. })
  918. })
  919. }
  920. func Crash(err error, h core.RuntimeHandle) core.Observable {
  921. return core.Observable(func(pub core.DataPublisher) {
  922. pub.SyncReturn(func() (core.Object, error) {
  923. return core.Crash2[core.Object,error](
  924. h, core.ProgrammedCrash, err.Error(),
  925. )
  926. })
  927. })
  928. }
  929. func ObservableCatch(o core.Observable, f func(error,core.Observable)(core.Observable)) core.Observable {
  930. return o.Catch(f)
  931. }
  932. func ObservableRetry(o core.Observable, n int) core.Observable {
  933. return o.Retry(n)
  934. }
  935. func ObservableLogError(o core.Observable, h core.RuntimeHandle) core.Observable {
  936. return o.LogError(h)
  937. }
  938. func ObservableDistinctUntilChanged(o core.Observable, eq EqualToOperator) core.Observable {
  939. return o.DistinctUntilChanged(eq)
  940. }
  941. func ObservableWithLatestFrom(o core.Observable, another core.Observable) core.Observable {
  942. return o.WithLatestFrom(another)
  943. }
  944. func ObservableMapToLatestFrom(o core.Observable, another core.Observable) core.Observable {
  945. return o.MapToLatestFrom(another)
  946. }
  947. func ObservableWithCycle(o core.Observable, l core.List) core.Observable {
  948. return o.WithCycle(l)
  949. }
  950. func ObservableWithIndex(o core.Observable) core.Observable {
  951. return o.WithIndex()
  952. }
  953. func ObservableWithTime(o core.Observable) core.Observable {
  954. return o.WithTime()
  955. }
  956. func ObservableDelaySubscription(o core.Observable, ms int) core.Observable {
  957. return o.DelayRun(ms)
  958. }
  959. func ObservableDelayValues(o core.Observable, ms int) core.Observable {
  960. return o.DelayValues(ms)
  961. }
  962. func ObservableStartWith(o core.Observable, first core.Object) core.Observable {
  963. return o.StartWith(first)
  964. }
  965. func ObservableEndWith(o core.Observable, last core.Object) core.Observable {
  966. return o.EndWith(last)
  967. }
  968. func ObservableThrottle(o core.Observable, f func(core.Object)(core.Observable)) core.Observable {
  969. return o.Throttle(f)
  970. }
  971. func ObservableDebounce(o core.Observable, f func(core.Object)(core.Observable)) core.Observable {
  972. return o.Debounce(f)
  973. }
  974. func ObservableThrottleTime(o core.Observable, ms int) core.Observable {
  975. return o.ThrottleTime(ms)
  976. }
  977. func ObservableDebounceTime(o core.Observable, ms int) core.Observable {
  978. return o.DebounceTime(ms)
  979. }
  980. func ObservableCompleteOnEmit(o core.Observable) core.Observable {
  981. return o.CompleteOnEmit()
  982. }
  983. func ObservableSkip(o core.Observable, n int) core.Observable {
  984. return o.Skip(n)
  985. }
  986. func ObservableTake(o core.Observable, n int) core.Observable {
  987. return o.Take(n)
  988. }
  989. func ObservableTakeLast(o core.Observable) core.Observable {
  990. return o.TakeLast()
  991. }
  992. func ObservableTakeLastAsMaybe(o core.Observable) core.Observable {
  993. return o.TakeLast().Map(core.Just).EndWith(core.Nothing()).Take(1)
  994. }
  995. func ObservableTakeWhile(o core.Observable, f func(core.Object)(bool)) core.Observable {
  996. return o.TakeWhile(f)
  997. }
  998. func ObservableTakeWhileMaybeOK(o core.Observable) core.Observable {
  999. return o.TakeWhile(func(obj core.Object) bool {
  1000. var _, ok = core.UnwrapMaybe(obj)
  1001. return ok
  1002. }).Map(func(obj core.Object) core.Object {
  1003. var v, ok = core.UnwrapMaybe(obj)
  1004. if !(ok) { panic("something went wrong") }
  1005. return v
  1006. })
  1007. }
  1008. func ObservableTakeUntil(o core.Observable, stop core.Observable) core.Observable {
  1009. return o.TakeUntil(stop)
  1010. }
  1011. func ObservableCount(o core.Observable) core.Observable {
  1012. return o.Count()
  1013. }
  1014. func ObservableCollect(o core.Observable) core.Observable {
  1015. return o.Collect()
  1016. }
  1017. func ObservableBufferTime(o core.Observable, ms int) core.Observable {
  1018. return o.BufferTime(ms)
  1019. }
  1020. func ObservablePairwise(o core.Observable) core.Observable {
  1021. return o.Pairwise()
  1022. }
  1023. func ObservableBufferCount(o core.Observable, n int) core.Observable {
  1024. return o.BufferCount(n)
  1025. }
  1026. func ObservableMap(o core.Observable, f func(core.Object)(core.Object)) core.Observable {
  1027. return o.Map(f)
  1028. }
  1029. func ObservableMapTo(o core.Observable, v core.Object) core.Observable {
  1030. return o.MapTo(v)
  1031. }
  1032. func ObservableFilter(o core.Observable, f func(core.Object)(bool)) core.Observable {
  1033. return o.Filter(f)
  1034. }
  1035. func ObservableScan(o core.Observable, init core.Object, f func(core.Object,core.Object)(core.Object)) core.Observable {
  1036. return o.Scan(init, f)
  1037. }
  1038. func ObservableReduce(o core.Observable, init core.Object, f func(core.Object,core.Object)(core.Object)) core.Observable {
  1039. return o.Reduce(init, f)
  1040. }
  1041. func ObservableCombineLatest(o core.Observable, another core.Observable) core.Observable {
  1042. return o.CombineLatest(another)
  1043. }
  1044. func ListObservableCombineLatest(l ([] core.Observable)) core.Observable {
  1045. return core.CombineLatest(l...)
  1046. }
  1047. func ObservableAwait(o core.Observable, k func(core.Object)(core.Observable)) core.Observable {
  1048. return o.Await(k)
  1049. }
  1050. func ObservableAwaitNoexcept(o core.Observable, k func(core.Object)(core.Observable), h core.RuntimeHandle) core.Observable {
  1051. return o.AwaitNoexcept(h, k)
  1052. }
  1053. func ObservableThen(o core.Observable, k core.Observable) core.Observable {
  1054. return o.Then(k)
  1055. }
  1056. func ObservableWith(o core.Observable, bg core.Observable, h core.RuntimeHandle) core.Observable {
  1057. return o.With(bg, core.ErrorLogger(h))
  1058. }
  1059. func ObservableAnd(o core.Observable, bg core.Observable, h core.RuntimeHandle) core.Observable {
  1060. return o.And(bg, core.ErrorLogger(h))
  1061. }
  1062. func ObservableAutoMap(o core.Observable, f func(core.Object)(core.Observable)) core.Observable {
  1063. return o.MergeMap2(f, true)
  1064. }
  1065. func ListObservableMerge(l core.List) core.Observable {
  1066. return core.Merge(forEachObservable(l))
  1067. }
  1068. func ObservableMerge(o1 core.Observable, o2 core.Observable) core.Observable {
  1069. return core.Merge(core.YieldObservables(o1, o2))
  1070. }
  1071. func ObservableMergeMap(o core.Observable, f func(core.Object)(core.Observable)) core.Observable {
  1072. return o.MergeMap(f)
  1073. }
  1074. func ListObservableConcat(l core.List) core.Observable {
  1075. return core.Concat(forEachObservable(l))
  1076. }
  1077. func ObservableConcat(o1 core.Observable, o2 core.Observable) core.Observable {
  1078. return core.Concat(core.YieldObservables(o1, o2))
  1079. }
  1080. func ObservableConcatMap(o core.Observable, f func(core.Object)(core.Observable)) core.Observable {
  1081. return o.ConcatMap(f)
  1082. }
  1083. func ObservableSwitchMap(o core.Observable, f func(core.Object)(core.Observable)) core.Observable {
  1084. return o.SwitchMap(f)
  1085. }
  1086. func ObservableExhaustMap(o core.Observable, f func(core.Object)(core.Observable)) core.Observable {
  1087. return o.ExhaustMap(f)
  1088. }
  1089. func NumCPU() int {
  1090. return runtime.NumCPU()
  1091. }
  1092. func ListObservableConcurrent(l core.List, n int) core.Observable {
  1093. return core.Concurrent(n, forEachObservable(l))
  1094. }
  1095. func ObservableConcurrentMap(o core.Observable, f func(core.Object)(core.Observable), n int) core.Observable {
  1096. return o.ConcurrentMap(n, f)
  1097. }
  1098. func ListObservableForkJoin(l ([] core.Observable), n int) core.Observable {
  1099. return core.ForkJoin(n, l...)
  1100. }
  1101. func ObservableForkJoin(o core.Observable, another core.Observable, n int) core.Observable {
  1102. return o.ForkJoin(n, another)
  1103. }
  1104. func UUID() core.Observable {
  1105. return core.Observable(func(pub core.DataPublisher) {
  1106. pub.SyncReturn(func() (core.Object, error) {
  1107. var uuid = qt.UUID()
  1108. return core.ObjString(uuid), nil
  1109. })
  1110. })
  1111. }
  1112. func Random(supremum *big.Int, h core.RuntimeHandle) core.Observable {
  1113. return core.RandBigInt(supremum, h)
  1114. }
  1115. func Shuffle(l core.List, h core.RuntimeHandle) core.Observable {
  1116. return core.Rand(h, func(r *rand.Rand) core.Object {
  1117. var nodes = make([] core.ListNode, 0)
  1118. l.ForEach(func(value core.Object) {
  1119. nodes = append(nodes, core.ListNode {
  1120. Value: value,
  1121. })
  1122. })
  1123. r.Shuffle(len(nodes), func(i, j int) {
  1124. nodes[i], nodes[j] = nodes[j], nodes[i]
  1125. })
  1126. var shuffled = core.NodesToList(nodes)
  1127. return core.Obj(shuffled)
  1128. })
  1129. }
  1130. func CreateSubject(replay int, items ([] core.Object), h core.RuntimeHandle) core.Observable {
  1131. return core.Observable(func(pub core.DataPublisher) {
  1132. pub.SyncReturn(func() (core.Object, error) {
  1133. var bus = core.CreateSubject(h, replay, items...)
  1134. return core.Obj(bus), nil
  1135. })
  1136. })
  1137. }
  1138. func SubjectValues(b core.Subject) core.Observable {
  1139. return b.Observe()
  1140. }
  1141. func SubjectPlug(b core.Subject, input core.Observable) core.Observable {
  1142. return b.Plug(input)
  1143. }
  1144. func TimeString(t time.Time) string {
  1145. return t.String()
  1146. }
  1147. func TimeSubtractMillisecond(t time.Time, u time.Time) int {
  1148. return int(t.Sub(u).Milliseconds())
  1149. }
  1150. func Get(endpoint string, rt core.ReflectType, token string, h core.RuntimeHandle) core.Observable {
  1151. return request(core.GET, endpoint, rt, token, nil, h)
  1152. }
  1153. func Post(data core.ReflectValue, endpoint string, rt core.ReflectType, token string, h core.RuntimeHandle) core.Observable {
  1154. return request(core.POST, endpoint, rt, token, ctn.Just(data), h)
  1155. }
  1156. func Put(data core.ReflectValue, endpoint string, rt core.ReflectType, token string, h core.RuntimeHandle) core.Observable {
  1157. return request(core.PUT, endpoint, rt, token, ctn.Just(data), h)
  1158. }
  1159. func Delete(endpoint string, rt core.ReflectType, token string, h core.RuntimeHandle) core.Observable {
  1160. return request(core.DELETE, endpoint, rt, token, nil, h)
  1161. }
  1162. func Subscribe(endpoint string, rt core.ReflectType, token string, h core.RuntimeHandle) core.Observable {
  1163. return request(core.SUBSCRIBE, endpoint, rt, token, nil, h)
  1164. }
  1165. func request(method core.RequestMethod, endpoint_ string, rt core.ReflectType, token string, body_ ctn.Maybe[core.ReflectValue], h core.RuntimeHandle) core.Observable {
  1166. var endpoint, err = url.Parse(endpoint_)
  1167. if err != nil {
  1168. var msg = ("invalid endpoint URL: " + endpoint_)
  1169. core.Crash(h, core.InvalidArgument, msg)
  1170. }
  1171. var marshal_req = (func() core.Observable {
  1172. if rv, ok := body_.Value(); ok {
  1173. return marshal(rv, h)
  1174. } else {
  1175. return core.ObservableSyncValue(core.ObjBytes(nil))
  1176. }
  1177. })()
  1178. var unmarshal_resp = func(obj core.Object) core.Observable {
  1179. var binary = core.GetBytes(obj)
  1180. return unmarshal(binary, rt, h)
  1181. }
  1182. return marshal_req.Await(func(obj core.Object) core.Observable {
  1183. var body = core.GetBytes(obj)
  1184. var req = core.Request {
  1185. Method: method,
  1186. Endpoint: endpoint,
  1187. AuthToken: token,
  1188. BodyContent: body,
  1189. }
  1190. var resp = req.Observe(core.MakeLogger(h))
  1191. return resp.ConcatMap(unmarshal_resp)
  1192. })
  1193. }
  1194. func FileString(f core.File) string {
  1195. return f.Path
  1196. }
  1197. func FileEqual(f core.File, g core.File) bool {
  1198. return (f.Path == g.Path)
  1199. }
  1200. func ReadTextFile(f core.File, h core.RuntimeHandle) core.Observable {
  1201. return core.Observable(func(pub core.DataPublisher) {
  1202. go (func() {
  1203. core.MakeLogger(h).LogFileRead(f)
  1204. var content, err = os.ReadFile(f.Path)
  1205. if err != nil { pub.AsyncThrow(err); return }
  1206. var text, ok = util.WellBehavedTryDecodeUtf8(content)
  1207. if !(ok) {
  1208. var err = errors.New("invalid UTF-8")
  1209. { pub.AsyncThrow(err); return }
  1210. }
  1211. pub.AsyncReturn(core.ObjString(text))
  1212. })()
  1213. })
  1214. }
  1215. func WriteTextFile(f core.File, text string, h core.RuntimeHandle) core.Observable {
  1216. return core.Observable(func(pub core.DataPublisher) {
  1217. go (func() {
  1218. var content = ([] byte)(text)
  1219. core.MakeLogger(h).LogFileWrite(f, content)
  1220. var err = os.WriteFile(f.Path, content, 0666)
  1221. if err != nil { pub.AsyncThrow(err); return }
  1222. pub.AsyncReturn(nil)
  1223. })()
  1224. })
  1225. }
  1226. func ReadConfig(dir string, name string, default_ core.ReflectValue, h core.RuntimeHandle) core.Observable {
  1227. return core.Observable(func(pub core.DataPublisher) {
  1228. go (func() {
  1229. var ctx = h.SerializationContext()
  1230. var f, err = getConfigFile(dir, name)
  1231. if err != nil { pub.AsyncThrow(err); return }
  1232. if _, err := os.Stat(f); err != nil {
  1233. var binary, err = core.Marshal(default_, ctx)
  1234. if err != nil { pub.AsyncThrow(err); return }
  1235. { var fd, err = os.Create(f)
  1236. if err != nil { pub.AsyncThrow(err); return }
  1237. { var _, err = fd.Write(binary)
  1238. if err != nil { pub.AsyncThrow(err); return }
  1239. pub.AsyncReturn(default_.Value()) }}
  1240. } else {
  1241. var fd, err = os.Open(f)
  1242. if err != nil { pub.AsyncThrow(err); return }
  1243. { var binary, err = io.ReadAll(fd)
  1244. if err != nil { pub.AsyncThrow(err); return }
  1245. { var value, err = core.Unmarshal(binary, default_.Type(), ctx)
  1246. if err != nil { pub.AsyncThrow(err); return }
  1247. pub.AsyncReturn(value) }}
  1248. }
  1249. })()
  1250. })
  1251. }
  1252. func WriteConfig(dir string, name string, rv core.ReflectValue, h core.RuntimeHandle) core.Observable {
  1253. return core.Observable(func(pub core.DataPublisher) {
  1254. go (func() {
  1255. var ctx = h.SerializationContext()
  1256. var f, err = getConfigFile(dir, name)
  1257. if err != nil { pub.AsyncThrow(err); return }
  1258. { var binary, err = core.Marshal(rv, ctx)
  1259. if err != nil { pub.AsyncThrow(err); return }
  1260. { var fd, err = os.Create(f)
  1261. if err != nil { pub.AsyncThrow(err); return }
  1262. { var _, err = fd.Write(binary)
  1263. if err != nil { pub.AsyncThrow(err); return }
  1264. pub.AsyncReturn(nil) }}}
  1265. })()
  1266. })
  1267. }
  1268. func getConfigFile(dir string, name string) (string, error) {
  1269. for _, elem := range [] string { dir, name } {
  1270. if strings.ContainsAny(elem, "./\\:") {
  1271. return "", errors.New("invalid dir/file name")
  1272. }
  1273. }
  1274. var config, err = os.UserConfigDir()
  1275. if err != nil { return "", err }
  1276. { var dir = filepath.Join(config, dir)
  1277. _ = os.Mkdir(dir, 0777)
  1278. var name = filepath.Join(dir, name)
  1279. return name, nil }
  1280. }
  1281. func Arguments(h core.RuntimeHandle) ([] string) {
  1282. return h.ProgramArgs()
  1283. }
  1284. func Environment() ([] string) {
  1285. return os.Environ()
  1286. }
  1287. func FontSize() int {
  1288. return qt.FontSize()
  1289. }
  1290. func ShowInfo(content string, title string) core.Observable {
  1291. return showMessageBox(
  1292. qt.MsgBoxInfo(),
  1293. qt.MsgBoxOK(), qt.MsgBoxOK(),
  1294. title, content,
  1295. func(btn qt.MsgBoxBtn) (core.Object, bool) {
  1296. return nil, (btn == qt.MsgBoxOK())
  1297. },
  1298. )
  1299. }
  1300. func ShowWarning(content string, title string) core.Observable {
  1301. return showMessageBox(
  1302. qt.MsgBoxWarning(),
  1303. qt.MsgBoxOK(), qt.MsgBoxOK(),
  1304. title, content,
  1305. func(btn qt.MsgBoxBtn) (core.Object, bool) {
  1306. return nil, (btn == qt.MsgBoxOK())
  1307. },
  1308. )
  1309. }
  1310. func ShowCritical(content string, title string) core.Observable {
  1311. return showMessageBox(
  1312. qt.MsgBoxCritical(),
  1313. qt.MsgBoxOK(), qt.MsgBoxOK(),
  1314. title, content,
  1315. func(btn qt.MsgBoxBtn) (core.Object, bool) {
  1316. return nil, (btn == qt.MsgBoxOK())
  1317. },
  1318. )
  1319. }
  1320. func ShowYesNo(content string, title string) core.Observable {
  1321. return showMessageBox(
  1322. qt.MsgBoxQuestion(),
  1323. qt.MsgBoxYes().And(qt.MsgBoxNo()),
  1324. qt.MsgBoxYes(),
  1325. title,
  1326. content,
  1327. func(btn qt.MsgBoxBtn) (core.Object, bool) {
  1328. switch btn {
  1329. case qt.MsgBoxYes(): return core.ObjBool(true), true
  1330. case qt.MsgBoxNo(): return core.ObjBool(false), true
  1331. default: return nil, false
  1332. }
  1333. },
  1334. )
  1335. }
  1336. func ShowAbortRetryIgnore(content string, title string) core.Observable {
  1337. return showMessageBox(
  1338. qt.MsgBoxCritical(),
  1339. qt.MsgBoxAbort().And(qt.MsgBoxRetry()).And(qt.MsgBoxIgnore()),
  1340. qt.MsgBoxRetry(),
  1341. title,
  1342. content,
  1343. func(btn qt.MsgBoxBtn) (core.Object, bool) {
  1344. switch btn {
  1345. case qt.MsgBoxRetry(): return core.ToObject(RI_Retry), true
  1346. case qt.MsgBoxIgnore(): return core.ToObject(RI_Ignore), true
  1347. default: return nil, false
  1348. }
  1349. },
  1350. )
  1351. }
  1352. func ShowSaveDiscardCancel(content string, title string) core.Observable {
  1353. return showMessageBox(
  1354. qt.MsgBoxWarning(),
  1355. qt.MsgBoxSave().And(qt.MsgBoxDiscard()).And(qt.MsgBoxCancel()),
  1356. qt.MsgBoxCancel(),
  1357. title,
  1358. content,
  1359. func(btn qt.MsgBoxBtn) (core.Object, bool) {
  1360. switch btn {
  1361. case qt.MsgBoxSave(): return core.ToObject(SD_Save), true
  1362. case qt.MsgBoxDiscard(): return core.ToObject(SD_Discard), true
  1363. default: return nil, false
  1364. }
  1365. },
  1366. )
  1367. }
  1368. type RetryIgnore int
  1369. const (
  1370. RI_Retry RetryIgnore = iota
  1371. RI_Ignore
  1372. )
  1373. type SaveDiscard int
  1374. const (
  1375. SD_Save SaveDiscard = iota
  1376. SD_Discard
  1377. )
  1378. func GetChoice(prompt string, items ([] ComboBoxItem), title string, h core.RuntimeHandle) core.Observable {
  1379. if len(items) == 0 {
  1380. core.Crash(h, core.InvalidArgument, "item list cannot be empty")
  1381. }
  1382. return showComboBoxInputBox(items, title, prompt, h)
  1383. }
  1384. func GetLine(prompt string, initial string, title string) core.Observable {
  1385. return showInputBox(qt.InputText(), false, nil, initial, title, prompt, func(s string, _ int, _ float64) core.Object {
  1386. return core.ObjString(s)
  1387. })
  1388. }
  1389. func GetText(prompt string, initial string, title string) core.Observable {
  1390. return showInputBox(qt.InputText(), true, nil, initial, title, prompt, func(s string, _ int, _ float64) core.Object {
  1391. return core.ObjString(s)
  1392. })
  1393. }
  1394. func GetInt(prompt string, initial int, title string) core.Observable {
  1395. return showInputBox(qt.InputInt(), false, nil, initial, title, prompt, func(_ string, i int, _ float64) core.Object {
  1396. return core.ObjInt(i)
  1397. })
  1398. }
  1399. func GetFloat(prompt string, initial float64, title string) core.Observable {
  1400. return showInputBox(qt.InputDouble(), false, nil, initial, title, prompt, func(_ string, _ int, x float64) core.Object {
  1401. return core.ObjFloat(x)
  1402. })
  1403. }
  1404. func GetFileListToOpen(filter string) core.Observable {
  1405. return showFileDialog(qt.FileDialogModeOpenMultiple(), filter)
  1406. }
  1407. func GetFileToOpen(filter string) core.Observable {
  1408. return showFileDialog(qt.FileDialogModeOpenSingle(), filter)
  1409. }
  1410. func GetFileToSave(filter string) core.Observable {
  1411. return showFileDialog(qt.FileDialogModeSave(), filter)
  1412. }
  1413. func showFileDialog(mode qt.FileDialogMode, filter string) core.Observable {
  1414. return core.Observable(func(pub core.DataPublisher) {
  1415. var dialog = qt.CreateFileDialog(mode, filter)
  1416. dialog.Consume(func(files ([] string), ok bool) {
  1417. var yield, complete = core.DialogGenerate(pub); defer complete()
  1418. if ok {
  1419. switch mode {
  1420. default:
  1421. yield(core.ObjFile(files[0]))
  1422. case qt.FileDialogModeOpenMultiple():
  1423. yield(core.ObjList(ctn.MapEach(files, core.ObjFile)))
  1424. }
  1425. }
  1426. })
  1427. })
  1428. }
  1429. func Action(icon Icon, text string, shortcut string, repeat bool, enable core.Observable, h core.RuntimeHandle) core.Hook {
  1430. return core.MakeHookWithEffect(h, func() (core.Action, core.Observable, func()) {
  1431. var action, delete_ = core.WrapAction(func(ctx qt.Pkg) qt.Action {
  1432. return qt.CreateAction(convertIcon(icon, h), text, shortcut, repeat, ctx)
  1433. })
  1434. var bind_enable = enable.ConcatMap(func(obj core.Object) core.Observable {
  1435. return core.SetActionEnabled(action, core.GetBool(obj), h)
  1436. })
  1437. return action, bind_enable, delete_
  1438. })
  1439. }
  1440. func ActionTriggers(a core.Action, h core.RuntimeHandle) core.Observable {
  1441. return core.ConnectActionTrigger(a, h)
  1442. }
  1443. type ActionCheckBox_T struct { Checked core.Observable }
  1444. func ActionCheckBox(a core.Action, initial bool, h core.RuntimeHandle) core.Hook {
  1445. return core.ActionCheckBox(a, initial, h, func(checked core.Observable) core.Object {
  1446. return core.ToObject(ActionCheckBox_T { checked })
  1447. })
  1448. }
  1449. type ActionComboBox_T struct { SelectedItem core.Observable }
  1450. func ActionComboBox(items ([] ActionComboBoxItem), h core.RuntimeHandle) core.Hook {
  1451. if len(items) == 0 {
  1452. core.Crash(h, core.InvalidArgument, "item list cannot be empty")
  1453. }
  1454. var adapted = ctn.MapEach(items, adaptActionComboBoxItem)
  1455. return core.ActionComboBox(adapted, h, func(selected_ core.Observable) core.Object {
  1456. var selected = selected_.Map(func(obj core.Object) core.Object {
  1457. var index = core.GetInt(obj)
  1458. return items[index].Value
  1459. })
  1460. return core.ToObject(ActionComboBox_T { selected })
  1461. })
  1462. }
  1463. type MenuBar struct {
  1464. Menus [] Menu
  1465. }
  1466. func convertMenuBar(b MenuBar, h core.RuntimeHandle) qt.MenuBar {
  1467. if len(b.Menus) == 0 {
  1468. return qt.MenuBar {}
  1469. }
  1470. var menu_bar = qt.CreateMenuBar()
  1471. for _, m := range b.Menus {
  1472. menu_bar.AddMenu(convertMenu(m, h))
  1473. }
  1474. return menu_bar
  1475. }
  1476. type ToolBar struct {
  1477. Mode ToolBarMode
  1478. Items [] ToolBarItem
  1479. }
  1480. type ToolBarMode int
  1481. const (
  1482. TBM_IconOnly ToolBarMode = iota
  1483. TBM_TextOnly
  1484. TBM_TextBesideIcon
  1485. TBM_TextUnderIcon
  1486. )
  1487. type ToolBarItem struct {
  1488. pseudounion.Tag
  1489. Menu; Action(core.Action); Separator; Widget(core.Widget); Spacer
  1490. }
  1491. func convertToolBar(b ToolBar, h core.RuntimeHandle) qt.ToolBar {
  1492. if len(b.Items) == 0 {
  1493. return qt.ToolBar {}
  1494. }
  1495. var tool_bar = qt.CreateToolBar(convertToolBarMode(b.Mode))
  1496. for _, item := range b.Items {
  1497. addToolBarItem(item, tool_bar, h)
  1498. }
  1499. return tool_bar
  1500. }
  1501. func convertToolBarMode(m ToolBarMode) qt.ToolButtonStyle {
  1502. switch m {
  1503. case TBM_IconOnly: return qt.ToolButtonIconOnly()
  1504. case TBM_TextOnly: return qt.ToolButtonTextOnly()
  1505. case TBM_TextBesideIcon: return qt.ToolButtonTextBesideIcon()
  1506. case TBM_TextUnderIcon: return qt.ToolButtonTextUnderIcon()
  1507. default:
  1508. panic("impossible branch")
  1509. }
  1510. }
  1511. func addToolBarItem(i ToolBarItem, b qt.ToolBar, h core.RuntimeHandle) {
  1512. switch I := pseudounion.Load(i).(type) {
  1513. case Menu:
  1514. b.AddMenu(convertMenu(I, h))
  1515. case core.Action:
  1516. b.AddAction(I.Deref(h))
  1517. case Separator:
  1518. b.AddSeparator()
  1519. case core.Widget:
  1520. b.AddWidget(I.Deref(h))
  1521. case Spacer:
  1522. b.AddSpacer(I.Width, I.Height, I.Expand)
  1523. default:
  1524. panic("impossible branch")
  1525. }
  1526. }
  1527. func BindContextMenu(w core.Widget, m Menu, h core.RuntimeHandle) core.Observable {
  1528. return core.BindContextMenu(w, convertMenu(m, h), h)
  1529. }
  1530. type Menu struct {
  1531. Icon Icon
  1532. Name string
  1533. Items [] MenuItem
  1534. }
  1535. type MenuItem struct {
  1536. pseudounion.Tag
  1537. Menu; Action(core.Action); Separator
  1538. }
  1539. type Separator struct {}
  1540. func convertMenu(m Menu, h core.RuntimeHandle) qt.Menu {
  1541. var menu = qt.CreateMenu(convertIcon(m.Icon, h), m.Name)
  1542. for _, item := range m.Items {
  1543. addMenuItem(item, menu, h)
  1544. }
  1545. return menu
  1546. }
  1547. func addMenuItem(i MenuItem, m qt.Menu, h core.RuntimeHandle) {
  1548. switch I := pseudounion.Load(i).(type) {
  1549. case Menu:
  1550. m.AddMenu(convertMenu(I, h))
  1551. case core.Action:
  1552. m.AddAction(I.Deref(h))
  1553. case Separator:
  1554. m.AddSeparator()
  1555. default:
  1556. panic("impossible branch")
  1557. }
  1558. }
  1559. func ShowAndActivate(w core.Widget, h core.RuntimeHandle) core.Observable {
  1560. return core.Observable(func(pub core.DataPublisher) {
  1561. pub.SyncReturn(func() (core.Object, error) {
  1562. var W = w.Deref(h)
  1563. W.Show()
  1564. W.MoveToScreenCenter()
  1565. W.ActivateWindow()
  1566. return nil, nil
  1567. })
  1568. })
  1569. }
  1570. func BindInlineStyleSheet(w core.Widget, o core.Observable, h core.RuntimeHandle) core.Observable {
  1571. return core.BindInlineStyleSheet(w, o, h)
  1572. }
  1573. func ComboBoxSelectedItem(w core.Widget, items ([] ComboBoxItem), h core.RuntimeHandle) core.Observable {
  1574. var signal = core.MakeSignalWithValueGetter(qt.ComboBox_CurrentIndexChanged, true, func(W qt.Widget) core.Object {
  1575. return core.ObjInt(int(W.GetPropInt(qt.ComboBox_CurrentIndex)))
  1576. })
  1577. return signal.Connect(w, h).Map(func(obj core.Object) core.Object {
  1578. var index = core.GetInt(obj)
  1579. return items[index].Value
  1580. })
  1581. }
  1582. func CreateWidget(layout Layout, margin_x int, margin_y int, policy_x SizePolicy, policy_y SizePolicy, h core.RuntimeHandle) core.Hook {
  1583. return createWidget(func(ctx qt.Pkg) qt.Widget {
  1584. return qt.CreateWidget(convertLayout(layout, h), margin_x, margin_y, convertSizePolicy(policy_x), convertSizePolicy(policy_y), ctx)
  1585. })
  1586. }
  1587. func CreateScrollArea(scroll Scroll, layout Layout, margin_x int, margin_y int, h core.RuntimeHandle) core.Hook {
  1588. return createWidget(func(ctx qt.Pkg) qt.Widget {
  1589. return qt.CreateScrollArea(convertScroll(scroll), convertLayout(layout, h), margin_x, margin_y, ctx).Widget
  1590. })
  1591. }
  1592. func CreateGroupBox(title string, layout Layout, margin_x int, margin_y int, h core.RuntimeHandle) core.Hook {
  1593. return createWidget(func(ctx qt.Pkg) qt.Widget {
  1594. return qt.CreateGroupBox(title, convertLayout(layout, h), margin_x, margin_y, ctx).Widget
  1595. })
  1596. }
  1597. func CreateSplitter(list ([] core.Widget), h core.RuntimeHandle) core.Hook {
  1598. return createWidget(func(ctx qt.Pkg) qt.Widget {
  1599. var converted = make([] qt.Widget, len(list))
  1600. for i := range list {
  1601. converted[i] = list[i].Deref(h)
  1602. }
  1603. return qt.CreateSplitter(converted, ctx).Widget
  1604. })
  1605. }
  1606. func CreateMainWindow(menu_bar MenuBar, tool_bar ToolBar, layout Layout, margin_x int, margin_y int, width int, height int, icon Icon, h core.RuntimeHandle) core.Hook {
  1607. return createWidget(func(ctx qt.Pkg) qt.Widget {
  1608. return qt.CreateMainWindow(convertMenuBar(menu_bar, h), convertToolBar(tool_bar, h), convertLayout(layout, h), margin_x, margin_y, width, height, convertIcon(icon, h), ctx).Widget
  1609. })
  1610. }
  1611. func CreateDialog(layout Layout, margin_x int, margin_y int, width int, height int, icon Icon, h core.RuntimeHandle) core.Hook {
  1612. return createWidget(func(ctx qt.Pkg) qt.Widget {
  1613. return qt.CreateDialog(convertLayout(layout, h), margin_x, margin_y, width, height, convertIcon(icon, h), ctx).Widget
  1614. })
  1615. }
  1616. func CreateLabel(align Align, selectable bool) core.Hook {
  1617. return createWidget(func(ctx qt.Pkg) qt.Widget {
  1618. return qt.CreateLabel("", convertAlign(align), selectable, ctx).Widget
  1619. })
  1620. }
  1621. func CreateIconLabel(icon Icon, size int, h core.RuntimeHandle) core.Hook {
  1622. return createWidget(func(ctx qt.Pkg) qt.Widget {
  1623. return qt.CreateIconLabel(convertIcon(icon, h), size, ctx).Widget
  1624. })
  1625. }
  1626. func CreateElidedLabel() core.Hook {
  1627. return createWidget(func(ctx qt.Pkg) qt.Widget {
  1628. return qt.CreateElidedLabel("", ctx).Widget
  1629. })
  1630. }
  1631. func CreateTextView(format TextFormat) core.Hook {
  1632. return createWidget(func(ctx qt.Pkg) qt.Widget {
  1633. return qt.CreateTextView("", convertTextFormat(format), ctx).Widget
  1634. })
  1635. }
  1636. func CreateCheckBox(text string, checked bool) core.Hook {
  1637. return createWidget(func(ctx qt.Pkg) qt.Widget {
  1638. return qt.CreateCheckBox(text, checked, ctx).Widget
  1639. })
  1640. }
  1641. func CreateComboBox(items ([] ComboBoxItem), h core.RuntimeHandle) core.Hook {
  1642. if len(items) == 0 {
  1643. core.Crash(h, core.InvalidArgument, "item list cannot be empty")
  1644. }
  1645. return createWidget(func(ctx qt.Pkg) qt.Widget {
  1646. var items = ctn.MapEach(items, func(item ComboBoxItem) qt.ComboBoxItem {
  1647. return convertComboBoxItem(item, h)
  1648. })
  1649. return qt.CreateComboBox(items, ctx).Widget
  1650. })
  1651. }
  1652. func CreatePushButton(icon Icon, text string, tooltip string, h core.RuntimeHandle) core.Hook {
  1653. return createWidget(func(ctx qt.Pkg) qt.Widget {
  1654. return qt.CreatePushButton(convertIcon(icon, h), text, tooltip, ctx).Widget
  1655. })
  1656. }
  1657. func CreateLineEdit(text string) core.Hook {
  1658. return createWidget(func(ctx qt.Pkg) qt.Widget {
  1659. return qt.CreateLineEdit(text, ctx).Widget
  1660. })
  1661. }
  1662. func CreatePlainTextEdit(text string) core.Hook {
  1663. return createWidget(func(ctx qt.Pkg) qt.Widget {
  1664. return qt.CreatePlainTextEdit(text, ctx).Widget
  1665. })
  1666. }
  1667. func CreateSlider(value int, min int, max int) core.Hook {
  1668. return createWidget(func(ctx qt.Pkg) qt.Widget {
  1669. return qt.CreateSlider(min, max, value, ctx).Widget
  1670. })
  1671. }
  1672. func CreateProgressBar(max int, format string) core.Hook {
  1673. return createWidget(func(ctx qt.Pkg) qt.Widget {
  1674. return qt.CreateProgressBar(format, max, ctx).Widget
  1675. })
  1676. }
  1677. func Connect(s core.Signal, w core.Widget, h core.RuntimeHandle) core.Observable {
  1678. return s.Connect(w, h)
  1679. }
  1680. func Listen(s core.Events, w core.Widget, h core.RuntimeHandle) core.Observable {
  1681. return s.Listen(w, h)
  1682. }
  1683. func SignalToggled() core.Signal {
  1684. return core.MakeSignal(qt.S_Toggled)
  1685. }
  1686. func SignalClicked() core.Signal {
  1687. return core.MakeSignal(qt.S_Clicked)
  1688. }
  1689. func SignalTextChanged0() core.Signal {
  1690. return core.MakeSignal(qt.S_TextChanged0)
  1691. }
  1692. func SignalTextChanged1() core.Signal {
  1693. return core.MakeSignal(qt.S_TextChanged1)
  1694. }
  1695. func SignalReturnPressed() core.Signal {
  1696. return core.MakeSignal(qt.S_ReturnPressed)
  1697. }
  1698. func SignalValueChanged() core.Signal {
  1699. return core.MakeSignal(qt.S_ValueChanged)
  1700. }
  1701. func EventsShow() core.Events {
  1702. return core.MakeEvents(qt.EventShow(), false)
  1703. }
  1704. func EventsClose() core.Events {
  1705. return core.MakeEvents(qt.EventClose(), true)
  1706. }
  1707. func Read(p core.Prop, s core.Signal) core.Signal {
  1708. return p.Read(s)
  1709. }
  1710. func Bind(p core.Prop, o core.Observable, w core.Widget, h core.RuntimeHandle) core.Observable {
  1711. return p.Bind(o, w, h)
  1712. }
  1713. func ClearTextLater(w core.Widget, o core.Observable, h core.RuntimeHandle) core.Observable {
  1714. return o.ConcatMap(func(obj core.Object) core.Observable {
  1715. return core.Observable(func(pub core.DataPublisher) {
  1716. pub.SyncReturn(func() (core.Object, error) {
  1717. w.Deref(h).ClearTextLater()
  1718. return obj, nil
  1719. })
  1720. })
  1721. })
  1722. }
  1723. func PropEnabled() core.Prop {
  1724. return core.MakeProp(core.PropBool, qt.P_Enabled)
  1725. }
  1726. func PropWindowTitle() core.Prop {
  1727. return core.MakeProp(core.PropString, qt.P_WindowTitle)
  1728. }
  1729. func PropText() core.Prop {
  1730. return core.MakeProp(core.PropString, qt.P_Text)
  1731. }
  1732. func PropChecked() core.Prop {
  1733. return core.MakeProp(core.PropBool, qt.P_Checked)
  1734. }
  1735. func PropPlainText() core.Prop {
  1736. return core.MakeProp(core.PropString, qt.P_PlainText)
  1737. }
  1738. func PropValue() core.Prop {
  1739. return core.MakeProp(core.PropInt, qt.P_Value)
  1740. }
  1741. type ListView_T struct {
  1742. Widget core.Widget
  1743. Extension core.Observable
  1744. Current core.Observable
  1745. Selection core.Observable
  1746. }
  1747. func ListView(data core.Observable, key func(core.Object)(string), p core.ItemViewProvider, headers ([] HeaderView), stretch int, select_ ItemSelect, h core.RuntimeHandle) core.Hook {
  1748. var config = core.ListViewConfig {
  1749. CreateInterface: func(ctx qt.Pkg) qt.Lwi {
  1750. return qt.LwiCreateFromDefaultListWidget (
  1751. len(headers),
  1752. convertItemSelect(select_),
  1753. getHeaderWidgets(headers, h, ctx),
  1754. stretch,
  1755. ctx,
  1756. )
  1757. },
  1758. ReturnObject: func(w core.Widget, e core.Observable, c core.Observable, s core.Observable) core.Object {
  1759. return core.ToObject(ListView_T {
  1760. Widget: w,
  1761. Extension: e,
  1762. Current: c,
  1763. Selection: s,
  1764. })
  1765. },
  1766. }
  1767. return core.ListView(config, data, key, p, h)
  1768. }
  1769. type ListEditView_T struct {
  1770. Widget core.Widget
  1771. Output core.Observable
  1772. Extension core.Observable
  1773. EditOps core.Subject
  1774. }
  1775. func ListEditView(initial core.List, p core.ItemEditViewProvider, headers ([] HeaderView), stretch int, select_ ItemSelect, h core.RuntimeHandle) core.Hook {
  1776. var config = core.ListEditViewConfig {
  1777. CreateInterface: func(ctx qt.Pkg) qt.Lwi {
  1778. return qt.LwiCreateFromDefaultListWidget (
  1779. len(headers),
  1780. convertItemSelect(select_),
  1781. getHeaderWidgets(headers, h, ctx),
  1782. stretch,
  1783. ctx,
  1784. )
  1785. },
  1786. ReturnObject: func(w core.Widget, o core.Observable, e core.Observable, O core.Subject) core.Object {
  1787. return core.ToObject(ListEditView_T {
  1788. Widget: w,
  1789. Output: o,
  1790. Extension: e,
  1791. EditOps: O,
  1792. })
  1793. },
  1794. }
  1795. return core.ListEditView(config, initial, p, h)
  1796. }
  1797. type Icon struct {
  1798. Name string
  1799. }
  1800. func convertIcon(icon Icon, h core.RuntimeHandle) string {
  1801. var name = icon.Name
  1802. if strings.HasPrefix(name, qt.FileIconNamePrefix) {
  1803. var rel_path = strings.TrimPrefix(name, qt.FileIconNamePrefix)
  1804. var abs_path = filepath.Join(filepath.Dir(h.ProgramPath()), rel_path)
  1805. return (qt.FileIconNamePrefix + abs_path)
  1806. } else {
  1807. return name
  1808. }
  1809. }
  1810. type SizePolicy int
  1811. const (
  1812. SP_Rigid SizePolicy = iota
  1813. SP_Controlled
  1814. SP_Incompressible; SP_IncompressibleExpanding
  1815. SP_Free; SP_FreeExpanding
  1816. SP_Bounded
  1817. )
  1818. func convertSizePolicy(p SizePolicy) qt.SizePolicy {
  1819. switch p {
  1820. case SP_Rigid: return qt.SizePolicyRigid()
  1821. case SP_Controlled: return qt.SizePolicyControlled()
  1822. case SP_Incompressible: return qt.SizePolicyIncompressible()
  1823. case SP_IncompressibleExpanding: return qt.SizePolicyIncompressibleExpanding()
  1824. case SP_Free: return qt.SizePolicyFree()
  1825. case SP_FreeExpanding: return qt.SizePolicyFreeExpanding()
  1826. case SP_Bounded: return qt.SizePolicyBounded()
  1827. default:
  1828. panic("impossible branch")
  1829. }
  1830. }
  1831. type Align int
  1832. const (
  1833. A_Default Align = iota
  1834. A_Center
  1835. A_Left; A_Right; A_Top; A_Bottom
  1836. A_LeftTop; A_LeftBottom; A_RightTop; A_RightBottom
  1837. )
  1838. func convertAlign(a Align) qt.Alignment {
  1839. switch a {
  1840. case A_Default: return qt.AlignDefault()
  1841. case A_Center: return qt.AlignHCenter().And(qt.AlignVCenter())
  1842. case A_Left: return qt.AlignLeft().And(qt.AlignVCenter())
  1843. case A_Right: return qt.AlignRight().And(qt.AlignVCenter())
  1844. case A_Top: return qt.AlignTop().And(qt.AlignHCenter())
  1845. case A_Bottom: return qt.AlignBottom().And(qt.AlignHCenter())
  1846. case A_LeftTop: return qt.AlignLeft().And(qt.AlignTop())
  1847. case A_LeftBottom: return qt.AlignLeft().And(qt.AlignBottom())
  1848. case A_RightTop: return qt.AlignRight().And(qt.AlignTop())
  1849. case A_RightBottom: return qt.AlignRight().And(qt.AlignBottom())
  1850. default:
  1851. panic("impossible branch")
  1852. }
  1853. }
  1854. type Scroll int
  1855. const (
  1856. S_BothDirection Scroll = iota
  1857. S_VerticalOnly
  1858. S_HorizontalOnly
  1859. )
  1860. func convertScroll(s Scroll) qt.ScrollDirection {
  1861. switch s {
  1862. case S_BothDirection: return qt.ScrollBothDirection()
  1863. case S_VerticalOnly: return qt.ScrollVerticalOnly()
  1864. case S_HorizontalOnly: return qt.ScrollHorizontalOnly()
  1865. default:
  1866. panic("impossible branch")
  1867. }
  1868. }
  1869. type TextFormat int
  1870. const (
  1871. TF_Plain TextFormat = iota
  1872. TF_Html
  1873. TF_Markdown
  1874. )
  1875. func convertTextFormat(f TextFormat) qt.TextFormat {
  1876. switch f {
  1877. case TF_Plain: return qt.TextFormatPlain()
  1878. case TF_Html: return qt.TextFormatHtml()
  1879. case TF_Markdown: return qt.TextFormatMarkdown()
  1880. default:
  1881. panic("impossible branch")
  1882. }
  1883. }
  1884. type Layout struct {
  1885. pseudounion.Tag
  1886. Row; Column; Grid
  1887. }
  1888. type Row struct { Items ([] LayoutItem); Spacing int }
  1889. type Column struct { Items ([] LayoutItem); Spacing int }
  1890. type Grid struct { Spans ([] Span); RowSpacing int; ColumnSpacing int }
  1891. type Span struct {
  1892. Item LayoutItem
  1893. Row int; Column int; RowSpan int; ColumnSpan int; Align Align
  1894. }
  1895. type LayoutItem struct {
  1896. pseudounion.Tag
  1897. Layout; Widget(core.Widget); Spacer; String(string)
  1898. }
  1899. type Spacer struct { Width int; Height int; Expand bool }
  1900. type Wrapper struct { Widget core.Widget }
  1901. func convertLayout(l Layout, h core.RuntimeHandle) qt.Layout {
  1902. var q_span qt.GridSpan
  1903. var q_align = qt.AlignDefault()
  1904. switch L := pseudounion.Load(l).(type) {
  1905. case Row:
  1906. var layout = qt.CreateLayoutRow(L.Spacing)
  1907. for _, item := range L.Items {
  1908. addLayoutItem(item, layout, q_span, q_align, h)
  1909. }
  1910. return layout
  1911. case Column:
  1912. var layout = qt.CreateLayoutColumn(L.Spacing)
  1913. for _, item := range L.Items {
  1914. addLayoutItem(item, layout, q_span, q_align, h)
  1915. }
  1916. return layout
  1917. case Grid:
  1918. var layout = qt.CreateLayoutGrid(L.RowSpacing, L.ColumnSpacing)
  1919. for _, span := range L.Spans {
  1920. var item = span.Item
  1921. q_span.Row = span.Row
  1922. q_span.Column = span.Column
  1923. q_span.RowSpan = span.RowSpan
  1924. q_span.ColumnSpan = span.ColumnSpan
  1925. q_align = convertAlign(span.Align)
  1926. addLayoutItem(item, layout, q_span, q_align, h)
  1927. }
  1928. return layout
  1929. default:
  1930. panic("impossible branch")
  1931. }
  1932. }
  1933. func addLayoutItem(i LayoutItem, l qt.Layout, span qt.GridSpan, align qt.Alignment, h core.RuntimeHandle) {
  1934. switch I := pseudounion.Load(i).(type) {
  1935. case Layout:
  1936. l.AddLayout(convertLayout(I, h), span, align)
  1937. case Spacer:
  1938. l.AddSpacer(I.Width, I.Height, I.Expand, span, align)
  1939. case string:
  1940. l.AddLabel(I, span, align)
  1941. case core.Widget:
  1942. l.AddWidget(I.Deref(h), span, align)
  1943. default:
  1944. panic("impossible branch")
  1945. }
  1946. }
  1947. type ComboBoxItem struct {
  1948. Icon Icon; Name string; Value core.Object; Selected bool
  1949. }
  1950. func convertComboBoxItem(item ComboBoxItem, h core.RuntimeHandle) qt.ComboBoxItem {
  1951. return qt.ComboBoxItem {
  1952. Icon: convertIcon(item.Icon, h),
  1953. Name: item.Name,
  1954. Selected: item.Selected,
  1955. }
  1956. }
  1957. type ActionComboBoxItem struct {
  1958. Action core.Action; Value core.Object; Selected bool
  1959. }
  1960. func adaptActionComboBoxItem(item ActionComboBoxItem) core.ActionComboBoxItem {
  1961. return core.ActionComboBoxItem {
  1962. Action: item.Action,
  1963. Selected: item.Selected,
  1964. }
  1965. }
  1966. type HeaderView struct {
  1967. pseudounion.Tag
  1968. String string; Widget core.Widget
  1969. }
  1970. func getHeaderWidgets(headers ([] HeaderView), h core.RuntimeHandle, ctx qt.Pkg) ([] qt.Widget) {
  1971. return ctn.MapEach(headers, func(v HeaderView) qt.Widget {
  1972. switch V := pseudounion.Load(v).(type) {
  1973. case string:
  1974. var label = qt.CreateLabelLite(V, ctx)
  1975. var spacing = 0
  1976. var margin_x, margin_y = 6, 4
  1977. var policy_x, policy_y = qt.SizePolicyFree(), qt.SizePolicyFree()
  1978. var row = qt.CreateLayoutRow(spacing)
  1979. row.AddWidget(label.Widget, qt.GridSpan{}, qt.AlignDefault())
  1980. return qt.CreateWidget(row, margin_x, margin_y, policy_x, policy_y, ctx)
  1981. case core.Widget:
  1982. return V.Deref(h)
  1983. default:
  1984. panic("impossible branch")
  1985. }
  1986. })
  1987. }
  1988. type ItemSelect int
  1989. const (
  1990. IS_NA ItemSelect = iota
  1991. IS_Single
  1992. IS_Multiple
  1993. IS_MaybeMultiple
  1994. )
  1995. func convertItemSelect(m ItemSelect) qt.ItemSelectionMode {
  1996. switch m {
  1997. case IS_NA: return qt.ItemNoSelection()
  1998. case IS_Single: return qt.ItemSingleSelection()
  1999. case IS_Multiple: return qt.ItemMultiSelection()
  2000. case IS_MaybeMultiple: return qt.ItemExtendedSelection()
  2001. default:
  2002. panic("impossible branch")
  2003. }
  2004. }
  2005. func assumeValidRegexp(pattern string) *regexp.Regexp {
  2006. var value, err = regexp.Compile(pattern)
  2007. if err != nil { panic("something went wrong") }
  2008. return value
  2009. }
  2010. func forEachObservable(l core.List) func(func(core.Observable)) {
  2011. return func(yield func(core.Observable)) {
  2012. l.ForEach(func(item core.Object) {
  2013. yield(core.GetObservable(item))
  2014. })
  2015. }
  2016. }
  2017. func createWidget(k func(qt.Pkg)(qt.Widget)) core.Hook {
  2018. return core.MakeHook(func() (core.Widget, func()) {
  2019. return core.WrapWidget(k)
  2020. })
  2021. }
  2022. func showComboBoxInputBox(items ([] ComboBoxItem), title string, prompt string, h core.RuntimeHandle) core.Observable {
  2023. if len(items) == 0 {
  2024. panic("invalid argument")
  2025. }
  2026. return core.Observable(func(pub core.DataPublisher) {
  2027. var items_ = ctn.MapEach(items, func(item ComboBoxItem) qt.ComboBoxItem {
  2028. return convertComboBoxItem(item, h)
  2029. })
  2030. var dialog = qt.CreateComboBoxDialog(items_, title, prompt)
  2031. dialog.Consume(func(index int, ok bool) {
  2032. var yield, complete = core.DialogGenerate(pub); defer complete()
  2033. if ok {
  2034. yield(items[index].Value)
  2035. }
  2036. })
  2037. })
  2038. }
  2039. func showInputBox(mode qt.InputDialogMode, multilineText bool, choiceItems ([] string), value interface{}, title string, prompt string, f func(string,int,float64)(core.Object)) core.Observable {
  2040. return core.Observable(func(pub core.DataPublisher) {
  2041. var dialog = qt.CreateInputDialog(mode, value, title, prompt)
  2042. if multilineText {
  2043. dialog.UseMultilineText()
  2044. }
  2045. if len(choiceItems) > 0 {
  2046. dialog.UseChoiceItems(choiceItems)
  2047. }
  2048. dialog.Consume(func(s string, i int, x float64, ok bool) {
  2049. var yield, complete = core.DialogGenerate(pub); defer complete()
  2050. if ok {
  2051. yield(f(s,i,x))
  2052. }
  2053. })
  2054. })
  2055. }
  2056. func showMessageBox(icon qt.MsgBoxIcon, buttons qt.MsgBoxBtn, default_ qt.MsgBoxBtn, title string, content string, f func(qt.MsgBoxBtn)(core.Object,bool)) core.Observable {
  2057. return core.Observable(func(pub core.DataPublisher) {
  2058. var msgbox = qt.CreateMessageBox(icon, buttons, title, content)
  2059. msgbox.SetDefaultButton(default_)
  2060. msgbox.Consume(func(btn qt.MsgBoxBtn) {
  2061. var yield, complete = core.DialogGenerate(pub); defer complete()
  2062. if obj, ok := f(btn); ok {
  2063. yield(obj)
  2064. }
  2065. })
  2066. })
  2067. }