All BASIC

Message Boards => Compilers => Topic started by: John on December 03, 2015, 08:11:04 PM

Title: Apple Swift on Ubuntu
Post by: John on December 03, 2015, 08:11:04 PM
(http://www.itrunsonlinux.com/wp-content/uploads/2015/06/Apple_supports_Linux_with_Swift.png)

Introduction to Open Source Swift on Linux (http://www.raywenderlich.com/122189/introduction-to-open-source-swift-on-linux)

Swift Project Site (https://swift.org/) (pre-built binaries for Apple Xcode, Ubuntu 64 bit 14.04 & 15.10)

The Swift Programming Language (Swift 2.1) (https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID309) 

swift-corelibs-foundation (https://github.com/apple/swift-corelibs-foundation/search?p=1&q=NSUnimplemented&utf8=%E2%9C%93) Linux version of the foundation import functions created to date on Github

Implementation Status (https://github.com/apple/swift-corelibs-foundation/blob/master/Docs/Status.md) - What works and what doesn't.

Swift Github Repository (https://github.com/apple/swift)

Code: [Select]
Welcome to Swift version 2.2-dev (LLVM 46be9ff861, Clang 4deb154edc, Swift 778f82939c). Type :help for assistance.
  1> :help

The REPL (Read-Eval-Print-Loop) acts like an interpreter.  Valid statements, expressions, and declarations are immediately compiled
and executed.

The complete set of LLDB debugging commands are also available as described below.  Commands must be prefixed with a colon at the
REPL prompt (:quit for example.)  Typing just a colon followed by return will switch to the LLDB prompt.

Debugger commands:

  apropos           -- Find a list of debugger commands related to a particular word/subject.
  breakpoint        -- A set of commands for operating on breakpoints. Also see _regexp-break.
  bugreport         -- Set of commands for creating domain specific bugreports.
  command           -- A set of commands for managing or customizing the debugger commands.
  disassemble       -- Disassemble bytes in the current function, or elsewhere in the executable program as specified by the user.
  expression        -- Evaluate an expression (ObjC++ or Swift) in the current program context, using user defined variables and
                       variables currently in scope.
  frame             -- A set of commands for operating on the current thread's frames.
  gdb-remote        -- Connect to a remote GDB server.  If no hostname is provided, localhost is assumed.
  gui               -- Switch into the curses based GUI mode.
  help              -- Show a list of all debugger commands, or give details about specific commands.
  kdp-remote        -- Connect to a remote KDP server.  udp port 41139 is the default port number.
  language          -- A set of commands for managing language-specific functionality.'.
  log               -- A set of commands for operating on logs.
  memory            -- A set of commands for operating on memory.
  platform          -- A set of commands to manage and create platforms.
  plugin            -- A set of commands for managing or customizing plugin commands.
  process           -- A set of commands for operating on a process.
  quit              -- Quit out of the LLDB debugger.
  register          -- A set of commands to access thread registers.
  script            -- Pass an expression to the script interpreter for evaluation and return the results. Drop into the
                       interactive interpreter if no expression is given.
  settings          -- A set of commands for manipulating internal settable debugger variables.
  source            -- A set of commands for accessing source file information
  target            -- A set of commands for operating on debugger targets.
  thread            -- A set of commands for operating on one or more threads within a running process.
  type              -- A set of commands for operating on the type system
  version           -- Show version of LLDB debugger.
  watchpoint        -- A set of commands for operating on watchpoints.

Current command abbreviations (type ':help command alias' for more info):

  add-dsym  -- ('target symbols add')  Add a debug symbol file to one of the target's current modules by specifying a path to a
               debug symbols file, or using the options to specify a module to download symbols for.
  attach    -- ('_regexp-attach')  Attach to a process id if in decimal, otherwise treat the argument as a process name to attach
               to.
  b         -- ('_regexp-break')  Set a breakpoint using a regular expression to specify the location, where <linenum> is in
               decimal and <address> is in hex.
  bt        -- ('_regexp-bt')  Show a backtrace.  An optional argument is accepted; if that argument is a number, it specifies the
               number of frames to display.  If that argument is 'all', full backtraces of all threads are displayed.
  c         -- ('process continue')  Continue execution of all threads in the current process.
  call      -- ('expression --')  Evaluate an expression (ObjC++ or Swift) in the current program context, using user defined
               variables and variables currently in scope.
  continue  -- ('process continue')  Continue execution of all threads in the current process.
  detach    -- ('process detach')  Detach from the current process being debugged.
  di        -- ('disassemble')  Disassemble bytes in the current function, or elsewhere in the executable program as specified by
               the user.
  dis       -- ('disassemble')  Disassemble bytes in the current function, or elsewhere in the executable program as specified by
               the user.
  display   -- ('_regexp-display')  Add an expression evaluation stop-hook.
  down      -- ('_regexp-down')  Go down "n" frames in the stack (1 frame by default).
  env       -- ('_regexp-env')  Implements a shortcut to viewing and setting environment variables.
  exit      -- ('quit')  Quit out of the LLDB debugger.
  f         -- ('frame select')  Select a frame by index from within the current thread and make it the current frame.
  file      -- ('target create')  Create a target using the argument as the main executable.
  finish    -- ('thread step-out')  Finish executing the function of the currently selected frame and return to its call site in
               specified thread (current thread, if none specified).
  image     -- ('target modules')  A set of commands for accessing information for one or more target modules.
  j         -- ('_regexp-jump')  Sets the program counter to a new address.
  jump      -- ('_regexp-jump')  Sets the program counter to a new address.
  kill      -- ('process kill')  Terminate the current process being debugged.
  l         -- ('_regexp-list')  Implements the GDB 'list' command in all of its forms except FILE:FUNCTION and maps them to the
               appropriate 'source list' commands.
  list      -- ('_regexp-list')  Implements the GDB 'list' command in all of its forms except FILE:FUNCTION and maps them to the
               appropriate 'source list' commands.
  n         -- ('thread step-over')  Source level single step in specified thread (current thread, if none specified), stepping
               over calls.
  next      -- ('thread step-over')  Source level single step in specified thread (current thread, if none specified), stepping
               over calls.
  nexti     -- ('thread step-inst-over')  Single step one instruction in specified thread (current thread, if none specified),
               stepping over calls.
  ni        -- ('thread step-inst-over')  Single step one instruction in specified thread (current thread, if none specified),
               stepping over calls.
  p         -- ('expression --')  Evaluate an expression (ObjC++ or Swift) in the current program context, using user defined
               variables and variables currently in scope.
  po        -- ('expression -O  -- ')  Evaluate an expression (ObjC++ or Swift) in the current program context, using user defined
               variables and variables currently in scope.
  print     -- ('expression --')  Evaluate an expression (ObjC++ or Swift) in the current program context, using user defined
               variables and variables currently in scope.
  q         -- ('quit')  Quit out of the LLDB debugger.
  r         -- ('process launch -X true --')  Launch the executable in the debugger.
  rbreak    -- ('breakpoint set -r %1')  Sets a breakpoint or set of breakpoints in the executable.
  repl      -- ('expression -r  -- ')  Evaluate an expression (ObjC++ or Swift) in the current program context, using user defined
               variables and variables currently in scope.
  run       -- ('process launch -X true --')  Launch the executable in the debugger.
  s         -- ('thread step-in')  Source level single step in specified thread (current thread, if none specified).
  si        -- ('thread step-inst')  Single step one instruction in specified thread (current thread, if none specified).
  step      -- ('thread step-in')  Source level single step in specified thread (current thread, if none specified).
  stepi     -- ('thread step-inst')  Single step one instruction in specified thread (current thread, if none specified).
  t         -- ('thread select')  Select a thread as the currently active thread.
  tbreak    -- ('_regexp-tbreak')  Set a one shot breakpoint using a regular expression to specify the location, where <linenum> is
               in decimal and <address> is in hex.
  undisplay -- ('_regexp-undisplay')  Remove an expression evaluation stop-hook.
  up        -- ('_regexp-up')  Go up "n" frames in the stack (1 frame by default).
  x         -- ('memory read')  Read from the memory of the process being debugged.

For more information on any command, type ':help <command-name>'.
  1> let sb="Script BASIC"
sb: String = "Script BASIC"
  2> print(sb)
Script BASIC
  3> import Glibc
  4> random() % 10
$R0: Int = 3
  5> 
 


jrs@laptop:~/Swift/swift-2.2-SNAPSHOT-2015-12-01-b-ubuntu14.04/usr/bin$ ls -l
total 144920
lrwxrwxrwx 1 jrs jrs       10 Dec  2 12:14 lldb -> lldb-3.8.0
-rwxr-xr-x 1 jrs jrs    56975 Dec  2 12:10 lldb-3.8.0
-rwxr-xr-x 1 jrs jrs    86550 Dec  2 12:10 lldb-argdumper
lrwxrwxrwx 1 jrs jrs       13 Dec  2 12:14 lldb-mi -> lldb-mi-3.8.0
-rwxr-xr-x 1 jrs jrs   929212 Dec  2 12:10 lldb-mi-3.8.0
lrwxrwxrwx 1 jrs jrs       17 Dec  2 12:14 lldb-server -> lldb-server-3.8.0
-rwxr-xr-x 1 jrs jrs 63360159 Dec  2 12:10 lldb-server-3.8.0
-rwxr-xr-x 1 jrs jrs     9177 Dec  2 12:09 repl_swift
-rwxr-xr-x 1 jrs jrs 73628082 Dec  2 12:01 swift
lrwxrwxrwx 1 jrs jrs        5 Dec  2 12:14 swift-autolink-extract -> swift
-rwxr-xr-x 1 jrs jrs  1742176 Dec  2 12:14 swift-build
-rwxr-xr-x 1 jrs jrs  7702803 Dec  2 12:10 swift-build-tool
lrwxrwxrwx 1 jrs jrs        5 Dec  2 12:14 swiftc -> swift
-rwxr-xr-x 1 jrs jrs   857140 Dec  2 12:00 swift-demangle
jrs@laptop:~/Swift/swift-2.2-SNAPSHOT-2015-12-01-b-ubuntu14.04/usr/bin$


Code: Text
  1. jrs@laptop:~/Swift$ swift
  2. Welcome to Swift version 2.2-dev (LLVM 46be9ff861, Clang 4deb154edc, Swift 778f82939c). Type :help for assistance.
  3.   1>  
  4.   2.  
  5.   3.     extension Double {
  6.   4.         var km: Double { return self * 1_000.0 }
  7.   5.         var m: Double { return self }
  8.   6.         var cm: Double { return self / 100.0 }
  9.   7.         var mm: Double { return self / 1_000.0 }
  10.   8.         var ft: Double { return self / 3.28084 }
  11.   9.     }
  12.  10.     let oneInch = 25.4.mm
  13.  11.     print("One inch is \(oneInch) meters")
  14.  12.     // prints "One inch is 0.0254 meters"
  15.  13.     let threeFeet = 3.ft
  16.  14.     print("Three feet is \(threeFeet) meters")
  17.  15.     // prints "Three feet is 0.914399970739201 meters"
  18.  16.  
  19. One inch is 0.0254 meters
  20. Three feet is 0.914399970739201 meters
  21. oneInch: Double = 0.025399999999999999
  22. threeFeet: Double = 0.91439997073920098
  23.  16>
  24.  17> :platform list
  25. Available platforms:
  26. host: Local Linux user platform plug-in.
  27. remote-freebsd: Remote FreeBSD user platform plug-in.
  28. remote-linux: Remote Linux user platform plug-in.
  29. remote-windows: Remote Windows user platform plug-in.
  30. kalimba: Kalimba user platform plug-in.
  31. remote-android: Remote Android user platform plug-in.
  32. remote-ios: Remote iOS platform plug-in.
  33. remote-macosx: Remote Mac OS X user platform plug-in.
  34. remote-gdb-server: A platform that uses the GDB remote protocol as the communication transport.
  35.  17>  
  36.  
  37.  

A compiled Hello World is 14,457 bytes in size. (release mode)
Title: Re: Apple Swift on Ubuntu
Post by: wangrenxin on December 03, 2015, 10:34:50 PM
Nice! I like the programming paradigm in Swift as a video game developer. It would be attractive if someone would port it to Windows too; or re-create a clone as IronPython, IronRuby do.
Title: Re: Apple Swift on Ubuntu
Post by: John on December 03, 2015, 10:51:46 PM
I'm happy. Swift goals sound like it's talking about Script BASIC.  :)

Swift reminds me of CERN ROOT in BASIC scripting clothing.

It seems most of the code examples from the Apple iOS Swift docs seem to work in the Linux version.
Title: Re: Apple Swift on Ubuntu
Post by: John on December 04, 2015, 10:05:35 PM
I have been digging around for info on a GUI IDE like Xcode but nothing exists that I can find. Here (https://precompile.com/2015/07/09/swift-platform.html) is some info on the topic.

The curses GUI debugger is a start.
Title: Re: Apple Swift on Ubuntu
Post by: John on December 05, 2015, 12:34:05 PM
Introducing the IBM Swift Sandbox (https://developer.ibm.com/swift/2015/12/03/introducing-the-ibm-swift-sandbox/)

(http://developer.ibm.com/swift/wp-content/uploads/sites/69/2015/12/Screen-Shot-2015-12-04-at-7.26.25-AM-1024x391.png)


Quote
The IBM Swift Sandbox is an interactive website that lets you write Swift code and execute it in a server environment – on top of Linux! Each sandbox runs on IBM Cloud in a Docker container. In addition, both the latest versions of Swift and its standard library are available for you to use.
Title: Re: Apple Swift on Ubuntu - Fibonacci Benchmark
Post by: John on December 05, 2015, 03:05:21 PM
Here is a comparison between Swift, Script BASIC and C BASIC.

Code: Text
  1. /* Basic fibonacci function in swift.
  2.    Demostrates func calls and recursion.
  3. */
  4.  
  5. func fibonacci(i: Int) -> Int {
  6.     if i <= 2 {
  7.         return 1
  8.     } else {
  9.         return fibonacci(i - 1) + fibonacci(i - 2)
  10.     }
  11. }
  12.  
  13. print(fibonacci(32))
  14.  

Swift JIT

jrs@laptop:~/Swift/usr/share/examples$ time swift fibonacci.swift
2178309

real   0m0.121s
user   0m0.077s
sys   0m0.040s
jrs@laptop:~/Swift/usr/share/examples$


Swift compiled (13,644 bytes)

jrs@laptop:~/Swift/usr/share/examples$ swiftc fibonacci.swift -o fibonacci
jrs@laptop:~/Swift/usr/share/examples$ time ./fibonacci
2178309

real   0m0.039s
user   0m0.038s
sys   0m0.000s
jrs@laptop:~/Swift/usr/share/examples$


Code: Script BASIC
  1. FUNCTION Fibonacci(n)
  2.   IF n <= 2 THEN
  3.     Fibonacci = 1
  4.   ELSE
  5.     Fibonacci = Fibonacci(n - 1) + Fibonacci(n - 2)
  6.   END IF
  7. END FUNCTION
  8.  
  9. PRINT Fibonacci(32),"\n"
  10.  


jrs@laptop:~/sb/sb22/test$ time scriba fibonacci.sb
2178309

real   0m3.662s
user   0m3.656s
sys   0m0.004s
jrs@laptop:~/sb/sb22/test$


C BASIC (8,597 bytes)
Code: C
  1. #include <stdio.h>
  2. #include "cbasic.h"
  3.  
  4. FUNCTION int Fibonacci(int i)
  5. BEGIN_FUNCTION
  6.   IF (i <= 2) THEN
  7.     RETURN_FUNCTION(1);
  8.   ELSE
  9.     RETURN_FUNCTION(Fibonacci(i - 1) + Fibonacci(i - 2));
  10.   END_IF
  11. END_FUNCTION
  12.  
  13. MAIN
  14. BEGIN_FUNCTION
  15.   PRINT ("%i\n",Fibonacci(32));
  16. END_FUNCTION
  17.  


jrs@laptop:~/c_code$ gcc -O2 fibonacci.c -o fibonacci
jrs@laptop:~/c_code$ time ./fibonacci
2178309

real   0m0.018s
user   0m0.018s
sys   0m0.000s
jrs@laptop:~/c_code$


Title: Re: Apple Swift on Ubuntu - Client / Server
Post by: John on December 05, 2015, 10:13:48 PM
Code: Text
  1. /* Creates a server that is bound to a socket to listen for incoming
  2.    connections. Also creates a client which sends a "Hello world"
  3.    message to server. Shows how servers can be made in Swift.
  4. */
  5.  
  6. #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
  7.     import Darwin
  8. #else
  9.     import Glibc
  10. #endif
  11.  
  12. func make_socket (port:UInt16) -> Int32
  13. {
  14.     var name = sockaddr_in()
  15.    
  16.     // Create the socket
  17.     let sock = socket (PF_INET, 1, 0)
  18.     if sock < 0 {
  19.         perror ("socket")
  20.         exit (EXIT_FAILURE)
  21.     }
  22.        
  23.         // Make the address reusable for multiple runs
  24.         var on: Int32 = 1
  25.         setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on, socklen_t(sizeof(Int32)))
  26.        
  27.     // Give the socket a name
  28.     name.sin_family = sa_family_t(AF_INET)
  29.     name.sin_port = UInt16(port).bigEndian
  30.        
  31.         // INADDR_ANY which equals 0
  32.     name.sin_addr.s_addr = in_addr_t(0)
  33.  
  34.         var bindAddr = sockaddr()
  35.         memcpy(&bindAddr, &name, Int(sizeof(sockaddr_in)))
  36.         let addrSize: socklen_t = socklen_t(sizeof(sockaddr_in))
  37.        
  38.         // Bind name to socket
  39.         if bind(sock, &bindAddr, addrSize) < 0 {
  40.                 perror("bind")
  41.                 exit(EXIT_FAILURE)
  42.         }
  43.        
  44.     return sock
  45. }
  46.  
  47. func read_from_client (filedes: Int32) -> Int
  48. {
  49.     let buffer = UnsafeMutablePointer<UInt8>.alloc(255)
  50.    
  51.     let nbytes = read (filedes, buffer, 255)
  52.     if nbytes < 0 {
  53.         // Read error
  54.         perror ("read")
  55.         exit (EXIT_FAILURE)
  56.     }
  57.     else if (nbytes == 0) {
  58.         // End-of-file
  59.         buffer.dealloc(255)
  60.         return -1;
  61.     }
  62.     else {
  63.         // Data read
  64.         var message = ""
  65.         for i in 0..<nbytes {
  66.             message += String(UnicodeScalar((buffer+i).memory))
  67.         }
  68.         print ( "Server: got message: " + message)
  69.         buffer.dealloc(255)
  70.         return 0
  71.     }
  72. }
  73.  
  74. #if os(Linux)
  75.        
  76.         /// Replacement for FD_ZERO macro
  77.        
  78.         func fdZero(inout set: fd_set) {
  79.                 set.__fds_bits = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
  80.         }
  81.        
  82.        
  83.         /// Replacement for FD_SET macro
  84.        
  85.         func fdSet(fd: Int32, inout set: fd_set) {
  86.                 let intOffset = Int(fd / 16)
  87.                 let bitOffset: Int = Int(fd % 16)
  88.                 let mask: Int = 1 << bitOffset
  89.                 switch intOffset {
  90.                 case 0: set.__fds_bits.0 = set.__fds_bits.0 | mask
  91.                 case 1: set.__fds_bits.1 = set.__fds_bits.1 | mask
  92.                 case 2: set.__fds_bits.2 = set.__fds_bits.2 | mask
  93.                 case 3: set.__fds_bits.3 = set.__fds_bits.3 | mask
  94.                 case 4: set.__fds_bits.4 = set.__fds_bits.4 | mask
  95.                 case 5: set.__fds_bits.5 = set.__fds_bits.5 | mask
  96.                 case 6: set.__fds_bits.6 = set.__fds_bits.6 | mask
  97.                 case 7: set.__fds_bits.7 = set.__fds_bits.7 | mask
  98.                 case 8: set.__fds_bits.8 = set.__fds_bits.8 | mask
  99.                 case 9: set.__fds_bits.9 = set.__fds_bits.9 | mask
  100.                 case 10: set.__fds_bits.10 = set.__fds_bits.10 | mask
  101.                 case 11: set.__fds_bits.11 = set.__fds_bits.11 | mask
  102.                 case 12: set.__fds_bits.12 = set.__fds_bits.12 | mask
  103.                 case 13: set.__fds_bits.13 = set.__fds_bits.13 | mask
  104.                 case 14: set.__fds_bits.14 = set.__fds_bits.14 | mask
  105.                 case 15: set.__fds_bits.15 = set.__fds_bits.15 | mask
  106.                 default: break
  107.                 }
  108.         }
  109.        
  110.        
  111.         /// Replacement for FD_CLR macro
  112.        
  113.         func fdClr(fd: Int32, inout set: fd_set) {
  114.                 let intOffset = Int(fd / 16)
  115.                 let bitOffset: Int = Int(fd % 16)
  116.                 let mask: Int = ~(1 << bitOffset)
  117.                 switch intOffset {
  118.                 case 0: set.__fds_bits.0 = set.__fds_bits.0 & mask
  119.                 case 1: set.__fds_bits.1 = set.__fds_bits.1 & mask
  120.                 case 2: set.__fds_bits.2 = set.__fds_bits.2 & mask
  121.                 case 3: set.__fds_bits.3 = set.__fds_bits.3 & mask
  122.                 case 4: set.__fds_bits.4 = set.__fds_bits.4 & mask
  123.                 case 5: set.__fds_bits.5 = set.__fds_bits.5 & mask
  124.                 case 6: set.__fds_bits.6 = set.__fds_bits.6 & mask
  125.                 case 7: set.__fds_bits.7 = set.__fds_bits.7 & mask
  126.                 case 8: set.__fds_bits.8 = set.__fds_bits.8 & mask
  127.                 case 9: set.__fds_bits.9 = set.__fds_bits.9 & mask
  128.                 case 10: set.__fds_bits.10 = set.__fds_bits.10 & mask
  129.                 case 11: set.__fds_bits.11 = set.__fds_bits.11 & mask
  130.                 case 12: set.__fds_bits.12 = set.__fds_bits.12 & mask
  131.                 case 13: set.__fds_bits.13 = set.__fds_bits.13 & mask
  132.                 case 14: set.__fds_bits.14 = set.__fds_bits.14 & mask
  133.                 case 15: set.__fds_bits.15 = set.__fds_bits.15 & mask
  134.                 default: break
  135.                 }
  136.         }
  137.        
  138.        
  139.         /// Replacement for FD_ISSET macro
  140.        
  141.         func fdIsSet(fd: Int32, inout set: fd_set) -> Bool {
  142.                 let intOffset = Int(fd / 16)
  143.                 let bitOffset = Int(fd % 16)
  144.                 let mask: Int = 1 << bitOffset
  145.                 switch intOffset {
  146.                 case 0: return set.__fds_bits.0 & mask != 0
  147.                 case 1: return set.__fds_bits.1 & mask != 0
  148.                 case 2: return set.__fds_bits.2 & mask != 0
  149.                 case 3: return set.__fds_bits.3 & mask != 0
  150.                 case 4: return set.__fds_bits.4 & mask != 0
  151.                 case 5: return set.__fds_bits.5 & mask != 0
  152.                 case 6: return set.__fds_bits.6 & mask != 0
  153.                 case 7: return set.__fds_bits.7 & mask != 0
  154.                 case 8: return set.__fds_bits.8 & mask != 0
  155.                 case 9: return set.__fds_bits.9 & mask != 0
  156.                 case 10: return set.__fds_bits.10 & mask != 0
  157.                 case 11: return set.__fds_bits.11 & mask != 0
  158.                 case 12: return set.__fds_bits.12 & mask != 0
  159.                 case 13: return set.__fds_bits.13 & mask != 0
  160.                 case 14: return set.__fds_bits.14 & mask != 0
  161.                 case 15: return set.__fds_bits.15 & mask != 0
  162.                 default: return false
  163.                 }
  164.                
  165.         }
  166.        
  167. #else
  168.        
  169.         /// Replacement for FD_ZERO macro
  170.        
  171.         func fdZero(inout set: fd_set) {
  172.                 set.fds_bits = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
  173.         }
  174.        
  175.        
  176.         /// Replacement for FD_SET macro
  177.        
  178.         func fdSet(fd: Int32, inout set: fd_set) {
  179.                 let intOffset = Int(fd / 32)
  180.                 let bitOffset = fd % 32
  181.                 let mask = 1 << bitOffset
  182.                 switch intOffset {
  183.                 case 0: set.fds_bits.0 = set.fds_bits.0 | mask
  184.                 case 1: set.fds_bits.1 = set.fds_bits.1 | mask
  185.                 case 2: set.fds_bits.2 = set.fds_bits.2 | mask
  186.                 case 3: set.fds_bits.3 = set.fds_bits.3 | mask
  187.                 case 4: set.fds_bits.4 = set.fds_bits.4 | mask
  188.                 case 5: set.fds_bits.5 = set.fds_bits.5 | mask
  189.                 case 6: set.fds_bits.6 = set.fds_bits.6 | mask
  190.                 case 7: set.fds_bits.7 = set.fds_bits.7 | mask
  191.                 case 8: set.fds_bits.8 = set.fds_bits.8 | mask
  192.                 case 9: set.fds_bits.9 = set.fds_bits.9 | mask
  193.                 case 10: set.fds_bits.10 = set.fds_bits.10 | mask
  194.                 case 11: set.fds_bits.11 = set.fds_bits.11 | mask
  195.                 case 12: set.fds_bits.12 = set.fds_bits.12 | mask
  196.                 case 13: set.fds_bits.13 = set.fds_bits.13 | mask
  197.                 case 14: set.fds_bits.14 = set.fds_bits.14 | mask
  198.                 case 15: set.fds_bits.15 = set.fds_bits.15 | mask
  199.                 case 16: set.fds_bits.16 = set.fds_bits.16 | mask
  200.                 case 17: set.fds_bits.17 = set.fds_bits.17 | mask
  201.                 case 18: set.fds_bits.18 = set.fds_bits.18 | mask
  202.                 case 19: set.fds_bits.19 = set.fds_bits.19 | mask
  203.                 case 20: set.fds_bits.20 = set.fds_bits.20 | mask
  204.                 case 21: set.fds_bits.21 = set.fds_bits.21 | mask
  205.                 case 22: set.fds_bits.22 = set.fds_bits.22 | mask
  206.                 case 23: set.fds_bits.23 = set.fds_bits.23 | mask
  207.                 case 24: set.fds_bits.24 = set.fds_bits.24 | mask
  208.                 case 25: set.fds_bits.25 = set.fds_bits.25 | mask
  209.                 case 26: set.fds_bits.26 = set.fds_bits.26 | mask
  210.                 case 27: set.fds_bits.27 = set.fds_bits.27 | mask
  211.                 case 28: set.fds_bits.28 = set.fds_bits.28 | mask
  212.                 case 29: set.fds_bits.29 = set.fds_bits.29 | mask
  213.                 case 30: set.fds_bits.30 = set.fds_bits.30 | mask
  214.                 case 31: set.fds_bits.31 = set.fds_bits.31 | mask
  215.                 default: break
  216.                 }
  217.         }
  218.        
  219.        
  220.         /// Replacement for FD_CLR macro
  221.        
  222.         func fdClr(fd: Int32, inout set: fd_set) {
  223.                 let intOffset = Int(fd / 32)
  224.                 let bitOffset = fd % 32
  225.                 let mask = ~(1 << bitOffset)
  226.                 switch intOffset {
  227.                 case 0: set.fds_bits.0 = set.fds_bits.0 & mask
  228.                 case 1: set.fds_bits.1 = set.fds_bits.1 & mask
  229.                 case 2: set.fds_bits.2 = set.fds_bits.2 & mask
  230.                 case 3: set.fds_bits.3 = set.fds_bits.3 & mask
  231.                 case 4: set.fds_bits.4 = set.fds_bits.4 & mask
  232.                 case 5: set.fds_bits.5 = set.fds_bits.5 & mask
  233.                 case 6: set.fds_bits.6 = set.fds_bits.6 & mask
  234.                 case 7: set.fds_bits.7 = set.fds_bits.7 & mask
  235.                 case 8: set.fds_bits.8 = set.fds_bits.8 & mask
  236.                 case 9: set.fds_bits.9 = set.fds_bits.9 & mask
  237.                 case 10: set.fds_bits.10 = set.fds_bits.10 & mask
  238.                 case 11: set.fds_bits.11 = set.fds_bits.11 & mask
  239.                 case 12: set.fds_bits.12 = set.fds_bits.12 & mask
  240.                 case 13: set.fds_bits.13 = set.fds_bits.13 & mask
  241.                 case 14: set.fds_bits.14 = set.fds_bits.14 & mask
  242.                 case 15: set.fds_bits.15 = set.fds_bits.15 & mask
  243.                 case 16: set.fds_bits.16 = set.fds_bits.16 & mask
  244.                 case 17: set.fds_bits.17 = set.fds_bits.17 & mask
  245.                 case 18: set.fds_bits.18 = set.fds_bits.18 & mask
  246.                 case 19: set.fds_bits.19 = set.fds_bits.19 & mask
  247.                 case 20: set.fds_bits.20 = set.fds_bits.20 & mask
  248.                 case 21: set.fds_bits.21 = set.fds_bits.21 & mask
  249.                 case 22: set.fds_bits.22 = set.fds_bits.22 & mask
  250.                 case 23: set.fds_bits.23 = set.fds_bits.23 & mask
  251.                 case 24: set.fds_bits.24 = set.fds_bits.24 & mask
  252.                 case 25: set.fds_bits.25 = set.fds_bits.25 & mask
  253.                 case 26: set.fds_bits.26 = set.fds_bits.26 & mask
  254.                 case 27: set.fds_bits.27 = set.fds_bits.27 & mask
  255.                 case 28: set.fds_bits.28 = set.fds_bits.28 & mask
  256.                 case 29: set.fds_bits.29 = set.fds_bits.29 & mask
  257.                 case 30: set.fds_bits.30 = set.fds_bits.30 & mask
  258.                 case 31: set.fds_bits.31 = set.fds_bits.31 & mask
  259.                 default: break
  260.                 }
  261.         }
  262.        
  263.        
  264.         /// Replacement for FD_ISSET macro
  265.        
  266.         func fdIsSet(fd: Int32, inout set: fd_set) -> Bool {
  267.                 let intOffset = Int(fd / 32)
  268.                 let bitOffset = fd % 32
  269.                 let mask = 1 << bitOffset
  270.                 switch intOffset {
  271.                 case 0: return set.fds_bits.0 & mask != 0
  272.                 case 1: return set.fds_bits.1 & mask != 0
  273.                 case 2: return set.fds_bits.2 & mask != 0
  274.                 case 3: return set.fds_bits.3 & mask != 0
  275.                 case 4: return set.fds_bits.4 & mask != 0
  276.                 case 5: return set.fds_bits.5 & mask != 0
  277.                 case 6: return set.fds_bits.6 & mask != 0
  278.                 case 7: return set.fds_bits.7 & mask != 0
  279.                 case 8: return set.fds_bits.8 & mask != 0
  280.                 case 9: return set.fds_bits.9 & mask != 0
  281.                 case 10: return set.fds_bits.10 & mask != 0
  282.                 case 11: return set.fds_bits.11 & mask != 0
  283.                 case 12: return set.fds_bits.12 & mask != 0
  284.                 case 13: return set.fds_bits.13 & mask != 0
  285.                 case 14: return set.fds_bits.14 & mask != 0
  286.                 case 15: return set.fds_bits.15 & mask != 0
  287.                 case 16: return set.fds_bits.16 & mask != 0
  288.                 case 17: return set.fds_bits.17 & mask != 0
  289.                 case 18: return set.fds_bits.18 & mask != 0
  290.                 case 19: return set.fds_bits.19 & mask != 0
  291.                 case 20: return set.fds_bits.20 & mask != 0
  292.                 case 21: return set.fds_bits.21 & mask != 0
  293.                 case 22: return set.fds_bits.22 & mask != 0
  294.                 case 23: return set.fds_bits.23 & mask != 0
  295.                 case 24: return set.fds_bits.24 & mask != 0
  296.                 case 25: return set.fds_bits.25 & mask != 0
  297.                 case 26: return set.fds_bits.26 & mask != 0
  298.                 case 27: return set.fds_bits.27 & mask != 0
  299.                 case 28: return set.fds_bits.28 & mask != 0
  300.                 case 29: return set.fds_bits.29 & mask != 0
  301.                 case 30: return set.fds_bits.30 & mask != 0
  302.                 case 31: return set.fds_bits.31 & mask != 0
  303.                 default: return false
  304.                 }
  305.                
  306.         }
  307.        
  308. #endif
  309.  
  310. // Create server socket
  311. let s = make_socket(10800)
  312. // Listen on socket with queue of 1
  313. listen(s,1)
  314.  
  315. // Create client file
  316. system("touch client.swift")
  317. // Open writer to client file
  318. let stream = fopen("client.swift", "r+")
  319. // Client code: creates socket and sends message to port 10800 (the server)
  320. let program = "#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)\n import Darwin\n #else\n import Glibc\n#endif\n func make_socket (port:UInt16) -> Int32 { \n" +
  321.     "var name = sockaddr_in() \n let sock = socket (PF_INET, 1, 0) \n" +
  322.     "name.sin_family = sa_family_t(AF_INET) \n name.sin_port = UInt16(port).bigEndian \n" +
  323.     "name.sin_addr.s_addr = in_addr_t(0) \n withUnsafePointer(&name) { unsafePointer in \n" +
  324.     "bind (sock, UnsafePointer.init( unsafePointer), UInt32(Int(sizeof (sockaddr_in)))) \n" +
  325.     "} \n return sock } \n" +
  326.     "let s2 = make_socket(49152) \n var name = sockaddr_in() \n" +
  327.     "name.sin_family = sa_family_t(AF_INET) \n name.sin_port = UInt16(10800).bigEndian \n" +
  328.     "name.sin_addr.s_addr = in_addr_t(0)  \n withUnsafePointer(&name) { unsafePointer in \n" +
  329.     "connect(s2,UnsafePointer.init( unsafePointer),UInt32(Int(sizeof (sockaddr_in)))) \n" +
  330.     "let message = \"Hello World\" \n write(s2,message,message.characters.count) \n" +
  331. "close(s2) \n }"
  332. fwrite(program,1,program.characters.count,stream)
  333. fclose(stream)
  334.  
  335. // starts REPL to run client code
  336. system("swift client.swift")
  337.  
  338. var active_fd_set = fd_set()
  339.  
  340. // Initialize the set of active sockets
  341. fdSet(s, set: &active_fd_set)
  342.  
  343. #if !os(Linux)
  344. let FD_SETSIZE = Int32(1024)    // On OS X, FD_SETSIZE is 1024
  345. #endif
  346.  
  347. var clientname = sockaddr_in ()
  348. var t = 0
  349. while t == 0 {
  350.    
  351.     // Block until input arrives on one or more active sockets
  352.     var read_fd_set = active_fd_set;
  353.     select (FD_SETSIZE, &read_fd_set, nil, nil, nil)
  354.     // Service all the sockets with input pending
  355.     for i in 0..<FD_SETSIZE {
  356.         if fdIsSet(i,set: &read_fd_set) {
  357.             if i == s {
  358.                 // Connection request on original socket
  359.                 var size = sizeof (sockaddr_in)
  360.                 // Accept request and assign socket
  361.                 withUnsafeMutablePointers(&clientname,&size) { up1, up2 in
  362.                     var new = accept (s,
  363.                         UnsafeMutablePointer(up1),
  364.                         UnsafeMutablePointer(up2))
  365.                     print("Server: connect from host " + String(inet_ntoa (clientname.sin_addr)) + ", port " + String(UInt16(clientname.sin_port).bigEndian))
  366.                     fdSet (new, set: &active_fd_set)
  367.                 }
  368.                
  369.             }
  370.             else {
  371.                 // Data arriving on an already-connected socket
  372.                 if read_from_client (i) < 0 {
  373.                     // Read complete, close socket
  374.                     close (i)
  375.                     fdClr (i, set: &active_fd_set)
  376.                     t = 1
  377.                 }
  378.             }
  379.         }
  380.     }
  381. }
  382.  


jrs@laptop:~/Swift/usr/share/examples$ swift server.swift
Server: connect from host 0x00007fa3eae6d718, port 49152
Server: got message: Hello World
jrs@laptop:~/Swift/usr/share/examples$

Title: Apple Swift on Ubuntu - Swift IUP
Post by: John on December 07, 2015, 07:25:42 PM
Here is a Hello World with IUP.

(http://files.allbasic.info/Swift/hwdialog.png)

Code: Text
  1. import Foundation
  2. import Glibc
  3.  
  4. IupOpen(nil, nil)
  5.  
  6. IupMessage("Swift IUP", "Hello world from IUP.")
  7.  
  8. IupClose()
  9.  


jrs@laptop:~/Swift/usr/share/examples$ swiftc iup.swift -import-objc-header /usr/include/iup/iup.h -liup -o swiftiup
jrs@laptop:~/Swift/usr/share/examples$ ./swiftiup


PS

Thanks AIR for the nil tip!
Title: Re: Apple Swift on Ubuntu - Callback Functions
Post by: John on December 08, 2015, 12:48:22 AM
I'm investigating how to create IUP callback functions in Swift. I found this article but it assumes I'm doing this on the Apple version.  :(

C Callbacks in Swift (http://oleb.net/blog/2015/06/c-callbacks-in-swift/)

Feel free to chime in if you have any ideas.



Title: Re: Apple Swift on Ubuntu
Post by: AIR on December 08, 2015, 04:57:50 PM
Using Leagacy C APIs with Swift (http://www.sitepoint.com/using-legacy-c-apis-swift/)
Title: Re: Apple Swift on Ubuntu
Post by: John on December 08, 2015, 05:16:50 PM
Thanks AIR!

Great info on Swift C pointer declarations and use. I didn't notice anything about defining callback functions though. Any ideas on that topic?
Title: Re: Apple Swift on Ubuntu
Post by: AIR on December 08, 2015, 06:05:51 PM
Just guessing here.  Using an IupButton callback as an example:

Code: [Select]
int button_cb(Ihandle* ih)
I think something like this?

Code: [Select]
func button_cb(ih: UnsafeMutablePointer<Ihandle>) -> Int32
As I mentioned, I'm just guessing...
Title: Re: Apple Swift on Ubuntu
Post by: John on December 08, 2015, 06:50:03 PM
Looks good to me and your guesses have always been right on or got me pointed in the right direction.

I need to find out how to get the callback pointer to pass to IUP. From what I have stumbled on, this is available and core Swift syntax.

I hit the wall. I can't even get a UnsafeMutablePointer variable declared let alone a callback function. :-\

Code: Text
  1. import Foundation
  2. import Glibc
  3.  
  4. var dlg:UnsafeMutablePointer<Int32> = nil
  5. var lbl:UnsafeMutablePointer<Int32> = nil
  6.  
  7. IupOpen(nil, nil)
  8.  
  9. lbl =  IupLabel("Hello world from IUP.")
  10. dlg = IupDialog(IupVbox(lbl, nil))
  11. IupSetAttribute(dlg, "TITLE", "Swift Hello World")
  12.  
  13. IupShowXY(dlg, IUP_CENTER, IUP_CENTER)
  14.  
  15. IupMainLoop()
  16.  
  17. IupClose()
  18.  


jrs@laptop:~/Swift/usr/share/examples$ swiftc iuphw2.swift -import-objc-header /usr/include/iup/iup.h -liup -o iuphw2
iuphw2.swift:9:8: error: cannot assign value of type 'COpaquePointer' to type 'UnsafeMutablePointer<Int32>'
lbl =  IupLabel("Hello world from IUP.")
       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
iuphw2.swift:10:25: error: cannot convert value of type 'UnsafeMutablePointer<Int32>' to expected argument type 'COpaquePointer'
dlg = IupDialog(IupVbox(lbl, nil))
                        ^~~
iuphw2.swift:11:17: error: cannot convert value of type 'UnsafeMutablePointer<Int32>' to expected argument type 'COpaquePointer'
IupSetAttribute(dlg, "TITLE", "Swift Hello World")
                ^~~
iuphw2.swift:13:11: error: cannot convert value of type 'UnsafeMutablePointer<Int32>' to expected argument type 'COpaquePointer'
IupShowXY(dlg, IUP_CENTER, IUP_CENTER)
          ^~~
jrs@laptop:~/Swift/usr/share/examples$
Title: Re: Apple Swift on Ubuntu
Post by: AIR on December 09, 2015, 04:30:55 AM
two things you could try.

change the UnsafeMutablePointer to COpaquePointer

or ditch the explicit declaration of the variables and create them inline

var lbl =  IupLabel("Hello world from IUP.")
Title: Re: Apple Swift on Ubuntu
Post by: John on December 09, 2015, 10:08:31 AM
Here is the results of your first idea. I'll try the other next. Thanks again for helping out!

AIR #1

Code: Text
  1. import Foundation
  2. import Glibc
  3.  
  4. var dlg: COpaquePointer<Int32> = nil
  5. var lbl: COpaquePointer<Int32> = nil
  6.  
  7. IupOpen(nil, nil)
  8.  
  9. lbl =  IupLabel("Hello world from IUP.")
  10. dlg = IupDialog(IupVbox(lbl, nil))
  11. IupSetAttribute(dlg, "TITLE", "Swift Hello World")
  12.  
  13. IupShowXY(dlg, IUP_CENTER, IUP_CENTER)
  14.  
  15. IupMainLoop()
  16.  
  17. IupClose()
  18.  


jrs@laptop:~/Swift/usr/share/examples$ swiftc iuphw2.swift -import-objc-header /usr/include/iup/iup.h -liup -o iuphw2
iuphw2.swift:4:10: error: cannot specialize non-generic type 'COpaquePointer'
var dlg: COpaquePointer<Int32> = nil
         ^
iuphw2.swift:5:10: error: cannot specialize non-generic type 'COpaquePointer'
var lbl: COpaquePointer<Int32> = nil
         ^
iuphw2.swift:10:30: error: nil is not compatible with expected argument type 'Any' (aka 'protocol<>')
dlg = IupDialog(IupVbox(lbl, nil))
                             ^
jrs@laptop:~/Swift/usr/share/examples$


AIR # 2

I think this is going to work. I just can't use variadic functions. Not supported yet.

Code: Text
  1. import Foundation
  2. import Glibc
  3.  
  4. IupOpen(nil, nil)
  5.  
  6. var lbl =  IupLabel("Hello world from IUP.")
  7. var dlg = IupDialog(IupVbox(lbl, 0))
  8. IupSetAttribute(dlg, "TITLE", "Swift Hello World")
  9.  
  10. IupShowXY(dlg, IUP_CENTER, IUP_CENTER)
  11.  
  12. IupMainLoop()
  13.  
  14. IupClose()
  15.  


jrs@laptop:~/Swift/usr/share/examples$ swiftc iuphw2.swift -import-objc-header /usr/include/iup/iup.h -liup -o iuphw2
iuphw2.swift:7:21: error: 'IupVbox' is unavailable: Variadic function is unavailable
var dlg = IupDialog(IupVbox(lbl, 0))
                    ^~~~~~~
__ObjC.IupVbox:2:13: note: 'IupVbox' has been explicitly marked unavailable here
public func IupVbox(child: COpaquePointer, _ varargs: Any...) -> COpaquePointer
            ^
jrs@laptop:~/Swift/usr/share/examples$

Title: Re: Apple Swift on Ubuntu
Post by: John on December 09, 2015, 10:41:06 AM
I got it to work.

Code: Text
  1. import Foundation
  2. import Glibc
  3.  
  4. IupOpen(nil, nil)
  5.  
  6. var dlg = IupCreate("dialog")
  7. var vbx = IupCreate("vbox")
  8. var lbl = IupCreate("label")
  9.  
  10. IupStoreAttribute(dlg, "TITLE", "Swift IUP")
  11. IupStoreAttribute(lbl, "TITLE", "Hello world from Swift IUP.")
  12.  
  13. IupAppend(vbx, lbl)
  14. IupAppend(dlg, vbx)
  15.  
  16. IupShowXY(dlg, IUP_CENTER, IUP_CENTER)
  17.  
  18. IupMainLoop()
  19.  
  20. IupClose()
  21.  

Compiles, no errors.
Title: Re: Apple Swift on Ubuntu
Post by: John on December 09, 2015, 02:48:28 PM
AIR,

I'm trying to get a callback function pointer but it seems elusive.

Code: Text
  1. import Foundation
  2. import Glibc
  3.  
  4. func btn_exit_cb(ih: Int32) -> Int32 {
  5.   return IUP_CLOSE
  6. }
  7.  
  8. IupOpen(nil, nil)
  9.  
  10. var dlg = IupCreate("dialog")
  11. var vbx = IupCreate("vbox")
  12. var lbl = IupCreate("label")
  13. var but = IupCreate("button")
  14.  
  15. IupStoreAttribute(dlg, "TITLE", "Swift IUP")
  16. IupStoreAttribute(lbl, "TITLE", "Hello world from Swift IUP.")
  17. IupStoreAttribute(but, "TITLE", "Quit")
  18.  
  19. IupAppend(vbx, lbl)
  20. IupAppend(vbx, but)
  21. IupAppend(dlg, vbx)
  22.  
  23. IupSetCallback(but, "ACTION", CUseCallback(btn_exit_cb, 1))
  24.  
  25. IupShowXY(dlg, IUP_CENTER, IUP_CENTER)
  26.  
  27. IupMainLoop()
  28.  
  29. IupClose()
  30.  


jrs@laptop:~/Swift/usr/share/examples$ swiftc iuphw2.swift -import-objc-header /usr/include/iup/iup.h -liup -o iuphw2
iuphw2.swift:23:31: error: use of unresolved identifier 'CUseCallback'
IupSetCallback(but, "ACTION", CUseCallback(btn_exit_cb, 1))
                              ^~~~~~~~~~~~
jrs@laptop:~/Swift/usr/share/examples$

Title: Re: Apple Swift on Ubuntu
Post by: AIR on December 09, 2015, 06:25:48 PM
Code: Text
  1. import Foundation
  2. import Glibc
  3.  
  4. func btn_exit_cb(ih: COpaquePointer) -> Int32 {
  5.   return IUP_CLOSE
  6. }
  7.  
  8. IupOpen(nil, nil)
  9.  
  10. var dlg = IupCreate("dialog")
  11. var vbx = IupCreate("vbox")
  12. var lbl = IupCreate("label")
  13. var but = IupCreate("button")
  14.  
  15. IupStoreAttribute(dlg, "TITLE", "Swift IUP")
  16. IupStoreAttribute(lbl, "TITLE", "Hello world from Swift IUP.")
  17. IupStoreAttribute(but, "TITLE", "Quit")
  18.  
  19. IupAppend(vbx, lbl)
  20. IupAppend(vbx, but)
  21. IupAppend(dlg, vbx)
  22.  
  23. IupSetCallback(but, "ACTION", btn_exit_cb)
  24.  
  25. IupShowXY(dlg, IUP_CENTER, IUP_CENTER)
  26.  
  27. IupMainLoop()
  28.  
  29. IupClose()
  30.  
Title: Re: Apple Swift on Ubuntu
Post by: John on December 09, 2015, 06:38:39 PM
Thanks AIR!

It closes the window when the quit button is clicked. This shows the core IUP functionality works in Swift. I'll try building on this.

Swift sure makes the syntax simple to use.

(http://www.johnspikowski.com/Swift-C/swiftiuphello.png)

Code: Text
  1. /*
  2. Linux Swift IUP Hello World Example
  3. Screen Shot: http://www.johnspikowski.com/Swift-C/swiftiuphello.png
  4. Compile: swiftc iuphw.swift -import-objc-header /usr/include/iup/iup.h -liup -o iuphw
  5. Contributors: John Spikowski, Armando I. Rivera (AIR) 2015-12-09
  6. */
  7.  
  8. import Foundation
  9. import Glibc
  10.  
  11. func btn_exit_cb(ih: COpaquePointer) -> Int32 {
  12.   return IUP_CLOSE
  13. }
  14.  
  15. IupOpen(nil, nil)
  16.  
  17. var dlg = IupCreate("dialog")
  18. var vbx = IupCreate("vbox")
  19. var lbl = IupCreate("label")
  20. var but = IupCreate("button")
  21.  
  22. IupStoreAttribute(dlg, "TITLE", "Swift IUP")
  23. IupSetAttributes(vbx, "MARGIN=10x10, ALIGNMENT=ACENTER")
  24. IupSetAttributes(lbl, "FONT=\"Arial, 24\", TITLE=\"Hello World\"")
  25. IupStoreAttribute(but, "TITLE", " Quit ")
  26.  
  27. IupAppend(vbx, lbl)
  28. IupAppend(vbx, but)
  29. IupAppend(dlg, vbx)
  30.  
  31. IupSetCallback(but, "ACTION", btn_exit_cb)
  32.  
  33. IupShowXY(dlg, IUP_CENTER, IUP_CENTER)
  34.  
  35. IupMainLoop()
  36.  
  37. IupClose()
  38.  


jrs@laptop:~/Swift/usr/share/examples$ swiftc iuphw.swift -import-objc-header /usr/include/iup/iup.h -liup -o iuphw
jrs@laptop:~/Swift/usr/share/examples$ ./iuphw


Attached is a screenshot of editing a Swift programs in UltraEdit and gedit.
Title: Re: Apple Swift on Ubuntu
Post by: John on December 11, 2015, 02:07:54 PM
AIR,

Here is an example of using a IUP LED screen definition to define the UI. The questions I have is will Swift support a multi-line string and how does LED process the defined callback function references? What would be cool is a string array of screen UI definitions and concatenated (assembled) just before the display.

Update
Quote
Unfortunately, swift doesn't appear to allow you to have a single literal over multiple lines but you can add + literals together over multiple lines.

(http://www.johnspikowski.com/Swift-C/iup_sample.png)

Code: Script BASIC
  1. ' Script BASIC IUP/LED
  2.  
  3. IMPORT iup.bas
  4. sample_led = """
  5.  
  6. img1 = IMAGE[0="0 0 0",1="BGCOLOR",2="255 0 0"]
  7. (32,32
  8. ,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1
  9. ,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1
  10. ,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1
  11. ,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1
  12. ,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1
  13. ,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1
  14. ,1,1,1,1,1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Menu 1",
  81.    MENU
  82.    (
  83.      ITEM[VALUE=ON]("IupItem 1 Checked",myaction),
  84.      SEPARATOR(),
  85.      ITEM[ACTIVE="NO"]("IupItem 2 Disabled",myaction)
  86.    )
  87.  ),
  88.  ITEM("IupItem 3",myaction),
  89.  ITEM("IupItem 4",myaction)
  90. )
  91.  
  92. dlg = DIALOG[TITLE="IupDialog Title",MENU="mnu"]
  93. (
  94.  VBOX[GAP="5",ALIGNMENT="ARIGHT",MARGIN="5x5"]
  95.  (
  96.    HBOX
  97.    (
  98.      FRAME[TITLE="IupButton"]
  99.      (
  100.        VBOX
  101.        (
  102.          BUTTON("Button Text",myaction),
  103.          BUTTON[IMAGE=img1]("",myaction),
  104.          BUTTON[IMAGE=img1,IMPRESS=img2]("",myaction)
  105.        )
  106.      ),
  107.      FRAME[TITLE="IupLabel"]
  108.      (
  109.        VBOX
  110.        (
  111.          LABEL("Label Text"),
  112.          LABEL[SEPARATOR=HORIZONTAL](""),
  113.          LABEL[IMAGE=img1]("")
  114.        )
  115.      ),
  116.      FRAME[TITLE="IupToggle"]
  117.      (
  118.        VBOX
  119.        (
  120.          TOGGLE[VALUE="ON"]("Toggle Text",myaction),
  121.          TOGGLE[IMAGE=img1,IMPRESS=img2]("",myaction),
  122.          FRAME[TITLE="IupRadio"]
  123.          (
  124.            RADIO
  125.            (
  126.              VBOX
  127.              (
  128.                TOGGLE("Toggle Text",myaction),
  129.                TOGGLE("Toggle Text",myaction)
  130.              )
  131.            )
  132.          )
  133.        )
  134.      ),
  135.      FRAME[TITLE="IupText/IupMultiline"]
  136.      (
  137.        VBOX
  138.        (
  139.          TEXT[SIZE="80x",VALUE="IupText Text"](myaction),
  140.          MULTILINE[SIZE="80x60",EXPAND="YES",VALUE="IupMultiline Text\nSecond Line\nThird Line"](myaction)
  141.        )
  142.      ),
  143.      FRAME[TITLE="IupList"]
  144.      (
  145.        VBOX
  146.        (
  147.          LIST[EXPAND="YES",VALUE="1",1="Item 1 Text",2="Item 2 Text",3="Item 3 Text"](myaction),
  148.          LIST[DROPDOWN="YES",EXPAND="YES",VALUE="2",1="Item 1 Text",2="Item 2 Text",3="Item 3 Text"](myaction),
  149.          LIST[EDITBOX="YES",EXPAND="YES",VALUE="3",1="Item 1 Text",2="Item 2 Text",3="Item 3 Text"](myaction)
  150.        )
  151.      )
  152.    ),
  153.    CANVAS[BGCOLOR="128 255 0"](myaction)
  154.  )
  155. )
  156. """
  157.  
  158. Iup::Open()
  159. Iup::LoadBuffer(sample_led)
  160. Iup::Show(Iup::GetHandle("dlg"))
  161. Iup::MLoop()
  162. IUP::Close()
  163.  
Title: Re: Apple Swift on Ubuntu
Post by: John on December 11, 2015, 05:24:12 PM
This works. I was able to locate more info on LED. (see attached)

This call associates the LED (expression/callback ID) to the actual function name being used.

Code: [Select]
IupSetFunction("LED_reference", callback_function_name)

(http://www.johnspikowski.com/Swift-C/swift_iupled.png)

Code: Text
  1. import Foundation
  2. import Glibc
  3.  
  4. func btn_exit_cb(ih: COpaquePointer) -> Int32 {
  5.   return IUP_CLOSE
  6. }
  7.  
  8. IupOpen(nil, nil)
  9.  
  10. IupLoad("sample.led")
  11.  
  12. IupSetFunction("exit_dlg", btn_exit_cb)
  13.  
  14. IupShow(IupGetHandle("dlg"))
  15.  
  16. IupMainLoop()
  17.  
  18. IupClose()
  19.  

sample.led
Code: [Select]
img1 = IMAGE[0="0 0 0",1="BGCOLOR",2="255 0 0"]
(32,32
,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1
,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1
,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1
,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1
,1,1,1,1,1,1,1,1,1,1,1,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IALOG[TITLE="Swift IUP LED",MENU="mnu"]
(
  VBOX[GAP="5",ALIGNMENT="ARIGHT",MARGIN="5x5"]
  (
    HBOX
    (
      FRAME[TITLE="IupButton"]
      (
        VBOX
        (
          BUTTON("Quit Dialog",exit_dlg),
          BUTTON[IMAGE=img1]("",myaction),
          BUTTON[IMAGE=img1,IMPRESS=img2]("",myaction)
        )
      ),
      FRAME[TITLE="IupLabel"]
      (
        VBOX
        (
          LABEL("Label Text"),
          LABEL[SEPARATOR=HORIZONTAL](""),
          LABEL[IMAGE=img1]("")
        )
      ),
      FRAME[TITLE="IupToggle"]
      (
        VBOX
        (
          TOGGLE[VALUE="ON"]("Toggle Text",myaction),
          TOGGLE[IMAGE=img1,IMPRESS=img2]("",myaction),
          FRAME[TITLE="IupRadio"]
          (
            RADIO
            (
              VBOX
              (
                TOGGLE("Toggle Text",myaction),
                TOGGLE("Toggle Text",myaction)
              )
            )
          )
        )
      ),
      FRAME[TITLE="IupText/IupMultiline"]
      (
        VBOX
        (
          TEXT[SIZE="80x",VALUE="IupText Text"](myaction),
          MULTILINE[SIZE="80x60",EXPAND="YES",VALUE="IupMultiline Text\nSecond Line\nThird Line"](myaction)
        )
      ),
      FRAME[TITLE="IupList"]
      (
        VBOX
        (
          LIST[EXPAND="YES",VALUE="1",1="Item 1 Text",2="Item 2 Text",3="Item 3 Text"](myaction),
          LIST[DROPDOWN="YES",EXPAND="YES",VALUE="2",1="Item 1 Text",2="Item 2 Text",3="Item 3 Text"](myaction),
          LIST[EDITBOX="YES",EXPAND="YES",VALUE="3",1="Item 1 Text",2="Item 2 Text",3="Item 3 Text"](myaction)
        )
      )
    ),
    CANVAS[BGCOLOR="128 255 0"](myaction)
  )
)


jrs@laptop:~/Swift/usr/share/examples$ swiftc iupled.swift -import-objc-header /usr/include/iup/iup.h -liup -o iupled
jrs@laptop:~/Swift/usr/share/examples$ ./iupled

Title: Re: Apple Swift on Ubuntu
Post by: John on December 11, 2015, 10:55:15 PM
AIR,

I found a Swift based SQLite3 wrapper for the Apple version. I tried to compile it but had some errors. I think this would be a good SQLite3 library interface if it wouldn't take a lot of work to get running.

SwiftData is a simple and effective wrapper around the SQLite3 C API written completely in Swift (https://github.com/ryanfowler/SwiftData)
Title: Re: Apple Swift on Ubuntu
Post by: AIR on December 12, 2015, 09:09:09 AM
Of course it has errors, it's using Apple-specific API calls.

To do this right, you should make use of the PackageManager support that Swift-Linux has to incorporate the dependencies you'll need.

IOW, you're probably gonna have to roll your own Sqlite3 implementation unless someone else has already done it.
Title: Re: Apple Swift on Ubuntu
Post by: John on December 12, 2015, 10:46:54 AM
Quote
Of course it has errors, it's using Apple-specific API calls.

I was fooled by the claim of being written in 100% Swift. I have never used Object-C or the Swift Package Manager for that matter. If you feel that this package is out of the Swift generic ballpark, then maybe we need to look elsewhere.

We could be traditional and you be the SQLite king as your were for Script BASIC.  8)

I'll leave it in your hands what we should do for a SQLite Swift solution.

Title: Re: Apple Swift on Ubuntu
Post by: John on December 12, 2015, 03:36:44 PM
IUP includes a Dialog Layout tool that lets you interactively modify your live dialog. In this example I modified the background and forground colors of the Quit Dialog button. Changes can be made without changing code and once you decide on your design you can export your new LED screen definition to a file. No recompiling needed.  :)

Code: Text
  1. /*
  2. Linux Swift IUP LED Example
  3. Screen Shot: http://www.johnspikowski.com/Swift-C/swift_iupled.png
  4. Compile: swiftc iupled.swift -import-objc-header /usr/include/iup/iup.h -liup -o iupled
  5. Contributors: John Spikowski 2015-12-11
  6. */
  7.  
  8.  
  9. import Foundation
  10. import Glibc
  11.  
  12. func btn_exit_cb(ih: COpaquePointer) -> Int32 {
  13.   return IUP_CLOSE
  14. }
  15.  
  16. IupOpen(nil, nil)
  17.  
  18. IupLoad("sample.led")
  19.  
  20. IupSetFunction("exit_dlg", btn_exit_cb)
  21.  
  22. IupShow(IupLayoutDialog(IupGetHandle("dlg")))
  23.  
  24. IupMainLoop()
  25.  
  26. IupClose()
  27.  

Dialog Layout Editor
(http://www.johnspikowski.com/Swift-C/iuplayoutdialog.png)

(http://www.johnspikowski.com/Swift-C/iupdialogchange.png)

(http://www.johnspikowski.com/Swift-C/iuppropbgclr.png)   (http://www.johnspikowski.com/Swift-C/iuppropcallback.png)

Here is the untouched export of sample.led via the Dialog Layout editor.

Code: Text
  1. #   Generated by IupLayoutDialog export to LED.
  2.  
  3. dlg = DIALOG[
  4.   MENU = mnu,
  5.   USERSIZE = 0x0,
  6.   TITLE = "Swift IUP LED"](
  7.     VBOX[
  8.       USERSIZE = 0x0,
  9.       MARGIN = 5x5,
  10.       GAP = 5,
  11.       ALIGNMENT = ARIGHT](
  12.         HBOX[
  13.           USERSIZE = 0x0](
  14.             FRAME[
  15.               USERSIZE = 0x0,
  16.               TITLE = IupButton](
  17.                 VBOX[
  18.                   USERSIZE = 0x0](
  19.                     BUTTON[
  20.                       USERSIZE = 0x0,
  21.                       TITLE = "Quit Dialog",
  22.                       ACTION = exit_dlg]("", exit_dlg),
  23.                     BUTTON[
  24.                       IMAGE = img1,
  25.                       USERSIZE = 0x0]("", do_nothing),
  26.                     BUTTON[
  27.                       IMPRESS = img2,
  28.                       IMAGE = img1,
  29.                       USERSIZE = 0x0]("", do_nothing))),
  30.             FRAME[
  31.               USERSIZE = 0x0,
  32.               TITLE = IupLabel](
  33.                 VBOX[
  34.                   USERSIZE = 0x0](
  35.                     LABEL[
  36.                       USERSIZE = 0x0,
  37.                       TITLE = "Label Text"](""),
  38.                     LABEL[
  39.                       SEPARATOR = HORIZONTAL,
  40.                       EXPAND = HORIZONTALFREE,
  41.                       USERSIZE = 0x0](""),
  42.                     LABEL[
  43.                       IMAGE = img1,
  44.                       USERSIZE = 0x0](""))),
  45.             FRAME[
  46.               USERSIZE = 0x0,
  47.               TITLE = IupToggle](
  48.                 VBOX[
  49.                   USERSIZE = 0x0](
  50.                     TOGGLE[
  51.                       USERSIZE = 0x0,
  52.                       TITLE = "Toggle Text",
  53.                       VALUE = ON]("", do_nothing),
  54.                     TOGGLE[
  55.                       IMPRESS = img2,
  56.                       IMAGE = img1,
  57.                       USERSIZE = 0x0]("", do_nothing),
  58.                     FRAME[
  59.                       USERSIZE = 0x0,
  60.                       TITLE = IupRadio](
  61.                         RADIO[
  62.                           USERSIZE = 0x0](
  63.                             VBOX[
  64.                               USERSIZE = 0x0](
  65.                                 TOGGLE[
  66.                                   USERSIZE = 0x0,
  67.                                   TITLE = "Toggle Text"]("", do_nothing),
  68.                                 TOGGLE[
  69.                                   USERSIZE = 0x0,
  70.                                   TITLE = "Toggle Text"]("", do_nothing)))))),
  71.             FRAME[
  72.               USERSIZE = 0x0,
  73.               TITLE = IupText/IupMultiline](
  74.                 VBOX[
  75.                   USERSIZE = 0x0](
  76.                     TEXT[
  77.                       SIZE = 80x,
  78.                       USERSIZE = 140x0,
  79.                       VALUE = "IupText Text"](do_nothing),
  80.                     MULTILINE[
  81.                       EXPAND = YES,
  82.                       SIZE = 80x60,
  83.                       USERSIZE = 140x128,
  84.                       VALUE = "IupMultiline Text\nSecond Line\nThird Line",
  85.                       MULTILINE = YES](do_nothing))),
  86.             FRAME[
  87.               USERSIZE = 0x0,
  88.               TITLE = IupList](
  89.                 VBOX[
  90.                   USERSIZE = 0x0](
  91.                     LIST[
  92.                       EXPAND = YES,
  93.                       USERSIZE = 0x0,
  94.                       VALUE = 1,
  95.                       1 = "Item 1 Text",
  96.                       2 = "Item 2 Text",
  97.                       3 = "Item 3 Text"](do_nothing),
  98.                     LIST[
  99.                       EXPAND = YES,
  100.                       USERSIZE = 0x0,
  101.                       VALUE = 2,
  102.                       1 = "Item 1 Text",
  103.                       2 = "Item 2 Text",
  104.                       3 = "Item 3 Text",
  105.                       DROPDOWN = YES](do_nothing),
  106.                     LIST[
  107.                       EXPAND = YES,
  108.                       USERSIZE = 0x0,
  109.                       EDITBOX = YES,
  110.                       VALUE = 3,
  111.                       1 = "Item 1 Text",
  112.                       2 = "Item 2 Text",
  113.                       3 = "Item 3 Text"](do_nothing)))),
  114.         CANVAS[
  115.           USERSIZE = 0x0,
  116.           BGCOLOR = "128 255 0"](do_nothing)))
  117.  

Quote
When the application defines the SIZE or RASTERSIZE attributes, it changes the User size in IUP. The initial internal value is "0x0". When set to NULL the User size is internally set to "0x0". If the element is not mapped then the returned value by SIZE or RASTERSIZE is the User size, if the element is mapped then the returned value is the Current size. To obtain the User size after the element is mapped use the USERSIZE attribute (since 3.12).

By default the layout computation uses the Natural size of the element to compose the layout of the dialog, but if the User size is defined then it is used instead of the Natural size. In this case the Natural size is not even computed. But there are two exceptions.

If the element is a container (not including the dialog) the User size will be used instead of the Natural size only if bigger than the Natural size. So for containers the User size will also act as a minimum value for Natural size.

For the dialog, if the User size is defined then it is used instead of the Natural size, but the Natural size of the dialog is always computed. And if the User size is not defined, the Natural size is used only if bigger than the Current size, so in this case the dialog will always increase its size to fit all its contents. In other words, in this case the dialog will not shrink its Current size unless the User size is defined. See the SHRINK attribute guide bellow for an alternative.

When the user is interactively changing the dialog size the Current size is updated. But the dialog contents will always occupy the Natural size available, being smaller or bigger than the dialog Current size.

When SIZE or RASTERSIZE attributes are set for the dialog (changing the User size) the Current size is also reset to "0x0". Allowing the application to force an update of its Window size. To only change the User size in pixels, without resetting the Current size, set the USERSIZE attribute (since 3.12).

After the Natural size is calculated for all the elements in the dialog, the the Current size is set based on the available space in the dialog. So the Current size is set from the outer element (the dialog) to the inner element, in opposite of what it is done for the Natural size.

After all the elements have their Current size updated, the elements positions are calculated, and finally, after the element is mapped, the Window size and position are set for the native elements. The Window size is set exactly to the Current size.

After the element is mapped the returned value for SIZE or RASTERSIZE is the Current size. It actually returns the native Window size of the element. Before mapping, the returned value is the User size.

ALIGNMENT (non inheritable): horizontal and vertical alignment. Possible values: "ALEFT", "ACENTER" and "ARIGHT",  combined to "ATOP", "ACENTER" and "ABOTTOM". Default: "ACENTER:ACENTER". Partial values are also accepted, like "ARIGHT" or ":ATOP", the other value will be used from the current alignment.

MARGIN, CMARGIN: Defines a margin in pixels, CMARGIN is in the same units of the SIZE attribute. Its value has the format "widthxheight", where width and height are integer values corresponding to the horizontal and vertical margins, respectively. Default: "0x0" (no margin).

GAP, CGAP: Defines a vertical space in pixels between the children, CGAP is in the same units of the SIZE attribute for the height. Default: "0".

To reduce the size of the dialog and its containers to a size smaller than the Natural size the SHRINK attribute of the dialog can be used. If set to YES all the containers of the dialog will be able to reduce its size. But be aware that elements may overlap and the layout result could be visually bad if the dialog size is smaller than its Natural size.

Another way to increase the size of elements is to use the EXPAND attribute. When there is room in the container to expand an element, the container layout will expand the elements that have the EXPAND attribute set to YES, HORIZONTAL or VERTICAL accordingly, even if they have the User size defined. The default is EXPAND=NO, but for containers is EXPAND=YES.

(http://webserver2.tecgraf.puc-rio.br/iup/en/elem/images/iupvbox_align.png)

(http://www.johnspikowski.com/Swift-C/iupalignment.png)
Title: Re: Apple Swift on Ubuntu
Post by: AIR on December 13, 2015, 12:34:10 PM
I'll leave it in your hands what we should do for a SQLite Swift solution.

This is the most fucking retarded way of implementing an interface to a C library I've ever encountered.  I've stated that I didn't care for Swift before, now I can say that I absolutely HATE it.

It definitely DOES NOT HELP that there is almost NO documentation that's worth anything at this point on the PackageManager under Linux.

I've attached what I managed to create as far as a Sqlite3 interface, but this is as far as I go.  After unpacking, cd into the directory and do:  swift build.  The binary will be in the .build/debug folder

If I ever use Swift again, it will be exclusively on my Mac.

Have fun repeatedly banging your head against a wall.....
Title: Re: Apple Swift on Ubuntu
Post by: John on December 13, 2015, 02:08:53 PM
That is the first time I've been kissed and slapped at the same time.  ;D

Didn't I mention that the Swift-C effort here was experimental?

Thanks again AIR for being a good friend and allowing me to continue being optimistic towards Swift's future. I have to laugh hearing you bad mouthing an Apple offering.  :-X
Title: Re: Apple Swift on Ubuntu
Post by: AIR on December 13, 2015, 02:58:39 PM
That is the first time I've been kissed and slapped at the same time.  ;D

Didn't I mention that the Swift-C effort here was experimental?

Thanks again AIR for being a good friend and allowing me to continue being optimistic towards Swift's future. I have to laugh hearing you bad mouthing an Apple offering.  :-X

Apple's not stupid:  They're selling the pipe dream that you'll be able to create apps for their store on non-Apple hardware/OS.  It might be possible at some point, but you won't be using the Cocoa and other Frameworks to do it anytime soon, if at all.

People use Swift because a huge (<--cue Donald Trump Accent) company is behind it.  Kind of like how Objective C became popular.  At least with Objective C, I can drop straight C into it without having to jump through crazy hoops to get shit to work.

I asked myself the question, is Swift worth all the effort to get something as simple as SQlite going?  After taking the same program and re doing it in NIM (5min, but it already has sqlite support), the answer is a resounding NO.

I'm really surprised that you dropped NIM, btw.  It already has an IUP module that works in Linux and Windows, and already has support for a large amount of 3rd party libraries.

Here's the same simple sqlite program in NIM:

Code: Text
  1. import db_sqlite
  2.  
  3.  
  4. let db = open("test.db", nil, nil, nil)
  5.  
  6. db.exec(sql("Drop table if exists cars"))
  7.  
  8. db.exec(sql("CREATE TABLE Cars(Id INT, Name TEXT, Price INT)"))
  9.  
  10. for x in items(["1, 'Audi', 52642",
  11.                 "2, 'Mercedes', 57127",
  12.                 "3, 'Skoda', 9000",
  13.                 "4, 'Volvo', 29000",
  14.                 "5, 'Bentley', 350000",
  15.                 "6, 'Citroen', 21000",
  16.                 "7, 'Hummer', 41400",
  17.                 "8, 'Volkswagen', 21600"]):
  18.  
  19.     db.exec(sql("INSERT INTO Cars VALUES(" & x & ")"))
  20.  
  21. for x in db.fastRows(sql("select Name,Price from cars Order by Price DESC")):
  22.   echo x[0], " ", x[1]
  23.  
  24. db.close()
  25.  

Same thing in Swift:
Code: Text
  1. import Foundation
  2. import Glibc
  3. import CSqlite3
  4.  
  5.  
  6.  
  7. func sqlColumnText(statement: COpaquePointer, column: Int32) -> String {
  8.         return String.fromCString(UnsafePointer<CChar>(sqlite3_column_text(statement,column)))!
  9. }
  10.  
  11. func sqlVersion() -> String {
  12.         let s = String.fromCString(sqlite3_libversion())!
  13.         return "Sqlite3 Version: \(s)"
  14. }
  15.  
  16. func sqlOpen(filename: String, database: UnsafeMutablePointer<COpaquePointer>) {
  17.         let rc = sqlite3_open(filename, database)
  18.  
  19.         if (rc != SQLITE_OK) {
  20.                 print("Cannot open database " + String.fromCString(sqlite3_errmsg(database.memory))!)
  21.                 exit(1)
  22.         }
  23. }
  24.  
  25. func sqlExec(database: COpaquePointer, query: String) {
  26.         var err_msg: UnsafeMutablePointer<CChar> = nil
  27.         let rc = sqlite3_exec(database, query, nil, nil, &err_msg)
  28.  
  29.         if (rc != SQLITE_OK ) {
  30.  
  31.             print("SQL error: " + String.fromCString( err_msg)!)
  32.  
  33.             sqlite3_free(err_msg)
  34.             sqlite3_close(database)
  35.  
  36.             exit(1)
  37.         }
  38. }
  39.  
  40. func sqlPrepare(database: COpaquePointer, query: String, statement: UnsafeMutablePointer<COpaquePointer>) {
  41.         let rc = sqlite3_prepare_v2(database,query,-1,statement,nil)
  42.  
  43.         if (rc != SQLITE_OK ) {
  44.  
  45.             print("Failed to select data")
  46.             print("SQL error: " + String.fromCString( sqlite3_errmsg(database))!)
  47.  
  48.  
  49.             sqlite3_close(database)
  50.  
  51.             exit(1)
  52.         }
  53. }
  54.  
  55. func sqlStep(statement: COpaquePointer) -> Int32 {
  56.         return sqlite3_step(statement)
  57. }
  58.  
  59. func sqlClose(database: COpaquePointer){
  60.         sqlite3_close(database)
  61. }
  62.  
  63.  
  64.  
  65.  
  66.  
  67. var db: COpaquePointer = nil
  68. var stmt: COpaquePointer = nil
  69.  
  70. print(sqlVersion(),"\n")
  71.  
  72. sqlOpen("test.db", database: &db)
  73.  
  74. var sql =       "DROP TABLE IF EXISTS Cars;" +
  75.             "CREATE TABLE Cars(Id INT, Name TEXT, Price INT);" +
  76.             "INSERT INTO Cars VALUES(1, 'Audi', 52642);" +
  77.             "INSERT INTO Cars VALUES(2, 'Mercedes', 57127);" +
  78.             "INSERT INTO Cars VALUES(3, 'Skoda', 9000);" +
  79.             "INSERT INTO Cars VALUES(4, 'Volvo', 29000);" +
  80.             "INSERT INTO Cars VALUES(5, 'Bentley', 350000);" +
  81.             "INSERT INTO Cars VALUES(6, 'Citroen', 21000);" +
  82.             "INSERT INTO Cars VALUES(7, 'Hummer', 41400);" +
  83.             "INSERT INTO Cars VALUES(8, 'Volkswagen', 21600);"
  84.  
  85. sqlExec(db, query: sql)
  86.  
  87.  
  88. sql = "SELECT Name,Price FROM Cars Order By Price DESC"
  89.  
  90. sqlPrepare(db, query: sql, statement: &stmt)
  91.  
  92. while sqlStep(stmt) == SQLITE_ROW {
  93.         var make  = sqlColumnText(stmt, column: 0)
  94.         var price = sqlColumnText(stmt, column: 1)
  95.         print(make,price)
  96.  
  97. }
  98.  
  99.  
  100. sqlClose(db)
  101.  

That's a ridiculous amount of casting just to get Swift to work with SQlite3.

One other thing, and this applies to MacOS as well:  If you use Swift, you also need to make the libraries available.  On the Mac, they're added to the application bundle, bloating the overall App size.  It also won't work on systems running os versions less than 10.9.  On Linux, you'll need to distribute the libraries in order for apps to work.  Reminds me of Mono on Mac and Linux.
Title: Re: Apple Swift on Ubuntu
Post by: John on December 13, 2015, 03:27:12 PM
I haven't given up on Script BASIC for the same reason. It might be slower than Swift but I can do anything I want with it and on multiple platforms with a common scripting code base. C BASIC for the extension module API even makes it easier to extend the language seamlessly.

To me, your Swift SQLite interface doesn't look bad and is very informative how one must interface with standard C libraries.

Thanks again for this effort and it gives me something to build on. (try to plug in my SDL_gfx generic library I initially did for BaCon)


jrs@laptop:~/Swift/sqldemo$ ls -l
total 12
-rw-rw-r-- 1 jrs jrs  151 Dec 13 12:17 Package.swift
drwxrwxr-x 2 jrs jrs 4096 Dec 13 15:57 sources
drwxrwxr-x 4 jrs jrs 4096 Dec 13 15:57 Sqlite3
jrs@laptop:~/Swift/sqldemo$ swift build
Cloning Packages/Sqlite3
Compiling Swift Module 'sqldemo' (1 sources)
Linking Executable:  .build/debug/sqldemo
jrs@laptop:~/Swift/sqldemo$ ls -la
total 28
drwxrwxr-x 6 jrs jrs 4096 Dec 13 16:05 .
drwxrwxr-x 7 jrs jrs 4096 Dec 13 15:57 ..
drwxrwxr-x 3 jrs jrs 4096 Dec 13 16:05 .build
drwxrwxr-x 3 jrs jrs 4096 Dec 13 16:05 Packages
-rw-rw-r-- 1 jrs jrs  151 Dec 13 12:17 Package.swift
drwxrwxr-x 2 jrs jrs 4096 Dec 13 15:57 sources
drwxrwxr-x 4 jrs jrs 4096 Dec 13 15:57 Sqlite3
jrs@laptop:~/Swift/sqldemo$ cd .build
jrs@laptop:~/Swift/sqldemo/.build$ ls -l
total 4
drwxrwxr-x 4 jrs jrs 4096 Dec 13 16:05 debug
jrs@laptop:~/Swift/sqldemo/.build$ cd debug
jrs@laptop:~/Swift/sqldemo/.build/debug$ ls -l
total 80
-rwxrwxr-x 1 jrs jrs 56275 Dec 13 16:05 sqldemo
drwxrwxr-x 5 jrs jrs  4096 Dec 13 16:05 sqldemo.o
-rw-rw-r-- 1 jrs jrs   540 Dec 13 16:05 sqldemo.swiftdoc
-rw-rw-r-- 1 jrs jrs 11148 Dec 13 16:05 sqldemo.swiftmodule
drwxrwxr-x 3 jrs jrs  4096 Dec 13 16:05 Sqlite3.o
jrs@laptop:~/Swift/sqldemo/.build/debug$ ./sqldemo
Sqlite3 Version: 3.8.2

Bentley 350000
Mercedes 57127
Audi 52642
Hummer 41400
Volvo 29000
Volkswagen 21600
Citroen 21000
Skoda 9000
jrs@laptop:~/Swift/sqldemo/.build/debug$
Title: Re: Apple Swift on Ubuntu
Post by: John on December 13, 2015, 04:47:33 PM
This works for me. How can I make your SQLite3 Swift code an include or import?

Code: Text
  1. import Foundation
  2. import Glibc
  3.  
  4.  
  5. func sqlColumnText(statement: COpaquePointer, column: Int32) -> String {
  6.         return String.fromCString(UnsafePointer<CChar>(sqlite3_column_text(statement,column)))!
  7. }
  8.  
  9. func sqlVersion() -> String {
  10.         let s = String.fromCString(sqlite3_libversion())!
  11.         return "Sqlite3 Version: \(s)"
  12. }
  13.  
  14. func sqlOpen(filename: String, database: UnsafeMutablePointer<COpaquePointer>) {
  15.         let rc = sqlite3_open(filename, database)
  16.  
  17.         if (rc != SQLITE_OK) {
  18.                 print("Cannot open database " + String.fromCString(sqlite3_errmsg(database.memory))!)
  19.                 exit(1)
  20.         }
  21. }
  22.  
  23. func sqlExec(database: COpaquePointer, query: String) {
  24.         var err_msg: UnsafeMutablePointer<CChar> = nil
  25.         let rc = sqlite3_exec(database, query, nil, nil, &err_msg)
  26.  
  27.         if (rc != SQLITE_OK ) {
  28.                
  29.             print("SQL error: " + String.fromCString( err_msg)!)
  30.            
  31.             sqlite3_free(err_msg)      
  32.             sqlite3_close(database)
  33.            
  34.             exit(1)
  35.         }
  36. }
  37.  
  38. func sqlPrepare(database: COpaquePointer, query: String, statement: UnsafeMutablePointer<COpaquePointer>) {
  39.         let rc = sqlite3_prepare_v2(database,query,-1,statement,nil)
  40.  
  41.         if (rc != SQLITE_OK ) {
  42.            
  43.             print("Failed to select data")
  44.             print("SQL error: " + String.fromCString( sqlite3_errmsg(database))!)
  45.  
  46.  
  47.             sqlite3_close(database)
  48.            
  49.             exit(1)
  50.         }
  51. }
  52.  
  53. func sqlStep(statement: COpaquePointer) -> Int32 {
  54.         return sqlite3_step(statement)
  55. }
  56.  
  57. func sqlClose(database: COpaquePointer){
  58.         sqlite3_close(database)
  59. }
  60.  
  61.  
  62. var db: COpaquePointer = nil
  63. var stmt: COpaquePointer = nil
  64.  
  65. print(sqlVersion(),"\n")
  66.  
  67. sqlOpen("test.db", database: &db)
  68.  
  69. var sql =       "DROP TABLE IF EXISTS Cars;" +
  70.             "CREATE TABLE Cars(Id INT, Name TEXT, Price INT);" +
  71.             "INSERT INTO Cars VALUES(1, 'Audi', 52642);" +
  72.             "INSERT INTO Cars VALUES(2, 'Mercedes', 57127);" +
  73.             "INSERT INTO Cars VALUES(3, 'Skoda', 9000);" +
  74.             "INSERT INTO Cars VALUES(4, 'Volvo', 29000);" +
  75.             "INSERT INTO Cars VALUES(5, 'Bentley', 350000);" +
  76.             "INSERT INTO Cars VALUES(6, 'Citroen', 21000);" +
  77.             "INSERT INTO Cars VALUES(7, 'Hummer', 41400);" +
  78.             "INSERT INTO Cars VALUES(8, 'Volkswagen', 21600);"
  79.  
  80. sqlExec(db, query: sql)
  81.  
  82. sql = "SELECT Name,Price FROM Cars Order By Price DESC"
  83.  
  84. sqlPrepare(db, query: sql, statement: &stmt)
  85.  
  86. while sqlStep(stmt) == SQLITE_ROW {
  87.         var make  = sqlColumnText(stmt, column: 0)
  88.         var price = sqlColumnText(stmt, column: 1)
  89.         print(make,price)
  90.  
  91. }    
  92.  
  93. sqlClose(db)
  94.  


jrs@laptop:~/Swift/usr/share/examples$ swiftc airlite.swift -import-objc-header /usr/include/sqlite3.h -lsqlite3 -o airlite
jrs@laptop:~/Swift/usr/share/examples$ time ./airlite
Sqlite3 Version: 3.8.2

Bentley 350000
Mercedes 57127
Audi 52642
Hummer 41400
Volvo 29000
Volkswagen 21600
Citroen 21000
Skoda 9000

real   0m1.226s
user   0m0.022s
sys   0m0.000s
jrs@laptop:~/Swift/usr/share/examples$
Title: Re: Apple Swift on Ubuntu
Post by: AIR on December 13, 2015, 05:37:41 PM
How can I make your SQLite3 Swift code an include or import?

By building on the CSQlite3 module I created.
Title: Re: Apple Swift on Ubuntu
Post by: John on December 13, 2015, 06:01:12 PM
AIR,

Here is your Swift example in Script BASIC clothing.

Code: Script BASIC
  1. IMPORT sqlite.bas
  2.  
  3. db = sqlite::OPEN("test.db")
  4.  
  5. PRINT sqlite::VERSION(),"\n"
  6.  
  7. sql = """
  8. DROP TABLE IF EXISTS Cars;
  9. CREATE TABLE Cars(Id INT, Name TEXT, Price INT);
  10. INSERT INTO Cars VALUES(1, 'Audi', 52642);
  11. INSERT INTO Cars VALUES(2, 'Mercedes', 57127);
  12. INSERT INTO Cars VALUES(3, 'Skoda', 9000);
  13. INSERT INTO Cars VALUES(4, 'Volvo', 29000);
  14. INSERT INTO Cars VALUES(5, 'Bentley', 350000);
  15. INSERT INTO Cars VALUES(6, 'Citroen', 21000);
  16. INSERT INTO Cars VALUES(7, 'Hummer', 41400);
  17. INSERT INTO Cars VALUES(8, 'Volkswagen', 21600);
  18. """
  19.  
  20. sqlite::EXECUTE(db, sql)
  21.  
  22. stmt = sqlite::QUERY(db, "SELECT Name,Price FROM Cars Order By Price DESC")
  23.  
  24. PRINTNL
  25. WHILE (sqlite::ROW(stmt) = sqlite::SQLITE3_ROW)
  26.   IF sqlite::FETCHHASH(stmt,column) THEN
  27.     PRINT column{"Name"}," ",column{"Price"},"\n"
  28.   END IF
  29. WEND
  30.  
  31. sqlite::CLOSE(db)
  32.  


jrs@laptop:~/sb/sb22/test$ time scriba sqlair.sb
3.7.12.1

Bentley 350000
Mercedes 57127
Audi 52642
Hummer 41400
Volvo 29000
Volkswagen 21600
Citroen 21000
Skoda 9000

real   0m1.232s
user   0m0.001s
sys   0m0.010s
jrs@laptop:~/sb/sb22/test$

Title: Re: Apple Swift on Ubuntu
Post by: John on December 14, 2015, 10:34:20 AM
Quote
By building on the CSQlite3 module I created.

@AIR - I can't seem to figure out how to get a module built that I can import.

What's the trick?

Ideally I would like to do something like this.

Code: Text
  1.     import Foundation
  2.     import Glibc
  3.     import SQLite    
  4.      
  5.     var db: COpaquePointer = nil
  6.     var stmt: COpaquePointer = nil
  7.      
  8.     print(sqlVersion(),"\n")
  9.      
  10.     sqlOpen("test.db", database: &db)
  11.      
  12.     var sql =       "DROP TABLE IF EXISTS Cars;" +
  13.                 "CREATE TABLE Cars(Id INT, Name TEXT, Price INT);" +
  14.                 "INSERT INTO Cars VALUES(1, 'Audi', 52642);" +
  15.                 "INSERT INTO Cars VALUES(2, 'Mercedes', 57127);" +
  16.                 "INSERT INTO Cars VALUES(3, 'Skoda', 9000);" +
  17.                 "INSERT INTO Cars VALUES(4, 'Volvo', 29000);" +
  18.                 "INSERT INTO Cars VALUES(5, 'Bentley', 350000);" +
  19.                 "INSERT INTO Cars VALUES(6, 'Citroen', 21000);" +
  20.                 "INSERT INTO Cars VALUES(7, 'Hummer', 41400);" +
  21.                 "INSERT INTO Cars VALUES(8, 'Volkswagen', 21600);"
  22.      
  23.     sqlExec(db, query: sql)
  24.      
  25.     sql = "SELECT Name,Price FROM Cars Order By Price DESC"
  26.      
  27.     sqlPrepare(db, query: sql, statement: &stmt)
  28.      
  29.     while sqlStep(stmt) == SQLITE_ROW {
  30.             var make  = sqlColumnText(stmt, column: 0)
  31.             var price = sqlColumnText(stmt, column: 1)
  32.             print(make,price)
  33.      
  34.     }    
  35.      
  36.     sqlClose(db)
  37.  
     


swiftc airlite.swift -o airlite

Title: Re: Apple Swift on Ubuntu
Post by: John on December 14, 2015, 09:30:21 PM
Quote from: AIR
People use Swift because a huge (<--cue Donald Trump Accent) company is behind it.  Kind of like how Objective C became popular.

Watch how Apple’s Swift evolved into an open source powerhouse (http://thenextweb.com/dd/2015/12/14/watch-how-apples-swift-evolved-into-an-open-source-powerhouse/)

Quote from: AIR
At least with Objective C, I can drop straight C into it without having to jump through crazy hoops to get shit to work.

That's how I feel about Script BASIC. If all I'm interested is in getting something done or test a proof of concept, SB works for me. If it's not a one off project and will be distributed, then I'll take another look what is the best solution for that environment.

@AIR - Thanks for the nudge! I will take another look at NIM.